repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
hackarada/youtube-dl
youtube_dl/extractor/apa.py
<reponame>hackarada/youtube-dl # coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( determine_ext, js_to_json, url_or_none, ) class APAIE(InfoExtractor): _VALID_URL = r'https?://[^/]+\.apa\.at/embed/(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})' _TESTS = [{ 'url': 'http://uvp.apa.at/embed/293f6d17-692a-44e3-9fd5-7b178f3a1029', 'md5': '2b12292faeb0a7d930c778c7a5b4759b', 'info_dict': { 'id': 'jjv85FdZ', 'ext': 'mp4', 'title': '"Blau ist mysteriös": Die Blue Man Group im Interview', 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e', 'thumbnail': r're:^https?://.*\.jpg$', 'duration': 254, 'timestamp': 1519211149, 'upload_date': '20180221', }, }, { 'url': 'https://uvp-apapublisher.sf.apa.at/embed/2f94e9e6-d945-4db2-9548-f9a41ebf7b78', 'only_matching': True, }, { 'url': 'http://uvp-rma.sf.apa.at/embed/70404cca-2f47-4855-bbb8-20b1fae58f76', 'only_matching': True, }, { 'url': 'http://uvp-kleinezeitung.sf.apa.at/embed/f1c44979-dba2-4ebf-b021-e4cf2cac3c81', 'only_matching': True, }] @staticmethod def _extract_urls(webpage): return [ mobj.group('url') for mobj in re.finditer( r'<iframe[^>]+\bsrc=(["\'])(?P<url>(?:https?:)?//[^/]+\.apa\.at/embed/[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}.*?)\1', webpage)] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) jwplatform_id = self._search_regex( r'media[iI]d\s*:\s*["\'](?P<id>[a-zA-Z0-9]{8})', webpage, 'jwplatform id', default=None) if jwplatform_id: return self.url_result( 'jwplatform:' + jwplatform_id, ie='JWPlatform', video_id=video_id) sources = self._parse_json( self._search_regex( r'sources\s*=\s*(\[.+?\])\s*;', webpage, 'sources'), video_id, transform_source=js_to_json) formats = [] for source in sources: if not isinstance(source, dict): continue source_url = url_or_none(source.get('file')) if not source_url: continue ext = determine_ext(source_url) if ext == 'm3u8': formats.extend(self._extract_m3u8_formats( source_url, video_id, 'mp4', entry_protocol='m3u8_native', m3u8_id='hls', fatal=False)) else: formats.append({ 'url': source_url, }) self._sort_formats(formats) thumbnail = self._search_regex( r'image\s*:\s*(["\'])(?P<url>(?:(?!\1).)+)\1', webpage, 'thumbnail', fatal=False, group='url') return { 'id': video_id, 'title': video_id, 'thumbnail': thumbnail, 'formats': formats, }
tilnewman/heroespath-src
src/combat/encounter.hpp
// ---------------------------------------------------------------------------- // "THE BEER-WARE LICENSE" (Revision 42): // <<EMAIL>> wrote this file. As long as you retain this notice you // can do whatever you want with this stuff. If we meet some day, and you think // this stuff is worth it, you can buy me a beer in return. <NAME> // ---------------------------------------------------------------------------- #ifndef HEROESPATH_COMBAT_ENCOUNTER_HPP_INCLUDED #define HEROESPATH_COMBAT_ENCOUNTER_HPP_INCLUDED // // encounter.hpp // Code that orchestrates an encounter from start to finish, // and owns the pointers to the non-player party. // #include "combat/turn-action-enum.hpp" #include "combat/turn-info.hpp" #include "item/item-cache.hpp" #include "item/treasure-image-enum.hpp" #include "item/treasure.hpp" #include "misc/boost-optional-that-throws.hpp" #include "misc/not-null.hpp" #include <memory> #include <string> #include <vector> namespace heroespath { namespace creature { // forward declarations class Creature; using CreaturePtr_t = misc::NotNull<Creature *>; using CreaturePVec_t = std::vector<CreaturePtr_t>; } // namespace creature namespace combat { namespace strategy { class CreatureStrategies; using CreatureStrategiesUPtr_t = std::unique_ptr<CreatureStrategies>; } // namespace strategy // Manages an encounter with the player party class Encounter { public: Encounter(const Encounter &) = delete; Encounter(Encounter &&) = delete; Encounter & operator=(const Encounter &) = delete; Encounter & operator=(Encounter &&) = delete; Encounter(); ~Encounter(); static misc::NotNull<Encounter *> Instance(); static void Acquire(); static void Release(); // the player party CreaturePtr_ts are kept by the game::GameState in a // creature::PlayerParty object, but all of the non-player CreaturePtr_ts are kept here in // these vectors const creature::CreaturePVec_t & LivingNonPlayers() const { return nonPlayerPartyPVec_; } const creature::CreaturePVec_t & DeadNonPlayers() const { return deadNonPlayerPartyPVec_; } const creature::CreaturePVec_t & RunawayNonPlayers() const { return runawayNonPlayerPartyPVec_; } const creature::CreaturePVec_t & RunawayPlayers() const { return runawayPlayersVec_; } const std::string LivingNonPlayersSummary() const { return CreaturesSummary(nonPlayerPartyPVec_); } bool IsRunaway(const creature::CreaturePtr_t) const; void Runaway(const creature::CreaturePtr_t); std::size_t GetRoundCount() { return roundCounter_; } bool HasStarted() const { return hasStarted_; } const creature::CreaturePtrOpt_t CurrentTurnCreaturePtrOpt() const { return turnCreaturePtrOpt_; } const TurnInfo GetTurnInfoCopy(const creature::CreaturePtr_t) const; void SetTurnInfo(const creature::CreaturePtr_t CREATURE_PTR, const TurnInfo & TURN_INFO) { turnInfoMap_[CREATURE_PTR] = TURN_INFO; } void SetIsFlying(const creature::CreaturePtr_t CREATURE_PTR, const bool IS_FLYING) { turnInfoMap_[CREATURE_PTR].SetIsFlying(IS_FLYING); } void SetTurnActionInfo( const creature::CreaturePtr_t CREATURE_PTR, const TurnActionInfo & TURN_ACTION_INFO) { turnInfoMap_[CREATURE_PTR].SetTurnActionInfo(TURN_ACTION_INFO); } void HandleKilledCreature(const creature::CreaturePtr_t); void IncrementTurn(); void BeginCombatTasks(); void EndCombatTasks(); item::TreasureImage::Enum BeginTreasureStageTasks(); void EndTreasureStageTasks( const item::ItemCache & ITEM_CACHE_WORN, const item::ItemCache & ITEM_CACHE_OWNED); const item::ItemCache TakeDeadNonPlayerItemsHeldCache(); const item::ItemCache TakeDeadNonPlayerItemsLockboxCache(); bool DidAllEnemiesRunAway() const; const creature::CreaturePtrOpt_t LockPickCreaturePtrOpt() const { return lockPickCreaturePtrOpt_; } void LockPickCreaturePtr(const creature::CreaturePtr_t CREATURE_PTR) { lockPickCreaturePtrOpt_ = CREATURE_PTR; } float DefeatedPartyTreasureRatioPer() const; void BeginAndEndFakeCombatForTesting(); private: void PopulateTurnInfoMap(); void SortAndSetTurnCreature(); const std::string CreaturesSummary(const creature::CreaturePVec_t &) const; private: static std::unique_ptr<Encounter> instanceUPtr_; // Non-player creature pointers are owned by these vectors. // Each non-player creature pointer must only ever be in one of these vectors at a time. // // The destructor calls Warehouse::Free() for each of these, but that is only in case // the application exits abnormally. Normally, the correct sequence of functions is called // (BeginCombatTasks(), EndCombatTasks(), BeginTreasureStageTasks(), // EndTreasureStageTasks()) which will leave these vectors empty. creature::CreaturePVec_t nonPlayerPartyPVec_; creature::CreaturePVec_t deadNonPlayerPartyPVec_; creature::CreaturePVec_t runawayNonPlayerPartyPVec_; // copies of player character pointers are stored temporarily in this vector creature::CreaturePVec_t runawayPlayersVec_; std::size_t roundCounter_; bool hasStarted_; creature::CreaturePVec_t turnOverPVec_; std::size_t turnIndex_; TurnInfoMap_t turnInfoMap_; // this member always stores a copy, and is never responsible for lifetime creature::CreaturePtrOpt_t turnCreaturePtrOpt_; // the pointers in these two item caches are observer pointers but this class is responsible // for their lifetime, meaning this class is responsible for calling ItemWarehouse::Free() // on each. Normally, the correct sequence of functions is called (BeginCombatTasks(), // EndCombatTasks(), BeginTreasureStageTasks(), EndTreasureStageTasks()) which frees and // empties these vectors. If the application exits abnormally, then the destructor will // will ensure these are free'd. // contains all items the dead enemies were wearing or holding when killed item::ItemCache deadNonPlayerItemsHeld_; // contains all the items the dead enemies were holding in the chest/lockbox item::ItemCache deadNonPlayerItemsLockbox_; // this member always stores a copy, and is never responsible for lifetime creature::CreaturePtrOpt_t lockPickCreaturePtrOpt_; strategy::CreatureStrategiesUPtr_t creatureStrategiesUPtr_; item::TreasureFactory treasureFactory_; }; } // namespace combat } // namespace heroespath #endif // HEROESPATH_COMBAT_ENCOUNTER_HPP_INCLUDED
fanzehua498/2018ForYou
BlueToothAbout/BlueToothAbout/Runtime/Protocol/RunProtocol.h
// // RunProtocol.h // BlueToothAbout // // Created by 知合金服-Mini on 2018/7/19. // Copyright © 2018年 fanzehua. All rights reserved. // #import <Foundation/Foundation.h> @protocol RunProtocol <NSObject> - (void)buy:(NSString *)str; - (void)sel:(NSString *)str; - (void)eat:(NSString *)str; - (void)push:(NSString *)str; @end
remz1337/ecj
contrib/xholon/org/primordion/ealontro/gp/XhKozaStatistics.java
<reponame>remz1337/ecj /* Ealontro - systems that evolve and adapt to their environment * Copyright (C) 2006, 2007 <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 */ package org.primordion.ealontro.gp; import java.io.IOException; import java.io.Writer; import java.util.Date; import org.primordion.xholon.base.IXholon; import org.primordion.xholon.util.Misc; import ec.EvolutionState; import ec.gp.GPIndividual; import ec.gp.koza.KozaFitness; import ec.gp.koza.KozaStatistics; /** * Generates Koza-style statistics, including an XML file that contains the best solution found. * The XML file can be used as CompositeStructureHierarchy.xml in a Xholon application. * @author <NAME> * @since 0.3 (Created on May 17, 2006) */ public class XhKozaStatistics extends KozaStatistics { // name and path of saved CompositeStructureHierarchy XML file protected static final String cshFileName = "EcjCompositeStructureHierarchy_Best.xml"; protected static String cshFilePath = "./"; // stored best, average, worst fitness (ECJ standardized fitness = ECJ raw fitness) of current generation protected float xhFitnessWorst; protected float xhFitnessAverage; protected float xhFitnessBest; /** * Get the worst fitness (ECJ standardized fitness = ECJ raw fitness) of this generation. * @return Worst fitness. */ public float getWorstFitnessThisGeneration() {return xhFitnessWorst;} /** * Get the average fitness (ECJ standardized fitness = ECJ raw fitness) of this generation. * @return Average fitness. */ public float getAverageFitnessThisGeneration() {return xhFitnessAverage;} /** * Get the best fitness (ECJ standardized fitness = ECJ raw fitness) of this generation. * @return Best fitness. */ public float getBestFitnessThisGeneration() {return xhFitnessBest;} /** * Set the best fitness (ECJ standardized fitness = ECJ raw fitness) of this generation. * @param state The current ECJ state. */ protected void setBestFitnessThisGeneration(EvolutionState state) { int subPop = 0; KozaFitness bestFit = (KozaFitness)state.population.subpops[subPop].individuals[0].fitness; for (int i = 1; i < state.population.subpops[subPop].individuals.length; ++i) { KozaFitness fit = (KozaFitness)state.population.subpops[subPop].individuals[i].fitness; if (fit.betterThan(bestFit)) bestFit = fit; } xhFitnessBest = bestFit.standardizedFitness(); } /** * Set the average fitness (ECJ standardized fitness = ECJ raw fitness) of this generation. * @param state The current ECJ state. */ protected void setAverageFitnessThisGeneration(EvolutionState state) { float meanAdjusted = 0.0f; int subPop = 0; for (int i = 0; i < state.population.subpops[subPop].individuals.length; ++i) { meanAdjusted += ((KozaFitness)(state.population.subpops[subPop].individuals[i].fitness)).standardizedFitness(); //.adjustedFitness(); } meanAdjusted /= state.population.subpops[subPop].individuals.length; xhFitnessAverage = meanAdjusted; } /** * Set the worst fitness (ECJ standardized fitness = ECJ raw fitness) of this generation. * @param state The current ECJ state. */ protected void setWorstFitnessThisGeneration(EvolutionState state) { int subPop = 0; KozaFitness worstFit = (KozaFitness)state.population.subpops[subPop].individuals[0].fitness; for (int i = 1; i < state.population.subpops[subPop].individuals.length; ++i) { KozaFitness fit = (KozaFitness)state.population.subpops[subPop].individuals[i].fitness; if (worstFit.betterThan(fit)) worstFit = fit; } xhFitnessWorst = worstFit.standardizedFitness(); } /* * @see ec.Statistics#postEvaluationStatistics(ec.EvolutionState) */ public void postEvaluationStatistics(final EvolutionState state) { super.postEvaluationStatistics(state); setWorstFitnessThisGeneration(state); setAverageFitnessThisGeneration(state); setBestFitnessThisGeneration(state); } /** * Set the CompositeStructureHierarchy.xml file path, given the name of the model. * @param modelName Model name (ex: ./config/ealontro/CartCentering/EcjCartCentering_xhn.xml) */ public static void setCshFilePath(String modelName) { System.out.println(modelName); int ix = modelName.lastIndexOf("/"); if (ix == -1) { ix = modelName.lastIndexOf("\\"); } if (ix != -1) { cshFilePath = modelName.substring(0, ix+1); } } /* * @see ec.Statistics#finalStatistics(ec.EvolutionState, int) */ public void finalStatistics(final EvolutionState state, final int result) { super.finalStatistics(state,result); // write XML file writeBestAsXhXml(state); } /** * Write the best of run individual as a CompositeStructureHierarchy XML file. * @param state The current ECJ state. */ protected void writeBestAsXhXml(EvolutionState state) { //System.out.println("writeBestAsXhXml"); // open file Writer out = Misc.openOutputFile(cshFilePath + cshFileName); //("./config/CompositeStructureHierarchy_Best.xml"); IXholon sysXh; String sysClassName; Date dateOut = new Date(); // write tree try { out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); sysXh = ((GPIndividual)best_of_run[0]).trees[0].getParentNode().getParentNode(); sysClassName = sysXh.getXhcName(); out.write("<!--\nBest of run for " + sysClassName + "\n" + "raw fitness: " + ((KozaFitness)best_of_run[0].fitness).rawFitness() + " adjusted fitness: " + ((KozaFitness)best_of_run[0].fitness).fitness() + " hits: " + ((KozaFitness)best_of_run[0].fitness).hits + "\n" //+ ((GPIndividual)best_of_run[0]).trees[0].child.printNode(state, (PrintWriter)out) + "\n" + "size of best tree: " + ((GPIndividual)best_of_run[0]).trees[0].treeSize() + " starting at " + ((GPIndividual)best_of_run[0]).trees[0].getName() + "\n" + dateOut + " (" + dateOut.getTime() + ")\n" + "-->\n"); out.write("<Population>\n"); out.write("\t<" + sysClassName + ">" + " <!-- xholon instance " + sysXh.getId() + " -->\n"); out.write("\t\t<" + sysXh.getFirstChild().getXhcName() + ">\n"); // <Structure> sysXh.getFirstChild().getFirstChild().writeXml(3, out); // Structure subtree out.write("\t\t</" + sysXh.getFirstChild().getXhcName() + ">\n"); // </Structure> out.write("\t\t<" + sysXh.getFirstChild().getNextSibling().getXhcName() + ">\n"); // <GeneticProgram> ((GPIndividual)best_of_run[0]).trees[0].writeXml(3, out); // GPTree PfWrapper and subtree out.write("\t\t</" + sysXh.getFirstChild().getNextSibling().getXhcName() + ">\n"); // <GeneticProgram> //((GPIndividual)best_of_run[0]).trees[0].getParentNode().getPreviousSibling().writeXml(2, out); out.write("\t</" + sysClassName + ">\n"); out.write("</Population>\n"); } catch (IOException e) { e.printStackTrace(); } // close file Misc.closeOutputFile( out ); } }
naterenegar/ormar
tests/test_queries/test_reserved_sql_keywords_escaped.py
import databases import pytest import sqlalchemy import ormar from tests.settings import DATABASE_URL database = databases.Database(DATABASE_URL, force_rollback=True) metadata = sqlalchemy.MetaData() class BaseMeta(ormar.ModelMeta): metadata = metadata database = database class User(ormar.Model): class Meta(BaseMeta): tablename = "user" id: int = ormar.Integer(primary_key=True, autoincrement=True, nullable=False) user: str = ormar.String( unique=True, index=True, nullable=False, max_length=255 ) # ID of the user on auth0 first: str = ormar.String(nullable=False, max_length=255) last: str = ormar.String(nullable=False, max_length=255) email: str = ormar.String(unique=True, index=True, nullable=False, max_length=255) display_name: str = ormar.String( unique=True, index=True, nullable=False, max_length=255 ) pic_url: str = ormar.Text(nullable=True) class Task(ormar.Model): class Meta(BaseMeta): tablename = "task" id: int = ormar.Integer(primary_key=True, autoincrement=True, nullable=False) from_: str = ormar.String(name="from", nullable=True, max_length=200) user = ormar.ForeignKey(User) @pytest.fixture(autouse=True, scope="module") def create_test_database(): engine = sqlalchemy.create_engine(DATABASE_URL) metadata.drop_all(engine) metadata.create_all(engine) yield metadata.drop_all(engine) @pytest.mark.asyncio async def test_single_model_quotes(): async with database: await User.objects.create( user="test", first="first", last="last", email="<EMAIL>", display_name="first last", ) user = await User.objects.order_by("user").get(first="first") assert user.last == "last" assert user.email == "<EMAIL>" @pytest.mark.asyncio async def test_two_model_quotes(): async with database: user = await User.objects.create( user="test", first="first", last="last", email="<EMAIL>", display_name="first last", ) await Task(user=user, from_="aa").save() await Task(user=user, from_="bb").save() task = ( await Task.objects.select_related("user") .order_by("user__user") .get(from_="aa") ) assert task.user.last == "last" assert task.user.email == "<EMAIL>" tasks = await Task.objects.select_related("user").order_by("-from").all() assert len(tasks) == 2 assert tasks[0].user.last == "last" assert tasks[0].user.email == "<EMAIL>" assert tasks[0].from_ == "bb" assert tasks[1].user.last == "last" assert tasks[1].user.email == "<EMAIL>" assert tasks[1].from_ == "aa"
kostyrko/small_eod
backend-project/small_eod/collections/tests/test_factories.py
from django.test import TestCase from ..factories import CollectionFactory from ..models import Collection from ...generic.tests.mixins import FactoryTestCaseMixin class CollectionFactoryTestCase(FactoryTestCaseMixin, TestCase): FACTORY = CollectionFactory MODEL = Collection
helloMrZhan/main-framework
mybatis/mybatis-anno-multi/mybatis_anno/src/main/java/com/zjq/domain/User.java
<reponame>helloMrZhan/main-framework package com.zjq.domain; import lombok.Data; import java.util.Date; import java.util.List; /** * <p>用户</p> * * @Author zjq * @Date 2021/8/3 */ @Data public class User { private int id; private String username; private String password; private Date birthday; /** * 当前用户具备哪些角色 */ private List<Role> roleList; /** * 描述的是当前用户具有的订单 */ private List<Order> orderList; @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", birthday=" + birthday + ", roleList=" + roleList + ", orderList=" + orderList + '}'; } }
colorofchange/Champaign
db/migrate/20170406200345_add_restricted_country_code_to_plugins_call_tools.rb
class AddRestrictedCountryCodeToPluginsCallTools < ActiveRecord::Migration[4.2] def change add_column :plugins_call_tools, :restricted_country_code, :string end end
osgvsun/lubanlou
lubanlou-master/lubanlou-common/src/main/java/net/gvsun/datashare/external/reportdata/VirtualExperimentDTO.java
<gh_stars>1-10 package net.gvsun.datashare.external.reportdata; /** * Created by Administrator on 2021/7/8. */ public class VirtualExperimentDTO { //表2-8-2虚拟仿真实验教学项目 private String experimentalNumber; private String experimentalName; private String level; private String createdDate; private Integer studentHoursInsideTheSchool; private Integer totalViews; private Integer totalParticipants; private String yearCode; private String academyNumber; public String getExperimentalNumber() { return experimentalNumber; } public void setExperimentalNumber(String experimentalNumber) { this.experimentalNumber = experimentalNumber; } public String getExperimentalName() { return experimentalName; } public void setExperimentalName(String experimentalName) { this.experimentalName = experimentalName; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getCreatedDate() { return createdDate; } public void setCreatedDate(String createdDate) { this.createdDate = createdDate; } public Integer getStudentHoursInsideTheSchool() { return studentHoursInsideTheSchool; } public void setStudentHoursInsideTheSchool(Integer studentHoursInsideTheSchool) { this.studentHoursInsideTheSchool = studentHoursInsideTheSchool; } public Integer getTotalViews() { return totalViews; } public void setTotalViews(Integer totalViews) { this.totalViews = totalViews; } public Integer getTotalParticipants() { return totalParticipants; } public void setTotalParticipants(Integer totalParticipants) { this.totalParticipants = totalParticipants; } public String getYearCode() { return yearCode; } public void setYearCode(String yearCode) { this.yearCode = yearCode; } public String getAcademyNumber() { return academyNumber; } public void setAcademyNumber(String academyNumber) { this.academyNumber = academyNumber; } }
LibraryOfCongress/embARC
src/main/com/portalmedia/embarc/parser/mxf/MXFMetadata.java
package com.portalmedia.embarc.parser.mxf; import java.util.HashMap; import java.util.LinkedHashMap; import com.portalmedia.embarc.parser.MetadataColumnDef; public class MXFMetadata { int videoTrackCount; int audioTrackCount; int captionTrackCount; int timecodeTrackCount; String format; String version; String profile; long fileSize; int bdCount; int tdCount; MXFFileDescriptorResult fileDescriptors; public MXFFileDescriptorResult getFileDescriptors() { return fileDescriptors; } public void setFileDescriptors(MXFFileDescriptorResult fileDescriptors) { this.fileDescriptors = fileDescriptors; } public int getTDCount() { return tdCount; } public void setTDCount(int tdCount) { this.tdCount = tdCount; } public int getBDCount() { return bdCount; } public void setBDCount(int bdCount) { this.bdCount = bdCount; } public int getVideoTrackCount() { return videoTrackCount; } public void setVideoTrackCount(int videoTrackCount) { this.videoTrackCount = videoTrackCount; } public int getCaptionTrackCount() { return captionTrackCount; } public void setCaptionTrackCount(int captionTrackCount) { this.captionTrackCount = captionTrackCount; } public int getTimecodeTrackCount() { return timecodeTrackCount; } public void setTimecodeTrackCount(int timecodeTrackCount) { this.timecodeTrackCount = timecodeTrackCount; } public int getAudioTrackCount() { return audioTrackCount; } public void setAudioTrackCount(int audioTrackCount) { this.audioTrackCount = audioTrackCount; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getProfile() { return profile; } public void setProfile(String profile) { this.profile = profile; } public long getFileSize() { return fileSize; } public void setFileSize(long fileSize) { this.fileSize = fileSize; } HashMap<MXFColumn, MetadataColumnDef> coreColumns = new LinkedHashMap<MXFColumn, MetadataColumnDef>(); // InstanceUID HashMap<String, LinkedHashMap<MXFColumn, MetadataColumnDef>> bdColumns = new HashMap<String, LinkedHashMap<MXFColumn, MetadataColumnDef>>(); HashMap<String, LinkedHashMap<MXFColumn, MetadataColumnDef>> tdColumns = new HashMap<String, LinkedHashMap<MXFColumn, MetadataColumnDef>>(); public HashMap<String, LinkedHashMap<MXFColumn, MetadataColumnDef>> getBDColumns() { return bdColumns; } public void setBDColumns(HashMap<String, LinkedHashMap<MXFColumn, MetadataColumnDef>> bdColumns) { this.bdColumns = bdColumns; } public HashMap<String, LinkedHashMap<MXFColumn, MetadataColumnDef>> getTDColumns() { return tdColumns; } public void setTDColumns(HashMap<String, LinkedHashMap<MXFColumn, MetadataColumnDef>> tdColumns) { this.tdColumns = tdColumns; } public HashMap<MXFColumn, MetadataColumnDef> getCoreColumns() { return coreColumns; } public void setCoreColumns(HashMap<MXFColumn, MetadataColumnDef> coreColumns) { this.coreColumns = coreColumns; } }
MahmoudFawzy01/C-Projects
01-Compiler Project/Brac_Checking.h
<reponame>MahmoudFawzy01/C-Projects #ifndef _BRACT_CHECKING_ #define _BRACT_CHECKING_ #include "file_manger.h" void Compiler_CheckBract(char * p_firstLine); #endif // _BRACT_CHECKING_
banuelosj/jsapi-samples
typescript-samples/sketch-text-symbol-picker/node_modules/@esri/calcite-components/dist/collection/components/calcite-slider/calcite-slider.js
import { Component, Element, Prop, Host, Event, Listen, Method, h, State, Watch } from "@stencil/core"; import { guid } from "../../utils/guid"; import { getKey } from "../../utils/key"; import { hasLabel } from "../../utils/dom"; export class CalciteSlider { constructor() { /** Disable and gray out the slider */ this.disabled = false; /** Minimum selectable value */ this.min = 0; /** Maximum selectable value */ this.max = 100; /** Currently selected number (if single select) */ this.value = null; /** Snap selection along the step interval */ this.snap = true; /** Interval to move on up/down keys */ this.step = 1; /** Indicates if a histogram is present */ this.hasHistogram = false; //-------------------------------------------------------------------------- // // Private State/Props // //-------------------------------------------------------------------------- /** @internal */ this.guid = `calcite-slider-${guid()}`; /** @internal */ this.isRange = false; /** @internal */ this.tickValues = []; /** @internal */ this.activeProp = "value"; /** @internal */ this.minMaxValueRange = null; /** @internal */ this.minValueDragRange = null; /** @internal */ this.maxValueDragRange = null; } histogramWatcher(newHistogram) { this.hasHistogram = newHistogram ? true : false; } //-------------------------------------------------------------------------- // // Lifecycle // //-------------------------------------------------------------------------- componentWillLoad() { this.isRange = !!(this.maxValue || this.maxValue === 0); this.tickValues = this.generateTickValues(); this.value = this.bound(this.value); if (this.snap) { this.value = this.getClosestStep(this.value); } if (this.histogram) { this.hasHistogram = true; } this.calciteSliderUpdate.emit(); } componentDidRender() { if (this.labelHandles) { this.adjustHostObscuredHandleLabel("value"); if (this.isRange) { this.adjustHostObscuredHandleLabel("minValue"); if (!(this.precise && this.isRange && !this.hasHistogram)) { this.hyphenateCollidingRangeHandleLabels(); } } } this.hideObscuredBoundingTickLabels(); } render() { const id = this.el.id || this.guid; const min = this.minValue || this.min; const max = this.maxValue || this.value; const maxProp = this.isRange ? "maxValue" : "value"; const value = this[maxProp]; const left = `${this.getUnitInterval(min) * 100}%`; const right = `${100 - this.getUnitInterval(max) * 100}%`; const handle = (h("button", { "aria-label": this.isRange ? this.maxLabel : this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": value, class: { thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = maxProp), onMouseDown: () => this.dragStart(maxProp), onTouchStart: (e) => this.dragStart(maxProp, e), ref: (el) => (this.maxHandle = el), role: "slider", style: { right } }, h("div", { class: "handle" }))); const labeledHandle = (h("button", { "aria-label": this.isRange ? this.maxLabel : this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": value, class: { thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = maxProp), onMouseDown: () => this.dragStart(maxProp), onTouchStart: (e) => this.dragStart(maxProp, e), ref: (el) => (this.maxHandle = el), role: "slider", style: { right } }, h("span", { "aria-hidden": "true", class: "handle__label handle__label--value" }, value ? value.toLocaleString() : value), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value static" }, value ? value.toLocaleString() : value), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value transformed" }, value ? value.toLocaleString() : value), h("div", { class: "handle" }))); const histogramLabeledHandle = (h("button", { "aria-label": this.isRange ? this.maxLabel : this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": value, class: { thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = maxProp), onMouseDown: () => this.dragStart(maxProp), onTouchStart: (e) => this.dragStart(maxProp, e), ref: (el) => (this.maxHandle = el), role: "slider", style: { right } }, h("div", { class: "handle" }), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value" }, value ? value.toLocaleString() : value), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value static" }, value ? value.toLocaleString() : value), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value transformed" }, value ? value.toLocaleString() : value))); const preciseHandle = (h("button", { "aria-label": this.isRange ? this.maxLabel : this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": value, class: { thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp, "thumb--precise": true }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = maxProp), onMouseDown: () => this.dragStart(maxProp), onTouchStart: (e) => this.dragStart(maxProp, e), ref: (el) => (this.maxHandle = el), role: "slider", style: { right } }, h("div", { class: "handle" }), h("div", { class: "handle-extension" }))); const histogramPreciseHandle = (h("button", { "aria-label": this.isRange ? this.maxLabel : this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": value, class: { thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp, "thumb--precise": true }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = maxProp), onMouseDown: () => this.dragStart(maxProp), onTouchStart: (e) => this.dragStart(maxProp, e), ref: (el) => (this.maxHandle = el), role: "slider", style: { right } }, h("div", { class: "handle-extension" }), h("div", { class: "handle" }))); const labeledPreciseHandle = (h("button", { "aria-label": this.isRange ? this.maxLabel : this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": value, class: { thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp, "thumb--precise": true }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = maxProp), onMouseDown: () => this.dragStart(maxProp), onTouchStart: (e) => this.dragStart(maxProp, e), ref: (el) => (this.maxHandle = el), role: "slider", style: { right } }, h("span", { "aria-hidden": "true", class: "handle__label handle__label--value" }, value ? value.toLocaleString() : value), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value static" }, value ? value.toLocaleString() : value), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value transformed" }, value ? value.toLocaleString() : value), h("div", { class: "handle" }), h("div", { class: "handle-extension" }))); const histogramLabeledPreciseHandle = (h("button", { "aria-label": this.isRange ? this.maxLabel : this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": value, class: { thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp, "thumb--precise": true }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = maxProp), onMouseDown: () => this.dragStart(maxProp), onTouchStart: (e) => this.dragStart(maxProp, e), ref: (el) => (this.maxHandle = el), role: "slider", style: { right } }, h("div", { class: "handle-extension" }), h("div", { class: "handle" }), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value" }, value ? value.toLocaleString() : value), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value static" }, value ? value.toLocaleString() : value), h("span", { "aria-hidden": "true", class: "handle__label handle__label--value transformed" }, value ? value.toLocaleString() : value))); const minHandle = (h("button", { "aria-label": this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": this.minValue, class: { thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue" }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = "minValue"), onMouseDown: () => this.dragStart("minValue"), onTouchStart: (e) => this.dragStart("minValue", e), ref: (el) => (this.minHandle = el), role: "slider", style: { left } }, h("div", { class: "handle" }))); const minLabeledHandle = (h("button", { "aria-label": this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": this.minValue, class: { thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue" }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = "minValue"), onMouseDown: () => this.dragStart("minValue"), onTouchStart: (e) => this.dragStart("minValue", e), ref: (el) => (this.minHandle = el), role: "slider", style: { left } }, h("span", { "aria-hidden": "true", class: "handle__label handle__label--minValue" }, this.minValue && this.minValue.toLocaleString()), h("span", { "aria-hidden": "true", class: "handle__label handle__label--minValue static" }, this.minValue && this.minValue.toLocaleString()), h("span", { "aria-hidden": "true", class: "handle__label handle__label--minValue transformed" }, this.minValue && this.minValue.toLocaleString()), h("div", { class: "handle" }))); const minHistogramLabeledHandle = (h("button", { "aria-label": this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": this.minValue, class: { thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue" }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = "minValue"), onMouseDown: () => this.dragStart("minValue"), onTouchStart: (e) => this.dragStart("minValue", e), ref: (el) => (this.minHandle = el), role: "slider", style: { left } }, h("div", { class: "handle" }), h("span", { "aria-hidden": "true", class: "handle__label handle__label--minValue" }, this.minValue && this.minValue.toLocaleString()), h("span", { "aria-hidden": "true", class: "handle__label handle__label--minValue static" }, this.minValue && this.minValue.toLocaleString()), h("span", { "aria-hidden": "true", class: "handle__label handle__label--minValue transformed" }, this.minValue && this.minValue.toLocaleString()))); const minPreciseHandle = (h("button", { "aria-label": this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": this.minValue, class: { thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue", "thumb--precise": true }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = "minValue"), onMouseDown: () => this.dragStart("minValue"), onTouchStart: (e) => this.dragStart("minValue", e), ref: (el) => (this.minHandle = el), role: "slider", style: { left } }, h("div", { class: "handle-extension" }), h("div", { class: "handle" }))); const minLabeledPreciseHandle = (h("button", { "aria-label": this.minLabel, "aria-orientation": "horizontal", "aria-valuemax": this.max, "aria-valuemin": this.min, "aria-valuenow": this.minValue, class: { thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue", "thumb--precise": true }, disabled: this.disabled, onBlur: () => (this.activeProp = null), onFocus: () => (this.activeProp = "minValue"), onMouseDown: () => this.dragStart("minValue"), onTouchStart: (e) => this.dragStart("minValue", e), ref: (el) => (this.minHandle = el), role: "slider", style: { left } }, h("div", { class: "handle-extension" }), h("div", { class: "handle" }), h("span", { "aria-hidden": "true", class: "handle__label handle__label--minValue" }, this.minValue && this.minValue.toLocaleString()), h("span", { "aria-hidden": "true", class: "handle__label handle__label--minValue static" }, this.minValue && this.minValue.toLocaleString()), h("span", { "aria-hidden": "true", class: "handle__label handle__label--minValue transformed" }, this.minValue && this.minValue.toLocaleString()))); return (h(Host, { id: id, "is-range": this.isRange }, this.renderGraph(), h("div", { class: "track" }, h("div", { class: "track__range", onMouseDown: () => this.dragStart("minMaxValue"), onTouchStart: (e) => this.dragStart("minMaxValue", e), style: { left, right } }), h("div", { class: "ticks" }, this.tickValues.map((tick) => (h("span", { class: { tick: true, "tick--active": tick >= min && tick <= max }, style: { left: `${this.getUnitInterval(tick) * 100}%` } }, this.renderTickLabel(tick)))))), !this.precise && !this.labelHandles && this.isRange && minHandle, !this.hasHistogram && !this.precise && this.labelHandles && this.isRange && minLabeledHandle, this.precise && !this.labelHandles && this.isRange && minPreciseHandle, this.precise && this.labelHandles && this.isRange && minLabeledPreciseHandle, this.hasHistogram && !this.precise && this.labelHandles && this.isRange && minHistogramLabeledHandle, !this.precise && !this.labelHandles && handle, !this.hasHistogram && !this.precise && this.labelHandles && labeledHandle, !this.hasHistogram && this.precise && !this.labelHandles && preciseHandle, this.hasHistogram && this.precise && !this.labelHandles && histogramPreciseHandle, !this.hasHistogram && this.precise && this.labelHandles && labeledPreciseHandle, this.hasHistogram && !this.precise && this.labelHandles && histogramLabeledHandle, this.hasHistogram && this.precise && this.labelHandles && histogramLabeledPreciseHandle)); } renderGraph() { return this.histogram ? (h("div", { class: "graph" }, h("calcite-graph", { data: this.histogram, height: 48, highlightMax: this.isRange ? this.maxValue : this.value, highlightMin: this.isRange ? this.minValue : this.min, width: 300 }))) : null; } renderTickLabel(tick) { const isMinTickLabel = tick === this.min; const isMaxTickLabel = tick === this.max; const tickLabel = (h("span", { class: { tick__label: true, "tick__label--min": isMinTickLabel, "tick__label--max": isMaxTickLabel } }, tick.toLocaleString())); if (this.labelTicks && !this.hasHistogram && !this.isRange) { return tickLabel; } if (this.labelTicks && !this.hasHistogram && this.isRange && !this.precise && !this.labelHandles) { return tickLabel; } if (this.labelTicks && !this.hasHistogram && this.isRange && !this.precise && this.labelHandles) { return tickLabel; } if (this.labelTicks && !this.hasHistogram && this.isRange && this.precise && (isMinTickLabel || isMaxTickLabel)) { return tickLabel; } if (this.labelTicks && this.hasHistogram && !this.precise && !this.labelHandles) { return tickLabel; } if (this.labelTicks && this.hasHistogram && this.precise && !this.labelHandles && (isMinTickLabel || isMaxTickLabel)) { return tickLabel; } if (this.labelTicks && this.hasHistogram && !this.precise && this.labelHandles && (isMinTickLabel || isMaxTickLabel)) { return tickLabel; } if (this.labelTicks && this.hasHistogram && this.precise && this.labelHandles && (isMinTickLabel || isMaxTickLabel)) { return tickLabel; } return null; } //-------------------------------------------------------------------------- // // Event Listeners // //-------------------------------------------------------------------------- handleLabelFocus(e) { if (e.detail.interactedEl !== this.el && hasLabel(e.detail.labelEl, this.el)) { this.setFocus(); } } keyDownHandler(e) { const value = this[this.activeProp]; switch (getKey(e.key)) { case "ArrowUp": case "ArrowRight": e.preventDefault(); this[this.activeProp] = this.bound(value + this.step, this.activeProp); this.calciteSliderUpdate.emit(); break; case "ArrowDown": case "ArrowLeft": e.preventDefault(); this[this.activeProp] = this.bound(value - this.step, this.activeProp); this.calciteSliderUpdate.emit(); break; case "PageUp": if (this.pageStep) { e.preventDefault(); this[this.activeProp] = this.bound(value + this.pageStep, this.activeProp); this.calciteSliderUpdate.emit(); } break; case "PageDown": if (this.pageStep) { e.preventDefault(); this[this.activeProp] = this.bound(value - this.pageStep, this.activeProp); this.calciteSliderUpdate.emit(); } break; case "Home": e.preventDefault(); this[this.activeProp] = this.bound(this.min, this.activeProp); this.calciteSliderUpdate.emit(); break; case "End": e.preventDefault(); this[this.activeProp] = this.bound(this.max, this.activeProp); this.calciteSliderUpdate.emit(); break; } } clickHandler(e) { const x = e.clientX || e.pageX; const num = this.translate(x); let prop = "value"; if (this.isRange) { if (this.lastDragProp === "minMaxValue") { prop = "minMaxValue"; } else { const closerToMax = Math.abs(this.maxValue - num) < Math.abs(this.minValue - num); prop = closerToMax ? "maxValue" : "minValue"; } } this[prop] = this.bound(num, prop); this.calciteSliderUpdate.emit(); switch (prop) { default: case "maxValue": this.maxHandle.focus(); break; case "minValue": this.minHandle.focus(); break; case "minMaxValue": break; } } //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- async setFocus() { const handle = this.minHandle ? this.minHandle : this.maxHandle; handle.focus(); } //-------------------------------------------------------------------------- // // Private Methods // //-------------------------------------------------------------------------- generateTickValues() { const ticks = []; let current = this.min; while (this.ticks && current < this.max + this.ticks) { ticks.push(current); current = current + this.ticks; } return ticks; } dragStart(prop, e) { if (e) { e.preventDefault(); } if (this.dragListener) { this.dragEnd(); } this.dragProp = prop; this.lastDragProp = this.dragProp; this.activeProp = prop; this.dragListener = this.dragListener || this.dragUpdate.bind(this); document.addEventListener("mousemove", this.dragListener); document.addEventListener("touchmove", this.dragListener, { capture: false }); document.addEventListener("mouseup", this.dragEnd.bind(this)); document.addEventListener("touchend", this.dragEnd.bind(this), false); document.addEventListener("touchcancel", this.dragEnd.bind(this)); } dragUpdate(e) { e.preventDefault(); e.stopPropagation(); if (this.dragProp) { const value = this.translate(e.clientX || e.pageX); if (this.isRange && this.dragProp === "minMaxValue") { if (this.minValueDragRange && this.maxValueDragRange && this.minMaxValueRange) { const newMinValue = value - this.minValueDragRange; const newMaxValue = value + this.maxValueDragRange; if (newMaxValue <= this.max && newMinValue >= this.min && newMaxValue - newMinValue === this.minMaxValueRange) { this.minValue = this.bound(newMinValue, "minValue"); this.maxValue = this.bound(newMaxValue, "maxValue"); } } else { this.minValueDragRange = value - this.minValue; this.maxValueDragRange = this.maxValue - value; this.minMaxValueRange = this.maxValue - this.minValue; } } else { this[this.dragProp] = this.bound(value, this.dragProp); } this.calciteSliderUpdate.emit(); } } dragEnd() { this.dragProp = null; document.removeEventListener("mousemove", this.dragListener); document.removeEventListener("touchmove", this.dragListener); this.minValueDragRange = null; this.maxValueDragRange = null; this.minMaxValueRange = null; } /** * If number is outside range, constrain to min or max * @internal */ bound(num, prop) { num = Math.min(num, this.max); num = Math.max(num, this.min); // ensure that maxValue and minValue don't swap positions if (prop === "maxValue") { num = Math.max(num, this.minValue); } if (prop === "minValue") { num = Math.min(num, this.maxValue); } return num; } /** * Translate a pixel position to value along the range * @internal */ translate(x) { const range = this.max - this.min; const { left, width } = this.el.getBoundingClientRect(); const percent = (x - left) / width; let value = this.bound(this.min + range * percent); if (this.snap && this.step) { value = this.getClosestStep(value); } return value; } /** * Get closest allowed value along stepped values * @internal */ getClosestStep(num) { num = this.bound(num); if (this.step) { const step = Math.round(num / this.step) * this.step; num = this.bound(step); } return num; } getFontSizeForElement(element) { return Number(window.getComputedStyle(element).getPropertyValue("font-size").match(/\d+/)[0]); } /** * Get position of value along range as fractional value * @return {number} number in the unit interval [0,1] * @internal */ getUnitInterval(num) { num = this.bound(num); const range = this.max - this.min; return (num - this.min) / range; } adjustHostObscuredHandleLabel(name) { const label = this.el.shadowRoot.querySelector(`.handle__label--${name}`); const labelStatic = this.el.shadowRoot.querySelector(`.handle__label--${name}.static`); const labelTransformed = this.el.shadowRoot.querySelector(`.handle__label--${name}.transformed`); const labelStaticOffset = this.getHostOffset(labelStatic.getBoundingClientRect().left, labelStatic.getBoundingClientRect().right); label.style.transform = `translateX(${labelStaticOffset}px)`; labelTransformed.style.transform = `translateX(${labelStaticOffset}px)`; } hyphenateCollidingRangeHandleLabels() { const minValueLabel = this.el.shadowRoot.querySelector(`.handle__label--minValue`); const minValueLabelStatic = this.el.shadowRoot.querySelector(`.handle__label--minValue.static`); const minValueLabelTransformed = this.el.shadowRoot.querySelector(`.handle__label--minValue.transformed`); const minValueLabelStaticHostOffset = this.getHostOffset(minValueLabelStatic.getBoundingClientRect().left, minValueLabelStatic.getBoundingClientRect().right); const valueLabel = this.el.shadowRoot.querySelector(`.handle__label--value`); const valueLabelStatic = this.el.shadowRoot.querySelector(`.handle__label--value.static`); const valueLabelTransformed = this.el.shadowRoot.querySelector(`.handle__label--value.transformed`); const valueLabelStaticHostOffset = this.getHostOffset(valueLabelStatic.getBoundingClientRect().left, valueLabelStatic.getBoundingClientRect().right); const labelFontSize = this.getFontSizeForElement(minValueLabel); const labelTransformedOverlap = this.getRangeLabelOverlap(minValueLabelTransformed, valueLabelTransformed); if (labelTransformedOverlap > 0) { minValueLabel.classList.add("hyphen"); if (valueLabelStaticHostOffset === 0 && minValueLabelStaticHostOffset === 0) { // Neither handle overlaps the host boundary let minValueLabelTranslate = labelTransformedOverlap / 2 - labelFontSize / 2; if (Math.sign(minValueLabelTranslate) === -1) { minValueLabelTranslate = Math.abs(minValueLabelTranslate); } else { minValueLabelTranslate = -minValueLabelTranslate; } const minValueLabelTransformedHostOffset = this.getHostOffset(minValueLabelTransformed.getBoundingClientRect().left + minValueLabelTranslate - labelFontSize / 2, minValueLabelTransformed.getBoundingClientRect().right + minValueLabelTranslate - labelFontSize / 2); let valueLabelTranslate = labelTransformedOverlap / 2; const valueLabelTransformedHostOffset = this.getHostOffset(valueLabelTransformed.getBoundingClientRect().left + valueLabelTranslate, valueLabelTransformed.getBoundingClientRect().right + valueLabelTranslate); if (minValueLabelTransformedHostOffset !== 0) { minValueLabelTranslate = minValueLabelTranslate + minValueLabelTransformedHostOffset; valueLabelTranslate = valueLabelTranslate + minValueLabelTransformedHostOffset; } if (valueLabelTransformedHostOffset !== 0) { minValueLabelTranslate = minValueLabelTranslate + valueLabelTransformedHostOffset; valueLabelTranslate = valueLabelTranslate + valueLabelTransformedHostOffset; } minValueLabel.style.transform = `translateX(${minValueLabelTranslate}px)`; minValueLabelTransformed.style.transform = `translateX(${minValueLabelTranslate - labelFontSize / 2}px)`; valueLabel.style.transform = `translateX(${valueLabelTranslate}px)`; valueLabelTransformed.style.transform = `translateX(${valueLabelTranslate}px)`; } else if (minValueLabelStaticHostOffset !== 0 && (Math.sign(valueLabelStaticHostOffset) === 0 || Math.sign(valueLabelStaticHostOffset) === 1)) { // minValueLabel overlaps host boundary on the left side minValueLabel.style.transform = `translateX(${minValueLabelStaticHostOffset + labelFontSize / 2}px)`; valueLabel.style.transform = `translateX(${labelTransformedOverlap + valueLabelStaticHostOffset}px)`; valueLabelTransformed.style.transform = `translateX(${labelTransformedOverlap + valueLabelStaticHostOffset}px)`; } else if (valueLabelStaticHostOffset !== 0) { // valueLabel overlaps host boundary on the right side let minValueLabelTranslate = Math.abs(minValueLabelStaticHostOffset) + labelTransformedOverlap - labelFontSize / 2; if (Math.sign(minValueLabelTranslate) === -1) { minValueLabelTranslate = Math.abs(minValueLabelTranslate); } else { minValueLabelTranslate = -minValueLabelTranslate; } minValueLabel.style.transform = `translateX(${minValueLabelTranslate}px)`; minValueLabelTransformed.style.transform = `translateX(${minValueLabelTranslate - labelFontSize / 2}px)`; } } else { minValueLabel.classList.remove("hyphen"); minValueLabel.style.transform = `translateX(${minValueLabelStaticHostOffset}px)`; minValueLabelTransformed.style.transform = `translateX(${minValueLabelStaticHostOffset}px)`; valueLabel.style.transform = `translateX(${valueLabelStaticHostOffset}px)`; valueLabelTransformed.style.transform = `translateX(${valueLabelStaticHostOffset}px)`; } } /** * Hides bounding tick labels that are obscured by either handle. */ hideObscuredBoundingTickLabels() { if (!this.hasHistogram && !this.isRange && !this.labelHandles && !this.precise) { return; } if (!this.hasHistogram && !this.isRange && this.labelHandles && !this.precise) { return; } if (!this.hasHistogram && !this.isRange && !this.labelHandles && this.precise) { return; } if (!this.hasHistogram && !this.isRange && this.labelHandles && this.precise) { return; } if (!this.hasHistogram && this.isRange && !this.precise) { return; } if (this.hasHistogram && !this.precise && !this.labelHandles) { return; } const minHandle = this.el.shadowRoot.querySelector(".thumb--minValue"); const maxHandle = this.el.shadowRoot.querySelector(".thumb--value"); const minTickLabel = this.el.shadowRoot.querySelector(".tick__label--min"); const maxTickLabel = this.el.shadowRoot.querySelector(".tick__label--max"); if (!minHandle && maxHandle && minTickLabel && maxTickLabel) { if (this.isMinTickLabelObscured(minTickLabel, maxHandle)) { minTickLabel.style.opacity = "0"; } else { minTickLabel.style.opacity = "1"; } if (this.isMaxTickLabelObscured(maxTickLabel, maxHandle)) { maxTickLabel.style.opacity = "0"; } else { maxTickLabel.style.opacity = "1"; } } if (minHandle && maxHandle && minTickLabel && maxTickLabel) { if (this.isMinTickLabelObscured(minTickLabel, minHandle) || this.isMinTickLabelObscured(minTickLabel, maxHandle)) { minTickLabel.style.opacity = "0"; } else { minTickLabel.style.opacity = "1"; } if (this.isMaxTickLabelObscured(maxTickLabel, minHandle) || (this.isMaxTickLabelObscured(maxTickLabel, maxHandle) && this.hasHistogram)) { maxTickLabel.style.opacity = "0"; } else { maxTickLabel.style.opacity = "1"; } } } /** * Returns an integer representing the number of pixels to offset on the left or right side based on desired position behavior. * @internal */ getHostOffset(leftBounds, rightBounds) { const hostBounds = this.el.getBoundingClientRect(); if (leftBounds + 7 < hostBounds.left) { const offset = hostBounds.left - leftBounds - 7; return offset; } if (rightBounds - 7 > hostBounds.right) { const offset = -(rightBounds - hostBounds.right) + 7; return offset; } return 0; } /** * Returns an integer representing the number of pixels that the two given span elements are overlapping, taking into account * a space in between the two spans equal to the font-size set on them to account for the space needed to render a hyphen. * @param minValueLabel * @param valueLabel */ getRangeLabelOverlap(minValueLabel, valueLabel) { const minValueLabelBounds = minValueLabel.getBoundingClientRect(); const valueLabelBounds = valueLabel.getBoundingClientRect(); const minValueLabelFontSize = this.getFontSizeForElement(minValueLabel); const rangeLabelOverlap = minValueLabelBounds.right + minValueLabelFontSize - valueLabelBounds.left; return rangeLabelOverlap > 0 ? rangeLabelOverlap : 0; } /** * Returns a boolean value representing if the minLabel span element is obscured (being overlapped) by the given handle button element. * @param minLabel * @param handle */ isMinTickLabelObscured(minLabel, handle) { const minLabelBounds = minLabel.getBoundingClientRect(); const handleBounds = handle.getBoundingClientRect(); if (handleBounds.left < minLabelBounds.right) { return true; } return false; } /** * Returns a boolean value representing if the maxLabel span element is obscured (being overlapped) by the given handle button element. * @param maxLabel * @param handle */ isMaxTickLabelObscured(maxLabel, handle) { const maxLabelBounds = maxLabel.getBoundingClientRect(); const handleBounds = handle.getBoundingClientRect(); if (handleBounds.right > maxLabelBounds.left) { return true; } return false; } static get is() { return "calcite-slider"; } static get encapsulation() { return "shadow"; } static get originalStyleUrls() { return { "$": ["calcite-slider.scss"] }; } static get styleUrls() { return { "$": ["calcite-slider.css"] }; } static get properties() { return { "theme": { "type": "string", "mutable": false, "complexType": { "original": "\"light\" | \"dark\"", "resolved": "\"dark\" | \"light\"", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Select theme (light or dark)" }, "attribute": "theme", "reflect": true }, "disabled": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Disable and gray out the slider" }, "attribute": "disabled", "reflect": true, "defaultValue": "false" }, "min": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Minimum selectable value" }, "attribute": "min", "reflect": true, "defaultValue": "0" }, "max": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Maximum selectable value" }, "attribute": "max", "reflect": true, "defaultValue": "100" }, "value": { "type": "number", "mutable": true, "complexType": { "original": "null | number", "resolved": "number", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Currently selected number (if single select)" }, "attribute": "value", "reflect": true, "defaultValue": "null" }, "minValue": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Currently selected lower number (if multi-select)" }, "attribute": "min-value", "reflect": false }, "maxValue": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Currently selected upper number (if multi-select)" }, "attribute": "max-value", "reflect": false }, "minLabel": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Label for first (or only) handle (ex. \"Temperature, lower bound\")" }, "attribute": "min-label", "reflect": false }, "maxLabel": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Label for second handle if needed (ex. \"Temperature, upper bound\")" }, "attribute": "max-label", "reflect": false }, "snap": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Snap selection along the step interval" }, "attribute": "snap", "reflect": false, "defaultValue": "true" }, "step": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Interval to move on up/down keys" }, "attribute": "step", "reflect": false, "defaultValue": "1" }, "pageStep": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Interval to move on page up/page down keys" }, "attribute": "page-step", "reflect": false }, "ticks": { "type": "number", "mutable": false, "complexType": { "original": "number", "resolved": "number", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Show tick marks on the number line at provided interval" }, "attribute": "ticks", "reflect": false }, "labelTicks": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Label tick marks with their numeric value." }, "attribute": "label-ticks", "reflect": true }, "labelHandles": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Label handles with their numeric value" }, "attribute": "label-handles", "reflect": true }, "precise": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Use finer point for handles" }, "attribute": "precise", "reflect": false }, "histogram": { "type": "unknown", "mutable": false, "complexType": { "original": "DataSeries", "resolved": "Point[]", "references": { "DataSeries": { "location": "import", "path": "../../interfaces/Graph" } } }, "required": false, "optional": true, "docs": { "tags": [], "text": "Display a histogram above the slider" } }, "hasHistogram": { "type": "boolean", "mutable": true, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Indicates if a histogram is present" }, "attribute": "has-histogram", "reflect": true, "defaultValue": "false" } }; } static get states() { return { "tickValues": {}, "activeProp": {}, "minMaxValueRange": {}, "minValueDragRange": {}, "maxValueDragRange": {} }; } static get events() { return [{ "method": "calciteSliderUpdate", "name": "calciteSliderUpdate", "bubbles": true, "cancelable": true, "composed": true, "docs": { "tags": [], "text": "Fires on all updates to the slider.\n:warning: Will be fired frequently during drag. If you are performing any\nexpensive operations consider using a debounce or throttle to avoid\nlocking up the main thread." }, "complexType": { "original": "any", "resolved": "any", "references": {} } }]; } static get methods() { return { "setFocus": { "complexType": { "signature": "() => Promise<void>", "parameters": [], "references": { "Promise": { "location": "global" } }, "return": "Promise<void>" }, "docs": { "text": "", "tags": [] } } }; } static get elementRef() { return "el"; } static get watchers() { return [{ "propName": "histogram", "methodName": "histogramWatcher" }]; } static get listeners() { return [{ "name": "calciteLabelFocus", "method": "handleLabelFocus", "target": "window", "capture": false, "passive": false }, { "name": "keydown", "method": "keyDownHandler", "target": undefined, "capture": false, "passive": false }, { "name": "click", "method": "clickHandler", "target": undefined, "capture": false, "passive": false }]; } }
jurgendl/jhaws
jhaws/swing/src/main/java/org/swingeasy/RowNumberList.java
package org.swingeasy; import java.awt.Component; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JViewport; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListDataListener; public class RowNumberList extends JList<Object> implements ChangeListener, PropertyChangeListener { public class RowNumberListModel implements ListModel<Object> { protected final ListModel<?> parentModel; public RowNumberListModel(ListModel<?> parentModel) { this.parentModel = parentModel; } @Override public void addListDataListener(ListDataListener l) { parentModel.addListDataListener(l); } @Override public Object getElementAt(int index) { return String.valueOf(index + 1); } @Override public int getSize() { return parentModel.getSize(); } @Override public void removeListDataListener(ListDataListener l) { parentModel.removeListDataListener(l); } } private static final long serialVersionUID = 1043313908886653227L; protected JList<?> main; public RowNumberList(JList<?> list) { this(list, 4); } protected RowNumberList(JList<?> list, double cw) { main = list; main.addPropertyChangeListener(this); setFocusable(false); setModel(new RowNumberListModel(main.getModel())); setSelectionModel(main.getSelectionModel()); @SuppressWarnings("unchecked") ListCellRenderer<Object> renderer = ListCellRenderer.class.cast(list.getCellRenderer()); if (renderer instanceof JLabel) { JLabel labelRenderer = JLabel.class.cast(renderer); labelRenderer.setHorizontalAlignment(SwingConstants.RIGHT); } setCellRenderer(renderer); setFixedCellWidth((int) cw); setFixedCellHeight(list.getFixedCellHeight()); } public RowNumberList(JList<?> list, int chars) { this(list, new JTextField(chars).getPreferredSize().getWidth()); } @Override public void addNotify() { super.addNotify(); Component c = getParent(); if (c instanceof JViewport) { JViewport viewport = (JViewport) c; viewport.addChangeListener(this); } } @Override public void propertyChange(PropertyChangeEvent e) { if ("selectionModel".equals(e.getPropertyName())) { setSelectionModel(main.getSelectionModel()); } if ("model".equals(e.getPropertyName())) { setModel(new RowNumberListModel(main.getModel())); } } @Override public void stateChanged(ChangeEvent e) { JViewport viewport = (JViewport) e.getSource(); JScrollPane scrollPane = (JScrollPane) viewport.getParent(); scrollPane.getVerticalScrollBar().setValue(viewport.getViewPosition().y); } }
ryokbys/nap
nappy/fitpot/cs.py
<reponame>ryokbys/nap #!/usr/bin/env python """ Cuckoo search. Usage: cs.py [options] Options: -h, --help Show this message and exit. -n N Number of generations in CS. [default: 20] --print-level LEVEL Print verbose level. [default: 1] """ from __future__ import print_function import os import sys from docopt import docopt import numpy as np from numpy import exp, sin, cos import random import copy from multiprocessing import Process, Pool from time import time from scipy.special import gamma __author__ = "<NAME>" __version__ = "190920" _fname_gen = 'out.cs.generations' _fname_ind = 'out.cs.individuals' def test_func(var, vranges, **kwargs): x,y= var res= x**2 +y**2 +100.0*exp(-x**2 -y**2)*sin(2.0*(x+y))*cos(2*(x-y)) \ +80.0*exp(-(x-1)**2 -(y-1)**2)*cos(x+4*y)*sin(2*x-y) \ +200.0*sin(x+y)*exp(-(x-3)**2-(y-1)**2) return res def test_write_func(vs,vrs,fname,**kwargs): with open(fname,'w') as f: for i,v in enumerate(vs): vr = vrs[i] f.write(' {0:10.3f} {1:10.3f} {2:10.3f}\n'.format(v,*vr)) return None def wrap(vs,vrs): vsnew = copy.copy(vs) for i,v in enumerate(vsnew): vmin, vmax = vrs[i] vsnew[i] = min(max(v,vmin),vmax) return vsnew def update_vrange(vrs,vrsh,all_indivisuals): """ Update variable ranges adaptively using all the individuals information. """ #...Extract top NTOPS individuals from all ntops = 100 tops = [] # print('len(all_indivisuals)=',len(all_indivisuals)) for i,ind in enumerate(all_indivisuals): if len(tops) < ntops: # add the individual # print(' i (< ntops)=',i) for it,t in enumerate(tops): if ind.val < t.val: tops.insert(it,ind) break if not ind in tops: tops.append(ind) else: # insert the individual and pop out the worst one # print(' i (>=ntops)=',i) for it,t in enumerate(tops): if ind.val < t.val: tops.insert(it,ind) break if len(tops) > ntops: del tops[ntops:len(tops)] # print('len(tops)=',len(tops)) # print('iids= ',[t.iid for t in tops]) #...Get new ranges new_vrs = np.array(vrs) vss = np.zeros((len(tops),len(vrs))) for i,ind in enumerate(tops): vi = ind.vector vss[i,:] = vi[:] # print('i,vi=',i,vi) for j in range(len(new_vrs)): # print('j,min,max=',i,min(vss[:,j]),max(vss[:,j])) new_vrs[j,0] = max(new_vrs[j,0],min(vss[:,j])) new_vrs[j,1] = min(new_vrs[j,1],max(vss[:,j])) #...Set best variables center in the ranges fbest = tops[0].val vbest = tops[0].vector for j in range(len(vbest)): vjmin = new_vrs[j,0] vjmax = new_vrs[j,1] wmax = max(abs(vjmin-vbest[j]),abs(vjmax-vbest[j])) new_vrs[j,0] = max(min(vjmin,vbest[j]-wmax),vrsh[j,0]) new_vrs[j,1] = min(max(vjmax,vbest[j]+wmax),vrsh[j,1]) return new_vrs class Individual: """ Individual class that consists of variables as vector elements. """ def __init__(self, iid, ndim, vranges, loss_func): self.iid = iid self.ndim = ndim self.loss_func = loss_func self.vector = np.zeros(self.ndim) self.vranges = vranges self.val = None def set_variable(self,variables): if len(variables) != len(self.vector): raise ValueError() self.vector = variables # print('iid, v before wrap,vrs =',self.iid,self.vector,self.vranges) self.wrap_range() # print('iid, v after wrap,vrs =',self.iid,self.vector,self.vranges) self.val = None return None def init_random(self): for i in range(self.ndim): vmin, vmax = self.vranges[i] # vmin = self.vranges[i,0] # vmax = self.vranges[i,1] v = random.random()*(vmax -vmin) +vmin self.vector[i] = v # print(' i,vmin,vmax,v=',i,vmin,vmax,v) self.wrap_range() self.val = None return None def wrap_range(self): self.vector = wrap(self.vector, self.vranges) def calc_loss_func(self,kwargs): """ Compute loss function value using self.loss_func function given in the constructor. In order to return a result in multiprocessing.Process, it also takes an argument q. """ # print('type(kwargs)=',type(kwargs)) val = self.loss_func(self.vector, self.vranges, **kwargs) # print(' iid,v,val=',self.iid,self.vector,val) # q.put(val) return val,kwargs['index'] class CS: """ Cuckoo search class. """ def __init__(self, N, F, variables, vranges, vhardlimit, loss_func, write_func, nproc=0,**kwargs): """ Conctructor of CS class. N: Number of individuals. F: Fraction of worse individuals to be abondoned. loss_func: Loss function to be minimized with variables and **kwargs. nproc: Number of processes used to run N individuals. """ if N < 2: raise ValueError('N must be greater than 1 in CS!') self.N = N # Number of individuals in a generation self.F = F # Fraction of worse individuals to be abondoned self.nproc = nproc self.ndim = len(variables) self.vs = variables self.vrs0 = vranges self.vrs = copy.copy(self.vrs0) self.vrsh = vhardlimit self.vws = np.zeros(self.ndim) for i in range(self.ndim): self.vws[i] = max(self.vrs[i,1] -self.vrs[i,0], 0.0) # print('original variables=',self.vs,self.vrs) self.loss_func = loss_func self.write_func = write_func self.kwargs = kwargs self.bestind = None self.print_level = 0 if 'print_level' in kwargs.keys(): self.print_level = int(kwargs['print_level']) if 'update_vrange' in kwargs.keys(): self.update_vrs_per = kwargs['update_vrange'] self.beta = 1.5 self.betai = 1.0 /self.beta self.usgm = (gamma(1+self.beta)*np.sin(np.pi*self.beta/2)/ \ gamma((1+self.beta)/2)*self.beta*2.0**((self.beta-1)/2))**self.betai self.vsgm = 1.0 #...initialize population self.population = [] self.all_indivisuals = [] self.iidmax = 0 for i in range(N): self.iidmax += 1 ind = Individual(self.iidmax, self.ndim, self.vrs, self.loss_func) if i == 0: ind.set_variable(self.vs) else: ind.init_random() self.population.append(ind) #...Evaluate loss function values prcs = [] if self.nproc > 0 : # use specified number of cores by nproc pool = Pool(processes=self.nproc) else: pool = Pool() for ip,pi in enumerate(self.population): kwtmp = copy.copy(self.kwargs) kwtmp['index'] = ip kwtmp['iid'] = pi.iid #prcs.append(pool.apply_async(pi.calc_loss_func, (kwtmp,qs[ip]))) prcs.append(pool.apply_async(pi.calc_loss_func, (kwtmp,))) results = [ res.get() for res in prcs ] for res in results: val,ip = res self.population[ip].val = val pool.close() self.keep_best() self.all_indivisuals.extend(self.population) if self.print_level > 2: for pi in self.population: fname = 'in.vars.fitpot.{0:d}'.format(pi.iid) self.write_variables(pi, fname=fname, **self.kwargs) else: fname = 'in.vars.fitpot.{0:d}'.format(self.bestind.iid) self.write_variables(self.bestind, fname=fname, **self.kwargs) return None def keep_best(self): vals = [] for i,pi in enumerate(self.population): # print('i,val,vec=',i,pi.val,pi.vector) if pi.val == None: raise ValueError('Something went wrong.') vals.append(pi.val) minval = min(vals) if self.bestind == None or minval < self.bestind.val: idx = vals.index(minval) self.bestind = copy.deepcopy(self.population[idx]) return None def sort_individuals(self): """ Sort individuals in the population in the ascending order. """ jtop = self.N for i in range(self.N): jtop -= 1 for j in range(jtop): pj = self.population[j] pjp = self.population[j+1] if pj.val > pjp.val: self.population[j] = pjp self.population[j+1] = pj return None def run(self,maxiter=100): """ Perfom CS. """ if 'start' in self.kwargs.keys(): start = self.kwargs['start'] else: start = time() fgen = open(_fname_gen,'w') find = open(_fname_ind,'w') for i,ind in enumerate(self.population): fgen.write(' 0 {0:8d} {1:12.4e}\n'.format(ind.iid, ind.val)) find.write(' {0:8d} {1:12.4e}'.format(ind.iid, ind.val)) for j,vj in enumerate(ind.vector): find.write(' {0:11.3e}'.format(vj)) find.write('\n') if self.print_level > 0: print(' step,time,best,vars= {0:6d} {1:8.1f} {2:8.4f}'.format(0, time()-start, self.bestind.val),end="") for i in range(min(16,self.ndim)): print(' {0:6.3f}'.format(self.bestind.vector[i]),end="") print('', flush=True) #...Create pool before going into maxiter-loop, #...since creating pool inside could cause "Too many files" error. if self.nproc > 0 : # use specified number of cores by nproc pool = Pool(processes=self.nproc) else: pool = Pool() for it in range(maxiter): self.sort_individuals() #...Create candidates from current population using Levy flight candidates = [] vbest = self.bestind.vector for ip,pi in enumerate(self.population): vi = pi.vector vnew =np.array(vi) for iv in range(self.ndim): u = np.random.normal()*self.usgm v = abs(np.random.normal()*self.vsgm) v = max(v,1.0e-8) w = u/v**self.betai zeta = self.vws[iv] *0.01 *w # zeta = self.vws[iv]*0.01 *w *(vi[iv] -vbest[iv]) # if ip == 0: # zeta = self.vws[iv] *0.001 *w # else: # zeta = 0.01 *w *(vi[iv] -vbest[iv]) vnew[iv] = vnew[iv] +zeta*np.random.normal() #...create new individual for trial # print('ip,vi,vnew=',ip,vi,vnew) self.iidmax += 1 newind = Individual(self.iidmax, self.ndim, self.vrs, self.loss_func) newind.set_variable(vnew) candidates.append(newind) #...Create new completely random candidates iab = int((1.0 -self.F)*self.N) rnd_candidates = [] for iv in range(iab,self.N): self.iidmax += 1 newind = Individual(self.iidmax, self.ndim, self.vrs, self.loss_func) newind.init_random() rnd_candidates.append(newind) #...Evaluate loss function values of updated candidates and new random ones prcs = [] for ic,ci in enumerate(candidates): kwtmp = copy.copy(self.kwargs) kwtmp['index'] = ic kwtmp['iid'] = ci.iid # prcs.append(Process(target=ci.calc_loss_func, args=(kwtmp,qs[ic]))) prcs.append(pool.apply_async(ci.calc_loss_func, (kwtmp,))) rnd_prcs = [] for ic,ci in enumerate(rnd_candidates): kwtmp = copy.copy(self.kwargs) kwtmp['index'] = len(candidates) +ic kwtmp['iid'] = ci.iid # prcs.append(Process(target=ci.calc_loss_func, args=(kwtmp,qs[ic]))) rnd_prcs.append(pool.apply_async(ci.calc_loss_func, (kwtmp,))) results = [ res.get() for res in prcs ] rnd_results = [ res.get() for res in rnd_prcs ] for res in results: val,ic = res candidates[ic].val = val self.all_indivisuals.extend(candidates) for res in rnd_results: val,ic_rnd = res ic = ic_rnd -len(candidates) rnd_candidates[ic].val = val self.all_indivisuals.extend(rnd_candidates) #...Pick j that is to be compared with i js = random.sample(range(self.N),k=self.N) #...Decide whether or not to adopt new one for jc,jv in enumerate(js): pj = self.population[jv] cj = candidates[jc] dval = cj.val -pj.val if dval < 0.0: # replace with new individual self.population[jv] = cj find.write(' {0:8d} {1:12.4e}'.format(cj.iid, cj.val)) for k,vk in enumerate(cj.vector): find.write(' {0:11.3e}'.format(vk)) find.write('\n') find.flush() else: pass #...Rank individuals self.sort_individuals() #...Replace to-be-abandoned ones with new random ones ic = 0 for iv in range(iab,self.N): ci = rnd_candidates[ic] ic += 1 self.population[iv] = ci #...Check best best_updated = False for ic,ci in enumerate(self.population): if ci.val < self.bestind.val: self.bestind = ci best_updated = True if best_updated: fname = 'in.vars.fitpot.{0:d}'.format(self.bestind.iid) self.write_variables(self.bestind, fname=fname, **self.kwargs) os.system('cp -f {0:s} in.vars.fitpot.best'.format(fname)) #...Update variable ranges if needed if self.update_vrs_per > 0 and (it+1) % self.update_vrs_per == 0: self.vrs = update_vrange(self.vrs,self.vrsh,self.all_indivisuals) print(' Update variable ranges') for i in range(len(self.vrs)): print(' {0:2d}: {1:7.3f} {2:7.3f}'.format(i+1,self.vrs[i,0],self.vrs[i,1])) #...Set variable ranges of all individuals in the population for iv in range(len(self.population)): self.population[iv].vranges = self.vrs if self.print_level > 0: print(' step,time,best,vars= {0:6d} {1:8.1f} {2:8.4f}'.format(it+1, time()-start, self.bestind.val),end="") for i in range(min(16,self.ndim)): print(' {0:6.3f}'.format(self.bestind.vector[i]),end="") print('', flush=True) for i,ind in enumerate(self.population): fgen.write(' {0:5d} {1:8d} {2:12.4e}\n'.format(it+1, ind.iid, ind.val)) fgen.flush() fgen.close() find.close() pool.close() #...Finaly write out the best one self.write_variables(self.bestind,fname='in.vars.fitpot.best',**self.kwargs) return None def write_variables(self,ind,fname='in.vars.fitpot',**kwargs): vs = ind.vector vrs = ind.vranges self.write_func(vs,vrs,fname,**kwargs) return None if __name__ == "__main__": args = docopt(__doc__) n = int(args['-n']) kwargs = {} kwargs['print_level'] = int(args['--print-level']) vs = np.array([1.0, -0.5]) vrs = np.array([[-1.0, 2.0],[-1.0, 1.0]]) cs = CS(10, 0.25, vs, vrs, test_func, test_write_func, **kwargs) cs.run(n)
hpi-swt2/contacts-portal
db/migrate/20210122155255_add_jitsi_calls.rb
<reponame>hpi-swt2/contacts-portal class AddJitsiCalls < ActiveRecord::Migration[6.0] def change create_table :jitsi_calls do |t| t.string :room_name t.timestamps end create_join_table :users, :jitsi_calls, table_name: :call_participants do |t| t.string :role t.string :state t.timestamps end end end
HubSpot/Baragon
BaragonCore/src/main/java/com/hubspot/baragon/models/BaragonGroup.java
package com.hubspot.baragon.models; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; @JsonIgnoreProperties(ignoreUnknown = true) public class BaragonGroup { private final String name; @Deprecated private Optional<String> domain; private Set<TrafficSource> trafficSources; @Deprecated private Set<String> sources; private Optional<String> defaultDomain; private Set<String> domains; private Map<String, Set<String>> domainAliases; private Integer minHealthyAgents; @JsonCreator public BaragonGroup( @JsonProperty("name") String name, @JsonProperty("domain") Optional<String> domain, @JsonProperty("trafficSources") Set<TrafficSource> trafficSources, @JsonProperty("sources") Set<String> sources, @JsonProperty("defaultDomain") Optional<String> defaultDomain, @JsonProperty("domains") Set<String> domains, @JsonProperty("domainAliases") Map<String, Set<String>> domainAliases, @JsonProperty(value = "minHealthyAgents", defaultValue = "1") Integer minHealthyAgents ) { this.name = name; this.domain = domain; this.defaultDomain = defaultDomain; this.domains = MoreObjects.firstNonNull(domains, Collections.emptySet()); this.domainAliases = MoreObjects.firstNonNull(domainAliases, Collections.emptyMap()); this.sources = Collections.emptySet(); this.minHealthyAgents = minHealthyAgents; if (trafficSources == null && sources != null) { this.trafficSources = sources .stream() .map( source -> new TrafficSource(source, TrafficSourceType.CLASSIC, RegisterBy.INSTANCE_ID) ) .collect(Collectors.toSet()); } else { this.trafficSources = trafficSources != null ? trafficSources : Collections.emptySet(); } } public String getName() { return name; } @Deprecated public Optional<String> getDomain() { return getDefaultDomain(); } @Deprecated public void setDomain(Optional<String> domain) { this.domain = domain; } @Deprecated public Set<String> getSources() { return Collections.emptySet(); } @Deprecated public void setSources(Set<String> sources) {} public Set<TrafficSource> getTrafficSources() { return trafficSources; } public void setTrafficSources(Set<TrafficSource> sources) { this.trafficSources = sources; } public void removeTrafficSource(TrafficSource trafficSource) { this.trafficSources.remove(trafficSource); } public void addTrafficSource(TrafficSource trafficSource) { this.trafficSources.add(trafficSource); } public Optional<String> getDefaultDomain() { return defaultDomain.or(domain); } public void setDefaultDomain(Optional<String> defaultDomain) { this.defaultDomain = defaultDomain; } public Set<String> getDomains() { return domains; } public void setDomains(Set<String> domains) { this.domains = domains; } public Map<String, Set<String>> getDomainAliases() { return domainAliases; } public void setDomainAliases(Map<String, Set<String>> domainAliases) { this.domainAliases = domainAliases; } public void setMinHealthyAgents(Integer minHealthyAgents) { this.minHealthyAgents = minHealthyAgents; } public Integer getMinHealthyAgents() { return this.minHealthyAgents == null ? Integer.valueOf(1) : this.minHealthyAgents; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BaragonGroup that = (BaragonGroup) o; return ( Objects.equals(name, that.name) && Objects.equals(domain, that.domain) && Objects.equals(trafficSources, that.trafficSources) && Objects.equals(sources, that.sources) && Objects.equals(defaultDomain, that.defaultDomain) && Objects.equals(domains, that.domains) && Objects.equals(minHealthyAgents, that.minHealthyAgents) && Objects.equals(domainAliases, that.domainAliases) ); } @Override public int hashCode() { return Objects.hash( name, domain, trafficSources, sources, defaultDomain, domains, domainAliases, minHealthyAgents ); } @Override public String toString() { return ( "BaragonGroup{" + "name='" + name + '\'' + ", domain=" + domain + ", trafficSources=" + trafficSources + ", sources=" + sources + ", defaultDomain=" + defaultDomain + ", domains=" + domains + ", domainAliases=" + domainAliases + ", minHealthyAgents=" + getMinHealthyAgents() + '}' ); } }
embeddedlabsiu/snn_exploration_spinnaker
scripts/ann_architectures/BinaryConnect/binarynet_noBN.py
# coding=utf-8 """ This python script trains a ConvNet on CIFAR-10 with BinaryNet. It should run for about 15 hours on a GeForce GTX 980 Ti GPU. The final test error should be around 11.40%. Source: https://github.com/MatthieuCourbariaux/BinaryNet """ from __future__ import print_function import lasagne # specifying the gpu to use import theano.sandbox.cuda from scripts.ann_architectures.BinaryConnect import binary_net theano.sandbox.cuda.use('gpu0') def build_network(): """Build network. Returns ------- """ import theano import theano.tensor as t from collections import OrderedDict # BinaryOut activation = binary_net.binary_tanh_unit print("activation = binary_net.binary_tanh_unit") # activation = binary_net.binary_sigmoid_unit # print("activation = binary_net.binary_sigmoid_unit") # BinaryConnect binary = True print("binary = " + str(binary)) stochastic = False print("stochastic = " + str(stochastic)) # (-h,+h) are the two binary values # h = "Glorot" h = 1. print("h = " + str(h)) # w_lr_scale = 1. # "Glorot" means we are using the coefficients from Glorot's paper w_lr_scale = "Glorot" print("w_lr_scale = " + str(w_lr_scale)) # Prepare Theano variables for inputs and targets input_var = t.tensor4('inputs') target = t.matrix('targets') lr = t.scalar('lr', dtype=theano.config.floatX) cnn = lasagne.layers.InputLayer(shape=(None, 3, 32, 32), input_var=input_var) # 128C3-128C3-P2 cnn = binary_net.Conv2DLayer( cnn, # b=None, binary=binary, stochastic=stochastic, H=h, W_LR_scale=w_lr_scale, num_filters=128, filter_size=(3, 3), pad=1, nonlinearity=lasagne.nonlinearities.identity) cnn = lasagne.layers.NonlinearityLayer( cnn, nonlinearity=activation) cnn = binary_net.Conv2DLayer( cnn, # b=None, binary=binary, stochastic=stochastic, H=h, W_LR_scale=w_lr_scale, num_filters=128, filter_size=(3, 3), pad=1, nonlinearity=lasagne.nonlinearities.identity) cnn = lasagne.layers.MaxPool2DLayer(cnn, pool_size=(2, 2)) cnn = lasagne.layers.NonlinearityLayer( cnn, nonlinearity=activation) # 256C3-256C3-P2 cnn = binary_net.Conv2DLayer( cnn, # b=None, binary=binary, stochastic=stochastic, H=h, W_LR_scale=w_lr_scale, num_filters=256, filter_size=(3, 3), pad=1, nonlinearity=lasagne.nonlinearities.identity) cnn = lasagne.layers.NonlinearityLayer( cnn, nonlinearity=activation) cnn = binary_net.Conv2DLayer( cnn, # b=None, binary=binary, stochastic=stochastic, H=h, W_LR_scale=w_lr_scale, num_filters=256, filter_size=(3, 3), pad=1, nonlinearity=lasagne.nonlinearities.identity) cnn = lasagne.layers.MaxPool2DLayer(cnn, pool_size=(2, 2)) cnn = lasagne.layers.NonlinearityLayer( cnn, nonlinearity=activation) # 512C3-512C3-P2 cnn = binary_net.Conv2DLayer( cnn, # b=None, binary=binary, stochastic=stochastic, H=h, W_LR_scale=w_lr_scale, num_filters=512, filter_size=(3, 3), pad=1, nonlinearity=lasagne.nonlinearities.identity) cnn = lasagne.layers.NonlinearityLayer( cnn, nonlinearity=activation) cnn = binary_net.Conv2DLayer( cnn, # b=None, binary=binary, stochastic=stochastic, H=h, W_LR_scale=w_lr_scale, num_filters=512, filter_size=(3, 3), pad=1, nonlinearity=lasagne.nonlinearities.identity) cnn = lasagne.layers.MaxPool2DLayer(cnn, pool_size=(2, 2)) cnn = lasagne.layers.NonlinearityLayer( cnn, nonlinearity=activation) # print(model.output_shape) # 1024FP-1024FP-10FP cnn = binary_net.DenseLayer( cnn, # b=None, binary=binary, stochastic=stochastic, H=h, W_LR_scale=w_lr_scale, nonlinearity=lasagne.nonlinearities.identity, num_units=1024) cnn = lasagne.layers.NonlinearityLayer( cnn, nonlinearity=activation) cnn = binary_net.DenseLayer( cnn, # b=None, binary=binary, stochastic=stochastic, H=h, W_LR_scale=w_lr_scale, nonlinearity=lasagne.nonlinearities.identity, num_units=1024) cnn = lasagne.layers.NonlinearityLayer( cnn, nonlinearity=activation) cnn = binary_net.DenseLayer( cnn, # b=None, binary=binary, stochastic=stochastic, H=h, W_LR_scale=w_lr_scale, nonlinearity=lasagne.nonlinearities.identity, num_units=10) train_output = lasagne.layers.get_output(cnn, deterministic=False) # squared hinge loss loss = t.mean(t.sqr(t.maximum(0., 1. - target * train_output))) if binary: from itertools import chain # w updates w = lasagne.layers.get_all_params(cnn, binary=True) w_grads = binary_net.compute_grads(loss, cnn) updates = lasagne.updates.adam(loss_or_grads=w_grads, params=w, learning_rate=lr) updates = binary_net.clipping_scaling(updates, cnn) # other parameters updates params = lasagne.layers.get_all_params(cnn, trainable=True, binary=False) updates = OrderedDict(chain(updates.items(), lasagne.updates.adam( loss_or_grads=loss, params=params, learning_rate=lr).items())) else: params = lasagne.layers.get_all_params(cnn, trainable=True) updates = lasagne.updates.adam(loss_or_grads=loss, params=params, learning_rate=lr) test_output = lasagne.layers.get_output(cnn, deterministic=True) test_loss = t.mean(t.sqr(t.maximum(0., 1. - target * test_output))) test_err = t.mean(t.neq(t.argmax(test_output, axis=1), t.argmax(target, axis=1)), dtype=theano.config.floatX) # Compile a function performing a training step on a mini-batch (by giving # the updates dictionary) and returning the corresponding training loss: train_fn = theano.function([input_var, target, lr], loss, updates=updates) # Compile a second function computing the validation loss and accuracy: val_fn = theano.function([input_var, target], [test_loss, test_err]) return cnn, train_fn, val_fn if __name__ == "__main__": from pylearn2.datasets.cifar10 import CIFAR10 import numpy as np from snntoolbox.datasets.utils import save_parameters np.random.seed(1234) # for reproducibility? # Training parameters batch_size = 50 print("batch_size = " + str(batch_size)) num_epochs = 500 print("num_epochs = " + str(num_epochs)) # Decaying LR LR_start = 0.001 print("LR_start = " + str(LR_start)) LR_fin = 0.0000003 print("LR_fin = " + str(LR_fin)) LR_decay = (LR_fin / LR_start) ** (1. / num_epochs) print("LR_decay = " + str(LR_decay)) # BTW, LR decay might good for the BN moving average... train_set_size = 45000 print("train_set_size = " + str(train_set_size)) shuffle_parts = 1 print("shuffle_parts = " + str(shuffle_parts)) print('Loading CIFAR-10 dataset...') train_set = CIFAR10(which_set="train", start=0, stop=train_set_size) valid_set = CIFAR10(which_set="train", start=train_set_size, stop=50000) test_set = CIFAR10(which_set="test") # bc01 format # Inputs in the range [-1,+1] # print("Inputs in the range [-1,+1]") train_set.X = np.reshape( np.subtract(np.multiply(2. / 255., train_set.X), 1.), (-1, 3, 32, 32)) valid_set.X = np.reshape( np.subtract(np.multiply(2. / 255., valid_set.X), 1.), (-1, 3, 32, 32)) test_set.X = np.reshape( np.subtract(np.multiply(2. / 255., test_set.X), 1.), (-1, 3, 32, 32)) # flatten targets train_set.y = np.hstack(train_set.y) valid_set.y = np.hstack(valid_set.y) test_set.y = np.hstack(test_set.y) # Onehot the targets train_set.y = np.float32(np.eye(10)[train_set.y]) valid_set.y = np.float32(np.eye(10)[valid_set.y]) test_set.y = np.float32(np.eye(10)[test_set.y]) # for hinge loss train_set.y = 2 * train_set.y - 1. valid_set.y = 2 * valid_set.y - 1. test_set.y = 2 * test_set.y - 1. print('Building the CNN...') model, train_func, val_func = build_network() print('Training...') binary_net.train(train_func, val_func, model, batch_size, LR_start, LR_decay, num_epochs, train_set.X, train_set.y, valid_set.X, valid_set.y, test_set.X, test_set.y, shuffle_parts=shuffle_parts) W = lasagne.layers.get_all_layers(model)[1].W.get_value() import matplotlib.pyplot as plt plt.hist(W.flatten()) plt.title("Weight distribution of first hidden convolution layer") # Dump the network weights to a file filepath = '70.14.h5' parameters = lasagne.layers.get_all_param_values(model) save_parameters(parameters, filepath)
XboxBedrock/terraplusplus
src/main/java/io/github/terra121/control/fragments/terra/TerraInvertWaterFragment.java
package io.github.terra121.control.fragments.terra; import io.github.opencubicchunks.cubicchunks.api.worldgen.ICubeGenerator; import io.github.opencubicchunks.cubicchunks.core.server.CubeProviderServer; import io.github.terra121.control.fragments.CommandFragment; import io.github.terra121.dataset.impl.Water; import io.github.terra121.generator.EarthGenerator; import io.github.terra121.projection.GeographicProjection; import io.github.terra121.projection.OutOfProjectionBoundsException; import io.github.terra121.util.ChatUtil; import io.github.terra121.util.TranslateUtil; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; public class TerraInvertWaterFragment extends CommandFragment { @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) { World world = sender.getEntityWorld(); IChunkProvider cp = world.getChunkProvider(); if (!(cp instanceof CubeProviderServer)) { sender.sendMessage(ChatUtil.getNotCC()); return; } ICubeGenerator gen = ((CubeProviderServer) cp).getCubeGenerator(); if (!(gen instanceof EarthGenerator)) { sender.sendMessage(ChatUtil.getNotTerra()); return; } EarthGenerator terrain = (EarthGenerator) gen; GeographicProjection projection = terrain.projection; if (!terrain.cfg.settings.osmwater || terrain.osm == null || terrain.osm.water == null) { sender.sendMessage(ChatUtil.combine(TextFormatting.RED, TranslateUtil.translate("terra121.error.nowtr"))); return; } double[] c; try { c = projection.toGeo(sender.getPositionVector().x, sender.getPositionVector().z); } catch (OutOfProjectionBoundsException e) { //out of bounds, set c to null to print error c = null; } if (c == null || Double.isNaN(c[0])) { sender.sendMessage(ChatUtil.combine(TextFormatting.RED, TranslateUtil.translate("terra121.fragment.terra.where.notproj"))); return; } ChunkPos region = terrain.osm.getRegion(c[0], c[1]); Water water = terrain.osm.water; water.doingInverts = true; boolean restore = false; if (args.length > 0) { if (!(args[0].equalsIgnoreCase("true") || args[0].equalsIgnoreCase("false"))) { sender.sendMessage(new TextComponentString(TextFormatting.RED + "Usage: /terra invertwater [restore:<true/false>]")); return; } else { if (args[0].equalsIgnoreCase("true")) { restore = true; } } } if (restore ? water.inverts.remove(region) : water.inverts.add(region)) { sender.sendMessage(ChatUtil.combine(TextFormatting.RED, TranslateUtil.format(restore ? "terra121.commands.terra.rstwtr" : "terra121.commands.terra.invwtr", region.x, region.z))); return; } sender.sendMessage(ChatUtil.titleAndCombine(TextFormatting.RED, TranslateUtil.format("terra121.error.invwtr", region.x, region.z))); } @Override public String[] getName() { return new String[]{"invertwater", "invwtr", "restorewater", "rstwtr"}; } @Override public String getPurpose() { return TranslateUtil.translate("terra121.fragment.terra.winvert.purpose").getUnformattedComponentText(); } @Override public String[] getArguments() { return new String[]{"[restore:<true/false>]"}; } @Override public String getPermission() { return "terra121.commands.terra.utility"; } }
hw233/home3
core/server/toolProject/shineTool/src/main/java/com/home/shineTool/tool/export/DataDataExportTool.java
package com.home.shineTool.tool.export; import com.home.shine.ctrl.Ctrl; import com.home.shine.support.collection.SList; import com.home.shine.support.func.ObjectFunc2; import com.home.shine.utils.StringUtils; import com.home.shineTool.constlist.CodeType; import com.home.shineTool.constlist.DataGroupType; import com.home.shineTool.constlist.VisitType; import com.home.shineTool.global.ShineToolSetting; import com.home.shineTool.reflect.MethodArgInfo; import com.home.shineTool.reflect.MethodInfo; import com.home.shineTool.reflect.cls.ClassInfo; import com.home.shineTool.reflect.code.CodeWriter; import com.home.shineTool.tool.base.BaseExportTool; import com.home.shineTool.tool.base.RecordDataClassInfo; import com.home.shineTool.tool.data.DataExportTool; public class DataDataExportTool extends DataExportTool { /** 角色事务 */ private static final int Work_Player=1; /** 区服事务 */ private static final int Work_Area=2; /** 中心服事务 */ private static final int Work_Center=3; /** 常规事务 */ private static final int NormalWork=1; /** TCC事务到达 */ private static final int TCCWork=2; /** TCC事务结果 */ private static final int TCCWorkResult=3; //playerWork private static final int PlayerWork=0; private static final int PlayerToRoleGroupTCCResult=1; private static final int PlayerToPlayerTCC=2; private static final int PlayerToPlayerTCCResult=3; //area private static final int AreaWork=0; private static final int RoleGroupWork=1; private static final int PlayerToRoleGroupTCC=2; //center private static final int CenterWork=0; /** 根导出工具 */ private BaseDataExportTool _rootExportTool; private DataDataExportTool _superTool; /** 角色事务控制类 */ private ClassInfo _playerWorkControl; /** 区服事务控制类 */ private ClassInfo _areaWorkControl; /** 中心服事务控制类 */ private ClassInfo _centerWorkControl; private WorkInfo[] _playerWorkArr; private WorkInfo[] _areaWorkArr; private WorkInfo[] _centerWorkArr; private SList<WorkInfo> _playerWorkFindList; private SList<WorkInfo> _areaWorkFindList; private SList<WorkInfo> _centerWorkFindList; private boolean _hasAny=false; public void setRootDataExportTool(BaseDataExportTool tool) { _rootExportTool=tool; } private void initWork() { WorkInfo workInfo; _playerWorkArr=new WorkInfo[4]; _playerWorkFindList=new SList<>(); _areaWorkArr=new WorkInfo[3]; _areaWorkFindList=new SList<>(); _centerWorkArr=new WorkInfo[1]; _centerWorkFindList=new SList<>(); //center _centerWorkFindList.add(_centerWorkArr[CenterWork]=new WorkInfo(ShineToolSetting.centerWorkDOQName,NormalWork,Work_Center,"regist","注册","registOne")); //先area _areaWorkFindList.add(_areaWorkArr[AreaWork]=new WorkInfo(ShineToolSetting.areaWorkDOQName,NormalWork,Work_Area,"regist","注册","registOne")); _areaWorkFindList.add(workInfo=_areaWorkArr[RoleGroupWork]=new WorkInfo(ShineToolSetting.roleGroupWorkDOQName,NormalWork,Work_Area,"registRoleGroup","注册玩家群事务","registOneRoleGroup")); workInfo.hasRoleGroup=true; _areaWorkFindList.add(workInfo=_areaWorkArr[PlayerToRoleGroupTCC]=new WorkInfo(ShineToolSetting.playerToRoleGroupTCCWorkDOQName,TCCWork,Work_Area,"registRoleGroupTCC","注册玩家群TCC事务","registOneRoleGroupTCC")); workInfo.hasRoleGroup=true; //再player _playerWorkFindList.add(_playerWorkArr[PlayerWork]=new WorkInfo(ShineToolSetting.playerWorkDOQName,NormalWork,Work_Player,"regist","注册","registOne")); _areaWorkFindList.add(_playerWorkArr[PlayerToRoleGroupTCCResult]=new WorkInfo(ShineToolSetting.playerToRoleGroupTCCWorkDOQName,TCCWorkResult,Work_Player,"registRoleGroupTCCResult","注册玩家群TCC事务结果","registOneRoleGroupTCCResult")); _playerWorkFindList.add(_playerWorkArr[PlayerToPlayerTCC]=new WorkInfo(ShineToolSetting.playerToPlayerTCCWorkDOQName,TCCWork,Work_Player,"registPlayerTCC","注册玩家TCC事务到达","registOnePlayerTCC")); _playerWorkFindList.add(_playerWorkArr[PlayerToPlayerTCCResult]=new WorkInfo(ShineToolSetting.playerToPlayerTCCWorkDOQName,TCCWorkResult,Work_Player,"registPlayerTCCResult","注册玩家TCC事务结果","registOnePlayerTCCResult")); } /** 检查当前是否需要执行 */ @Override protected boolean checkNeedDoCurrent() { if(!super.checkNeedDoCurrent()) return false; boolean need=true; if(_outputInfo.isClientOrRobot()) { if(checkInputClassDontOut(_inputCls.getQName(),1)) { need=false; } } else { if(checkInputClassDontOut(_inputCls.getQName(),2)) { need=false; } } return need; } @Override protected void toExecuteFileList() { //无论是G还是H,都可用来做下面createClass的逻辑 _superTool=(DataDataExportTool)getUpTool(); initWork(); if(_rootExportTool instanceof NormalDataExportTool) { NormalDataExportTool rootE=(NormalDataExportTool)_rootExportTool; String mark=_superTool==null ? "" : "G"; String path=rootE.projectRoots[NormalDataExportTool.ServerGame]+"/control/"+mark+"PlayerWorkControl."+CodeType.getExName(getOutputInfo(DataGroupType.Server).codeType); _playerWorkControl=ClassInfo.getClassInfoFromPath(path); if(_playerWorkControl==null) { if(_superTool==null) { Ctrl.throwError("C层未找到"); } else { _playerWorkControl=ClassInfo.getClassInfoFromPathAbs(path); _playerWorkControl.extendsClsName=_superTool._playerWorkControl.clsName; _playerWorkControl.addImport(_superTool._playerWorkControl.getQName()); } } path=rootE.projectRoots[NormalDataExportTool.ServerGame]+"/control/"+mark+"AreaWorkControl."+CodeType.getExName(getOutputInfo(DataGroupType.Server).codeType); _areaWorkControl=ClassInfo.getClassInfoFromPath(path); if(_areaWorkControl==null) { if(_superTool==null) { Ctrl.throwError("C层未找到"); } else { _areaWorkControl=ClassInfo.getClassInfoFromPathAbs(path); _areaWorkControl.extendsClsName=_superTool._areaWorkControl.clsName; _areaWorkControl.addImport(_superTool._areaWorkControl.getQName()); } } path=rootE.projectRoots[NormalDataExportTool.ServerCenter]+"/control/"+mark+"CenterWorkControl."+CodeType.getExName(getOutputInfo(DataGroupType.Server).codeType); _centerWorkControl=ClassInfo.getClassInfoFromPath(path); if(_centerWorkControl==null) { if(_superTool==null) { Ctrl.throwError("C层未找到"); } else { _centerWorkControl=ClassInfo.getClassInfoFromPathAbs(path); _centerWorkControl.extendsClsName=_superTool._centerWorkControl.clsName; _centerWorkControl.addImport(_superTool._centerWorkControl.getQName()); } } for(WorkInfo v:_playerWorkArr) { addRegistMethod(_playerWorkControl,v.methodName,v.describe); } for(WorkInfo v:_areaWorkArr) { addRegistMethod(_areaWorkControl,v.methodName,v.describe); } for(WorkInfo v:_centerWorkArr) { addRegistMethod(_centerWorkControl,v.methodName,v.describe); } } super.toExecuteFileList(); } private void addRegistMethod(ClassInfo cls,String name,String describe) { MethodInfo registMethod=cls.getMethodByName(name); if(registMethod==null) { registMethod=new MethodInfo(); registMethod.name=name; registMethod.visitType=VisitType.Protected; registMethod.isOverride=true; registMethod.returnType=cls.getCode().Void; registMethod.describe=describe; cls.addMethod(registMethod); } } @Override protected void toMakeAfter() { super.toMakeAfter(); //server if(_outputInfo.group==DataGroupType.Server) { RecordDataClassInfo cls=BaseExportTool.newRecordClsDic.get(_inputCls.getQName()); //是事务 if(isExtendFrom(cls,ShineToolSetting.workDOQName)) { String front=_outputCls.clsName.substring(0,_outputCls.clsName.length()-_outputInfo.nameTail.length()); //角色事务 if(isExtendFrom(cls,ShineToolSetting.playerWorkDOQName)) { doOneFunc(cls,front,_playerWorkFindList); } //区服事务 else if(isExtendFrom(cls,ShineToolSetting.areaWorkDOQName)) { doOneFunc(cls,front,_areaWorkFindList); } //中心服 else if(isExtendFrom(cls,ShineToolSetting.centerWorkDOQName)) { doOneFunc(cls,front,_centerWorkFindList); } } } } private void doOneFunc(RecordDataClassInfo cls,String front,SList<WorkInfo> list) { WorkInfo workInfo; for(int i=list.size()-1;i>=0;--i) { workInfo=list.get(i); if(isExtendFrom(cls,workInfo.qName)) { if(workInfo.entityType==Work_Player) { addPlayerFunc(front,workInfo.dataName,workInfo.type); } else if(workInfo.entityType==Work_Area) { addAreaFunc(workInfo.hasRoleGroup,front,workInfo.dataName,workInfo.type); } else if(workInfo.entityType==Work_Center) { addCenterFunc(front,workInfo.dataName,workInfo.type); } workInfo.hasDid=true; _hasAny=true; //不是结果组 if(workInfo.type!=TCCWorkResult) { return; } } } } private void addPlayerFunc(String front,String workName,int type) { MethodInfo method=new MethodInfo(); method.name="do"+front; method.visitType=VisitType.Private; if(type==TCCWork) method.returnType=_outputCls.getCode().Int; else method.returnType=_outputCls.getCode().Void; method.describe=_outputCls.clsDescribe; method.args.add(new MethodArgInfo("me","Player")); method.args.add(new MethodArgInfo("wData",workName)); if(type==TCCWorkResult) { method.name+="Result"; method.args.add(new MethodArgInfo("result",_outputCls.getCode().Int)); } //没有 if(_playerWorkControl.getMethod(method.getKey())==null) { CodeWriter writer=_outputCls.createWriter(); writer.writeVarCreate("data",_outputCls.clsName,_outputCls.getCode().getVarTypeTrans("wData",_outputCls.clsName)); if(_superTool!=null) { String me=ShineToolSetting.needHotfix ? "hme" : "gme"; String player=ShineToolSetting.needHotfix ? "HPlayer" : "GPlayer"; writer.writeVarCreate(me,player,_outputCls.getCode().getVarTypeTrans("me",player)); } writer.writeEmptyLine(); if(type==TCCWork) { writer.writeReturnBoolean(true); } writer.writeEnd(); method.content=writer.toString(); _playerWorkControl.addImport(_outputCls.getQName()); _playerWorkControl.addMethod(method); } } private void addAreaFunc(boolean isRoleGroup,String front,String workName,int type) { MethodInfo method=new MethodInfo(); method.name="do"+front; method.visitType=VisitType.Private; if(type==TCCWork) method.returnType=_outputCls.getCode().Int; else method.returnType=_outputCls.getCode().Void; method.describe=_outputCls.clsDescribe; if(isRoleGroup) { method.args.add(new MethodArgInfo("me","RoleGroup")); } method.args.add(new MethodArgInfo("wData",workName)); if(type==TCCWorkResult) { method.name+="Result"; method.args.add(new MethodArgInfo("result",_outputCls.getCode().Int)); } //没有 if(_areaWorkControl.getMethod(method.getKey())==null) { CodeWriter writer=_outputCls.createWriter(); writer.writeVarCreate("data",_outputCls.clsName,_outputCls.getCode().getVarTypeTrans("wData",_outputCls.clsName)); //if(_superTool!=null) //{ // String me=ShineToolSetting.needHotfix ? "hme" : "gme"; // String player=ShineToolSetting.needHotfix ? "HPlayer" : "GPlayer"; // writer.writeVarCreate(me,player,_outputCls.getCode().getVarTypeTrans("me",player)); //} writer.writeEmptyLine(); if(type==TCCWork) { writer.writeReturn("0"); } writer.writeEnd(); method.content=writer.toString(); _areaWorkControl.addImport(_outputCls.getQName()); _areaWorkControl.addMethod(method); } } private void addCenterFunc(String front,String workName,int type) { MethodInfo method=new MethodInfo(); method.name="do"+front; method.visitType=VisitType.Private; if(type==TCCWork) method.returnType=_outputCls.getCode().Int; else method.returnType=_outputCls.getCode().Void; method.describe=_outputCls.clsDescribe; //if(isRoleGroup) //{ // method.args.add(new MethodArgInfo("me","RoleGroup")); //} method.args.add(new MethodArgInfo("wData",workName)); if(type==TCCWorkResult) { method.name+="Result"; method.args.add(new MethodArgInfo("result",_outputCls.getCode().Int)); } //没有 if(_centerWorkControl.getMethod(method.getKey())==null) { CodeWriter writer=_outputCls.createWriter(); writer.writeVarCreate("data",_outputCls.clsName,_outputCls.getCode().getVarTypeTrans("wData",_outputCls.clsName)); writer.writeEmptyLine(); if(type==TCCWork) { writer.writeReturn("0"); } writer.writeEnd(); method.content=writer.toString(); _centerWorkControl.addImport(_outputCls.getQName()); _centerWorkControl.addMethod(method); } } @Override protected void endExecute() { super.endExecute(); if(_hasAny) { endRegistFirst(_playerWorkControl,_playerWorkArr); endRegistFirst(_areaWorkControl,_areaWorkArr); endRegistFirst(_centerWorkControl,_centerWorkArr); _allInputQNameSet.getSortedList().forEach(k-> { RecordDataClassInfo cls=BaseExportTool.newRecordClsDic.get(k); //是事务 if(isExtendFrom(cls,ShineToolSetting.workDOQName)) { //角色事务 if(isExtendFrom(cls,ShineToolSetting.playerWorkDOQName)) { doOneWrite(cls,_playerWorkFindList); } else if(isExtendFrom(cls,ShineToolSetting.areaWorkDOQName)) { doOneWrite(cls,_areaWorkFindList); } else if(isExtendFrom(cls,ShineToolSetting.centerWorkDOQName)) { doOneWrite(cls,_centerWorkFindList); } } }); endRegistLast(_playerWorkControl,_playerWorkArr); endRegistLast(_areaWorkControl,_areaWorkArr); endRegistLast(_centerWorkControl,_centerWorkArr); } } private void doOneWrite(RecordDataClassInfo cls,SList<WorkInfo> list) { WorkInfo workInfo; for(int i=list.size()-1;i>=0;--i) { workInfo=list.get(i); if(isExtendFrom(cls,workInfo.qName)) { addRegistOne(workInfo,cls); //不是结果组 if(workInfo.type!=TCCWorkResult) { return; } } } } private void endRegistFirst(ClassInfo cls,WorkInfo[] arr) { WorkInfo workInfo; for(int i=0;i<arr.length;i++) { workInfo=arr[i]; workInfo.registMethod=cls.getMethodByName(workInfo.methodName); workInfo.writer=cls.createWriter(); if(_superTool!=null) { workInfo.writer.writeSuperMethod(workInfo.registMethod); workInfo.writer.writeEmptyLine(); } } } private void endRegistLast(ClassInfo cls,WorkInfo[] arr) { WorkInfo workInfo; for(int i=0;i<arr.length;i++) { workInfo=arr[i]; workInfo.writer.writeEnd(); workInfo.registMethod.content=workInfo.writer.toString(); } cls.write(); } private void addRegistOne(WorkInfo info,RecordDataClassInfo cls) { String cName=StringUtils.getClassNameForQName(cls.clsQName); cName=cName.substring(0,cName.length()-_mark.length()); String outName=cName+getOutputInfo(DataGroupType.Server).nameTail; if(info.type==TCCWorkResult) { cName+="Result"; } info.writer.writeCustom(info.registOneMethodName+"("+outName+".dataID,this::do"+cName+");"); } private class WorkInfo { /** DO完全限定名 */ public String qName; public String dataName; /** 事务类型 */ public int type; /** 主体类型 */ public int entityType; public String methodName; public String describe; public String registOneMethodName; /** 是否有执行的 */ public boolean hasDid; public boolean hasRoleGroup=false; public MethodInfo registMethod; public CodeWriter writer; public WorkInfo(String qName,int type,int entityType,String methodName,String describe,String registOneMethodName) { this.qName=qName; String temp=StringUtils.getClassNameForQName(qName); this.dataName=temp.substring(0,temp.length()-2)+"Data"; this.type=type; this.entityType=entityType; this.methodName=methodName; this.describe=describe; this.registOneMethodName=registOneMethodName; } } }
wangyan-1993/FollowMe
FollowMe/FollowMe/Mine/Controllers/InformationViewController.h
// // InformationViewController.h // FollowMe // // Created by SCJY on 16/3/21. // Copyright © 2016年 SCJY. All rights reserved. // #import <UIKit/UIKit.h> @interface InformationViewController : UIViewController @property(nonatomic, copy) NSString *username; @property(nonatomic, copy) NSString *headerImage; @end
jhedden/jackhammer
web/app/lib/common/collections/wp_themes.rb
<gh_stars>1-10 # encoding: UTF-8 require 'common/collections/wp_themes/detectable' class WpThemes < WpItems extend WpThemes::Detectable end
shopg8felix/pwa
libraries/tracking/selectors/cart.js
<reponame>shopg8felix/pwa<gh_stars>10-100 import { createSelector } from 'reselect'; import { getProduct } from '@shopgate/pwa-common-commerce/product/selectors/product'; import { getSubTotal, getCurrency, getCartProducts, getDiscountsAmount, } from '@shopgate/pwa-common-commerce/cart/selectors/index'; import { convertPriceToString, formatCartProductData, formatAddToCartProductData, } from '../helpers'; /** * Selects the products from the cart and reformat them. * @param {Object} state The current state. * @return {Array} The reformatted products. */ const getProducts = createSelector( getCartProducts, products => products.map(formatCartProductData) ); /** * Selects products by ID and reformat them. * @param {Object} state The current state. * @param {Array} products Array of products. * @returns {Array} Formatted products. */ export const getAddToCartProducts = (state, products) => ( products .map(product => ({ product: getProduct(state, { productId: product.productId }), quantity: product.quantity, })) .map(formatAddToCartProductData) ); /** * Selects the cart information. * @param {Object} state The current state. * @returns {Object} The cart information. */ export default createSelector( getSubTotal, getDiscountsAmount, getCurrency, getProducts, (subTotal, discounts, currency, products) => ({ amount: { gross: convertPriceToString(subTotal - discounts), // TODO: Correct net prices are not possible atm. net: convertPriceToString(subTotal - discounts), currency, }, products, productsCount: products.length, }) );
SUNET/eduid-front
src/login/components/DataTable/DataTable.js
import React, { Component } from "react"; import PropTypes from "prop-types"; import i18n from "../../translation/InjectIntl_HOC_factory"; import DataTableRow from "./DataTableRow/DataTableRow"; class DataTable extends Component { render() { let data = this.props.data; // console.log("this is data in Table", data); return ( <div className="table-responsive"> <table className="table-form"> <tbody> <DataTableRow data={data} handleStartConfirmation={this.props.handleStartConfirmation} handleMakePrimary={this.props.handleMakePrimary} handleRemove={this.props.handleRemove} /> </tbody> </table> </div> ); } } DataTable.propTypes = { data: PropTypes.any, handleStartConfirmation: PropTypes.func, handleMakePrimary: PropTypes.func, handleRemove: PropTypes.func, }; export default i18n(DataTable);
peter-leonov/babel-plugin-intoscope
logger/proxySpy.js
<reponame>peter-leonov/babel-plugin-intoscope const { cloneDeepWith } = require('lodash'); const spiesCache = new WeakMap(); const addToCache = (v, id, spy) => { const spiesById = spiesCache.get(v); if (spiesById) { spiesById.set(id, spy); } else { const spiesById = new Map(); spiesById.set(id, spy); spiesCache.set(v, spiesById); } }; const getFromCache = (v, id) => { const spiesById = spiesCache.get(v); if (spiesById) { return spiesById.get(id); } return undefined; }; const spiesRegistry = new WeakMap(); const putToRegistry = (v, id, spy) => { addToCache(v, id, spy); spiesRegistry.set(spy, v); return spy; }; const isSpy = spy => spiesRegistry.has(spy); const getSpyTarget = spy => spiesRegistry.get(spy); const serializeWithSpies = v => cloneDeepWith(v, value => (isSpy(value) ? getSpyTarget(value) : value)); const isSpyable = v => typeof v == 'function' || (typeof v == 'object' && v !== null); const proxySpyFactory = ({ serialize }) => { const proxySpy = (logger, recorder, id, v, conf = { deep: false }) => { if (!isSpyable(v)) return v; const cached = getFromCache(v, id); if (cached) return cached; // wrap in a new proxy with the same logger const deep = conf.deep ? (id2, v) => proxySpy(logger, recorder, `${id}.${String(id2)}`, v) : (_, v) => v; return putToRegistry( v, id, new Proxy(v, { apply(_, that, args) { if (that === undefined) { logger(['call', id, serialize(args)]); if (recorder && recorder.playback) { if (recorder.results.length === 0) { throw new Error( `not enough stored results for mock with name "${id}"`, ); } else { const result = recorder.results.shift(); if (result[0] !== id) { throw new Error( `mismatching call order, wrong call with name "${ result[0] }" for mock with name "${id}"`, ); } return deep('call', result[1]); } } const result = Reflect.apply(...arguments); if (recorder && recorder.recording) { recorder.results.push([id, result]); } return deep('call', result); } else { logger(['apply', id, serialize(that), serialize(args)]); if (recorder && recorder.playback) { if (recorder.results.length === 0) { throw new Error( `not enough stored results for mock with name "${id}"`, ); } else { const result = recorder.results.shift(); if (result[0] !== id) { throw new Error( `mismatching call order, wrong call with name "${ result[0] }" for mock with name "${id}"`, ); } return deep('apply', result[1]); } } const result = Reflect.apply(...arguments); if (recorder && recorder.recording) { recorder.results.push([id, result]); } return deep('apply', result); } }, get(_, prop) { logger(['get', id, prop]); return deep(prop, Reflect.get(...arguments)); }, set(_, prop, value) { logger(['set', String(id), prop, serialize(value)]); return Reflect.set(...arguments); }, }), ); }; return proxySpy; }; const proxySpy = proxySpyFactory({ serialize: serializeWithSpies }); module.exports = { serializeWithSpies, isSpy, getSpyTarget, proxySpyFactory, proxySpy, };
alxalx14/Sea-Of-Thieves-SDK
SDK/ContestMatchmaking_structs.h
#pragma once // Name: SeaOfThieves, Version: 2.0.23 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Script Structs //--------------------------------------------------------------------------- // ScriptStruct ContestMatchmaking.ServerCrewModel // 0x0060 struct FServerCrewModel { struct FGuid CrewId; // 0x0000(0x0010) (ZeroConstructor, IsPlainOldData, NoDestructor) struct FUniqueNetIdRepl UserId; // 0x0010(0x0018) struct FGuid ServerId; // 0x0028(0x0010) (ZeroConstructor, IsPlainOldData, NoDestructor) int SessionType; // 0x0038(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) unsigned char UnknownData_F6O2[0x4]; // 0x003C(0x0004) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY) TArray<struct FVector2D> Positions; // 0x0040(0x0010) (ZeroConstructor) TArray<uint32_t> Resources; // 0x0050(0x0010) (ZeroConstructor) void AfterRead(); void BeforeDelete(); }; // ScriptStruct ContestMatchmaking.ContestMatchmakingServerRequestModel // 0x0088 struct FContestMatchmakingServerRequestModel { struct FGuid ServerId; // 0x0000(0x0010) (ZeroConstructor, IsPlainOldData, NoDestructor) struct FString VmId; // 0x0010(0x0010) (ZeroConstructor, HasGetValueTypeHash) struct FString PrivateServerId; // 0x0020(0x0010) (ZeroConstructor, HasGetValueTypeHash) struct FString ServerLocation; // 0x0030(0x0010) (ZeroConstructor, HasGetValueTypeHash) uint32_t FeatureHash; // 0x0040(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) unsigned char UnknownData_AS8P[0x4]; // 0x0044(0x0004) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY) TArray<struct FString> PlayModeTags; // 0x0048(0x0010) (ZeroConstructor) TArray<struct FString> PlayModeStates; // 0x0058(0x0010) (ZeroConstructor) TArray<struct FServerCrewModel> Crews; // 0x0068(0x0010) (ZeroConstructor) struct FGuid RequestCorrelationId; // 0x0078(0x0010) (ZeroConstructor, IsPlainOldData, NoDestructor) void AfterRead(); void BeforeDelete(); }; // ScriptStruct ContestMatchmaking.ServerRegionModel // 0x000C struct FServerRegionModel { struct FVector2D Position; // 0x0000(0x0008) (ZeroConstructor, IsPlainOldData, NoDestructor) float Radius; // 0x0008(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void AfterRead(); void BeforeDelete(); }; // ScriptStruct ContestMatchmaking.ServerContendedModel // 0x0030 struct FServerContendedModel { TArray<struct FVector2D> Positions; // 0x0000(0x0010) (ZeroConstructor) TArray<struct FServerRegionModel> Regions; // 0x0010(0x0010) (ZeroConstructor) TArray<uint32_t> Resources; // 0x0020(0x0010) (ZeroConstructor) void AfterRead(); void BeforeDelete(); }; // ScriptStruct ContestMatchmaking.ServerCrewRequestModel // 0x00B0 struct FServerCrewRequestModel { struct FGuid ServerId; // 0x0000(0x0010) (ZeroConstructor, IsPlainOldData, NoDestructor) struct FString VmId; // 0x0010(0x0010) (ZeroConstructor, HasGetValueTypeHash) struct FString PrivateServerId; // 0x0020(0x0010) (ZeroConstructor, HasGetValueTypeHash) struct FString ServerLocation; // 0x0030(0x0010) (ZeroConstructor, HasGetValueTypeHash) uint32_t FeatureHash; // 0x0040(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) unsigned char UnknownData_YNZS[0x4]; // 0x0044(0x0004) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY) TArray<struct FString> PlayModeTags; // 0x0048(0x0010) (ZeroConstructor) struct FString PlayModeState; // 0x0058(0x0010) (ZeroConstructor, HasGetValueTypeHash) int CrewCount; // 0x0068(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) int CrewCountBucket; // 0x006C(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) int CrewMin; // 0x0070(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) int CrewMax; // 0x0074(0x0004) (ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FTimespan Uptime; // 0x0078(0x0008) (ZeroConstructor) struct FServerContendedModel Contended; // 0x0080(0x0030) void AfterRead(); void BeforeDelete(); }; // ScriptStruct ContestMatchmaking.ServerCrewResponseModel // 0x0028 struct FServerCrewResponseModel { TArray<struct FServerCrewModel> Crews; // 0x0000(0x0010) (ZeroConstructor) struct FTimespan RetryAfter; // 0x0010(0x0008) (ZeroConstructor) struct FTimespan MigrationThreshold; // 0x0018(0x0008) (ZeroConstructor) struct FTimespan ExpireAfter; // 0x0020(0x0008) (ZeroConstructor) void AfterRead(); void BeforeDelete(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
chengzongxin/Demo
Demo/HomeSection/NewcomerProcess/THKNewcomerHomeSelectStageView.h
<filename>Demo/HomeSection/NewcomerProcess/THKNewcomerHomeSelectStageView.h // // THKNewcomerHomeSelectStageView.h // Demo // // Created by Joe.cheng on 2021/12/6. // #import "THKView.h" #import "THKNewcomerHomeSelectStageViewModel.h" NS_ASSUME_NONNULL_BEGIN @interface THKNewcomerHomeSelectStageView : THKView @property (nonatomic, strong, readonly) THKNewcomerHomeSelectStageViewModel *viewModel; @end NS_ASSUME_NONNULL_END
starsep/NewsBlur
apps/reader/admin.py
<reponame>starsep/NewsBlur<gh_stars>1000+ from apps.reader.models import UserSubscription, UserSubscriptionFolders, Feature from django.contrib import admin admin.site.register(UserSubscription) admin.site.register(UserSubscriptionFolders) admin.site.register(Feature)
joshgav/v8docs
private/structv8_1_1base_1_1_default_create_trait.js
var structv8_1_1base_1_1_default_create_trait = [ [ "Create", "structv8_1_1base_1_1_default_create_trait.html#a7129781d18e9d3d897de61a95b219ade", null ] ];
y2ghost/study
java/mybatis/oneToMany/src/test/java/study/ywork/mybatis/dao/AccountTest.java
<filename>java/mybatis/oneToMany/src/test/java/study/ywork/mybatis/dao/AccountTest.java<gh_stars>0 package study.ywork.mybatis.dao; import study.ywork.mybatis.domain.Account; import study.ywork.mybatis.domain.AccountUser; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.InputStream; import java.util.List; class AccountTest { private InputStream in; private SqlSession sqlSession; private IAccountDao accountDao; @BeforeEach void init() throws Exception { // 1.读取配置文件,生成字节输入流 in = Resources.getResourceAsStream("SqlMapConfig.xml"); // 2.获取SqlSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 3.获取SqlSession对象 sqlSession = factory.openSession(true); // 4.获取dao的代理对象 accountDao = sqlSession.getMapper(IAccountDao.class); } @AfterEach void destroy() throws Exception { // 6.释放资源 sqlSession.close(); in.close(); } /** * 测试查询所有 */ @Test void testFindAll() { List<Account> accounts = accountDao.findAll(); for (Account account : accounts) { System.out.println("--------每个account的信息------------"); System.out.println(account); System.out.println(account.getUser()); } } /** * 测试查询所有账户,同时包含用户名称和地址 */ @Test void testFindAllAccountUser() { List<AccountUser> aus = accountDao.findAllAccount(); for (AccountUser au : aus) { System.out.println(au); } } }
stoyannk/dx11-framework
Dx11/Rendering/MeshLoader.cpp
<filename>Dx11/Rendering/MeshLoader.cpp // Copyright (c) 2011-2014, <NAME> // All rights reserved. // This software is governed by a permissive BSD-style license. See LICENSE. #include "stdafx.h" #ifndef MINIMAL_SIZE #include "MeshLoader.h" #include "Mesh.h" #include "ObjLoader.h" #include "RawLoader.h" Mesh* MeshLoader::LoadMesh(DxRenderer* renderer, const std::string& filename, std::string& errors, MeshSDF* sdf) { Mesh* mesh = nullptr; const size_t dotPos = filename.rfind('.'); if(dotPos == filename.npos) { errors += "Unable to specify the input format for file " + filename; return mesh; } std::string ext(filename.begin() + dotPos, filename.end()); boost::algorithm::to_lower(ext); if(ext == ".obj") { ObjLoader loader; mesh = loader.Load(renderer, filename, errors); } else if(ext == ".rmesh") { RawLoader loader; mesh = loader.Load(renderer, filename, errors, sdf); } else { errors += "Unsupported file format for file " + filename; } return mesh; } #endif
Rerito/suffix-tree-v2
suffixtree/include/Penjing/SuffixTree/Builders/Ukkonen/Canonize.hpp
// Copyright (c) 2021, Rerito // SPDX-License-Identifier: MIT #pragma once #include <cassert> #include <functional> #include <ranges> #include <tuple> #include "../../Concepts/Node.hpp" #include "../../Concepts/StringView.hpp" namespace Penjing { namespace SuffixTree { namespace Builders { namespace Ukkonen { namespace CPO { // /!\ Warning: do not use outside of the Ukkonen builder class Canonize { public: // This function is always called with a wordPath related to the string // being added. The canonical path is sure to exist thanks to // "open transitions" left during the tree construction. template< typename Node, typename StrView > requires(Concepts::Node< Node >&& Concepts::StringView< typename Node::StringType, StrView >) constexpr auto operator()(Node const& node, StrView wordPath) const { auto canonicalNode = std::cref(node); // If the wordPath to follow is empty, the state is explicit // and therefore already canonical. if (std::ranges::empty(wordPath)) { return std::make_tuple(canonicalNode, wordPath); } // Otherwise, wordPath must be fast-walked to canonize the given state. auto t = canonicalNode.get()[*std::ranges::begin(wordPath)]; assert(!!t); // As long as there is a transition with a matching begin, wordPath and // its label are sure to match up until: // min(size(wordPath), size(label)). // This is the "fast" walk, as there is no need to compare characters. while (std::ranges::size((*t).get().label()) <= std::ranges::size(wordPath)) { // Skim wordPath at the beginning of size(label) characters to // prepare for the next iteration wordPath = { std::ranges::begin(wordPath) + std::ranges::size((*t).get().label()), std::ranges::end(wordPath)}; canonicalNode = std::cref(*((*t).get())); // The wordPath has been fully walked down if (std::ranges::empty(wordPath)) { break; } // Otherwise, there is necessarily an existing transition that // shares a common prefix with wordPath t = canonicalNode.get()[*std::ranges::begin(wordPath)]; assert(!!t); } return std::make_tuple(canonicalNode, wordPath); } }; } // namespace CPO inline namespace Cust { inline constexpr CPO::Canonize canonize{}; } // namespace Cust struct CanonizePolicy { template< typename Node, typename StrView > constexpr auto canonize(Node const& node, StrView&& wordPath) const noexcept( noexcept(Cust::canonize(node, std::forward< StrView >(wordPath)))) { return Cust::canonize(node, std::forward< StrView >(wordPath)); } }; } // namespace Ukkonen } // namespace Builders } // namesapce SuffixTree } // namespace Penjing
ezefranca/LogiKiD-Allegro5-Game
doc/Doxygen/html/search/defines_6c.js
<filename>doc/Doxygen/html/search/defines_6c.js var searchData= [ ['largura',['LARGURA',['../comum_8h.html#a39993a19ea179e022fb3346fdc794808',1,'comum.h']]] ];
GaloisInc/hacrypto
src/C/Security-57031.40.6/SecurityTests/regressions/test/testenv.c
/* * Copyright (c) 2005-2006 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ * * testenv.c */ #include <fcntl.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "testmore.h" #include "testenv.h" static int current_dir = -1; static char scratch_dir[50]; static char *home_var; int rmdir_recursive(const char *path) { char command_buf[256]; if (strlen(path) + 10 > sizeof(command_buf) || strchr(path, '\'')) { fprintf(stderr, "# rmdir_recursive: invalid path: %s", path); return -1; } sprintf(command_buf, "rm -rf '%s'", path); return system(command_buf); } int tests_begin(int argc, char * const *argv) { char library_dir[70]; char preferences_dir[80]; setup("tests_begin"); /* Create scratch dir for tests to run in. */ sprintf(scratch_dir, "/tmp/tst-%d", getpid()); sprintf(library_dir, "%s/Library", scratch_dir); sprintf(preferences_dir, "%s/Preferences", library_dir); return (ok_unix(mkdir(scratch_dir, 0755), "mkdir") && ok_unix(current_dir = open(".", O_RDONLY), "open") && ok_unix(chdir(scratch_dir), "chdir") && ok_unix(setenv("HOME", scratch_dir, 1), "setenv") && /* @@@ Work around a bug that the prefs code in libsecurity_keychain never creates the Library/Preferences dir. */ ok_unix(mkdir(library_dir, 0755), "mkdir") && ok_unix(mkdir(preferences_dir, 0755), "mkdir") && ok_unix(home_var = getenv("HOME"), "getenv")); } int tests_end(int result) { setup("tests_end"); /* Restore previous cwd and remove scratch dir. */ return (ok_unix(fchdir(current_dir), "fchdir") && ok_unix(close(current_dir), "close") && ok_unix(rmdir_recursive(scratch_dir), "rmdir_recursive")); }
thilinah/icehrm-api
models/EmployeeCertifications.js
/* jshint indent: 2 */ module.exports = function(sequelize, DataTypes) { return sequelize.define('EmployeeCertifications', { id: { type: DataTypes.BIGINT, allowNull: false, primaryKey: true, autoIncrement: true }, certification_id: { type: DataTypes.BIGINT, allowNull: true, references: { model: 'Certifications', key: 'id' } }, employee: { type: DataTypes.BIGINT, allowNull: false, references: { model: 'Employees', key: 'id' } }, institute: { type: DataTypes.STRING(400), allowNull: true }, date_start: { type: DataTypes.DATEONLY, allowNull: true, defaultValue: '0000-00-00' }, date_end: { type: DataTypes.DATEONLY, allowNull: true, defaultValue: '0000-00-00' } }, { tableName: 'EmployeeCertifications' }); };
mfkiwl/fletcher-accelerator-FPGA
integrations/vivado_hls/src/fletcher/components/operators.h
<gh_stars>100-1000 #pragma once #include "fletcher/components/operators/arith.h" #include "fletcher/components/operators/indecrement.h" #include "fletcher/components/operators/logical.h" //template <typename T> //f_packet<T> operator+(f_packet<T> &rhs) { // return f_packet<T>(+rhs.data, rhs.dvalid, rhs.last); //} //template <typename T> //f_packet<T> operator-(f_packet<T> &rhs) { // return f_packet<T>(-rhs.data, rhs.dvalid, rhs.last); //} // //#pragma region Packet <-> Packet operators //template <typename T> //friend bool operator<(f_packet<T> &lhs, f_packet<T> &rhs) { // return lhs.data < rhs.data; //} //template <typename T> //friend bool operator>(f_packet<T> &lhs, f_packet<T> &rhs) { // return rhs < lhs; //} //template <typename T> //friend bool operator<=(f_packet<T> &lhs, f_packet<T> &rhs) { // return !(rhs < lhs); //} //template <typename T> //friend bool operator>=(f_packet<T> &lhs, f_packet<T> &rhs) { // return !(lhs < rhs); //} // //template <typename T> //friend f_packet<T> operator-(f_packet<T> &lhs, f_packet<T> &rhs) { // return f_packet<T>(lhs.data - rhs.data, lhs.dvalid, lhs.last); //} //template <typename T> //friend f_packet<T> operator*(f_packet<T> &lhs, f_packet<T> &rhs) { // return f_packet<T>(lhs.data * rhs.data, lhs.dvalid, lhs.last); //} //template <typename T> //friend f_packet<T> operator/(f_packet<T> &lhs, f_packet<T> &rhs) { // return f_packet<T>(lhs.data / rhs.data, lhs.dvalid, lhs.last); //} //template <typename T> //friend bool operator==(f_packet<T> &lhs, f_packet<T> &rhs) { // return lhs.data == rhs.data; //} //template <typename T> //friend bool operator!=(f_packet<T> &lhs, f_packet<T> &rhs) { // return !(rhs == lhs); //} // //#pragma endregion // //#pragma region Packet <-> Base type operators //template <typename T> //friend bool operator<(f_packet<T> &lhs, T &rhs) { // return lhs.data < rhs; //} //template <typename T> //friend bool operator>(f_packet<T> &lhs, T &rhs) { // return rhs < lhs; //} //template <typename T> //friend bool operator<=(f_packet<T> &lhs, T &rhs) { // return !(rhs < lhs); //} //template <typename T> //friend bool operator>=(f_packet<T> &lhs, T &rhs) { // return !(lhs < rhs); //} //template <typename T> //friend f_packet<T> operator+(f_packet<T> &lhs, T &rhs) { // return f_packet<T>(lhs.data + rhs, lhs.dvalid, lhs.last); //} //template <typename T> //friend f_packet<T> operator-(f_packet<T> &lhs, T &rhs) { // return f_packet<T>(lhs.data - rhs, lhs.dvalid, lhs.last); //} //template <typename T> //friend f_packet<T> operator*(f_packet<T> &lhs, T &rhs) { // return f_packet<T>(lhs.data * rhs, lhs.dvalid, lhs.last); //} //template <typename T> //friend f_packet<T> operator/(f_packet<T> &lhs, T &rhs) { // return f_packet<T>(lhs.data / rhs, lhs.dvalid, lhs.last); //} //template <typename T> //friend bool operator==(f_packet<T> &lhs, T &rhs) { // return lhs.data == rhs; //} //template <typename T> //friend bool operator!=(f_packet<T> &lhs, T &rhs) { // return !(rhs == lhs); //} // //#pragma endregion // //#pragma region Base type <-> Packet operators //template <typename T> //friend bool operator<(T &lhs, f_packet<T> &rhs) { // return lhs < rhs.data; //} //template <typename T> //friend bool operator>(T &lhs, f_packet<T> &rhs) { // return rhs < lhs; //} //template <typename T> //friend bool operator<=(T &lhs, f_packet<T> &rhs) { // return !(rhs < lhs); //} //template <typename T> //friend bool operator>=(T &lhs, f_packet<T> &rhs) { // return !(lhs < rhs); //} //template <typename T> //friend f_packet<T> operator+(T &lhs, f_packet<T> &rhs) { // return f_packet<T>(lhs + rhs.data, rhs.dvalid, rhs.last); //} //template <typename T> //friend f_packet<T> operator-(T &lhs, f_packet<T> &rhs) { // return f_packet<T>(lhs - rhs.data, rhs.dvalid, rhs.last); //} //template <typename T> //friend f_packet<T> operator*(T &lhs, f_packet<T> &rhs) { // return f_packet<T>(lhs * rhs.data, rhs.dvalid, rhs.last); //} //template <typename T> //friend f_packet<T> operator/(T &lhs, f_packet<T> &rhs) { // return f_packet<T>(lhs / rhs.data, rhs.dvalid, rhs.last); //} //template <typename T> //friend bool operator==(T &lhs, f_packet<T> &rhs) { // return lhs == rhs.data; //} //template <typename T> //friend bool operator!=(T &lhs, f_packet<T> &rhs) { // return !(rhs == lhs); //} // //#pragma endregion
LuisaRoa/React-proyectoDocente
src/views/actividadDocente/Docentes.js
import React from 'react' import 'bootstrap/dist/css/bootstrap.min.css'; import { BsFillPeopleFill, BsSearch } from 'react-icons/bs'; import { CButton, CCard, CCardBody, CCardHeader, CCol, CDataTable, CRow, CNav, CForm, CInput, } from '@coreui/react' import { Component } from 'react'; import axios from 'axios'; import UserProfile from '../usuarios/UserProfile'; import { Link } from "react-router-dom"; const fields = ['documento', 'nombre', 'codigo', 'fechaIngreso', 'correo', 'sede', 'opciones'] const url = "http://ec2-3-136-234-55.us-east-2.compute.amazonaws.com:8080/docente/retornarAdministrativo/"; class Docentes extends Component { state = { data: [], tablaData: [], busqueda: "", modalInsertar: false, modalEliminar: false, form: { id: '', documento: '', codigo: '', nombre: '', direccion: '', celular: '', fechaNacimiento: '', sexo: '', fechaIngreso: '', correo: '', sede: '', administrativo: { admi_id: UserProfile.getId() }, admin: '', tipoModal: '' }, error: {}, campo: {}, enviado: false, director: [] } peticionGet = () => { //Petición para traer todos los docentes relacionados con un administrativo axios.get(url + UserProfile.getId(), { headers: { Authorization: `Bearer ${sessionStorage.getItem(UserProfile.getToken().TOKEN_NAME)}` } }).then(response => { this.setState({ data: response.data }); this.setState({ tablaData: response.data }); }).catch(error => { console.log(error.message); }) } modalInsertar = () => { this.setState({ modalInsertar: !this.state.modalInsertar }); } seleccionarUsuario = (usuario) => { //Función para guardar los datos del docente seleccionado this.setState({ tipoModal: 'actualizar', form: { id: usuario.id, documento: usuario.documento, codigo: usuario.codigo, nombre: usuario.nombre, direccion: usuario.direccion, celular: usuario.celular, fechaNacimiento: usuario.fechaNacimiento, sexo: usuario.sexo, fechaIngreso: usuario.fechaIngreso, correo: usuario.correo, sede: usuario.sede, administrativo: { admi_id: usuario.administrativo.admi_id }, admin: usuario.administrativo.admi_id } }) } handleChanges = e => { //Función para guardar los datos de busqueda this.setState({ busqueda: e.target.value }); this.filtrar(e.target.value) } filtrar = (terminoBusqueda) => { //Función para filtrar los datos de la tabla var resultadosBusqueda = this.state.tablaData.filter((elemento) => { if (elemento.nombre.toString().toLowerCase().includes(terminoBusqueda.toString().toLowerCase()) || elemento.codigo.toString().toLowerCase().includes(terminoBusqueda.toString().toLowerCase()) ) { return elemento; } }); this.setState({ data: resultadosBusqueda }); } componentDidMount() { this.peticionGet(); } render() { return ( <> <CRow> <CCol> <CCard style={{ textAlign: 'center' }}> <CCardHeader> <CForm className="form-inline"> <h2 ><BsFillPeopleFill size="50px" /> Docentes</h2> <CCol col="2" className="mb-3 mb-xl-0 text-center"> <CNav className="navbar navbar-light bg-light" > <CForm className="form-inline"> <CInput className="form-control mr-sm-2" value={this.state.busqueda} placeholder="Buscar" aria-label="Search" onChange={this.handleChanges} /> </CForm> </CNav> </CCol> </CForm> </CCardHeader> <CCardBody> <CDataTable items={this.state.data} fields={fields} hover striped bordered size="sm" itemsPerPage={5} pagination scopedSlots={{ 'opciones': (item) => ( <tr> <td> <Link to={`Actividades/${item.id}`}> <CButton size="lg"><BsSearch /></CButton> </Link> </td> </tr> ) }} /> </CCardBody> </CCard> </CCol> </CRow> </> ); } } export default Docentes
tomaszkowalczyk94/warhammer-rpg-helper
src/main/java/warhammerrpg/database/entity/PersonMethod.java
package warhammerrpg.database.entity; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface PersonMethod{ public enum Type {GETTER, SETTER}; Person.Field forField(); Type type(); }
jainsakshi2395/linux
arch/csky/abiv1/inc/abi/switch_context.h
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef __ABI_CSKY_PTRACE_H #define __ABI_CSKY_PTRACE_H struct switch_stack { unsigned long r8; unsigned long r9; unsigned long r10; unsigned long r11; unsigned long r12; unsigned long r13; unsigned long r14; unsigned long r15; }; #endif /* __ABI_CSKY_PTRACE_H */
ville-k/vinn
benchmarks/matrix_benchmarks.cpp
#include "benchmarks.h" #include "vi/la.h" static void BM_matrix_scalar_multiply(benchmark::State& state) { size_t context_index = state.range_x(); size_t size = state.range_y(); vi::la::context& context = *benchmarks::all_contexts()[context_index]; vi::la::matrix m(context, size, size, 2.0); while (state.KeepRunning()) { vi::la::matrix result = m * 2.0; } size_t flops_per_iteration = size * size; size_t bytes_per_iteration = flops_per_iteration * sizeof(float); state.SetBytesProcessed(state.iterations() * bytes_per_iteration); state.SetItemsProcessed(state.iterations() * flops_per_iteration); } static void BM_matrix_matrix_multiply(benchmark::State& state) { size_t context_index = state.range_x(); size_t size = state.range_y(); vi::la::context& context = *benchmarks::all_contexts()[context_index]; vi::la::matrix a(context, size, size, 2.0); vi::la::matrix b(context, size, size, 2.0); while (state.KeepRunning()) { vi::la::matrix result = a * b; } // x^2 * (x multiplies + x additions) size_t flops_per_iteration = (size + size) * size * size; size_t bytes_per_iteration = flops_per_iteration * sizeof(float); state.SetBytesProcessed(state.iterations() * bytes_per_iteration); state.SetItemsProcessed(state.iterations() * flops_per_iteration); } static void BM_matrix_sub_matrix(benchmark::State& state) { size_t context_index = state.range_x(); size_t size = state.range_y(); vi::la::context& context = *benchmarks::all_contexts()[context_index]; const size_t MAX_SIZE = 512; vi::la::matrix m(context, MAX_SIZE, MAX_SIZE, 2.0); while (state.KeepRunning()) { vi::la::matrix sub_matrix = m.sub_matrix(0, size - 1, 0, size - 1); } size_t flops_per_iteration = size * size; size_t bytes_per_iteration = flops_per_iteration * sizeof(float); state.SetBytesProcessed(state.iterations() * bytes_per_iteration); state.SetItemsProcessed(state.iterations() * flops_per_iteration); } static void BM_matrix_transpose(benchmark::State& state) { size_t context_index = state.range_x(); size_t size = state.range_y(); vi::la::context& context = *benchmarks::all_contexts()[context_index]; vi::la::matrix m(context, size, size, 2.0); while (state.KeepRunning()) { vi::la::matrix result = m.transpose(); } size_t flops_per_iteration = size * size; size_t bytes_per_iteration = flops_per_iteration * sizeof(float); state.SetBytesProcessed(state.iterations() * bytes_per_iteration); state.SetItemsProcessed(state.iterations() * flops_per_iteration); } using benchmarks::all_contexts_16_to_512; BENCHMARK(BM_matrix_scalar_multiply)->Apply(all_contexts_16_to_512); BENCHMARK(BM_matrix_matrix_multiply)->Apply(all_contexts_16_to_512); BENCHMARK(BM_matrix_sub_matrix)->Apply(all_contexts_16_to_512); BENCHMARK(BM_matrix_transpose)->Apply(all_contexts_16_to_512);
emlowry/AIEFramework
PhysX-3.2.4_PC_SDK_Core/Source/PhysXCharacterKinematic/src/CctCharacterController.cpp
<reponame>emlowry/AIEFramework // This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include <assert.h> #include "CctCharacterController.h" #include "CctSweptBox.h" #include "CctSweptCapsule.h" #include "CctObstacleContext.h" #include "CctUtils.h" #include "PxController.h" #include "PxRigidDynamic.h" #include "PxShape.h" #include "PxBoxGeometry.h" #include "PxCapsuleGeometry.h" #include "PxSphereGeometry.h" #include "PxFiltering.h" #include "PxGeometryQuery.h" #include "GuGeometryQuery.h" #include "CmRenderOutput.h" #include "PsMathUtils.h" #include "PsUtilities.h" #include "PxSceneQueryReport.h" #include "PxShapeExt.h" #include "PxMathUtils.h" #include "GuIntersectionBoxBox.h" #include "GuDistanceSegmentBox.h" // PT: TODO: remove those includes.... shouldn't be allowed from here #include "PxControllerObstacles.h" // (*) #include "CctInternalStructs.h" // (*) #include "PxControllerManager.h" // (*) #include "PxControllerBehavior.h" // (*) #define ASSERT assert #define MAX_ITER 10 using namespace physx; using namespace Cct; static const PxSceneQueryFlags gSweepHintFlags = PxSceneQueryFlag::eDISTANCE | PxSceneQueryFlag::eIMPACT | PxSceneQueryFlag::eNORMAL|PxSceneQueryFlag::eINITIAL_OVERLAP | PxSceneQueryFlag::eDIRECT_SWEEP;//|PxSceneQueryFlag::eINITIAL_OVERLAP_KEEP; static const PxU32 gObstacleDebugColor = (PxU32)PxDebugColor::eARGB_CYAN; //static const PxU32 gCCTBoxDebugColor = (PxU32)PxDebugColor::eARGB_YELLOW; static const PxU32 gTBVDebugColor = (PxU32)PxDebugColor::eARGB_MAGENTA; static const bool gUsePartialUpdates = true; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static const bool gUseLocalSpace = true; static PxVec3 worldToLocal(const PxObstacle& obstacle, const PxExtendedVec3& worldPos) { const PxTransform tr(toVec3(obstacle.mPos), obstacle.mRot); return tr.transformInv(toVec3(worldPos)); } static PxVec3 localToWorld(const PxObstacle& obstacle, const PxVec3& localPos) { const PxTransform tr(toVec3(obstacle.mPos), obstacle.mRot); return tr.transform(localPos); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static PX_INLINE void computeReflexionVector(PxVec3& reflected, const PxVec3& incomingDir, const PxVec3& outwardNormal) { reflected = incomingDir - outwardNormal * 2.0f * (incomingDir.dot(outwardNormal)); } static PX_INLINE void collisionResponse(PxExtendedVec3& targetPosition, const PxExtendedVec3& currentPosition, const PxVec3& currentDir, const PxVec3& hitNormal, PxF32 bump, PxF32 friction, bool normalize=false) { // Compute reflect direction PxVec3 reflectDir; computeReflexionVector(reflectDir, currentDir, hitNormal); reflectDir.normalize(); // Decompose it PxVec3 normalCompo, tangentCompo; Ps::decomposeVector(normalCompo, tangentCompo, reflectDir, hitNormal); // Compute new destination position const PxExtended amplitude = distance(targetPosition, currentPosition); targetPosition = currentPosition; if(bump!=0.0f) { if(normalize) normalCompo.normalize(); targetPosition += normalCompo*float(bump*amplitude); } if(friction!=0.0) { if(normalize) tangentCompo.normalize(); targetPosition += tangentCompo*float(friction*amplitude); } } static PX_INLINE void relocateBox(PxBoxGeometry& boxGeom, PxTransform& pose, const PxExtendedVec3& center, const PxVec3& extents, const PxExtendedVec3& origin, const PxQuat& quatFromUp) { boxGeom.halfExtents = extents; pose.p.x = float(center.x - origin.x); pose.p.y = float(center.y - origin.y); pose.p.z = float(center.z - origin.z); pose.q = quatFromUp; } static PX_INLINE void relocateBox(PxBoxGeometry& boxGeom, PxTransform& pose, const TouchedUserBox& userBox) { relocateBox(boxGeom, pose, userBox.mBox.center, userBox.mBox.extents, userBox.mOffset, userBox.mBox.rot); } static PX_INLINE void relocateBox(PxBoxGeometry& boxGeom, PxTransform& pose, const TouchedBox& box) { boxGeom.halfExtents = box.mExtents; pose.p = box.mCenter; pose.q = box.mRot; } static PX_INLINE void relocateCapsule( PxCapsuleGeometry& capsuleGeom, PxTransform& pose, const SweptCapsule* sc, const PxQuat& quatFromUp, const PxExtendedVec3& center, const PxExtendedVec3& origin) { capsuleGeom.radius = sc->mRadius; capsuleGeom.halfHeight = 0.5f * sc->mHeight; pose.p.x = float(center.x - origin.x); pose.p.y = float(center.y - origin.y); pose.p.z = float(center.z - origin.z); pose.q = quatFromUp; } static PX_INLINE void relocateCapsule(PxCapsuleGeometry& capsuleGeom, PxTransform& pose, const PxVec3& p0, const PxVec3& p1, PxReal radius) { capsuleGeom.radius = radius; pose = PxTransformFromSegment(p0, p1, &capsuleGeom.halfHeight); } static PX_INLINE void relocateCapsule(PxCapsuleGeometry& capsuleGeom, PxTransform& pose, const TouchedUserCapsule& userCapsule) { PxVec3 p0, p1; p0.x = float(userCapsule.mCapsule.p0.x - userCapsule.mOffset.x); p0.y = float(userCapsule.mCapsule.p0.y - userCapsule.mOffset.y); p0.z = float(userCapsule.mCapsule.p0.z - userCapsule.mOffset.z); p1.x = float(userCapsule.mCapsule.p1.x - userCapsule.mOffset.x); p1.y = float(userCapsule.mCapsule.p1.y - userCapsule.mOffset.y); p1.z = float(userCapsule.mCapsule.p1.z - userCapsule.mOffset.z); relocateCapsule(capsuleGeom, pose, p0, p1, userCapsule.mCapsule.radius); } static bool SweepBoxUserBox(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eBOX); ASSERT(geom->mType==TouchedGeomType::eUSER_BOX); const SweptBox* SB = static_cast<const SweptBox*>(volume); const TouchedUserBox* TC = static_cast<const TouchedUserBox*>(geom); PxBoxGeometry boxGeom0; PxTransform boxPose0; // To precompute relocateBox(boxGeom0, boxPose0, center, SB->mExtents, TC->mOffset, test->mUserParams.mQuatFromUp); PxBoxGeometry boxGeom1; PxTransform boxPose1; relocateBox(boxGeom1, boxPose1, *TC); PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom0, boxPose0, boxGeom1, boxPose1, sweepHit, gSweepHintFlags)) return false; if(sweepHit.distance >= impact.mDistance) return false; impact.mWorldNormal = sweepHit.normal; impact.mDistance = sweepHit.distance; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; impact.setWorldPos(sweepHit.impact, TC->mOffset); return true; } static bool SweepBoxUserCapsule(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eBOX); ASSERT(geom->mType==TouchedGeomType::eUSER_CAPSULE); const SweptBox* SB = static_cast<const SweptBox*>(volume); const TouchedUserCapsule* TC = static_cast<const TouchedUserCapsule*>(geom); PxBoxGeometry boxGeom; PxTransform boxPose; // To precompute relocateBox(boxGeom, boxPose, center, SB->mExtents, TC->mOffset, test->mUserParams.mQuatFromUp); PxCapsuleGeometry capsuleGeom; PxTransform capsulePose; relocateCapsule(capsuleGeom, capsulePose, *TC); PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom, boxPose, capsuleGeom, capsulePose, sweepHit, gSweepHintFlags)) return false; if(sweepHit.distance >= impact.mDistance) return false; impact.mDistance = sweepHit.distance; impact.mWorldNormal = sweepHit.normal; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; if(sweepHit.distance==0.0f) { setZero(impact.mWorldPos); impact.mWorldNormal = PxVec3(0); // ### this fixes the bug on box-capsule but I'm not sure it's valid: // - when the capsule is moving, it's ok to return false // - when the box is moving, it's not! because it means the motion is completely free!! return false; } else //TO CHECK: Investigate whether any significant performance improvement can be achieved through // making the impact point computation optional in the sweep calls and compute it later /*{ // ### check this float t; PxVec3 p; float d = gUtilLib->PxSegmentOBBSqrDist(Capsule, Box0.center, Box0.extents, Box0.rot, &t, &p); Box0.rot.multiply(p,p); impact.mWorldPos.x = p.x + Box0.center.x + TC->mOffset.x; impact.mWorldPos.y = p.y + Box0.center.y + TC->mOffset.y; impact.mWorldPos.z = p.z + Box0.center.z + TC->mOffset.z; }*/ { impact.setWorldPos(sweepHit.impact, TC->mOffset); } return true; } static bool sweepVolumeVsMesh( const SweepTest* sweepTest, const TouchedMesh* touchedMesh, SweptContact& impact, const PxVec3& unitDir, const PxGeometry& geom, const PxTransform& pose, PxU32 nbTris, const PxTriangle* triangles, PxU32 cachedIndex) { PxSweepHit sweepHit; if(Gu::GeometryQuery::sweep(unitDir, impact.mDistance, geom, pose, nbTris, triangles, sweepHit, gSweepHintFlags, &cachedIndex)) { if(sweepHit.distance >= impact.mDistance) return false; impact.mDistance = sweepHit.distance; impact.mWorldNormal = sweepHit.normal; impact.setWorldPos(sweepHit.impact, touchedMesh->mOffset); // Returned index is only between 0 and nbTris, i.e. it indexes the array of cached triangles, not the original mesh. PX_ASSERT(sweepHit.faceIndex < nbTris); sweepTest->mCachedTriIndex[sweepTest->mCachedTriIndexIndex] = sweepHit.faceIndex; // The CCT loop will use the index from the start of the cache... impact.mInternalIndex = sweepHit.faceIndex + touchedMesh->mIndexWorldTriangles; const PxU32* triangleIndices = &sweepTest->mTriangleIndices[touchedMesh->mIndexWorldTriangles]; impact.mTriangleIndex = triangleIndices[sweepHit.faceIndex]; return true; } return false; } static bool SweepBoxMesh(const SweepTest* sweep_test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eBOX); ASSERT(geom->mType==TouchedGeomType::eMESH); const SweptBox* SB = static_cast<const SweptBox*>(volume); const TouchedMesh* TM = static_cast<const TouchedMesh*>(geom); PxU32 nbTris = TM->mNbTris; if(!nbTris) return false; // Fetch triangle data for current mesh (the stream may contain triangles from multiple meshes) const PxTriangle* T = &sweep_test->mWorldTriangles[TM->mIndexWorldTriangles]; // PT: this only really works when the CCT collides with a single mesh, but that's the most common case. When it doesn't, there's just no speedup but it still works. PxU32 CachedIndex = sweep_test->mCachedTriIndex[sweep_test->mCachedTriIndexIndex]; if(CachedIndex>=nbTris) CachedIndex=0; PxBoxGeometry boxGeom; boxGeom.halfExtents = SB->mExtents; PxTransform boxPose(PxVec3(float(center.x - TM->mOffset.x), float(center.y - TM->mOffset.y), float(center.z - TM->mOffset.z)), sweep_test->mUserParams.mQuatFromUp); // Precompute return sweepVolumeVsMesh(sweep_test, TM, impact, dir, boxGeom, boxPose, nbTris, T, CachedIndex); } static bool SweepCapsuleMesh( const SweepTest* sweep_test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eCAPSULE); ASSERT(geom->mType==TouchedGeomType::eMESH); const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume); const TouchedMesh* TM = static_cast<const TouchedMesh*>(geom); PxU32 nbTris = TM->mNbTris; if(!nbTris) return false; // Fetch triangle data for current mesh (the stream may contain triangles from multiple meshes) const PxTriangle* T = &sweep_test->mWorldTriangles[TM->mIndexWorldTriangles]; // PT: this only really works when the CCT collides with a single mesh, but that's the most common case. // When it doesn't, there's just no speedup but it still works. PxU32 CachedIndex = sweep_test->mCachedTriIndex[sweep_test->mCachedTriIndexIndex]; if(CachedIndex>=nbTris) CachedIndex=0; PxCapsuleGeometry capsuleGeom; PxTransform capsulePose; relocateCapsule(capsuleGeom, capsulePose, SC, sweep_test->mUserParams.mQuatFromUp, center, TM->mOffset); return sweepVolumeVsMesh(sweep_test, TM, impact, dir, capsuleGeom, capsulePose, nbTris, T, CachedIndex); } static bool SweepBoxBox(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eBOX); ASSERT(geom->mType==TouchedGeomType::eBOX); const SweptBox* SB = static_cast<const SweptBox*>(volume); const TouchedBox* TB = static_cast<const TouchedBox*>(geom); PxBoxGeometry boxGeom0; PxTransform boxPose0; // To precompute relocateBox(boxGeom0, boxPose0, center, SB->mExtents, TB->mOffset, test->mUserParams.mQuatFromUp); PxBoxGeometry boxGeom1; PxTransform boxPose1; relocateBox(boxGeom1, boxPose1, *TB); PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom0, boxPose0, boxGeom1, boxPose1, sweepHit, gSweepHintFlags)) return false; if(sweepHit.distance >= impact.mDistance) return false; impact.mWorldNormal = sweepHit.normal; impact.mDistance = sweepHit.distance; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; impact.setWorldPos(sweepHit.impact, TB->mOffset); return true; } static bool SweepBoxSphere(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eBOX); ASSERT(geom->mType==TouchedGeomType::eSPHERE); const SweptBox* SB = static_cast<const SweptBox*>(volume); const TouchedSphere* TS = static_cast<const TouchedSphere*>(geom); PxBoxGeometry boxGeom; PxTransform boxPose; // To precompute relocateBox(boxGeom, boxPose, center, SB->mExtents, TS->mOffset, test->mUserParams.mQuatFromUp); PxSphereGeometry sphereGeom; sphereGeom.radius = TS->mRadius; PxTransform spherePose; spherePose.p = TS->mCenter; spherePose.q = PxQuat::createIdentity(); PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom, boxPose, sphereGeom, spherePose, sweepHit, gSweepHintFlags)) return false; impact.mDistance = sweepHit.distance; impact.mWorldNormal = sweepHit.normal; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; if(sweepHit.distance==0.0f) { setZero(impact.mWorldPos); impact.mWorldNormal = PxVec3(0); return false; } else //TO CHECK: Investigate whether any significant performance improvement can be achieved through // making the impact point computation optional in the sweep calls and compute it later /* { // The sweep test doesn't compute the impact point automatically, so we have to do it here. PxVec3 NewSphereCenter = TS->mSphere.center - d * dir; PxVec3 Closest; gUtilLib->PxPointOBBSqrDist(NewSphereCenter, Box0.center, Box0.extents, Box0.rot, &Closest); // Compute point on the box, after sweep Box0.rot.multiply(Closest, Closest); impact.mWorldPos.x = TS->mOffset.x + Closest.x + Box0.center.x + d * dir.x; impact.mWorldPos.y = TS->mOffset.y + Closest.y + Box0.center.y + d * dir.y; impact.mWorldPos.z = TS->mOffset.z + Closest.z + Box0.center.z + d * dir.z; impact.mWorldNormal = -impact.mWorldNormal; }*/ { impact.setWorldPos(sweepHit.impact, TS->mOffset); } return true; } static bool SweepBoxCapsule(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eBOX); ASSERT(geom->mType==TouchedGeomType::eCAPSULE); const SweptBox* SB = static_cast<const SweptBox*>(volume); const TouchedCapsule* TC = static_cast<const TouchedCapsule*>(geom); PxBoxGeometry boxGeom; PxTransform boxPose; // To precompute relocateBox(boxGeom, boxPose, center, SB->mExtents, TC->mOffset, test->mUserParams.mQuatFromUp); PxCapsuleGeometry capsuleGeom; PxTransform capsulePose; relocateCapsule(capsuleGeom, capsulePose, TC->mP0, TC->mP1, TC->mRadius); PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(dir, impact.mDistance, boxGeom, boxPose, capsuleGeom, capsulePose, sweepHit, gSweepHintFlags)) return false; if(sweepHit.distance >= impact.mDistance) return false; impact.mDistance = sweepHit.distance; impact.mWorldNormal = sweepHit.normal; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; if(sweepHit.distance==0.0f) { setZero(impact.mWorldPos); impact.mWorldNormal = PxVec3(0); // ### this fixes the bug on box-capsule but I'm not sure it's valid: // - when the capsule is moving, it's ok to return false // - when the box is moving, it's not! because it means the motion is completely free!! return false; } else //TO CHECK: Investigate whether any significant performance improvement can be achieved through // making the impact point computation optional in the sweep calls and compute it later /*{ float t; PxVec3 p; float d = gUtilLib->PxSegmentOBBSqrDist(TC->mCapsule, Box0.center, Box0.extents, Box0.rot, &t, &p); Box0.rot.multiply(p,p); impact.mWorldPos.x = p.x + Box0.center.x + TC->mOffset.x; impact.mWorldPos.y = p.y + Box0.center.y + TC->mOffset.y; impact.mWorldPos.z = p.z + Box0.center.z + TC->mOffset.z; }*/ { impact.setWorldPos(sweepHit.impact, TC->mOffset); } return true; } static bool SweepCapsuleBox(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eCAPSULE); ASSERT(geom->mType==TouchedGeomType::eBOX); const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume); const TouchedBox* TB = static_cast<const TouchedBox*>(geom); PxCapsuleGeometry capsuleGeom; PxTransform capsulePose; relocateCapsule(capsuleGeom, capsulePose, SC, test->mUserParams.mQuatFromUp, center, TB->mOffset); PxBoxGeometry boxGeom; PxTransform boxPose; // To precompute relocateBox(boxGeom, boxPose, *TB); // The box and capsule coordinates are relative to the center of the cached bounding box PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom, capsulePose, boxGeom, boxPose, sweepHit, gSweepHintFlags)) return false; if(sweepHit.distance >= impact.mDistance) return false; impact.mDistance = sweepHit.distance; impact.mWorldNormal = sweepHit.normal; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; if(sweepHit.distance==0.0f) { // ### this part makes the capsule goes through the box sometimes setZero(impact.mWorldPos); impact.mWorldNormal = PxVec3(0); // ### this fixes the bug on box-capsule but I'm not sure it's valid: // - when the capsule is moving, it's ok to return false // - when the box is moving, it's not! because it means the motion is completely free!! return false; } else //TO CHECK: Investigate whether any significant performance improvement can be achieved through // making the impact point computation optional in the sweep calls and compute it later /*{ float t; PxVec3 p; float d = gUtilLib->PxSegmentOBBSqrDist(Capsule, TB->mBox.center, TB->mBox.extents, TB->mBox.rot, &t, &p); TB->mBox.rot.multiply(p,p); p += TB->mBox.center; impact.mWorldPos.x = p.x + TB->mOffset.x; impact.mWorldPos.y = p.y + TB->mOffset.y; impact.mWorldPos.z = p.z + TB->mOffset.z; }*/ { impact.setWorldPos(sweepHit.impact, TB->mOffset); } return true; } static bool SweepCapsuleSphere(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eCAPSULE); ASSERT(geom->mType==TouchedGeomType::eSPHERE); const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume); const TouchedSphere* TS = static_cast<const TouchedSphere*>(geom); PxCapsuleGeometry capsuleGeom; PxTransform capsulePose; relocateCapsule(capsuleGeom, capsulePose, SC, test->mUserParams.mQuatFromUp, center, TS->mOffset); PxSphereGeometry sphereGeom; sphereGeom.radius = TS->mRadius; PxTransform spherePose; spherePose.p = TS->mCenter; spherePose.q = PxQuat::createIdentity(); PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(-dir, impact.mDistance, sphereGeom, spherePose, capsuleGeom, capsulePose, sweepHit, gSweepHintFlags)) return false; if(sweepHit.distance >= impact.mDistance) return false; impact.mDistance = sweepHit.distance; impact.mWorldNormal = sweepHit.normal; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; if(sweepHit.distance==0.0f) { setZero(impact.mWorldPos); impact.mWorldNormal = PxVec3(0); return false; } else { impact.setWorldPos(sweepHit.impact, TS->mOffset); } return true; } static bool SweepCapsuleCapsule(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eCAPSULE); ASSERT(geom->mType==TouchedGeomType::eCAPSULE); const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume); const TouchedCapsule* TC = static_cast<const TouchedCapsule*>(geom); PxCapsuleGeometry capsuleGeom0; PxTransform capsulePose0; relocateCapsule(capsuleGeom0, capsulePose0, SC, test->mUserParams.mQuatFromUp, center, TC->mOffset); PxCapsuleGeometry capsuleGeom1; PxTransform capsulePose1; relocateCapsule(capsuleGeom1, capsulePose1, TC->mP0, TC->mP1, TC->mRadius); PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom0, capsulePose0, capsuleGeom1, capsulePose1, sweepHit, gSweepHintFlags)) return false; if(sweepHit.distance >= impact.mDistance) return false; impact.mDistance = sweepHit.distance; impact.mWorldNormal = sweepHit.normal; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; if(sweepHit.distance==0.0f) { setZero(impact.mWorldPos); impact.mWorldNormal = PxVec3(0); return false; } else { impact.setWorldPos(sweepHit.impact, TC->mOffset); } return true; } static bool SweepCapsuleUserCapsule(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eCAPSULE); ASSERT(geom->mType==TouchedGeomType::eUSER_CAPSULE); const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume); const TouchedUserCapsule* TC = static_cast<const TouchedUserCapsule*>(geom); PxCapsuleGeometry capsuleGeom0; PxTransform capsulePose0; relocateCapsule(capsuleGeom0, capsulePose0, SC, test->mUserParams.mQuatFromUp, center, TC->mOffset); PxCapsuleGeometry capsuleGeom1; PxTransform capsulePose1; relocateCapsule(capsuleGeom1, capsulePose1, *TC); PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom0, capsulePose0, capsuleGeom1, capsulePose1, sweepHit, gSweepHintFlags)) return false; if(sweepHit.distance >= impact.mDistance) return false; impact.mDistance = sweepHit.distance; impact.mWorldNormal = sweepHit.normal; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; if(sweepHit.distance==0.0f) { setZero(impact.mWorldPos); impact.mWorldNormal = PxVec3(0); return false; } else { impact.setWorldPos(sweepHit.impact, TC->mOffset); } return true; } static bool SweepCapsuleUserBox(const SweepTest* test, const SweptVolume* volume, const TouchedGeom* geom, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { ASSERT(volume->getType()==SweptVolumeType::eCAPSULE); ASSERT(geom->mType==TouchedGeomType::eUSER_BOX); const SweptCapsule* SC = static_cast<const SweptCapsule*>(volume); const TouchedUserBox* TB = static_cast<const TouchedUserBox*>(geom); PxCapsuleGeometry capsuleGeom; PxTransform capsulePose; relocateCapsule(capsuleGeom, capsulePose, SC, test->mUserParams.mQuatFromUp, center, TB->mOffset); PxBoxGeometry boxGeom; PxTransform boxPose; relocateBox(boxGeom, boxPose, *TB); PxSweepHit sweepHit; if(!PxGeometryQuery::sweep(dir, impact.mDistance, capsuleGeom, capsulePose, boxGeom, boxPose, sweepHit, gSweepHintFlags)) return false; if(sweepHit.distance >= impact.mDistance) return false; impact.mDistance = sweepHit.distance; impact.mWorldNormal = sweepHit.normal; impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; if(sweepHit.distance==0.0f) { // ### this part makes the capsule goes through the box sometimes setZero(impact.mWorldPos); impact.mWorldNormal = PxVec3(0); // ### this fixes the bug on box-capsule but I'm not sure it's valid: // - when the capsule is moving, it's ok to return false // - when the box is moving, it's not! because it means the motion is completely free!! return false; } else //TO CHECK: Investigate whether any significant performance improvement can be achieved through // making the impact point computation optional in the sweep calls and compute it later /*{ // ### check this float t; PxVec3 p; float d = gUtilLib->PxSegmentOBBSqrDist(Capsule, Box.center, Box.extents, Box.rot, &t, &p); p += Box.center; impact.mWorldPos.x = p.x + TB->mOffset.x; impact.mWorldPos.y = p.y + TB->mOffset.y; impact.mWorldPos.z = p.z + TB->mOffset.z; }*/ { impact.setWorldPos(sweepHit.impact, TB->mOffset); } return true; } typedef bool (*SweepFunc) (const SweepTest*, const SweptVolume*, const TouchedGeom*, const PxExtendedVec3&, const PxVec3&, SweptContact&); static SweepFunc gSweepMap[SweptVolumeType::eLAST][TouchedGeomType::eLAST] = { // Box funcs { SweepBoxUserBox, SweepBoxUserCapsule, SweepBoxMesh, SweepBoxBox, SweepBoxSphere, SweepBoxCapsule }, // Capsule funcs { SweepCapsuleUserBox, SweepCapsuleUserCapsule, SweepCapsuleMesh, SweepCapsuleBox, SweepCapsuleSphere, SweepCapsuleCapsule } }; PX_COMPILE_TIME_ASSERT(sizeof(gSweepMap)==SweptVolumeType::eLAST*TouchedGeomType::eLAST*sizeof(SweepFunc)); static bool CollideGeoms( const SweepTest* sweep_test, const SweptVolume& volume, const IntArray& geom_stream, const PxExtendedVec3& center, const PxVec3& dir, SweptContact& impact) { impact.mInternalIndex = PX_INVALID_U32; impact.mTriangleIndex = PX_INVALID_U32; impact.mGeom = NULL; static const PxU32 GeomSizes[] = { sizeof(TouchedUserBox), sizeof(TouchedUserCapsule), sizeof(TouchedMesh), sizeof(TouchedBox), sizeof(TouchedSphere), sizeof(TouchedCapsule), }; bool Status = false; const PxU32* Data = geom_stream.begin(); const PxU32* Last = geom_stream.end(); while(Data!=Last) { TouchedGeom* CurrentGeom = (TouchedGeom*)Data; SweepFunc ST = gSweepMap[volume.getType()][CurrentGeom->mType]; if(ST) { SweptContact C; C.mDistance = impact.mDistance; // Initialize with current best distance C.mInternalIndex = PX_INVALID_U32; C.mTriangleIndex = PX_INVALID_U32; if((ST)(sweep_test, &volume, CurrentGeom, center, dir, C)) { if(C.mDistance<impact.mDistance) { impact = C; impact.mGeom = CurrentGeom; Status = true; if(impact.mDistance <= 0) // there is no point testing for closer hits return Status; // since we are touching a shape already } } } PxU8* ptr = (PxU8*)Data; ptr += GeomSizes[CurrentGeom->mType]; Data = (const PxU32*)ptr; } return Status; } CCTParams::CCTParams() : mNonWalkableMode (PxCCTNonWalkableMode::ePREVENT_CLIMBING), mQuatFromUp (PxQuat::createIdentity()), mUpDirection (PxVec3(0.0f)), mSlopeLimit (0.0f), mContactOffset (0.0f), mStepOffset (0.0f), mInvisibleWallHeight (0.0f), mMaxJumpHeight (0.0f), mMaxEdgeLength2 (0.0f), mTessellation (false), mHandleSlope (false) { } SweepTest::SweepTest() : mRenderBuffer (NULL), mRenderFlags (0), mWorldTriangles (PX_DEBUG_EXP("sweepTestTrigs")), mTriangleIndices (PX_DEBUG_EXP("sweepTestTriangleIndices")), mGeomStream (PX_DEBUG_EXP("sweepTestStream")), mSQTimeStamp (0xffffffff), mNbFullUpdates (0), mNbPartialUpdates (0), mNbIterations (0), mFlags (0) { mCachedTBV.setEmpty(); mCachedTriIndexIndex = 0; mCachedTriIndex[0] = mCachedTriIndex[1] = mCachedTriIndex[2] = 0; mNbCachedStatic = 0; mNbCachedT = 0; mTouchedShape = NULL; mTouchedActor = NULL; mTouchedObstacleHandle = INVALID_OBSTACLE_HANDLE; mTouchedPos = PxVec3(0); mTouchedPosShape_Local = PxVec3(0); mTouchedPosShape_World = PxVec3(0); mTouchedPosObstacle_Local = PxVec3(0); mTouchedPosObstacle_World = PxVec3(0); // mVolumeGrowth = 1.2f; // Must be >1.0f and not too big mVolumeGrowth = 1.5f; // Must be >1.0f and not too big // mVolumeGrowth = 2.0f; // Must be >1.0f and not too big mContactNormalDownPass = PxVec3(0.0f); mContactNormalSidePass = PxVec3(0.0f); mTouchedTriMin = 0.0f; mTouchedTriMax = 0.0f; } SweepTest::~SweepTest() { if(mTouchedActor) { mTouchedActor->unregisterObserver(*this); } } void SweepTest::onObstacleAdded(ObstacleHandle index, const PxObstacleContext* context, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance ) { if(mTouchedObstacleHandle != INVALID_OBSTACLE_HANDLE) { // check if new obstacle is closer const ObstacleContext* obstContext = static_cast<const ObstacleContext*> (context); PxRaycastHit obstacleHit; const PxObstacle* obst = obstContext->raycastSingle(obstacleHit,index,origin,unitDir,distance); if(obst && (obstacleHit.impact.dot(unitDir))<(mTouchedPosObstacle_World.dot(unitDir))) { PX_ASSERT(obstacleHit.distance<=distance); mTouchedObstacleHandle = index; if(!gUseLocalSpace) { mTouchedPos = toVec3(obst->mPos); } else { mTouchedPosObstacle_World = obstacleHit.impact; mTouchedPosObstacle_Local = worldToLocal(*obst, PxExtendedVec3(obstacleHit.impact.x,obstacleHit.impact.y,obstacleHit.impact.z)); } } } } void SweepTest::onObstacleRemoved(ObstacleHandle index, ObstacleHandle movedIndex) { if(index == mTouchedObstacleHandle) { mTouchedObstacleHandle = INVALID_OBSTACLE_HANDLE; } if(movedIndex == mTouchedObstacleHandle) { mTouchedObstacleHandle = index; } } void SweepTest::onObstacleUpdated(ObstacleHandle index, const PxObstacleContext* context, const PxVec3& origin, const PxVec3& unitDir, const PxReal distance) { if(index == mTouchedObstacleHandle) { // check if updated obstacle is still closest const ObstacleContext* obstContext = static_cast<const ObstacleContext*> (context); PxRaycastHit obstacleHit; ObstacleHandle closestHandle = INVALID_OBSTACLE_HANDLE; const PxObstacle* obst = obstContext->raycastSingle(obstacleHit,origin,unitDir,distance,closestHandle); if(mTouchedObstacleHandle == closestHandle) return; if(obst) { PX_ASSERT(obstacleHit.distance<=distance); mTouchedObstacleHandle = closestHandle; if(!gUseLocalSpace) { mTouchedPos = toVec3(obst->mPos); } else { mTouchedPosObstacle_World = obstacleHit.impact; mTouchedPosObstacle_Local = worldToLocal(*obst, PxExtendedVec3(obstacleHit.impact.x,obstacleHit.impact.y,obstacleHit.impact.z)); } } } } static PxBounds3 getBounds3(const PxExtendedBounds3& extended) { return PxBounds3(toVec3(extended.minimum), toVec3(extended.maximum)); // LOSS OF ACCURACY } // PT: finds both touched CCTs and touched user-defined obstacles void SweepTest::findTouchedObstacles(const UserObstacles& userObstacles, const PxExtendedBounds3& worldBox) { PxExtendedVec3 Origin; // Will be TouchedGeom::mOffset getCenter(worldBox, Origin); { const PxU32 nbBoxes = userObstacles.mNbBoxes; const PxExtendedBox* boxes = userObstacles.mBoxes; const void** boxUserData = userObstacles.mBoxUserData; const PxBounds3 singlePrecisionWorldBox = getBounds3(worldBox); // Find touched boxes, i.e. other box controllers for(PxU32 i=0;i<nbBoxes;i++) { Gu::Box obb; obb.rot = PxMat33(boxes[i].rot); // #### PT: TODO: useless conversion here obb.center = toVec3(boxes[i].center); // LOSS OF ACCURACY obb.extents = boxes[i].extents; if(!Gu::intersectOBBAABB(obb, singlePrecisionWorldBox)) continue; TouchedUserBox* UserBox = (TouchedUserBox*)reserve(mGeomStream, sizeof(TouchedUserBox)/sizeof(PxU32)); UserBox->mType = TouchedGeomType::eUSER_BOX; UserBox->mUserData = boxUserData[i]; UserBox->mOffset = Origin; UserBox->mBox = boxes[i]; } } { // Find touched capsules, i.e. other capsule controllers const PxU32 nbCapsules = userObstacles.mNbCapsules; const PxExtendedCapsule* capsules = userObstacles.mCapsules; const void** capsuleUserData = userObstacles.mCapsuleUserData; PxExtendedVec3 Center; PxVec3 Extents; getCenter(worldBox, Center); getExtents(worldBox, Extents); for(PxU32 i=0;i<nbCapsules;i++) { // PT: do a quick AABB check first, to avoid calling the SDK too much const PxF32 r = capsules[i].radius; const float capMinx = PxMin(capsules[i].p0.x, capsules[i].p1.x); const float capMaxx = PxMax(capsules[i].p0.x, capsules[i].p1.x); if((capMinx - r > worldBox.maximum.x) || (worldBox.minimum.x > capMaxx + r)) continue; const float capMiny = PxMin(capsules[i].p0.y, capsules[i].p1.y); const float capMaxy = PxMax(capsules[i].p0.y, capsules[i].p1.y); if((capMiny - r > worldBox.maximum.y) || (worldBox.minimum.y > capMaxy + r)) continue; const float capMinz = PxMin(capsules[i].p0.z, capsules[i].p1.z); const float capMaxz = PxMax(capsules[i].p0.z, capsules[i].p1.z); if((capMinz - r > worldBox.maximum.z) || (worldBox.minimum.z > capMaxz + r)) continue; // PT: more accurate capsule-box test. Not strictly necessary but worth doing if available const PxReal d2 = Gu::distanceSegmentBoxSquared(toVec3(capsules[i].p0), toVec3(capsules[i].p1), toVec3(Center), Extents, PxMat33::createIdentity()); if(d2>r*r) continue; TouchedUserCapsule* UserCapsule = (TouchedUserCapsule*)reserve(mGeomStream, sizeof(TouchedUserCapsule)/sizeof(PxU32)); UserCapsule->mType = TouchedGeomType::eUSER_CAPSULE; UserCapsule->mUserData = capsuleUserData[i]; UserCapsule->mOffset = Origin; UserCapsule->mCapsule = capsules[i]; } } } void SweepTest::updateTouchedGeoms( const InternalCBData_FindTouchedGeom* userData, const UserObstacles& userObstacles, const PxExtendedBounds3& worldBox, const PxControllerFilters& filters) { /* - if this is the first iteration (new frame) we have to redo the dynamic objects & the CCTs. The static objects can be cached. - if this is not, we can cache everything */ // PT: using "worldBox" instead of "mCachedTBV" seems to produce TTP 6207 //#define DYNAMIC_BOX worldBox #define DYNAMIC_BOX mCachedTBV bool NewCachedBox = false; CCTFilter filter; filter.mFilterData = filters.mFilterData; filter.mFilterCallback = filters.mFilterCallback; filter.mPreFilter = filters.mFilterFlags & PxSceneQueryFilterFlag::ePREFILTER; filter.mPostFilter = filters.mFilterFlags & PxSceneQueryFilterFlag::ePOSTFILTER; // PT: detect changes to the static pruning structure bool sceneHasChanged = false; { const PxU32 currentTimestamp = getSceneTimestamp(userData); if(currentTimestamp!=mSQTimeStamp) { mSQTimeStamp = currentTimestamp; sceneHasChanged = true; } } // If the input box is inside the cached box, nothing to do if(gUsePartialUpdates && !sceneHasChanged && worldBox.isInside(mCachedTBV) && !(mFlags & STF_RECREATE_CACHE)) { //printf("CACHEIN%d\n", mFirstUpdate); if(mFlags & STF_FIRST_UPDATE) { mFlags &= ~STF_FIRST_UPDATE; // Only redo the dynamic mGeomStream.forceSize_Unsafe(mNbCachedStatic); mWorldTriangles.forceSize_Unsafe(mNbCachedT); mTriangleIndices.forceSize_Unsafe(mNbCachedT); filter.mStaticShapes = false; if(filters.mFilterFlags & PxSceneQueryFilterFlag::eDYNAMIC) filter.mDynamicShapes = true; findTouchedGeometry(userData, DYNAMIC_BOX, mWorldTriangles, mTriangleIndices, mGeomStream, filter, mUserParams); findTouchedObstacles(userObstacles, DYNAMIC_BOX); mNbPartialUpdates++; } } else { mFlags &= ~STF_RECREATE_CACHE; //printf("CACHEOUTNS=%d\n", mNbCachedStatic); NewCachedBox = true; // Cache BV used for the query mCachedTBV = worldBox; // Grow the volume a bit. The temporal box here doesn't take sliding & collision response into account. // In bad cases it is possible to eventually touch a portion of space not covered by this volume. Just // in case, we grow the initial volume slightly. Then, additional tests are performed within the loop // to make sure the TBV is always correct. There's a tradeoff between the original (artificial) growth // of the volume, and the number of TBV recomputations performed at runtime... scale(mCachedTBV, mVolumeGrowth); // Gather triangles touched by this box. This covers multiple meshes. mWorldTriangles.clear(); mTriangleIndices.clear(); mGeomStream.clear(); mCachedTriIndexIndex = 0; mCachedTriIndex[0] = mCachedTriIndex[1] = mCachedTriIndex[2] = 0; mNbFullUpdates++; if(filters.mFilterFlags & PxSceneQueryFilterFlag::eSTATIC) filter.mStaticShapes = true; filter.mDynamicShapes = false; findTouchedGeometry(userData, mCachedTBV, mWorldTriangles, mTriangleIndices, mGeomStream, filter, mUserParams); mNbCachedStatic = mGeomStream.size(); mNbCachedT = mWorldTriangles.size(); PX_ASSERT(mTriangleIndices.size()==mNbCachedT); filter.mStaticShapes = false; if(filters.mFilterFlags & PxSceneQueryFilterFlag::eDYNAMIC) filter.mDynamicShapes = true; findTouchedGeometry(userData, DYNAMIC_BOX, mWorldTriangles, mTriangleIndices, mGeomStream, filter, mUserParams); // We can't early exit when no tris are touched since we also have to handle the boxes findTouchedObstacles(userObstacles, DYNAMIC_BOX); mFlags &= ~STF_FIRST_UPDATE; //printf("CACHEOUTNSDONE=%d\n", mNbCachedStatic); } if(mRenderBuffer) { // PT: worldBox = temporal BV for this frame Cm::RenderOutput out(*mRenderBuffer); if(mRenderFlags & PxControllerDebugRenderFlags::eTEMPORAL_BV) { out << gTBVDebugColor; out << Cm::DebugBox(getBounds3(worldBox)); } if(mRenderFlags & PxControllerDebugRenderFlags::eCACHED_BV) { if(NewCachedBox) out << (PxU32)(PxDebugColor::eARGB_RED); else out << (PxU32)(PxDebugColor::eARGB_GREEN); out << Cm::DebugBox(getBounds3(mCachedTBV)); } } } // This is the generic sweep test for all swept volumes, but not character-controller specific bool SweepTest::doSweepTest(const InternalCBData_FindTouchedGeom* userData, const InternalCBData_OnHit* userHitData, const UserObstacles& userObstacles, SweptVolume& swept_volume, const PxVec3& direction, PxU32 max_iter, PxU32* nb_collisions, float min_dist, const PxControllerFilters& filters, SweepPass sweepPass) { // Early exit when motion is zero. Since the motion is decomposed into several vectors // and this function is called for each of them, it actually happens quite often. if(direction.isZero()) return false; bool HasMoved = false; mFlags &= ~(STF_VALIDATE_TRIANGLE_DOWN|STF_TOUCH_OTHER_CCT|STF_TOUCH_OBSTACLE); if(mTouchedActor) { mTouchedActor->unregisterObserver(*this); } mTouchedActor = NULL; mTouchedShape = NULL; mTouchedObstacleHandle = INVALID_OBSTACLE_HANDLE; PxExtendedVec3 CurrentPosition = swept_volume.mCenter; PxExtendedVec3 TargetOrientation = swept_volume.mCenter; TargetOrientation += direction; /* if(direction.y==0.0f) { printf("New pass\n"); }*/ PxU32 NbCollisions = 0; while(max_iter--) { mNbIterations++; // Compute current direction PxVec3 CurrentDirection = TargetOrientation - CurrentPosition; /* if(direction.y==0.0f) { printf("CurrentDirection: %f | %f | %f\n", CurrentDirection.x, CurrentDirection.y, CurrentDirection.z); }*/ // Make sure the new TBV is still valid { // Compute temporal bounding box. We could use a capsule or an OBB instead: // - the volume would be smaller // - but the query would be slower // Overall it's unclear whether it's worth it or not. // TODO: optimize this part ? PxExtendedBounds3 TemporalBox; swept_volume.computeTemporalBox(*this, TemporalBox, CurrentPosition, CurrentDirection); // Gather touched geoms updateTouchedGeoms( userData, userObstacles, TemporalBox, filters); } const float Length = CurrentDirection.magnitude(); if(Length<=min_dist) //Use <= to handle the case where min_dist is zero. break; CurrentDirection /= Length; // From Quake2: "if velocity is against the original velocity, stop dead to avoid tiny occilations in sloping corners" if((CurrentDirection.dot(direction)) <= 0.0f) break; // From this point, we're going to update the position at least once HasMoved = true; // Find closest collision SweptContact C; C.mDistance = Length + mUserParams.mContactOffset; if(!CollideGeoms(this, swept_volume, mGeomStream, CurrentPosition, CurrentDirection, C)) { // no collision found => move to desired position CurrentPosition = TargetOrientation; break; } ASSERT(C.mGeom); // If we reach this point, we must have touched a geom bool stopSliding = true; if(C.mGeom->mType==TouchedGeomType::eUSER_BOX || C.mGeom->mType==TouchedGeomType::eUSER_CAPSULE) { // We touched a user object, typically another CCT, but can also be a user-defined obstacle // PT: TODO: technically lines marked with (*) shouldn't be here... revisit later const PxObstacle* touchedObstacle = NULL; // (*) ObstacleHandle touchedObstacleHandle = INVALID_OBSTACLE_HANDLE; // if(mValidateCallback) { PxInternalCBData_OnHit* internalData = (PxInternalCBData_OnHit*)(userHitData); // (*) internalData->touchedObstacle = NULL; // (*) internalData->touchedObstacleHandle = INVALID_OBSTACLE_HANDLE; const PxU32 behaviorFlags = userHitCallback(userHitData, C, CurrentDirection, Length); stopSliding = (behaviorFlags & PxControllerBehaviorFlag::eCCT_SLIDE)==0; // (*) touchedObstacle = internalData->touchedObstacle; // (*) touchedObstacleHandle = internalData->touchedObstacleHandle; } // printf("INTERNAL: %d\n", int(touchedObstacle)); if(sweepPass==SWEEP_PASS_DOWN) { // (*) if(touchedObstacle) { mFlags |= STF_TOUCH_OBSTACLE; mTouchedObstacleHandle = touchedObstacleHandle; if(!gUseLocalSpace) { mTouchedPos = toVec3(touchedObstacle->mPos); } else { mTouchedPosObstacle_World = toVec3(C.mWorldPos); mTouchedPosObstacle_Local = worldToLocal(*touchedObstacle, C.mWorldPos); } } else { mFlags |= STF_TOUCH_OTHER_CCT; } } } else { PxShape* touchedShape = (PxShape*)C.mGeom->mUserData; PX_ASSERT(touchedShape); PxRigidActor& touchedActor = touchedShape->getActor(); // We touched a normal object if(sweepPass==SWEEP_PASS_DOWN) { mFlags &= ~(STF_TOUCH_OTHER_CCT|STF_TOUCH_OBSTACLE); #ifdef USE_CONTACT_NORMAL_FOR_SLOPE_TEST mFlags |= STF_VALIDATE_TRIANGLE_DOWN; mContactNormalDownPass = C.mWorldNormal; #else // Work out if the shape is attached to a static or dynamic actor. // The slope limit is currently only considered when walking on static actors. // It is ignored for shapes attached attached to dynamics and kinematics. // TODO: 1. should we treat stationary kinematics the same as statics. // 2. should we treat all kinematics the same as statics. // 3. should we treat no kinematics the same as statics. if((touchedActor.getConcreteType() == PxConcreteType::eRIGID_STATIC) && (C.mInternalIndex!=PX_INVALID_U32)) { mFlags |= STF_VALIDATE_TRIANGLE_DOWN; const PxTriangle& touchedTri = mWorldTriangles[C.mInternalIndex]; const PxVec3& upDirection = mUserParams.mUpDirection; const float dp0 = touchedTri.verts[0].dot(upDirection); const float dp1 = touchedTri.verts[1].dot(upDirection); const float dp2 = touchedTri.verts[2].dot(upDirection); float dpmin = dp0; dpmin = physx::intrinsics::selectMin(dpmin, dp1); dpmin = physx::intrinsics::selectMin(dpmin, dp2); float dpmax = dp0; dpmax = physx::intrinsics::selectMax(dpmax, dp1); dpmax = physx::intrinsics::selectMax(dpmax, dp2); PxExtendedVec3 cacheCenter; getCenter(mCachedTBV, cacheCenter); const float offset = upDirection.dot(toVec3(cacheCenter)); mTouchedTriMin = dpmin + offset; mTouchedTriMax = dpmax + offset; touchedTri.normal(mContactNormalDownPass); } #endif // Update touched shape in down pass if (mTouchedActor) mTouchedActor->unregisterObserver(*this); mTouchedShape = touchedShape; mTouchedActor = &touchedActor; mTouchedActor->registerObserver(*this); // mTouchedPos = getShapeGlobalPose(*touchedShape).p; const PxTransform shapeTransform = getShapeGlobalPose(*touchedShape); const PxVec3 worldPos = toVec3(C.mWorldPos); mTouchedPosShape_World = worldPos; mTouchedPosShape_Local = shapeTransform.transformInv(worldPos); } else if(sweepPass==SWEEP_PASS_SIDE) { if((touchedActor.getConcreteType() == PxConcreteType::eRIGID_STATIC) && (C.mInternalIndex!=PX_INVALID_U32)) { mFlags |= STF_VALIDATE_TRIANGLE_SIDE; const PxTriangle& touchedTri = mWorldTriangles[C.mInternalIndex]; touchedTri.normal(mContactNormalSidePass); // printf("%f | %f | %f\n", mContactNormalSidePass.x, mContactNormalSidePass.y, mContactNormalSidePass.z); } } // if(mValidateCallback) { const PxU32 behaviorFlags = shapeHitCallback(userHitData, C, CurrentDirection, Length); stopSliding = (behaviorFlags & PxControllerBehaviorFlag::eCCT_SLIDE)==0; // (*) } } if(sweepPass==SWEEP_PASS_DOWN && !stopSliding) { // Trying to solve the following problem: // - by default, the CCT "friction" is infinite, i.e. a CCT will not slide on a slope (this is by design) // - this produces bad results when a capsule CCT stands on top of another capsule CCT, without sliding. Visually it looks // like the character is standing on the other character's head, it looks bad. So, here, we would like to let the CCT // slide away, i.e. we don't want friction. // So here we simply increase the number of iterations (== let the CCT slide) when the first down collision is with another CCT. if(!NbCollisions) max_iter += 9; // max_iter += 1; } NbCollisions++; // mContactPointHeight = (float)C.mWorldPos[mUserParams.mUpDirection]; // UBI mContactPointHeight = toVec3(C.mWorldPos).dot(mUserParams.mUpDirection); // UBI const float DynSkin = mUserParams.mContactOffset; if(C.mDistance>DynSkin/*+0.01f*/) CurrentPosition += CurrentDirection*(C.mDistance-DynSkin); PxVec3 WorldNormal = C.mWorldNormal; if((mFlags & STF_WALK_EXPERIMENT) && (mUserParams.mNonWalkableMode!=PxCCTNonWalkableMode::eFORCE_SLIDING)) { // Make sure the auto-step doesn't bypass this ! // PT: cancel out normal compo // WorldNormal[mUserParams.mUpDirection]=0.0f; // WorldNormal.normalize(); PxVec3 normalCompo, tangentCompo; Ps::decomposeVector(normalCompo, tangentCompo, WorldNormal, mUserParams.mUpDirection); WorldNormal = tangentCompo; WorldNormal.normalize(); } const float Bump = 0.0f; // ### doesn't work when !=0 because of Quake2 hack! const float Friction = 1.0f; collisionResponse(TargetOrientation, CurrentPosition, CurrentDirection, WorldNormal, Bump, Friction, (mFlags & STF_NORMALIZE_RESPONSE)!=0); } if(nb_collisions) *nb_collisions = NbCollisions; // Final box position that should be reflected in the graphics engine swept_volume.mCenter = CurrentPosition; // If we didn't move, don't update the box position at all (keeping possible lazy-evaluated structures valid) return HasMoved; } void SweepTest::onRelease(const PxObservable& observable) { const PxRigidActor* actor = static_cast<const PxRigidActor*> (&observable); if (actor == mTouchedActor) { mTouchedActor = NULL; mTouchedShape = NULL; mFlags |= STF_RECREATE_CACHE; } } PX_FORCE_INLINE bool PxcIsAlmostZero(const PxVec3& v) { if(PxAbs(v.x)>1e-6 || PxAbs(v.y)>1e-6 || PxAbs(v.z)>1e-6) return false; return true; } // ### have a return code to tell if we really moved or not // Using swept code & direct position update (no physics engine) // This function is the generic character controller logic, valid for all swept volumes PxU32 SweepTest::moveCharacter( const InternalCBData_FindTouchedGeom* userData, const InternalCBData_OnHit* userHitData, SweptVolume& volume, const PxVec3& direction, const UserObstacles& userObstacles, float min_dist, const PxControllerFilters& filters, bool constrainedClimbingMode, bool standingOnMoving ) { bool standingOnMovingUp = standingOnMoving; mFlags &= ~STF_HIT_NON_WALKABLE; PxU32 CollisionFlags = 0; const PxU32 MaxIter = MAX_ITER; // 1 for "collide and stop" const PxU32 MaxIterSides = MaxIter; const PxU32 MaxIterDown = ((mFlags & STF_WALK_EXPERIMENT) && mUserParams.mNonWalkableMode==PxCCTNonWalkableMode::eFORCE_SLIDING) ? MaxIter : 1; // const PxU32 MaxIterDown = 1; // ### this causes the artificial gap on top of chars float StepOffset = mUserParams.mStepOffset; // Default step offset can be cancelled in some cases. // Save initial height const PxVec3& upDirection = mUserParams.mUpDirection; // const PxExtended OriginalHeight = volume.mCenter[upDirection]; const PxVec3 volumeCenter = toVec3(volume.mCenter); const PxExtended OriginalHeight = volumeCenter.dot(upDirection); const PxExtended OriginalBottomPoint = OriginalHeight - volume.mHalfHeight; // UBI // TEST! Disable auto-step when flying. Not sure this is really useful. // if(direction[upDirection]>0.0f) const float dir_dot_up = direction.dot(upDirection); //printf("%f\n", dir_dot_up); if(dir_dot_up>0.0f) { mFlags |= STF_IS_MOVING_UP; // PT: this makes it fail on a platform moving up when jumping // However if we don't do that a jump when moving up a slope doesn't work anymore! // Not doing this also creates jittering when a capsule CCT jumps against another capsule CCT if(!standingOnMovingUp) // PT: if we're standing on something moving up it's safer to do the up motion anyway, even though this won't work well before we add the flag in TA13542 { // static int count=0; printf("Cancelling step offset... %d\n", count++); StepOffset = 0.0f; } } else { mFlags &= ~STF_IS_MOVING_UP; } // Decompose motion into 3 independent motions: up, side, down // - if the motion is purely down (gravity only), the up part is needed to fight accuracy issues. For example if the // character is already touching the geometry a bit, the down sweep test might have troubles. If we first move it above // the geometry, the problems disappear. // - if the motion is lateral (character moving forward under normal gravity) the decomposition provides the autostep feature // - if the motion is purely up, the down part can be skipped PxVec3 UpVector(0.0f, 0.0f, 0.0f); PxVec3 DownVector(0.0f, 0.0f, 0.0f); PxVec3 normal_compo, tangent_compo; Ps::decomposeVector(normal_compo, tangent_compo, direction, upDirection); // if(direction[upDirection]<0.0f) if(dir_dot_up<=0.0f) // DownVector[upDirection] = direction[upDirection]; DownVector = normal_compo; else // UpVector[upDirection] = direction[upDirection]; UpVector = normal_compo; // PxVec3 SideVector = direction; // SideVector[upDirection] = 0.0f; PxVec3 SideVector = tangent_compo; // If the side motion is zero, i.e. if the character is not really moving, disable auto-step. // This is important to prevent the CCT from automatically climbing on small objects that move // against it. We should climb over those only if there's a valid side motion from the player. const bool sideVectorIsZero = !standingOnMovingUp && PxcIsAlmostZero(SideVector); // We can't use PxVec3::isZero() safely with arbitrary up vectors // #### however if we do this the up pass is disabled, with bad consequences when the CCT is on a dynamic object!! // ### this line makes it possible to push other CCTs by jumping on them // const bool sideVectorIsZero = false; // printf("sideVectorIsZero: %d\n", sideVectorIsZero); // if(!SideVector.isZero()) if(!sideVectorIsZero) // UpVector[upDirection] += StepOffset; UpVector += upDirection*StepOffset; // printf("StepOffset: %f\n", StepOffset); // ==========[ Initial volume query ]=========================== if(1) { PxExtendedBounds3 TemporalBox; volume.computeTemporalBox(*this, TemporalBox, volume.mCenter, direction); // Gather touched geoms updateTouchedGeoms( userData, userObstacles, TemporalBox, filters); } // ==========[ UP PASS ]=========================== mCachedTriIndexIndex = 0; const bool PerformUpPass = true; PxU32 NbCollisions=0; const PxU32 MaxIterUp = PxcIsAlmostZero(SideVector) ? MaxIter : 1; if(PerformUpPass) { // printf("%f | %f | %f\n", UpVector.x, UpVector.y, UpVector.z); // Prevent user callback for up motion. This up displacement is artificial, and only needed for auto-stepping. // If we call the user for this, we might eventually apply upward forces to objects resting on top of us, even // if we visually don't move. This produces weird-looking motions. // mValidateCallback = false; // PT: actually I think the previous comment is wrong. It's not only needed for auto-stepping: when the character // jumps there's a legit up motion and the lack of callback in that case could need some object can't be pushed // by the character's 'head' (for example). So I now think it's better to use the callback all the time, and // let users figure out what to do using the available state (like "isMovingUp", etc). // mValidateCallback = true; // In the walk-experiment we explicitly want to ban any up motions, to avoid characters climbing slopes they shouldn't climb. // So let's bypass the whole up pass. if(!(mFlags & STF_WALK_EXPERIMENT)) { // ### MaxIter here seems to "solve" the V bug if(doSweepTest(userData, userHitData, userObstacles, volume, UpVector, MaxIterUp, &NbCollisions, min_dist, filters, SWEEP_PASS_UP)) { if(NbCollisions) { CollisionFlags |= PxControllerFlag::eCOLLISION_UP; // Clamp step offset to make sure we don't undo more than what we did // PxExtended Delta = volume.mCenter[upDirection] - OriginalHeight; PxExtended Delta = toVec3(volume.mCenter).dot(upDirection) - OriginalHeight; if(Delta<StepOffset) { StepOffset=float(Delta); } } } } } // ==========[ SIDE PASS ]=========================== mCachedTriIndexIndex = 1; // mValidateCallback = true; const bool PerformSidePass = true; mFlags &= ~STF_VALIDATE_TRIANGLE_SIDE; if(PerformSidePass) { NbCollisions=0; //printf("BS:%.2f %.2f %.2f NS=%d\n", volume.mCenter.x, volume.mCenter.y, volume.mCenter.z, mNbCachedStatic); if(doSweepTest(userData, userHitData, userObstacles, volume, SideVector, MaxIterSides, &NbCollisions, min_dist, filters, SWEEP_PASS_SIDE)) { if(NbCollisions) CollisionFlags |= PxControllerFlag::eCOLLISION_SIDES; } //printf("AS:%.2f %.2f %.2f NS=%d\n", volume.mCenter.x, volume.mCenter.y, volume.mCenter.z, mNbCachedStatic); } // ==========[ DOWN PASS ]=========================== mCachedTriIndexIndex = 2; const bool PerformDownPass = true; if(PerformDownPass) { NbCollisions=0; // if(!SideVector.isZero()) // We disabled that before so we don't have to undo it in that case if(!sideVectorIsZero) // We disabled that before so we don't have to undo it in that case // DownVector[upDirection] -= StepOffset; // Undo our artificial up motion DownVector -= upDirection*StepOffset; // Undo our artificial up motion mFlags &= ~STF_VALIDATE_TRIANGLE_DOWN; if(mTouchedActor) { mTouchedActor->unregisterObserver(*this); } mTouchedActor = NULL; mTouchedShape = NULL; mTouchedObstacleHandle = INVALID_OBSTACLE_HANDLE; // min_dist actually makes a big difference :( // AAARRRGGH: if we get culled because of min_dist here, mValidateTriangle never becomes valid! if(doSweepTest(userData, userHitData, userObstacles, volume, DownVector, MaxIterDown, &NbCollisions, min_dist, filters, SWEEP_PASS_DOWN)) { if(NbCollisions) { if(dir_dot_up<=0.0f) // PT: fix attempt CollisionFlags |= PxControllerFlag::eCOLLISION_DOWN; if(mUserParams.mHandleSlope && !(mFlags & (STF_TOUCH_OTHER_CCT|STF_TOUCH_OBSTACLE))) // PT: I think the following fix shouldn't be performed when mHandleSlope is false. { // PT: the following code is responsible for a weird capsule behaviour, // when colliding against a highly tesselated terrain: // - with a large direction vector, the capsule gets stuck against some part of the terrain // - with a slower direction vector (but in the same direction!) the capsule manages to move // I will keep that code nonetheless, since it seems to be useful for them. if((mFlags & STF_VALIDATE_TRIANGLE_SIDE) && testSlope(mContactNormalSidePass, upDirection, mUserParams.mSlopeLimit)) { // constrainedClimbingMode if(constrainedClimbingMode && mContactPointHeight > OriginalBottomPoint + StepOffset) { mFlags |= STF_HIT_NON_WALKABLE; if(!(mFlags & STF_WALK_EXPERIMENT)) return CollisionFlags; } } //~constrainedClimbingMode } } } //printf("AD:%.2f %.2f %.2f NS=%d\n", volume.mCenter.x, volume.mCenter.y, volume.mCenter.z, mNbCachedStatic); // printf("%d\n", mTouchOtherCCT); // TEST: do another down pass if we're on a non-walkable poly // ### kind of works but still not perfect // ### could it be because we zero the Y impulse later? // ### also check clamped response vectors // if(mUserParams.mHandleSlope && mValidateTriangle && direction[upDirection]<0.0f) // if(mUserParams.mHandleSlope && !mTouchOtherCCT && !mTouchObstacle && mValidateTriangle && dir_dot_up<0.0f) if(mUserParams.mHandleSlope && !(mFlags & (STF_TOUCH_OTHER_CCT|STF_TOUCH_OBSTACLE)) && (mFlags & STF_VALIDATE_TRIANGLE_DOWN) && dir_dot_up<=0.0f) { PxVec3 Normal; #ifdef USE_CONTACT_NORMAL_FOR_SLOPE_TEST Normal = mContactNormalDownPass; #else //mTouchedTriangle.normal(Normal); Normal = mContactNormalDownPass; #endif const float touchedTriHeight = mTouchedTriMax - OriginalBottomPoint; if(touchedTriHeight>mUserParams.mStepOffset && testSlope(Normal, upDirection, mUserParams.mSlopeLimit)) { mFlags |= STF_HIT_NON_WALKABLE; // Early exit if we're going to run this again anyway... if(!(mFlags & STF_WALK_EXPERIMENT)) return CollisionFlags; /* CatchScene()->GetRenderer()->AddLine(mTouchedTriangle.mVerts[0], mTouched.mVerts[1], ARGB_YELLOW); CatchScene()->GetRenderer()->AddLine(mTouchedTriangle.mVerts[0], mTouched.mVerts[2], ARGB_YELLOW); CatchScene()->GetRenderer()->AddLine(mTouchedTriangle.mVerts[1], mTouched.mVerts[2], ARGB_YELLOW); */ // ==========[ WALK EXPERIMENT ]=========================== mFlags |= STF_NORMALIZE_RESPONSE; const PxExtended tmp = toVec3(volume.mCenter).dot(upDirection); PxExtended Delta = tmp > OriginalHeight ? tmp - OriginalHeight : 0.0f; // PxExtended Delta = volume.mCenter[upDirection] > OriginalHeight ? volume.mCenter[upDirection] - OriginalHeight : 0.0f; Delta += fabsf(direction.dot(upDirection)); // Delta += fabsf(direction[upDirection]); PxExtended Recover = Delta; NbCollisions=0; const PxExtended MD = Recover < min_dist ? Recover/float(MaxIter) : min_dist; PxVec3 RecoverPoint(0,0,0); // RecoverPoint[upDirection]=-float(Recover); RecoverPoint = -upDirection*float(Recover); // PT: we pass "SWEEP_PASS_UP" for compatibility with previous code, but it's technically wrong (this is a 'down' pass) if(doSweepTest(userData, userHitData, userObstacles, volume, RecoverPoint, MaxIter, &NbCollisions, float(MD), filters, SWEEP_PASS_UP)) { // if(NbCollisions) CollisionFlags |= COLLISION_Y_DOWN; // PT: why did we do this ? Removed for now. It creates a bug (non registered event) when we land on a steep poly. // However this might have been needed when we were sliding on those polygons, and we didn't want the land anim to // start while we were sliding. // if(NbCollisions) CollisionFlags &= ~PxControllerFlag::eCOLLISION_DOWN; } mFlags &= ~STF_NORMALIZE_RESPONSE; } } } return CollisionFlags; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // This is an interface between NX users and the internal character controller module. #include "CctInternalStructs.h" #include "CctBoxController.h" #include "CctCapsuleController.h" #include "CctCharacterControllerManager.h" #include "PxActor.h" #include "PxScene.h" #include "PxControllerBehavior.h" #include "CctObstacleContext.h" // PT: we use a local class instead of making "Controller" a PxSceneQueryFilterCallback, since it would waste more memory. // Ideally we'd have a C-style callback and a user-data pointer, instead of being forced to create a class. class ControllerFilter : public PxSceneQueryFilterCallback { public: PxSceneQueryHitType::Enum preFilter(const PxFilterData& filterData, PxShape* shape, PxSceneQueryFilterFlags& filterFlags) { // PT: we want to discard our own internal shapes only if(mShapeHashSet->contains(const_cast<PxShape*>(shape))) return PxSceneQueryHitType::eNONE; // PT: otherwise we revert to the user-callback, if it exists, and if users enabled that call if(mUserFilterCallback && (mUserFilterFlags | PxSceneQueryFilterFlag::ePREFILTER)) return mUserFilterCallback->preFilter(filterData, shape, filterFlags); return PxSceneQueryHitType::eBLOCK; } PxSceneQueryHitType::Enum postFilter(const PxFilterData& filterData, const PxSceneQueryHit& hit) { // PT: we may get called if users have asked for such a callback if(mUserFilterCallback && (mUserFilterFlags | PxSceneQueryFilterFlag::ePOSTFILTER)) return mUserFilterCallback->postFilter(filterData, hit); PX_ASSERT(0); // PT: otherwise we shouldn't have been called return PxSceneQueryHitType::eNONE; } Ps::HashSet<PxShape*>* mShapeHashSet; PxSceneQueryFilterCallback* mUserFilterCallback; PxSceneQueryFilterFlags mUserFilterFlags; }; bool Controller::filterTouchedShape(const PxControllerFilters& filters) { PxSceneQueryFilterFlags filterFlags = PxSceneQueryFilterFlag::eDYNAMIC|PxSceneQueryFilterFlag::ePREFILTER; PxSceneQueryFilterData filterData(filters.mFilterData ? *filters.mFilterData : PxFilterData(), filterFlags); PxSceneQueryFlags hitFlags = PxSceneQueryFlag::eDISTANCE; if(filters.mFilterCallback && (filters.mFilterFlags | PxSceneQueryFilterFlag::ePREFILTER)) { PxSceneQueryHitType::Enum retVal = filters.mFilterCallback->preFilter(filterData.data, mCctModule.mTouchedShape, filterFlags); if(retVal != PxSceneQueryHitType::eNONE) return true; else return false; } return true; } void Controller::findTouchedObject(const PxControllerFilters& filters, const PxObstacleContext* obstacleContext, const PxVec3& upDirection) { PX_ASSERT(!mCctModule.mTouchedShape && (mCctModule.mTouchedObstacleHandle == INVALID_OBSTACLE_HANDLE)); // PT: the CCT works perfectly on statics without this extra mechanism, so we only raycasts against dynamics. // The pre-filter callback is used to filter out our own proxy actor shapes. We need to make sure our own filter // doesn't disturb the user-provided filter(s). // PT: for starter, if user doesn't want to collide against dynamics, we can skip the whole thing if(filters.mFilterFlags & PxSceneQueryFilterFlag::eDYNAMIC) { ControllerFilter preFilter; preFilter.mShapeHashSet = &mManager->mCCTShapes; preFilter.mUserFilterCallback = filters.mFilterCallback; preFilter.mUserFilterFlags = filters.mFilterFlags; // PT: for our own purpose we just want dynamics & pre-filter PxSceneQueryFilterFlags filterFlags = PxSceneQueryFilterFlag::eDYNAMIC|PxSceneQueryFilterFlag::ePREFILTER; // PT: but we may need the post-filter callback as well if users want it if(filters.mFilterFlags & PxSceneQueryFilterFlag::ePOSTFILTER) filterFlags |= PxSceneQueryFilterFlag::ePOSTFILTER; PxSceneQueryFilterData filterData(filters.mFilterData ? *filters.mFilterData : PxFilterData(), filterFlags); const PxF32 probeLength = getHalfHeightInternal(); // Distance to feet const PxF32 extra = 0.0f;//probeLength * 0.1f; const PxVec3 rayOrigin = toVec3(mPosition); PxRaycastHit hit; hit.distance = FLT_MAX; if(mScene->raycastSingle(rayOrigin, -upDirection, probeLength+extra, PxSceneQueryFlag::eDISTANCE, hit, filterData, &preFilter)) { ASSERT(hit.shape); ASSERT(hit.distance<=probeLength+extra); mCctModule.mTouchedShape = hit.shape; mCctModule.mTouchedActor = &mCctModule.mTouchedShape->getActor(); mCctModule.mTouchedActor->registerObserver(mCctModule); // mCctModule.mTouchedPos = getShapeGlobalPose(*hit.shape).p - upDirection*(probeLength-hit.distance); // PT: we only care about the up delta here const PxTransform shapeTransform = getShapeGlobalPose(*hit.shape); mCctModule.mTouchedPosShape_World = PxVec3(0) - upDirection*(probeLength-hit.distance); mCctModule.mTouchedPosShape_Local = shapeTransform.transformInv(PxVec3(0)); mPreviousSceneTimestamp = mScene->getTimestamp()-1; // PT: just make sure cached timestamp is different } if(obstacleContext) { const ObstacleContext* obstacles = static_cast<const ObstacleContext*>(obstacleContext); PxRaycastHit obstacleHit; ObstacleHandle obstacleHandle; const PxObstacle* touchedObstacle = obstacles->raycastSingle(obstacleHit, rayOrigin, -upDirection, probeLength+extra, obstacleHandle); // printf("Touched raycast obstacle: %d\n", int(touchedObstacle)); if(touchedObstacle && obstacleHit.distance<hit.distance) { ASSERT(hit.distance<=probeLength+extra); mCctModule.mTouchedObstacleHandle = obstacleHandle; if(!gUseLocalSpace) { mCctModule.mTouchedPos = toVec3(touchedObstacle->mPos) - upDirection*(probeLength-obstacleHit.distance); } else { // PT: we only care about the up delta here mCctModule.mTouchedPosObstacle_World = PxVec3(0) - upDirection*(probeLength-obstacleHit.distance); mCctModule.mTouchedPosObstacle_Local = worldToLocal(*touchedObstacle, PxExtendedVec3(0,0,0)); } } } } } bool Controller::rideOnTouchedObject(SweptVolume& volume, const PxVec3& upDirection, PxVec3& disp, const PxObstacleContext* obstacleContext) { PX_ASSERT(mCctModule.mTouchedShape || (mCctModule.mTouchedObstacleHandle != INVALID_OBSTACLE_HANDLE)); bool standingOnMoving = false; bool canDoUpdate = true; // Always true on obstacles PxU32 behaviorFlags = 0; // Default on shapes PxVec3 delta(0); float timeCoeff = 1.0f; if(mCctModule.mTouchedShape) { // PT: riding on a shape // PT: it is important to skip this stuff for static meshes, // otherwise accuracy issues create bugs like TA14007. if(mCctModule.mTouchedActor->getConcreteType()!=PxConcreteType::eRIGID_STATIC) { // PT: we only do the update when the timestamp has changed, otherwise "delta" will be zero // even if the underlying shape is moving. const PxU32 timestamp = mScene->getTimestamp(); // printf("TimeStamp: %d\n", timestamp); canDoUpdate = timestamp!=mPreviousSceneTimestamp; if(canDoUpdate) { mPreviousSceneTimestamp = timestamp; const float elapsedTime = mGlobalTime - mPreviousGlobalTime; mPreviousGlobalTime = mGlobalTime; timeCoeff = 1.0f / elapsedTime; if(mBehaviorCallback) behaviorFlags = mBehaviorCallback->getBehaviorFlags(*mCctModule.mTouchedShape); // delta = getShapeGlobalPose(*mCctModule.mTouchedShape).p - mCctModule.mTouchedPos; const PxTransform shapeTransform = getShapeGlobalPose(*mCctModule.mTouchedShape); const PxVec3 posPreviousFrame = mCctModule.mTouchedPosShape_World; const PxVec3 posCurrentFrame = shapeTransform.transform(mCctModule.mTouchedPosShape_Local); delta = posCurrentFrame - posPreviousFrame; } } } else { // PT: riding on an obstacle behaviorFlags = PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT; // Default on obstacles const float elapsedTime = mGlobalTime - mPreviousGlobalTime; mPreviousGlobalTime = mGlobalTime; timeCoeff = 1.0f / elapsedTime; const PxObstacle* touchedObstacle = obstacleContext->getObstacleByHandle(mCctModule.mTouchedObstacleHandle); PX_ASSERT(touchedObstacle); if(mBehaviorCallback) behaviorFlags = mBehaviorCallback->getBehaviorFlags(*touchedObstacle); if(!gUseLocalSpace) { delta = toVec3(touchedObstacle->mPos) - mCctModule.mTouchedPos; } else { PxVec3 posPreviousFrame = mCctModule.mTouchedPosObstacle_World; PxVec3 posCurrentFrame = localToWorld(*touchedObstacle, mCctModule.mTouchedPosObstacle_Local); delta = posCurrentFrame - posPreviousFrame; } } if(canDoUpdate && !(behaviorFlags & PxControllerBehaviorFlag::eCCT_USER_DEFINED_RIDE)) { // PT: amazingly enough even PxcIsAlmostZero doesn't solve this one. // Moving on a static mesh sometimes produces delta bigger than 1e-6f! // This may also explain the drift on some rotating platforms. It looks // like this delta computation is not very accurate. // standingOnMoving = !delta.isZero(); standingOnMoving = !PxcIsAlmostZero(delta); mCachedStandingOnMoving = standingOnMoving; //printf("%f %f %f\n", delta.x, delta.y, delta.z); if(standingOnMoving) { const float dir_dot_up = delta.dot(upDirection); const bool deltaMovingUp = dir_dot_up>0.0f; PxVec3 deltaUpDisp, deltaSideDisp; Ps::decomposeVector(deltaUpDisp, deltaSideDisp, delta, upDirection); if(deltaMovingUp) { volume.mCenter.x += deltaUpDisp.x; volume.mCenter.y += deltaUpDisp.y; volume.mCenter.z += deltaUpDisp.z; } else { disp += deltaUpDisp; } if(behaviorFlags & PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT) disp += deltaSideDisp; } // printf("delta in: %f %f %f (%f)\n", delta.x, delta.y, delta.z, 1.0f/timeCoeff); mDeltaXP = delta * timeCoeff; } else { standingOnMoving = mCachedStandingOnMoving; } // mDelta = delta; return standingOnMoving; } PxU32 Controller::move(SweptVolume& volume, const PxVec3& originalDisp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacleContext, bool constrainedClimbingMode) { mGlobalTime += elapsedTime; // Init CCT with per-controller settings Cm::RenderBuffer* renderBuffer = mManager->mRenderBuffer; const PxU32 debugRenderFlags = mManager->mDebugRenderingFlags; mCctModule.mRenderBuffer = renderBuffer; mCctModule.mRenderFlags = debugRenderFlags; mCctModule.mUserParams = mUserParams; mCctModule.mFlags |= STF_FIRST_UPDATE; mCctModule.mNbFullUpdates = 0; mCctModule.mNbPartialUpdates = 0; mCctModule.mNbIterations = 0; mCctModule.mUserParams.mMaxEdgeLength2 = mManager->mMaxEdgeLength * mManager->mMaxEdgeLength; mCctModule.mUserParams.mTessellation = mManager->mTessellation; const PxVec3& upDirection = mUserParams.mUpDirection; /////////// PxVec3 disp = originalDisp + mOverlapRecover; mOverlapRecover = PxVec3(0.0f); bool standingOnMoving = false; // PT: whether the CCT is currently standing on a moving object //printf("Touched shape: %d\n", int(mCctModule.mTouchedShape)); //standingOnMoving=true; // printf("Touched obstacle: %d\n", int(mCctModule.mTouchedObstacle)); if(mCctModule.mTouchedActor && mCctModule.mTouchedShape) { PxU32 nbShapes = mCctModule.mTouchedActor->getNbShapes(); bool found = false; for(PxU32 i=0;i<nbShapes;i++) { PxShape* shape = NULL; mCctModule.mTouchedActor->getShapes(&shape, 1, i); if(shape==mCctModule.mTouchedShape) { found = true; break; } } if(!found) { if(mCctModule.mTouchedActor) mCctModule.mTouchedActor->unregisterObserver(mCctModule); mCctModule.mTouchedActor = NULL; mCctModule.mTouchedShape = NULL; } else { // check if we are still in the same scene if(mCctModule.mTouchedActor->getScene() != mScene) { if(mCctModule.mTouchedActor) mCctModule.mTouchedActor->unregisterObserver(mCctModule); mCctModule.mTouchedShape = NULL; mCctModule.mTouchedActor = NULL; } else { // check if the shape still does have the sq flag if(!(mCctModule.mTouchedShape->getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE)) { if(mCctModule.mTouchedActor) mCctModule.mTouchedActor->unregisterObserver(mCctModule); mCctModule.mTouchedShape = NULL; mCctModule.mTouchedActor = NULL; } else { // invoke the CCT filtering for the shape if(!filterTouchedShape(filters)) { if(mCctModule.mTouchedActor) mCctModule.mTouchedActor->unregisterObserver(mCctModule); mCctModule.mTouchedShape = NULL; mCctModule.mTouchedActor = NULL; } } } } } if(!mCctModule.mTouchedShape && (mCctModule.mTouchedObstacleHandle == INVALID_OBSTACLE_HANDLE)) findTouchedObject(filters, obstacleContext, upDirection); if(mCctModule.mTouchedShape || (mCctModule.mTouchedObstacleHandle != INVALID_OBSTACLE_HANDLE)) { standingOnMoving = rideOnTouchedObject(volume, upDirection, disp, obstacleContext); } else { mCachedStandingOnMoving = false; mDeltaXP = PxVec3(0.0f); } // printf("standingOnMoving: %d\n", standingOnMoving); /////////// Ps::Array<const void*>& boxUserData = mManager->mBoxUserData; Ps::Array<PxExtendedBox>& boxes = mManager->mBoxes; Ps::Array<const void*>& capsuleUserData = mManager->mCapsuleUserData; Ps::Array<PxExtendedCapsule>& capsules = mManager->mCapsules; PX_ASSERT(!boxUserData.size()); PX_ASSERT(!boxes.size()); PX_ASSERT(!capsuleUserData.size()); PX_ASSERT(!capsules.size()); if(1) { // Experiment - to do better const PxU32 nbControllers = mManager->getNbControllers(); Controller** controllers = mManager->getControllers(); for(PxU32 i=0;i<nbControllers;i++) { Controller* currentController = controllers[i]; if(currentController==this) continue; // Depending on user settings the current controller can be: // - discarded // - always kept // - or tested against filtering flags const PxCCTInteractionMode::Enum interactionMode = currentController->mInteractionMode; bool keepController = true; if(interactionMode==PxCCTInteractionMode::eEXCLUDE) { keepController = false; } else if(interactionMode==PxCCTInteractionMode::eUSE_FILTER) { keepController = (filters.mActiveGroups & currentController->mGroupsBitmask)!=0; if(keepController && filters.mCCTFilterCallback) { keepController = filters.mCCTFilterCallback->filter(*getPxController(), *currentController->getPxController()); } if(keepController && filters.mFilterCallback) { PxFilterData cctFilterData = filters.mFilterData ? *filters.mFilterData : PxFilterData(); PxShape* currentShape = currentController->getKineShape(); PxSceneQueryFilterFlags filterFlags = filters.mFilterFlags; if(keepController && (filters.mFilterFlags & PxSceneQueryFilterFlag::ePREFILTER)) { keepController = (filters.mFilterCallback->preFilter(cctFilterData, currentShape, filterFlags) != PxSceneQueryHitType::eNONE); } /* //GY - not sure exactly where to apply the post filter or even if we should. if(keepController && (filters.mFilterFlags & PxSceneQueryFilterFlag::ePOSTFILTER)) { PxSceneQueryHit hit; keepController = (filters.mFilterCallback->postFilter(cctFilterData, hit) != PxSceneQueryHitType::eNONE); } */ } } if(keepController) { if(currentController->mType==PxControllerShapeType::eBOX) { // PT: TODO: optimize this BoxController* BC = static_cast<BoxController*>(currentController); PxExtendedBox obb; BC->getOBB(obb); boxes.pushBack(obb); #ifdef REMOVED if(renderBuffer /*&& (debugRenderFlags & PxControllerDebugRenderFlags::eOBSTACLES)*/) { Cm::RenderOutput out(*renderBuffer); out << gCCTBoxDebugColor; out << PxTransform(toVec3(obb.center), obb.rot); out << Cm::DebugBox(obb.extents, true); } #endif const size_t code = encodeUserObject(i, USER_OBJECT_CCT); boxUserData.pushBack((const void*)code); } else if(currentController->mType==PxControllerShapeType::eCAPSULE) { CapsuleController* CC = static_cast<CapsuleController*>(currentController); // PT: TODO: optimize this PxExtendedCapsule worldCapule; CC->getCapsule(worldCapule); capsules.pushBack(worldCapule); const size_t code = encodeUserObject(i, USER_OBJECT_CCT); capsuleUserData.pushBack((const void*)code); } else ASSERT(0); } } } const ObstacleContext* obstacles = NULL; if(obstacleContext) { obstacles = static_cast<const ObstacleContext*>(obstacleContext); // PT: TODO: optimize this const PxU32 nbExtraBoxes = obstacles->mBoxObstacles.size(); for(PxU32 i=0;i<nbExtraBoxes;i++) { const PxBoxObstacle& userBoxObstacle = obstacles->mBoxObstacles[i]; PxExtendedBox extraBox; extraBox.center = userBoxObstacle.mPos; extraBox.extents = userBoxObstacle.mHalfExtents; extraBox.rot = userBoxObstacle.mRot; boxes.pushBack(extraBox); const size_t code = encodeUserObject(i, USER_OBJECT_BOX_OBSTACLE); boxUserData.pushBack((const void*)code); if(renderBuffer && (debugRenderFlags & PxControllerDebugRenderFlags::eOBSTACLES)) { Cm::RenderOutput out(*renderBuffer); out << gObstacleDebugColor; out << PxTransform(toVec3(userBoxObstacle.mPos), userBoxObstacle.mRot); out << Cm::DebugBox(userBoxObstacle.mHalfExtents, true); } } const PxU32 nbExtraCapsules = obstacles->mCapsuleObstacles.size(); for(PxU32 i=0;i<nbExtraCapsules;i++) { const PxCapsuleObstacle& userCapsuleObstacle = obstacles->mCapsuleObstacles[i]; PxExtendedCapsule extraCapsule; const PxVec3 capsuleAxis = userCapsuleObstacle.mRot.getBasisVector0() * userCapsuleObstacle.mHalfHeight; extraCapsule.p0 = PxExtendedVec3( userCapsuleObstacle.mPos.x - capsuleAxis.x, userCapsuleObstacle.mPos.y - capsuleAxis.y, userCapsuleObstacle.mPos.z - capsuleAxis.z); extraCapsule.p1 = PxExtendedVec3( userCapsuleObstacle.mPos.x + capsuleAxis.x, userCapsuleObstacle.mPos.y + capsuleAxis.y, userCapsuleObstacle.mPos.z + capsuleAxis.z); extraCapsule.radius = userCapsuleObstacle.mRadius; capsules.pushBack(extraCapsule); const size_t code = encodeUserObject(i, USER_OBJECT_CAPSULE_OBSTACLE); capsuleUserData.pushBack((const void*)code); if(renderBuffer && (debugRenderFlags & PxControllerDebugRenderFlags::eOBSTACLES)) { Cm::RenderOutput out(*renderBuffer); out << gObstacleDebugColor; const PxMat33 rotM(userCapsuleObstacle.mRot); Cm::Matrix34 absPose; absPose.base0 = rotM.column0; absPose.base1 = rotM.column1; absPose.base2 = rotM.column2; absPose.base3 = toVec3(userCapsuleObstacle.mPos); out.outputCapsule(userCapsuleObstacle.mRadius, userCapsuleObstacle.mHalfHeight, absPose); } } } UserObstacles userObstacles; const PxU32 nbBoxes = boxes.size(); userObstacles.mNbBoxes = nbBoxes; userObstacles.mBoxes = nbBoxes ? boxes.begin() : NULL; userObstacles.mBoxUserData = nbBoxes ? boxUserData.begin() : NULL; const PxU32 nbCapsules = capsules.size(); userObstacles.mNbCapsules = nbCapsules; userObstacles.mCapsules = nbCapsules ? capsules.begin() : NULL; userObstacles.mCapsuleUserData = nbCapsules ? capsuleUserData.begin() : NULL; PxInternalCBData_OnHit userHitData; userHitData.controller = this; userHitData.obstacles = obstacles; /////////// PxU32 collisionFlags = 0; PxInternalCBData_FindTouchedGeom findGeomData; findGeomData.scene = mScene; findGeomData.renderBuffer = renderBuffer; findGeomData.cctShapeHashSet = &mManager->mCCTShapes; mCctModule.mFlags &= ~STF_WALK_EXPERIMENT; PxExtendedVec3 Backup = volume.mCenter; collisionFlags = mCctModule.moveCharacter(&findGeomData, &userHitData, volume, disp, userObstacles, minDist, filters, constrainedClimbingMode, standingOnMoving); if(mCctModule.mFlags & STF_HIT_NON_WALKABLE) { // A bit slow, but everything else I tried was less convincing... mCctModule.mFlags |= STF_WALK_EXPERIMENT; volume.mCenter = Backup; PxVec3 xpDisp; if(mUserParams.mNonWalkableMode==PxCCTNonWalkableMode::eFORCE_SLIDING) { PxVec3 tangent_compo; Ps::decomposeVector(xpDisp, tangent_compo, disp, upDirection); } else xpDisp = disp; collisionFlags = mCctModule.moveCharacter(&findGeomData, &userHitData, volume, xpDisp, userObstacles, minDist, filters, constrainedClimbingMode, standingOnMoving); mCctModule.mFlags &= ~STF_WALK_EXPERIMENT; } mCollisionFlags = collisionFlags; // Copy results back mPosition = volume.mCenter; // Update kinematic actor if(mKineActor) { const PxVec3 delta = Backup - volume.mCenter; const PxF32 deltaM2 = delta.magnitudeSquared(); if(deltaM2!=0.0f) { PxTransform targetPose = mKineActor->getGlobalPose(); targetPose.p = toVec3(mPosition); mKineActor->setKinematicTarget(targetPose); } } mManager->resetObstaclesBuffers(); return collisionFlags; } PxU32 BoxController::move(const PxVec3& disp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacles) { PX_SIMD_GUARD; // Create internal swept box SweptBox sweptBox; sweptBox.mCenter = mPosition; sweptBox.mExtents = PxVec3(mHalfHeight, mHalfSideExtent, mHalfForwardExtent); sweptBox.mHalfHeight = mHalfHeight; // UBI return Controller::move(sweptBox, disp, minDist, elapsedTime, filters, obstacles, false); } PxU32 CapsuleController::move(const PxVec3& disp, PxF32 minDist, PxF32 elapsedTime, const PxControllerFilters& filters, const PxObstacleContext* obstacles) { PX_SIMD_GUARD; // Create internal swept capsule SweptCapsule sweptCapsule; sweptCapsule.mCenter = mPosition; sweptCapsule.mRadius = mRadius; sweptCapsule.mHeight = mHeight; sweptCapsule.mHalfHeight = mHeight*0.5f + mRadius; // UBI return Controller::move(sweptCapsule, disp, minDist, elapsedTime, filters, obstacles, mClimbingMode==PxCapsuleClimbingMode::eCONSTRAINED); }
bio-org-au/nsl-editor
test/models/instance_note/validations/one_apc_dist_note_only_test.rb
# frozen_string_literal: true # Copyright 2015 Australian National Botanic Gardens # # This file is part of the NSL Editor. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "test_helper" # Single instance note model test. class InstanceNoteOneApcDistNoteOnlyTest < ActiveSupport::TestCase test "instance can have only one apc dist note" do assert_raises ActiveRecord::RecordInvalid, "Record should be invalid" do instance_note = InstanceNote.new( instance: instances(:has_apc_dist_note), instance_note_key: instance_note_keys(:apc_dist), value: "some string", created_by: "test", updated_by: "test", namespace: namespaces(:apni) ) instance_note.save! end end end
josehu07/SplitFS
kernel/linux-5.4/drivers/extcon/extcon-intel-mrfld.c
// SPDX-License-Identifier: GPL-2.0 /* * extcon driver for Basin Cove PMIC * * Copyright (c) 2019, Intel Corporation. * Author: <NAME> <<EMAIL>> */ #include <linux/extcon-provider.h> #include <linux/interrupt.h> #include <linux/mfd/intel_soc_pmic.h> #include <linux/mfd/intel_soc_pmic_mrfld.h> #include <linux/mod_devicetable.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/regmap.h> #include "extcon-intel.h" #define BCOVE_USBIDCTRL 0x19 #define BCOVE_USBIDCTRL_ID BIT(0) #define BCOVE_USBIDCTRL_ACA BIT(1) #define BCOVE_USBIDCTRL_ALL (BCOVE_USBIDCTRL_ID | BCOVE_USBIDCTRL_ACA) #define BCOVE_USBIDSTS 0x1a #define BCOVE_USBIDSTS_GND BIT(0) #define BCOVE_USBIDSTS_RARBRC_MASK GENMASK(2, 1) #define BCOVE_USBIDSTS_RARBRC_SHIFT 1 #define BCOVE_USBIDSTS_NO_ACA 0 #define BCOVE_USBIDSTS_R_ID_A 1 #define BCOVE_USBIDSTS_R_ID_B 2 #define BCOVE_USBIDSTS_R_ID_C 3 #define BCOVE_USBIDSTS_FLOAT BIT(3) #define BCOVE_USBIDSTS_SHORT BIT(4) #define BCOVE_CHGRIRQ_ALL (BCOVE_CHGRIRQ_VBUSDET | BCOVE_CHGRIRQ_DCDET | \ BCOVE_CHGRIRQ_BATTDET | BCOVE_CHGRIRQ_USBIDDET) #define BCOVE_CHGRCTRL0 0x4b #define BCOVE_CHGRCTRL0_CHGRRESET BIT(0) #define BCOVE_CHGRCTRL0_EMRGCHREN BIT(1) #define BCOVE_CHGRCTRL0_EXTCHRDIS BIT(2) #define BCOVE_CHGRCTRL0_SWCONTROL BIT(3) #define BCOVE_CHGRCTRL0_TTLCK BIT(4) #define BCOVE_CHGRCTRL0_BIT_5 BIT(5) #define BCOVE_CHGRCTRL0_BIT_6 BIT(6) #define BCOVE_CHGRCTRL0_CHR_WDT_NOKICK BIT(7) struct mrfld_extcon_data { struct device *dev; struct regmap *regmap; struct extcon_dev *edev; unsigned int status; unsigned int id; }; static const unsigned int mrfld_extcon_cable[] = { EXTCON_USB, EXTCON_USB_HOST, EXTCON_CHG_USB_SDP, EXTCON_CHG_USB_CDP, EXTCON_CHG_USB_DCP, EXTCON_CHG_USB_ACA, EXTCON_NONE, }; static int mrfld_extcon_clear(struct mrfld_extcon_data *data, unsigned int reg, unsigned int mask) { return regmap_update_bits(data->regmap, reg, mask, 0x00); } static int mrfld_extcon_set(struct mrfld_extcon_data *data, unsigned int reg, unsigned int mask) { return regmap_update_bits(data->regmap, reg, mask, 0xff); } static int mrfld_extcon_sw_control(struct mrfld_extcon_data *data, bool enable) { unsigned int mask = BCOVE_CHGRCTRL0_SWCONTROL; struct device *dev = data->dev; int ret; if (enable) ret = mrfld_extcon_set(data, BCOVE_CHGRCTRL0, mask); else ret = mrfld_extcon_clear(data, BCOVE_CHGRCTRL0, mask); if (ret) dev_err(dev, "can't set SW control: %d\n", ret); return ret; } static int mrfld_extcon_get_id(struct mrfld_extcon_data *data) { struct regmap *regmap = data->regmap; unsigned int id; bool ground; int ret; ret = regmap_read(regmap, BCOVE_USBIDSTS, &id); if (ret) return ret; if (id & BCOVE_USBIDSTS_FLOAT) return INTEL_USB_ID_FLOAT; switch ((id & BCOVE_USBIDSTS_RARBRC_MASK) >> BCOVE_USBIDSTS_RARBRC_SHIFT) { case BCOVE_USBIDSTS_R_ID_A: return INTEL_USB_RID_A; case BCOVE_USBIDSTS_R_ID_B: return INTEL_USB_RID_B; case BCOVE_USBIDSTS_R_ID_C: return INTEL_USB_RID_C; } /* * PMIC A0 reports USBIDSTS_GND = 1 for ID_GND, * but PMIC B0 reports USBIDSTS_GND = 0 for ID_GND. * Thus we must check this bit at last. */ ground = id & BCOVE_USBIDSTS_GND; switch ('A' + BCOVE_MAJOR(data->id)) { case 'A': return ground ? INTEL_USB_ID_GND : INTEL_USB_ID_FLOAT; case 'B': return ground ? INTEL_USB_ID_FLOAT : INTEL_USB_ID_GND; } /* Unknown or unsupported type */ return INTEL_USB_ID_FLOAT; } static int mrfld_extcon_role_detect(struct mrfld_extcon_data *data) { unsigned int id; bool usb_host; int ret; ret = mrfld_extcon_get_id(data); if (ret < 0) return ret; id = ret; usb_host = (id == INTEL_USB_ID_GND) || (id == INTEL_USB_RID_A); extcon_set_state_sync(data->edev, EXTCON_USB_HOST, usb_host); return 0; } static int mrfld_extcon_cable_detect(struct mrfld_extcon_data *data) { struct regmap *regmap = data->regmap; unsigned int status, change; int ret; /* * It seems SCU firmware clears the content of BCOVE_CHGRIRQ1 * and makes it useless for OS. Instead we compare a previously * stored status to the current one, provided by BCOVE_SCHGRIRQ1. */ ret = regmap_read(regmap, BCOVE_SCHGRIRQ1, &status); if (ret) return ret; change = status ^ data->status; if (!change) return -ENODATA; if (change & BCOVE_CHGRIRQ_USBIDDET) { ret = mrfld_extcon_role_detect(data); if (ret) return ret; } data->status = status; return 0; } static irqreturn_t mrfld_extcon_interrupt(int irq, void *dev_id) { struct mrfld_extcon_data *data = dev_id; int ret; ret = mrfld_extcon_cable_detect(data); mrfld_extcon_clear(data, BCOVE_MIRQLVL1, BCOVE_LVL1_CHGR); return ret ? IRQ_NONE: IRQ_HANDLED; } static int mrfld_extcon_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct intel_soc_pmic *pmic = dev_get_drvdata(dev->parent); struct regmap *regmap = pmic->regmap; struct mrfld_extcon_data *data; unsigned int id; int irq, ret; irq = platform_get_irq(pdev, 0); if (irq < 0) return irq; data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->dev = dev; data->regmap = regmap; data->edev = devm_extcon_dev_allocate(dev, mrfld_extcon_cable); if (IS_ERR(data->edev)) return -ENOMEM; ret = devm_extcon_dev_register(dev, data->edev); if (ret < 0) { dev_err(dev, "can't register extcon device: %d\n", ret); return ret; } ret = devm_request_threaded_irq(dev, irq, NULL, mrfld_extcon_interrupt, IRQF_ONESHOT | IRQF_SHARED, pdev->name, data); if (ret) { dev_err(dev, "can't register IRQ handler: %d\n", ret); return ret; } ret = regmap_read(regmap, BCOVE_ID, &id); if (ret) { dev_err(dev, "can't read PMIC ID: %d\n", ret); return ret; } data->id = id; ret = mrfld_extcon_sw_control(data, true); if (ret) return ret; /* Get initial state */ mrfld_extcon_role_detect(data); mrfld_extcon_clear(data, BCOVE_MIRQLVL1, BCOVE_LVL1_CHGR); mrfld_extcon_clear(data, BCOVE_MCHGRIRQ1, BCOVE_CHGRIRQ_ALL); mrfld_extcon_set(data, BCOVE_USBIDCTRL, BCOVE_USBIDCTRL_ALL); platform_set_drvdata(pdev, data); return 0; } static int mrfld_extcon_remove(struct platform_device *pdev) { struct mrfld_extcon_data *data = platform_get_drvdata(pdev); mrfld_extcon_sw_control(data, false); return 0; } static const struct platform_device_id mrfld_extcon_id_table[] = { { .name = "mrfld_bcove_pwrsrc" }, {} }; MODULE_DEVICE_TABLE(platform, mrfld_extcon_id_table); static struct platform_driver mrfld_extcon_driver = { .driver = { .name = "mrfld_bcove_pwrsrc", }, .probe = mrfld_extcon_probe, .remove = mrfld_extcon_remove, .id_table = mrfld_extcon_id_table, }; module_platform_driver(mrfld_extcon_driver); MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_DESCRIPTION("extcon driver for Intel Merrifield Basin Cove PMIC"); MODULE_LICENSE("GPL v2");
yuri0x7c1/uxerp
uxcrm-ofbiz/generated-entity-service/src/main/java/org/apache/ofbiz/accounting/tax/service/base/TaxAuthorityRateProductBaseService.java
<reponame>yuri0x7c1/uxerp<gh_stars>0 package org.apache.ofbiz.accounting.tax.service.base; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.apache.ofbiz.common.ExecuteFindService.In; import org.apache.ofbiz.common.ExecuteFindService.Out; import org.apache.ofbiz.common.ExecuteFindService; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import java.util.Collections; import org.apache.commons.collections4.CollectionUtils; import java.util.Optional; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.condition.EntityConditionList; import org.apache.ofbiz.entity.condition.EntityExpr; import org.apache.ofbiz.entity.condition.EntityOperator; import com.github.yuri0x7c1.uxcrm.util.OfbizUtil; import org.apache.ofbiz.accounting.tax.TaxAuthorityRateProduct; import org.springframework.beans.factory.annotation.Autowired; import org.apache.ofbiz.accounting.tax.TaxAuthority; import org.apache.ofbiz.accounting.tax.TaxAuthorityRateType; import org.apache.ofbiz.product.store.ProductStore; import org.apache.ofbiz.product.category.ProductCategory; import org.apache.ofbiz.accounting.invoice.InvoiceItem; import org.apache.ofbiz.order.order.OrderAdjustment; import org.apache.ofbiz.order._return.ReturnAdjustment; @Slf4j @Component @SuppressWarnings("unchecked") public class TaxAuthorityRateProductBaseService { protected ExecuteFindService executeFindService; @Autowired public TaxAuthorityRateProductBaseService( ExecuteFindService executeFindService) { this.executeFindService = executeFindService; } /** * Count TaxAuthorityRateProducts */ public Integer count(EntityConditionList conditions) { In in = new In(); in.setEntityName(TaxAuthorityRateProduct.NAME); if (conditions == null) { in.setNoConditionFind(OfbizUtil.Y); } else { in.setEntityConditionList(conditions); } Out out = executeFindService.runSync(in); return out.getListSize(); } /** * Find TaxAuthorityRateProducts */ public List<TaxAuthorityRateProduct> find(Integer start, Integer number, List<String> orderBy, EntityConditionList conditions) { List<TaxAuthorityRateProduct> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(TaxAuthorityRateProduct.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); if (conditions == null) { in.setNoConditionFind(OfbizUtil.Y); } else { in.setEntityConditionList(conditions); } Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = TaxAuthorityRateProduct.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Find one TaxAuthorityRateProduct */ public Optional<TaxAuthorityRateProduct> findOne( Object taxAuthorityRateSeqId) { List<TaxAuthorityRateProduct> entityList = null; In in = new In(); in.setEntityName(TaxAuthorityRateProduct.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("taxAuthorityRateSeqId", EntityOperator.EQUALS, taxAuthorityRateSeqId)), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = TaxAuthorityRateProduct.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get tax authority */ public Optional<TaxAuthority> getTaxAuthority( TaxAuthorityRateProduct taxAuthorityRateProduct) { List<TaxAuthority> entityList = null; In in = new In(); in.setEntityName(TaxAuthority.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays.asList( new EntityExpr("taxAuthGeoId", EntityOperator.EQUALS, taxAuthorityRateProduct.getTaxAuthGeoId()), new EntityExpr("taxAuthPartyId", EntityOperator.EQUALS, taxAuthorityRateProduct.getTaxAuthPartyId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = TaxAuthority.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get tax authority rate type */ public Optional<TaxAuthorityRateType> getTaxAuthorityRateType( TaxAuthorityRateProduct taxAuthorityRateProduct) { List<TaxAuthorityRateType> entityList = null; In in = new In(); in.setEntityName(TaxAuthorityRateType.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("taxAuthorityRateTypeId", EntityOperator.EQUALS, taxAuthorityRateProduct .getTaxAuthorityRateTypeId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = TaxAuthorityRateType.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get product store */ public Optional<ProductStore> getProductStore( TaxAuthorityRateProduct taxAuthorityRateProduct) { List<ProductStore> entityList = null; In in = new In(); in.setEntityName(ProductStore.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("productStoreId", EntityOperator.EQUALS, taxAuthorityRateProduct.getProductStoreId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = ProductStore.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get product category */ public Optional<ProductCategory> getProductCategory( TaxAuthorityRateProduct taxAuthorityRateProduct) { List<ProductCategory> entityList = null; In in = new In(); in.setEntityName(ProductCategory.NAME); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("productCategoryId", EntityOperator.EQUALS, taxAuthorityRateProduct .getProductCategoryId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = ProductCategory.fromValues(out.getListIt() .getCompleteList()); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } if (CollectionUtils.isNotEmpty(entityList)) { return Optional.of(entityList.get(0)); } return Optional.empty(); } /** * Get invoice items */ public List<InvoiceItem> getInvoiceItems( TaxAuthorityRateProduct taxAuthorityRateProduct, Integer start, Integer number, List<String> orderBy) { List<InvoiceItem> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(InvoiceItem.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("taxAuthorityRateSeqId", EntityOperator.EQUALS, taxAuthorityRateProduct .getTaxAuthorityRateSeqId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = InvoiceItem.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Get order adjustments */ public List<OrderAdjustment> getOrderAdjustments( TaxAuthorityRateProduct taxAuthorityRateProduct, Integer start, Integer number, List<String> orderBy) { List<OrderAdjustment> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(OrderAdjustment.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("taxAuthorityRateSeqId", EntityOperator.EQUALS, taxAuthorityRateProduct .getTaxAuthorityRateSeqId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = OrderAdjustment.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } /** * Get return adjustments */ public List<ReturnAdjustment> getReturnAdjustments( TaxAuthorityRateProduct taxAuthorityRateProduct, Integer start, Integer number, List<String> orderBy) { List<ReturnAdjustment> entityList = Collections.emptyList(); In in = new In(); in.setEntityName(ReturnAdjustment.NAME); if (start == null) { start = OfbizUtil.DEFAULT_FIND_START; } if (number == null) { number = OfbizUtil.DEFAULT_FIND_NUMBER; } in.setOrderByList(orderBy); in.setEntityConditionList(new EntityConditionList<>(Arrays .asList(new EntityExpr("taxAuthorityRateSeqId", EntityOperator.EQUALS, taxAuthorityRateProduct .getTaxAuthorityRateSeqId())), EntityOperator.AND)); Out out = executeFindService.runSync(in); try { if (out.getListIt() != null) { entityList = ReturnAdjustment.fromValues(out.getListIt() .getPartialList(start, number)); out.getListIt().close(); } } catch (GenericEntityException e) { log.error(e.getMessage(), e); } return entityList; } }
reels-research/iOS-Private-Frameworks
CoreDuet.framework/_DKPRValueType.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/CoreDuet.framework/CoreDuet */ @interface _DKPRValueType : PBCodable <NSCopying> { int _type; long long _typeCode; } @property (nonatomic) int type; @property (nonatomic) long long typeCode; - (int)StringAsType:(id)arg1; - (void)copyTo:(id)arg1; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (id)description; - (id)dictionaryRepresentation; - (unsigned long long)hash; - (bool)isEqual:(id)arg1; - (void)mergeFrom:(id)arg1; - (bool)readFrom:(id)arg1; - (void)setType:(int)arg1; - (void)setTypeCode:(long long)arg1; - (int)type; - (id)typeAsString:(int)arg1; - (long long)typeCode; - (void)writeTo:(id)arg1; @end
atlasapi/atlas
src/main/java/org/atlasapi/remotesite/barb/channels/BarbChannelsModule.java
package org.atlasapi.remotesite.barb.channels; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.metabroadcast.common.ids.SubstitutionTableNumberCodec; import com.metabroadcast.common.scheduling.RepetitionRule; import com.metabroadcast.common.scheduling.RepetitionRules; import org.atlasapi.input.ChannelModelTransformer; import org.atlasapi.input.ImageModelTransformer; import org.atlasapi.media.channel.ChannelWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class BarbChannelsModule { private static final Logger log = LoggerFactory.getLogger(BarbChannelsModule.class); private static final RepetitionRule MAS_INGEST_REPETITION = RepetitionRules.NEVER; private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules().registerModule(new Jdk8Module()); private final ChannelModelTransformer modelTransformer; @Autowired private ChannelWriter channelWriter; // @Autowired // SimpleScheduler scheduler; // @Value("${barb.ftp.username}") // private String ftpUsername; // @Value("${barb.ftp.password}") // private String ftpPassword; // @Value("${barb.ftp.host}") // private String ftpHost; public BarbChannelsModule() { modelTransformer = ChannelModelTransformer.create( SubstitutionTableNumberCodec.lowerCaseOnly(), ImageModelTransformer.create() ); } @Bean protected BarbChannelIngestController barbChannelForceIngestController() { return new BarbChannelIngestController(channelWriter, modelTransformer, mapper); } // @PostConstruct // public void scheduleTask() { // ScheduledTask barbTask = BarbChannelDataIngester // .create(buildFtpClient()) // .withName("Barb .MAS Channel Updater"); // // scheduler.schedule(barbTask, MAS_INGEST_REPETITION); // } // // private FTPClient buildFtpClient() { // try { // FTPClient ftpClient = new FTPClient(); // ftpClient.user(ftpUsername); // ftpClient.pass(ftpPassword); // ftpClient.connect(ftpHost); // // return ftpClient; // } catch (IOException e) { // log.error("Failed to connect to ftp host", e); // throw Throwables.propagate(e); // } // } }
roderickmackenzie/gpvdm
gpvdm_gui/gui/lasers.py
<filename>gpvdm_gui/gui/lasers.py # # General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall # model for 1st, 2nd and 3rd generation solar cells. # Copyright (C) 2008-2022 <NAME> r.<EMAIL>.<EMAIL> at googlemail.com # # https://www.gpvdm.com # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License v2.0, as published by # the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # ## @package lasers # Main laser editor window. # import os import webbrowser from tab import tab_class from icon_lib import icon_get import i18n _ = i18n.language.gettext #qt from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication from PyQt5.QtGui import QIcon, QPainter, QFont, QColor from PyQt5.QtCore import QSize, Qt from PyQt5.QtWidgets import QWidget,QSizePolicy,QVBoxLayout,QPushButton,QDialog,QFileDialog,QToolBar,QLabel,QComboBox, QTabWidget,QStatusBar,QMenuBar, QTabBar, QStylePainter, QStyleOptionTab,QStyle #window from gui_util import yes_no_dlg from gui_util import dlg_get_text from util import wrap_text from QWidgetSavePos import QWidgetSavePos from cal_path import get_sim_path from css import css_apply from experiment import experiment class lasers(experiment): def __init__(self,data=None): experiment.__init__(self,window_save_name="laser_editor", window_title=_("Laser editor"),name_of_tab_class="jvexperiment_tab",json_search_path="gpvdm_data().lasers") self.notebook.currentChanged.connect(self.switch_page) #self.ribbon.tb_save.setVisible(False) self.switch_page() def switch_page(self): tab = self.notebook.currentWidget() #self.tb_lasers.update(tab.data)
j75689/Tmaster
pkg/utils/launcher/launcher.go
<filename>pkg/utils/launcher/launcher.go package launcher import ( "errors" "fmt" "os" "os/signal" "syscall" "time" ) // Launch service gracefully, or force exit after two consecutive signals func Launch(start func() error, shutdown func() error, timeout time.Duration) { done := make(chan int) go func() { if err := start(); err != nil { fmt.Println(err) done <- 1 } done <- 0 }() ch := make(chan os.Signal, 2) signal.Notify(ch, []os.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT}...) select { case exitCode := <-done: if shutdown != nil { if err := shutdownWithTimeout(shutdown, timeout); err != nil { fmt.Println(err) } } os.Exit(exitCode) case s := <-ch: fmt.Printf("received signal %s: terminating\n", s) if shutdown != nil { if err := shutdownWithTimeout(shutdown, timeout); err != nil { fmt.Println(err) } } os.Exit(0) } } func shutdownWithTimeout(shutdown func() error, timeout time.Duration) error { done := make(chan error) go func() { done <- shutdown() }() select { case <-time.After(timeout): return errors.New("timeout reached: terminating") case err := <-done: return err } }
damp-store/damp-store.github.io
theme/manual_install/theme1362/themes/theme1362/js/tools/vatManagement.js
<gh_stars>0 $(document).ready(function() { vat_number(); vat_number_ajax(); $(document).on('input', '#company, #company_invoice', function() { vat_number(); }); }); function vat_number() { if ($('#company').length && ($('#company').val() != '')) { $('#vat_number, #vat_number_block').show(); } else { $('#vat_number, #vat_number_block').hide(); } if ($('#company_invoice').length && ($('#company_invoice').val() != '')) { $('#vat_number_block_invoice').show(); } else { $('#vat_number_block_invoice').hide(); } } function vat_number_ajax() { $(document).on('change', '#id_country', function() { if ($('#company').length && !$('#company').val()) { return; } if (typeof vatnumber_ajax_call !== 'undefined' && vatnumber_ajax_call) { $.ajax({ type: 'POST', headers: {'cache-control': 'no-cache'}, url: baseDir + 'modules/vatnumber/ajax.php?id_country=' + parseInt($(this).val()) + '&rand=' + new Date().getTime(), success: function(isApplicable) { if (isApplicable == '1') { $('#vat_area').show(); $('#vat_number').show(); } else { $('#vat_area').hide(); } } }); } }); $(document).on('change', '#id_country_invoice', function() { if ($('#company_invoice').length && !$('#company_invoice').val()) { return; } if (typeof vatnumber_ajax_call !== 'undefined' && vatnumber_ajax_call) { $.ajax({ type: 'POST', headers: {'cache-control': 'no-cache'}, url: baseDir + 'modules/vatnumber/ajax.php?id_country=' + parseInt($(this).val()) + '&rand=' + new Date().getTime(), success: function(isApplicable) { if (isApplicable == '1') { $('#vat_area_invoice').show(); $('#vat_number_invoice').show(); } else { $('#vat_area_invoice').hide(); } } }); } }); }
Neusoft-Technology-Solutions/aws-sdk-cpp
aws-cpp-sdk-cognito-idp/source/model/DeviceRememberedStatusType.cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/cognito-idp/model/DeviceRememberedStatusType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace CognitoIdentityProvider { namespace Model { namespace DeviceRememberedStatusTypeMapper { static const int remembered_HASH = HashingUtils::HashString("remembered"); static const int not_remembered_HASH = HashingUtils::HashString("not_remembered"); DeviceRememberedStatusType GetDeviceRememberedStatusTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == remembered_HASH) { return DeviceRememberedStatusType::remembered; } else if (hashCode == not_remembered_HASH) { return DeviceRememberedStatusType::not_remembered; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<DeviceRememberedStatusType>(hashCode); } return DeviceRememberedStatusType::NOT_SET; } Aws::String GetNameForDeviceRememberedStatusType(DeviceRememberedStatusType enumValue) { switch(enumValue) { case DeviceRememberedStatusType::remembered: return "remembered"; case DeviceRememberedStatusType::not_remembered: return "not_remembered"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace DeviceRememberedStatusTypeMapper } // namespace Model } // namespace CognitoIdentityProvider } // namespace Aws
Kumulos/KumulosSdkObjectiveC
Sources/Shared/Http/KSUrlEncoding.h
// // KSUrlEncoding.h // KumulosSDK // #import <Foundation/Foundation.h> NSString* _Nonnull KSUrlEncodedStringFromDictionary(NSDictionary* _Nonnull obj);
ElSaico/vgmtrans
src/ui/windows/RawFileListView.h
<reponame>ElSaico/vgmtrans /** * VGMTrans (c) - 2002-2021 * Licensed under the zlib license * See the included LICENSE for more information */ #pragma once #include "VGMTransWindow.h" class RawFile; class CBmpBtn; #define VIEW_STYLES \ (LVS_REPORT | LVS_SHOWSELALWAYS | LVS_NOCOLUMNHEADER | LVS_SHOWSELALWAYS | LVS_SHAREIMAGELISTS | \ LVS_AUTOARRANGE) #define VIEW_EX_STYLES (LVS_EX_FULLROWSELECT) class CRawFileListView : public CWindowImpl<CRawFileListView, CListViewCtrl, CWinTraitsOR<VIEW_STYLES, VIEW_EX_STYLES>>, public VGMTransWindow<CRawFileListView> { protected: typedef CRawFileListView thisClass; typedef CWindowImpl<CRawFileListView, CListViewCtrl, CWinTraitsOR<VIEW_STYLES, VIEW_EX_STYLES>> baseClass; protected: WTL::CImageList m_ImageList; int nGenericFileIcon{}; public: DECLARE_WND_SUPERCLASS(NULL, CListViewCtrl::GetWndClassName()) BOOL PreTranslateMessage(MSG* pMsg); BEGIN_MSG_MAP(thisClass) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_DESTROY, OnDestroy) MSG_WM_SIZE(OnSize) MSG_WM_KEYDOWN(OnKeyDown) MSG_WM_CONTEXTMENU(OnContextMenu) COMMAND_ID_HANDLER_EX(ID_SAVERAWFILE, OnSaveAsRaw) COMMAND_ID_HANDLER_EX(IDC_CLOSEFILE, OnCloseFile) REFLECTED_NOTIFY_CODE_HANDLER(TVN_SELCHANGED, OnTvnSelchanged) if (uMsg == WM_FORWARDMSG) if (PreTranslateMessage((LPMSG)lParam)) return TRUE; DEFAULT_REFLECTION_HANDLER() END_MSG_MAP() LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled); void OnPaint(CDCHandle /*unused*/); void OnSize(UINT nType, CSize size); void OnKeyDown(TCHAR vkey, UINT repeats, UINT code); void OnLButtonDblClk(UINT nFlags, CPoint point); LRESULT OnTvnSelchanged(int idCtrl, LPNMHDR pnmh, BOOL& bHandled); LRESULT OnNMRClick(int idCtrl, LPNMHDR pnmh, BOOL& bHandled); LRESULT OnContextMenu(HWND hwndCtrl, CPoint ptClick); void OnSaveAsRaw(UINT uCode, int nID, HWND hwndCtrl); void OnCloseFile(UINT uCode, int nID, HWND hwndCtrl); void Init(); void InitImageLists(); void AddFile(RawFile* newFile); void RemoveFile(RawFile* theFile); }; extern CRawFileListView rawFileListView; #undef VIEW_STYLES #undef VIEW_EX_STYLES
ayjazz/OESS
nox/src/nox/netapps/lavi/lavi_flows.hh
<gh_stars>10-100 /* Copyright 2010 (C) Stanford University. * * This file is part of NOX. * * NOX is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NOX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NOX. If not, see <http://www.gnu.org/licenses/>. */ #ifndef lavi_flows_HH #define lavi_flows_HH #include "component.hh" #include "config.h" #include "messenger/jsonmessenger.hh" #include "flow.hh" #ifdef LOG4CXX_ENABLED #include <boost/format.hpp> #include "log4cxx/logger.h" #else #include "vlog.hh" #endif namespace vigil { using namespace std; using namespace vigil::container; /** \brief lavi_flows: base class for components handle flows * \ingroup noxcomponents * * Provides basic containers for subscribers and * function declaration for handling * * A request should be of the following JSON form * <PRE> * { * "type" : "lavi" * "command" : <string | "request", "subscribe", "unsubscribe"> * "flow_type" : <string | "all", ...> * } * </PRE> * * @author ykk * @date June 2010 */ class lavi_flows : public Component { public: /** \brief Retrieve stored flows? */ bool show_ongoing; /** \brief Constructor of lavi_flows. * * @param c context * @param node XML configuration (JSON object) */ lavi_flows(const Context* c, const json_object* node) : Component(c) {} /** \brief Configure lavi_flows. * * Parse the configuration, register event handlers, and * resolve any dependencies. * * @param c configuration */ void configure(const Configuration* c); /** \brief Start lavi_flows. * * Start the component. For example, if any threads require * starting, do it now. */ void install(); /** \brief Function to handle requests * * @param e json message event * @return CONTINUE */ Disposition handle_req(const Event& e); /** \brief Function to send list. * * @param stream message stream to send list to */ virtual void send_list(const Msg_stream& stream); /** \brief Get instance of lavi_flows. * @param c context * @param component reference to component */ static void getInstance(const container::Context* c, lavi_flows*& component); protected: /** \brief String describing flow type processed */ string flowtype; /** \brief List of interested subscribers */ list<Msg_stream*> interested; /** \brief Unsubscribe stream * * @param sock socket to unsubscribe */ virtual void unsubscribe(Msg_stream* sock); /** \brief Return flow id * * @param flow reference to flow * @return cookie, or hash code (if cookie==0) */ uint64_t get_id(const Flow& flow); }; } #endif
stackoverflow/novah-go
test/testutil.go
package test import "testing" func Equals[T comparable](t *testing.T, got, exp T) { if exp != got { t.Errorf("Result was incorrect: expected %v, got %v", exp, got) } }
Antholoj/netbeans
enterprise/j2ee.sun.ddui/src/org/netbeans/modules/j2ee/sun/ddloaders/multiview/web/SunWebJspConfigPropertyNode.java
<filename>enterprise/j2ee.sun.ddui/src/org/netbeans/modules/j2ee/sun/ddloaders/multiview/web/SunWebJspConfigPropertyNode.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.netbeans.modules.j2ee.sun.ddloaders.multiview.web; import java.util.ArrayList; import org.netbeans.modules.j2ee.sun.dd.api.ASDDVersion; import org.netbeans.modules.j2ee.sun.dd.api.CommonDDBean; import org.netbeans.modules.j2ee.sun.dd.api.web.JspConfig; import org.netbeans.modules.j2ee.sun.dd.api.web.SunWebApp; import org.netbeans.modules.j2ee.sun.dd.api.web.WebProperty; import org.netbeans.modules.j2ee.sun.ddloaders.multiview.BaseSectionNode; import org.netbeans.modules.j2ee.sun.ddloaders.multiview.tables.AttributeEntry; import org.netbeans.modules.j2ee.sun.ddloaders.multiview.tables.InnerTablePanel; import org.netbeans.modules.j2ee.sun.ddloaders.multiview.tables.ParentManagedDDBeanTableModel; import org.netbeans.modules.j2ee.sun.ddloaders.multiview.tables.TableEntry; import org.netbeans.modules.j2ee.sun.ddloaders.multiview.tables.ValueEntry; import org.netbeans.modules.xml.multiview.ui.SectionNodeInnerPanel; import org.netbeans.modules.xml.multiview.ui.SectionNodeView; import org.openide.util.NbBundle; /** * @author pfiala * @auther <NAME> */ public class SunWebJspConfigPropertyNode extends BaseSectionNode { public SunWebJspConfigPropertyNode(SectionNodeView sectionNodeView, SunWebApp sunWebApp, final ASDDVersion version) { super(sectionNodeView, sunWebApp, version, NbBundle.getMessage(SunWebJspConfigPropertyNode.class, "HEADING_JspConfigProperties"), ICON_BASE_MISC_NODE); } @Override protected SectionNodeInnerPanel createNodeInnerPanel() { ArrayList<TableEntry> tableColumns = new ArrayList<TableEntry>(3); tableColumns.add(new AttributeEntry( WebProperty.NAME, NbBundle.getMessage(SunWebJspConfigPropertyNode.class, "LBL_Name"), 150, true)); // NOI18N tableColumns.add(new AttributeEntry( WebProperty.VALUE, NbBundle.getMessage(SunWebJspConfigPropertyNode.class, "LBL_Value"), 150, true)); // NOI18N tableColumns.add(new ValueEntry( WebProperty.DESCRIPTION, NbBundle.getMessage(SunWebJspConfigPropertyNode.class, "LBL_Description"), 300)); // NOI18N SunWebApp swa = (SunWebApp) key; SectionNodeView sectionNodeView = getSectionNodeView(); return new InnerTablePanel(sectionNodeView, new ParentManagedDDBeanTableModel( sectionNodeView.getModelSynchronizer(), swa.getJspConfig(), JspConfig.PROPERTY, tableColumns, null, new JspConfigPropertyFactory()), version); } private static class JspConfigPropertyFactory implements ParentManagedDDBeanTableModel.ParentPropertyFactory { public CommonDDBean newInstance(CommonDDBean parent) { return ((JspConfig) parent).newWebProperty(); } } }
transitlinks/web-app
src/components/EmailInput/messages.js
<reponame>transitlinks/web-app<filename>src/components/EmailInput/messages.js import React from 'react'; import { defineMessages } from 'react-intl'; export default defineMessages({ 'email': { id: 'email.emailLabel', defaultMessage: 'E-mail', description: 'E-mail' }, 'missing-at': { id: 'email.missingAt', defaultMessage: '@ symbol is missing', description: '@ symbol is missing' }, 'missing-prefix': { id: 'email.missingPrefix', defaultMessage: 'E-mail prefix is missing', description: 'E-mail prefix is missing' }, 'too-many-ats': { id: 'email.tooManyAts', defaultMessage: 'Too many @ symbols', description: 'Too many @ symbols' }, 'missing-domain': { id: 'email.missingDomain', defaultMessage: 'Domain name is missing', description: 'Domain name is missing' }, 'missing-postfix': { id: 'email.missingPostfix', defaultMessage: 'Domain postfix is missing', description: 'Domain postfix is missing' }, 'postfix-too-short': { id: 'email.postfixTooShort', defaultMessage: 'Domain postfix too short', description: 'Domain postfix too short' } });
JumHorn/leetcode
Cplus/DeepestLeavesSum.cpp
#include <algorithm> using namespace std; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: int deepestLeavesSum(TreeNode *root) { return postorder(root).first; } pair<int, int> postorder(TreeNode *root) { if (root == nullptr) return {0, 0}; auto left = postorder(root->left); auto right = postorder(root->right); if (left.second == 0 && right.second == 0) return {root->val, 1}; if (left.second > right.second) return {left.first, left.second + 1}; if (left.second < right.second) return {right.first, right.second + 1}; return {left.first + right.first, left.second + 1}; } };
maartenbreddels/mab
gdfast/src/hyperquadtree.cpp
<filename>gdfast/src/hyperquadtree.cpp #include "hyperquadtree.hpp" //#include <boost/python.hpp> #include <algorithm> #include <iterator> namespace gd { //using namespace boost::python; void py_export_schw_hyperquadtree() { //NTree<2, double> quadtree(1.,2.,4.,6.); /*class_<DFGrid, boost::noncopyable >("DFGrid", init<int, int, double, double, Galaxy*>()) .def("output_grid", &DFGrid::output_grid) .def("n_dofs", &DFGrid::n_dofs) .def("refine_global", &DFGrid::refine_global) .def("shape_value", &DFGrid::shape_value) .def("print_dof_indices_per_face", &DFGrid::print_dof_indices_per_face) .def("print_dof_indices_per_face_on_level", &DFGrid::print_dof_indices_per_face_on_level) .def("print_vertices", &DFGrid::print_vertices) ;*/ } //template<size_t... Indices> //tuple<> get_indices( struct DoSomething { template<typename T> void operator()(T& t) const { //t.do_sth(); //printf("blaat"); } }; const int gs_scale = 300; // this makes gcc happy template<size_t N, typename... Tail> struct action; /*template<int A, int B> struct static_min { enum { value = A < B : A ? B }; };*/ template<int N> struct gridder { template<class Tree, class P> void grid(Tree *tree, ofstream& f, P p1, P p2, int *gridsizes) { cout << "Error: gridding not implemented for N = " << N << endl; } }; template<> struct gridder<2> { template<class Tree, class P> void grid(Tree *tree, ofstream& f, P p1, P p2, int *gridsizes) { double x1 = get<0>(p1); double x2 = get<0>(p2); double y1 = get<1>(p1); double y2 = get<1>(p2); cout << "x range" << x1 << " - " << x2 << endl; cout << "y range" << y1 << " - " << y2 << endl; f << "["; for(int xi = 0; xi < gridsizes[0]; xi++) { double x = x1 + xi * (x2-x1) / (gridsizes[0]-1); f << "["; for(int yi = 0; yi < gridsizes[1]; yi++) { double y = y1 + yi * (y2-y1) / (gridsizes[1]-1); //cout << "x,y" << x << "\t" << y << "\t" << tree->eval(x, y) << endl; //cout << "x,y" << x << "\t" << y << "\t" << tree->eval(x, y) << endl; f << tree->eval(x, y) << ","; } f << "],"; //cout << endl; } f << "]"; f.close(); } }; template<> struct gridder<3> { template<class Tree, class P> void grid(Tree *tree, ofstream& f, P p1, P p2, int *gridsizes) { double x1 = get<0>(p1); double x2 = get<0>(p2); double y1 = get<1>(p1); double y2 = get<1>(p2); double z1 = get<2>(p1); double z2 = get<2>(p2); cout << "x range" << x1 << " - " << x2 << endl; cout << "y range" << y1 << " - " << y2 << endl; cout << "z range" << z1 << " - " << z2 << endl; f << "["; for(int xi = 0; xi < gridsizes[0]; xi++) { f << "["; double x = x1 + xi * (x2-x1) / (gridsizes[0]-1); for(int yi = 0; yi < gridsizes[1]; yi++) { f << "["; double y = y1 + yi * (y2-y1) / (gridsizes[1]-1); for(int zi = 0; zi < gridsizes[2]; zi++) { double z = z1 + zi * (z2-z1) / (gridsizes[2]-1); //cout << "x,y" << x << "\t" << y << "\t" << tree->eval(x, y) << endl; //cout << "x,y" << x << "\t" << y << "\t" << tree->eval(x, y) << endl; f << tree->eval(x, y, z) << ","; } f << "],"; } //cout << endl; f << "],"; } f << "]"; f.close(); } }; template<size_t N, typename T, typename... Tail> struct action<N, T, Tail...> { typedef NTree<N, T, T, Tail...> HTree; typedef typename HTree::Point Point; typedef action<N-1, Tail...> sub_action_type; int dim; sub_action_type sub_action; HTree* tree; Point p1, p2; action(int dim) : dim(dim), sub_action(dim), tree(NULL) {} void init(int subdivides, string name) { //QuadTree::Point p1(0.0,0.0); if(N == dim) { tree = new HTree(p1, p2); //cout << "output: " << name << endl; while(subdivides--) tree->rootNode.split(); //tree->output(name); //tree.output_unknown(name); //tree->output_ps((name+".ps").c_str(), gs_scale, gs_scale); } else if(N >= 1) { sub_action.init(subdivides, name); } } void optimize(double absfraction=0.2, double relfraction=0.05, int Nabsmin=1, int Nrelmin=0, int maxlevel=8, int max_level_difference=0) { if(N == dim) { double error = 0; cout << "integral is: " << tree->integrate(error) << endl; cout << "error is: " << error << endl; tree->optimize(absfraction, relfraction, Nabsmin, Nrelmin, maxlevel, max_level_difference); } else { sub_action.optimize(absfraction, relfraction, Nabsmin, Nrelmin, maxlevel, max_level_difference); } } void limit_level_difference(int max_level_difference) { if(N == dim) { //double error = 0; tree->limit_level_difference(max_level_difference); } else { sub_action.limit_level_difference(max_level_difference); } } void read(string inputname) { if(N == dim) { ifstream f; string filename_state = inputname + ".state"; f.open(filename_state.c_str()); cout << "reading from: " << filename_state << endl; if(!f.is_open()) throw runtime_error((string("file doesn't exists: ") + filename_state)); //Point p1, p2; f >> p1 >> p2; cout << p1 << ", " << p2 << endl; vector<bool> splits; copy(istream_iterator<bool>(f), istream_iterator<bool>(), back_inserter(splits)); //copy(splits.begin(), splits.end(), ostream_iterator<bool>(cout, " ")); cout << "size: " << splits.size() << endl; //HTree tree(p1, p2); tree = new HTree(p1, p2); auto b = splits.begin(); tree->rootNode.split(&b); assert(b == splits.end()); tree->readpoints(inputname+".known"); tree->readpoints(inputname+".solved"); /*tree.output_ps((outputname+".check.ps").c_str(), gs_scale, gs_scale); tree.readpoints(inputname+".known"); tree.readpoints(inputname+".solved"); double error = 0; cout << "integral is: " << tree.integrate(error) << endl; cout << "error is: " << error << endl; tree.optimize(0.0, 0.0, 10, 0); tree.output(outputname); tree.output_ps((outputname+".ps").c_str(), gs_scale, gs_scale);*/ } else if(N >= 1) { sub_action.read(inputname); } } void write(string filename) { if(N == dim) { tree->output(filename); tree->output_ps((filename+".eps").c_str(), gs_scale, gs_scale); } else if(N >= 1) { sub_action.write(filename); } } void grid(string name, int* gridsizes) { if(N == dim) { ofstream f; string filename = name+".grid"; f.open(filename); cout << "output filename: " << filename << endl; gridder<N> g; g.grid(tree, f, p1, p2, gridsizes); } else if(N >= 1) { sub_action.grid(name, gridsizes); } } void set_point1(T value, int point_dim) { if(N == dim) { do_tuple(p1, point_dim, [&](T& tuple_ref, bool last) { tuple_ref = value;} ); } else if(N >= 1) { sub_action.set_point1(value, point_dim); } } void set_point2(T value, int point_dim) { if(N == dim) { do_tuple(p2, point_dim, [&](T& tuple_ref, bool last) { tuple_ref = value;} ); } else if(N >= 1) { sub_action.set_point2(value, point_dim); } } }; template<typename T> struct action<1, T> { action(int dim) {} void set_point1(T value, int point_dim) { } void set_point2(T value, int point_dim) { } void init(int subdivides, string name) { } void read(string inputname) { } void write(string inputname) { } void optimize(double absfraction=0.2, double relfraction=0.05, int Nabsmin=1, int Nrelmin=0, int maxlevel=8, int max_level_difference=0) {} void grid(string name, int* gridsizes) {} void limit_level_difference(int max_level_difference) { } }; #include <unistd.h> #include <getopt.h> int option_do_init = 0; int option_do_help = 0; option options[] = { {"init", no_argument, 0, 'i'}, {"grid", no_argument, 0, 'g'}, {"initialize", no_argument, 0, 'i'}, {"optimize", no_argument, 0, 't'}, {"help", no_argument, 0, 'h'}, {"dimension", required_argument, 0, 'd'}, {"limit-level-difference", required_argument, 0, 'l'}, {"subdivides", required_argument, 0, 's'}, {"output", required_argument, 0, 'o'}, {"input", optional_argument, 0, 'n'}, {0} }; extern "C" int main(int argc, char* const * argv) { //tuple<double, double, double> t(1,2,3); //tuple<double, double> t2 = get_indices<1,2>(t); //tuple<double, double> t(1,2); //std::cout << *boost::fusion::begin(t) << '\n'; //boost::fusion::for_each(t, DoSomething()); //return 0; /*cout << "test: " << log(0) << endl; cout << "test: " << exp(log(0)) << endl; cout << "test: " << isinf(log(0)) << endl; cout << "test: " << (log(0) < 0) << endl; cout << "test: " << save_exp(log(0)) << endl;*/ int indexptr; int c; int dim = 0; int subdivides = 0; int max_level_difference = 0; bool init = false; bool optimize = false; bool do_grid = false; //bool do_limit_level_difference = false; string outputname; string inputname; while((c = getopt_long(argc, argv, "gn:o:ihd:s:tl:", &options[0], &indexptr)) != -1) { switch(c) { case 0: printf("long option: %s", options[indexptr].name); if(optarg) printf("with arg: %s", optarg); printf("\n"); break; case 'h': printf("usage: %s -d <dim> [options]\n", argv[0]); break; case 'i': printf("initialize\n"); init = true; break; case 'g': printf("grid\n"); do_grid = true; break; case 'd': dim = atoi(optarg); printf("dimension: %i\n", dim); break; case 'l': max_level_difference = atoi(optarg); printf("maximum limit difference: %i\n", max_level_difference); //do_limit_level_difference = true; break; case 'o': outputname = string(optarg); printf("output: %s\n", outputname.c_str()); break; case 'n': inputname = string(optarg); printf("input: %s\n", inputname.c_str()); break; case 't': optimize = true; break; case 's': if(optarg == NULL) { fprintf(stderr, "subdivides requires int argument\n"); exit(-1); } subdivides = atoi(optarg); printf("subdivide: %d\n", subdivides); break; default: abort(); } } typedef action<5, double, double, double, double, double> action_highest_type; action_highest_type action_highest(dim); if(init) { for (int i = optind; i < argc; i++) { int index = i - optind; // 0 based index if(index >= dim) { //printf ("do %s\n", argv[i]); double value = atof(argv[i]); action_highest.set_point2(value, index-dim); } else { //printf ("do %s\n", argv[i]); double value = atof(argv[i]); action_highest.set_point1(value, index); } } /*cout << "p1 " << action_init_highest.p1 << endl; cout << "p2 " << action_init_highest.p2 << endl; cout << "p1 " << action_init_highest.sub_action.p1 << endl; cout << "p2 " << action_init_highest.sub_action.p2 << endl; cout << "p1s " << tuple_size<typename action_init_highest_type::Point>::value << endl;*/ //action_init_highest.subdivide(dim, outputname); action_highest.init(subdivides, outputname); action_highest.write(outputname); } if(optimize) { if((argc-optind) != 5) { fprintf(stderr, "please give optimization parameters\n"); exit(2); } double absfraction=atof(argv[optind+0]); double relfraction=atof(argv[optind+1]); int Nabsmin=atoi(argv[optind+2]); int Nrelmin=atoi(argv[optind+3]); int maxlevel=atoi(argv[optind+4]); cout << "absfraction, relfraction, Nabsmin, Nrelmin" << absfraction << "," << relfraction << "," << Nabsmin << "," << Nrelmin << endl; action_highest.read(inputname); action_highest.optimize(absfraction, relfraction, Nabsmin, Nrelmin, maxlevel, max_level_difference); /*if(do_limit_level_difference) { action_highest.limit_level_difference(max_level_difference); }*/ action_highest.write(outputname); } if(do_grid) { cout << "starting gridding..." << endl; action_highest.read(inputname); cout << "starting gridding..." << endl; if((argc-optind) != dim) { fprintf(stderr, "please give gridsize with proper dimension\n"); exit(2); } cout << "starting gridding..." << endl; int * gridsizes = new int[argc-optind]; for (int i = optind; i < argc; i++) { int index = i - optind; // 0 based index gridsizes[index] = atoi(argv[i]); printf ("gridsizes[%d] = %d\n", index, gridsizes[index]); } cout << "starting gridding..." << endl; action_highest.grid(inputname, gridsizes); delete gridsizes; //action_init_highest.do_grid(dim, subdivides, inputname, outputname); } return 0; int count = atoi(argv[1]); double absfraction = atof(argv[2]); int Nabsmin = atoi(argv[3]); double relfraction = atof(argv[4]); int Nrelmin = atoi(argv[5]); cout << "Nabsmin: " << Nabsmin << endl; double error = 0; //int optimize = atoi(argv[6]); NLinear<1, 2, double> linear(3., 2.); NLinear<1, 2, double> linear2(4., 6.); NLinear<2, 2, double> bilinear(linear, linear2); cout << "integral " << linear.integrate() << ", " << linear.integrate(0., 1., 0., 1.) << endl; cout << "integral " << linear2.integrate() << ", " << linear2.integrate(0., 1., 0., 1.) << endl; cout << "integral " << linear2.integrate(0., 1.0) << endl; cout << "integral " << bilinear.integrate() << endl; cout << "integral " << bilinear.integrate(0., 1., 0., 1.) << endl; cout << "integral " << bilinear.integrate(0., 0.5, 0., 0.5) << endl; cout << "integral " << bilinear.integrate2(0., 0.5, 0., 1., 0., 0.5, 0., 1.0) << endl; cout << "integral " << bilinear.integrate2(0.5, 3., 4., 10., 1., 5., 3., 8.0) << endl; //cout << "integral " << bilinear.integrate2(1., 5., 3., 8.0, 0.5, 3., 4., 10.) << endl; typedef NTree<2, double, double, double> QuadTree; typedef NTree<3, double, double, double, double> OcTree; QuadTree::Point p1(0.0,0.0); QuadTree::Point p2(14.0, 14.); set<QuadTree::Point> s; s.insert(p1); s.insert(p1); s.insert(p2); QuadTree quadtree(p1, p2); OcTree::Point v1(0.0,0.0,0.0); OcTree::Point v2(14.0,14.0,14.0); OcTree octree(v1, v2); //quadtree.add_point(0., 1.); //quadtree.rootNode.printinfo(); /*quadtree.rootNode.walkrange([](double x1, double x2, double y1, double y2) { cout << "quad x:[" << x1 << "," << x2 << "]" << " y:[" << y1 << "," << y2 << "]" << endl; }); quadtree.rootNode.walk([](double x, double y, double value) { cout << "point x:[" << x << "]" << " y:[" << y << "] value:" << value << endl; }); quadtree.rootNode.eval([](double x, double y) { return x*y; }); quadtree.rootNode.walk([](double x, double y, double value) { cout << "point x:[" << x << "]" << " y:[" << y << "] value:" << value << endl; });*/ /*for_each(quadtree.points.begin(), quadtree.points.end(), [](QuadTree::Point p) { cout << "p x:[" << get<0>(p) << "]" << " y:[" << get<1>(p) << "]" << endl; });*/ cout << "split" << endl; fflush(stdout); cout << "octree: # vertices: " << octree.points.size() << endl; octree.rootNode.split(); //octree.rootNode.split(); cout << "octree: # vertices: " << octree.points.size() << endl; cout << "quadtree: # vertices: " << quadtree.points.size() << endl; quadtree.rootNode.split(); cout << "quadtree: # vertices: " << quadtree.points.size() << endl; //octree.rootNode.split(); //quadtree.rootNode.split(); octree.eval([](OcTree::Point p) { double x = get<0>(p); double y = get<1>(p); double z = get<2>(p); return exp(-0.5*( pow(x-2,2) + pow(y-2, 2) + pow(z-9,2)) ) * 1./(2*M_PI); }); quadtree.eval([](QuadTree::Point p) { double x = get<0>(p); double y = get<1>(p); return exp(-0.5*( pow(x-2,2) + pow(y-2, 2) ) ) * 1./(2*M_PI);// + //exp(-0.5*( pow(x-8,2) + pow(y-8, 2) ) ) * 1./(2*M_PI); }); cout << "integrated: " << quadtree.integrate(error) << endl; //cout << "integrated(oc): " << octree.integrate() << endl; for(int i = 0; i < count; i++) { //quadtree.rootNode.split(); if(optimize) { quadtree.optimize(absfraction, relfraction, Nabsmin, Nrelmin); octree.optimize(absfraction, relfraction, Nabsmin, Nrelmin); } else { quadtree.rootNode.split(); octree.rootNode.split(); } quadtree.eval([](QuadTree::Point p) { double x = get<0>(p); double y = get<1>(p); return exp(-0.5*( pow(x-2,2) + pow(y-2, 2) ) ) * 1./(2*M_PI);// + //exp(-0.5*( pow(x-8,2) + pow(y-8, 2) ) ) * 1./(2*M_PI); }); octree.eval([](OcTree::Point p) { double x = get<0>(p); double y = get<1>(p); double z = get<2>(p); return exp(-0.5*( pow(x-2,2) + pow(y-2, 2) + pow(z-9,2)) ) * 1./(2*M_PI); }); error = 0.; cout << "# of points: " << quadtree.points.size() << endl; cout << "integrated: " << quadtree.integrate(error); cout << " error = " << error << endl; error = 0.; cout << "# of points(oc): " << octree.points.size() << endl; cout << "integrated(oc): " << octree.integrate(error); cout << " error = " << error << endl; } /* quadtree.rootNode.split(); quadtree.rootNode.left.subleft->split(); quadtree.rootNode.left.subleft->right.subright->split(); quadtree.rootNode.left.subleft->right.subright->left.subleft->split(); quadtree.rootNode.left.subleft->right.subright->left.subleft->right.subright->split(); quadtree.rootNode.split();*/ /*quadtree.rootNode.walk([](double x, double y, double value) { cout << "point x:[" << x << "]" << " y:[" << y << "] value:" << value << endl; });*/ /*for_each(quadtree.points.begin(), quadtree.points.end(), [](QuadTree::Point p) { cout << "p x:[" << get<0>(p) << "]" << " y:[" << get<1>(p) << "]" << endl; });*/ quadtree.output_ps("quadtree.ps", 30., 30., 1.); quadtree.output_gpl("quadtree.gpl", 30., 30., 1.); octree.output_ps<0,1>("octree_xy.ps", 30., 30., 1.); octree.output_ps<0,2>("octree_xz.ps", 30., 30., 1.); quadtree.output("quadtree.ntree"); /*cout << "size: " << quadtree.points.size() << endl; quadtree.rootNode.split(); cout << "size: " << quadtree.points.size() << endl; quadtree.rootNode.split(); cout << "size: " << quadtree.points.size() << endl;*/ //quadtree.rootNode.left.split() } };
eaxdev/JsonSQL4J
src/main/java/io/github/eaxdev/jsonsql4j/model/criteria/Gt.java
package io.github.eaxdev.jsonsql4j.model.criteria; import com.fasterxml.jackson.annotation.JsonTypeName; import lombok.Getter; import lombok.NoArgsConstructor; /** * @author eaxdev */ @Getter @JsonTypeName("gt") @NoArgsConstructor public class Gt extends SimpleCriteria { public Gt(String fieldName, String value) { super(fieldName, value); } @Override public SimpleConditionalOperator getSimpleConditionalOperator() { return SimpleConditionalOperator.GREATER_THAN; } @Override public CriteriaType getCriteriaType() { return CriteriaType.SIMPLE; } }
lechuckroh/code-assessment
app/exam/exam.js
<gh_stars>0 'use strict'; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const schemaHelper = require('../schema_helper'); const TestRun = require('./test_run'); /** * 인터뷰 대상자가 풀어야 할 문제들 */ const ExamSchema = new Schema({ interviewee: String, owner: String, archived: Boolean, dueDate: Date, createdAt: Date, startedAt: Date, finishedAt: Date, score: Number, tasks: [{ type: Schema.Types.ObjectId, ref: 'task' }], testRuns: [TestRun.schema] }); schemaHelper.customizeToJSON(ExamSchema); schemaHelper.customizeToObject(ExamSchema); const Exam = mongoose.model('exam', ExamSchema); module.exports = Exam;
Mu-L/iSulad
src/daemon/executor/container_cb/execution.c
<reponame>Mu-L/iSulad<filename>src/daemon/executor/container_cb/execution.c /****************************************************************************** * Copyright (c) Huawei Technologies Co., Ltd. 2017-2019. All rights reserved. * iSulad licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR * PURPOSE. * See the Mulan PSL v2 for more details. * Author: tanyifeng * Create: 2017-11-22 * Description: provide container list callback function definition ********************************************************************************/ #include "execution.h" #include <stdio.h> #include <pthread.h> #include <malloc.h> #include <sys/eventfd.h> #include <isula_libutils/container_config.h> #include <isula_libutils/container_config_v2.h> #include <isula_libutils/container_delete_request.h> #include <isula_libutils/container_delete_response.h> #include <isula_libutils/container_get_id_request.h> #include <isula_libutils/container_get_id_response.h> #include <isula_libutils/container_get_runtime_response.h> #include <isula_libutils/container_kill_request.h> #include <isula_libutils/container_kill_response.h> #include <isula_libutils/container_restart_request.h> #include <isula_libutils/container_restart_response.h> #include <isula_libutils/container_start_request.h> #include <isula_libutils/container_start_response.h> #include <isula_libutils/container_stop_request.h> #include <isula_libutils/container_stop_response.h> #include <isula_libutils/json_common.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "isula_libutils/log.h" #include "container_api.h" #include "execution_extend.h" #include "execution_information.h" #include "execution_stream.h" #include "execution_create.h" #include "io_handler.h" #include "runtime_api.h" #include "utils.h" #include "error.h" #include "events_sender_api.h" #include "service_container_api.h" #include "err_msg.h" #include "event_type.h" #include "utils_timestamp.h" #include "utils_verify.h" #ifdef ENABLE_NATIVE_NETWORK #include "utils_network.h" #include "service_network_api.h" #define STOP_TIMEOUT 10 #endif static int filter_by_label(const container_t *cont, const container_get_id_request *request) { int ret = 0; size_t i, len_key, len_val; char *p_equal = NULL; json_map_string_string *labels = NULL; if (request->label == NULL) { ret = 0; goto out; } if (cont->common_config->config == NULL || cont->common_config->config->labels == NULL || cont->common_config->config->labels->len == 0) { ERROR("No such container: %s", request->id_or_name); isulad_set_error_message("No such container: %s", request->id_or_name); ret = -1; goto out; } p_equal = strchr(request->label, '='); if (p_equal == NULL) { ERROR("Invalid label: %s", request->label); isulad_set_error_message("Invalid label: %s", request->label); ret = -1; goto out; } len_key = (size_t)(p_equal - request->label); len_val = (strlen(request->label) - len_key) - 1; labels = cont->common_config->config->labels; for (i = 0; i < labels->len; i++) { if (strlen(labels->keys[i]) == len_key && strncmp(labels->keys[i], request->label, len_key) == 0 && strlen(labels->values[i]) == len_val && strncmp(labels->values[i], p_equal + 1, len_val) == 0) { ret = 0; goto out; } } ret = -1; ERROR("No such container: %s", request->id_or_name); isulad_set_error_message("No such container: %s", request->id_or_name); out: return ret; } static void pack_get_id_response(container_get_id_response *response, const char *id, uint32_t cc) { if (response == NULL) { return; } response->cc = cc; if (g_isulad_errmsg != NULL) { response->errmsg = util_strdup_s(g_isulad_errmsg); DAEMON_CLEAR_ERRMSG(); } if (id != NULL) { response->id = util_strdup_s(id); } } static void pack_get_runtime_response(container_get_runtime_response *response, const char *runtime, uint32_t cc) { if (response == NULL) { return; } response->cc = cc; if (g_isulad_errmsg != NULL) { response->errmsg = util_strdup_s(g_isulad_errmsg); DAEMON_CLEAR_ERRMSG(); } if (runtime != NULL) { response->runtime = util_strdup_s(runtime); } } /* * This function gets long id of container by name or short id */ static int container_get_id_cb(const container_get_id_request *request, container_get_id_response **response) { char *id = NULL; uint32_t cc = ISULAD_SUCCESS; container_t *cont = NULL; DAEMON_CLEAR_ERRMSG(); if (request == NULL || response == NULL) { ERROR("Invalid NULL input"); return -1; } *response = util_common_calloc_s(sizeof(container_get_id_response)); if (*response == NULL) { ERROR("Out of memory"); cc = ISULAD_ERR_MEMOUT; goto pack_response; } if (!util_valid_container_id_or_name(request->id_or_name)) { ERROR("Invalid container name: %s", request->id_or_name ? request->id_or_name : ""); isulad_set_error_message("Invalid container name: %s", request->id_or_name ? request->id_or_name : ""); cc = ISULAD_ERR_EXEC; goto pack_response; } cont = containers_store_get(request->id_or_name); if (cont == NULL) { cc = ISULAD_ERR_EXEC; ERROR("No such container: %s", request->id_or_name); isulad_set_error_message("No such container: %s", request->id_or_name); goto pack_response; } if (filter_by_label(cont, request) != 0) { cc = ISULAD_ERR_EXEC; goto pack_response; } id = cont->common_config->id; pack_response: pack_get_id_response(*response, id, cc); container_unref(cont); return (cc == ISULAD_SUCCESS) ? 0 : -1; } static int container_get_runtime_cb(const char *real_id, container_get_runtime_response **response) { char *runtime = NULL; uint32_t cc = ISULAD_SUCCESS; container_t *cont = NULL; DAEMON_CLEAR_ERRMSG(); if (real_id == NULL || response == NULL) { ERROR("Invalid NULL input"); return -1; } *response = util_common_calloc_s(sizeof(container_get_runtime_response)); if (*response == NULL) { ERROR("Out of memory"); cc = ISULAD_ERR_MEMOUT; goto pack_response; } if (!util_valid_container_id_or_name(real_id)) { ERROR("Invalid container name: %s", real_id); isulad_set_error_message("Invalid container name: %s", real_id); cc = ISULAD_ERR_EXEC; goto pack_response; } cont = containers_store_get(real_id); if (cont == NULL) { cc = ISULAD_ERR_EXEC; ERROR("No such container: %s", real_id); isulad_set_error_message("No such container: %s", real_id); goto pack_response; } runtime = cont->runtime; pack_response: pack_get_runtime_response(*response, runtime, cc); container_unref(cont); return (cc == ISULAD_SUCCESS) ? 0 : -1; } static int start_request_check(const container_start_request *h) { int ret = 0; if (h == NULL || h->id == NULL) { ERROR("recive NULL Request id"); ret = -1; goto out; } if (!util_valid_container_id_or_name(h->id)) { ERROR("Invalid container name %s", h->id); isulad_set_error_message("Invalid container name %s", h->id); ret = -1; goto out; } out: return ret; } static int prepare_start_io(container_t *cont, const container_start_request *request, char **fifopath, char *fifos[], int stdinfd, struct io_write_wrapper *stdout_handler, struct io_write_wrapper *stderr_handler, int *sync_fd, pthread_t *thread_id) { int ret = 0; char *id = NULL; id = cont->common_config->id; if (request->attach_stdin || request->attach_stdout || request->attach_stderr) { if (create_daemon_fifos(id, cont->runtime, request->attach_stdin, request->attach_stdout, request->attach_stderr, "start", fifos, fifopath)) { ret = -1; goto out; } *sync_fd = eventfd(0, EFD_CLOEXEC); if (*sync_fd < 0) { ERROR("Failed to create eventfd: %s", strerror(errno)); ret = -1; goto out; } if (ready_copy_io_data(*sync_fd, false, request->stdin, request->stdout, request->stderr, stdinfd, stdout_handler, stderr_handler, (const char **)fifos, thread_id)) { ret = -1; goto out; } } out: return ret; } static void pack_start_response(container_start_response *response, uint32_t cc, const char *id) { if (response == NULL) { return; } response->cc = cc; if (g_isulad_errmsg != NULL) { response->errmsg = util_strdup_s(g_isulad_errmsg); DAEMON_CLEAR_ERRMSG(); } if (id != NULL) { response->id = util_strdup_s(id); } } static int container_start_prepare(container_t *cont, const container_start_request *request, int stdinfd, struct io_write_wrapper *stdout_handler, struct io_write_wrapper *stderr_handler, char **fifopath, char *fifos[], int *sync_fd, pthread_t *thread_id) { const char *id = cont->common_config->id; if (container_state_to_disk_locking(cont)) { ERROR("Failed to save container \"%s\" to disk", id); isulad_set_error_message("Failed to save container \"%s\" to disk", id); return -1; } if (prepare_start_io(cont, request, fifopath, fifos, stdinfd, stdout_handler, stderr_handler, sync_fd, thread_id) != 0) { return -1; } return 0; } static void handle_start_io_thread_by_cc(uint32_t cc, int sync_fd, pthread_t thread_id) { if (cc == ISULAD_SUCCESS) { if (thread_id > 0) { if (pthread_detach(thread_id) != 0) { SYSERROR("Failed to detach 0x%lx", thread_id); } } if (sync_fd >= 0) { close(sync_fd); } } else { if (sync_fd >= 0) { if (eventfd_write(sync_fd, 1) < 0) { ERROR("Failed to write eventfd: %s", strerror(errno)); } } if (thread_id > 0) { if (pthread_join(thread_id, NULL) != 0) { ERROR("Failed to join thread: 0x%lx", thread_id); } } if (sync_fd >= 0) { close(sync_fd); } } } static int container_start_cb(const container_start_request *request, container_start_response **response, int stdinfd, struct io_write_wrapper *stdout_handler, struct io_write_wrapper *stderr_handler) { uint32_t cc = ISULAD_SUCCESS; char *id = NULL; char *fifos[3] = { NULL, NULL, NULL }; char *fifopath = NULL; container_t *cont = NULL; int sync_fd = -1; pthread_t thread_id = 0; DAEMON_CLEAR_ERRMSG(); if (request == NULL || response == NULL) { ERROR("Invalid NULL input"); return -1; } *response = util_common_calloc_s(sizeof(container_start_response)); if (*response == NULL) { ERROR("Out of memory"); cc = ISULAD_ERR_MEMOUT; goto pack_response; } if (start_request_check(request)) { cc = ISULAD_ERR_INPUT; goto pack_response; } cont = containers_store_get(request->id); if (cont == NULL) { cc = ISULAD_ERR_EXEC; ERROR("No such container:%s", request->id); isulad_set_error_message("No such container:%s", request->id); goto pack_response; } id = cont->common_config->id; isula_libutils_set_log_prefix(id); EVENT("Event: {Object: %s, Type: Starting}", id); container_state_set_starting(cont->state); if (container_is_running(cont->state)) { INFO("Container is already running"); goto pack_response; } if (container_start_prepare(cont, request, stdinfd, stdout_handler, stderr_handler, &fifopath, fifos, &sync_fd, &thread_id) != 0) { cc = ISULAD_ERR_EXEC; goto pack_response; } if (start_container(cont, (const char **)fifos, true) != 0) { cc = ISULAD_ERR_EXEC; goto pack_response; } EVENT("Event: {Object: %s, Type: Running}", id); (void)isulad_monitor_send_container_event(id, START, -1, 0, NULL, NULL); pack_response: handle_start_io_thread_by_cc(cc, sync_fd, thread_id); delete_daemon_fifos(fifopath, (const char **)fifos); free(fifos[0]); free(fifos[1]); free(fifos[2]); free(fifopath); pack_start_response(*response, cc, id); if (cont != NULL) { container_state_reset_starting(cont->state); container_unref(cont); } isula_libutils_free_log_prefix(); malloc_trim(0); return (cc == ISULAD_SUCCESS) ? 0 : -1; } static int restart_container(container_t *cont) { int ret = 0; char timebuffer[512] = { 0 }; const char *id = cont->common_config->id; const char *runtime = cont->runtime; const char *rootpath = cont->root_path; rt_restart_params_t params = { 0 }; container_lock(cont); if (container_is_removal_in_progress(cont->state) || container_is_dead(cont->state)) { ERROR("Container is marked for removal and cannot be started."); isulad_set_error_message("Container is marked for removal and cannot be started."); goto out; } (void)util_get_now_time_buffer(timebuffer, sizeof(timebuffer)); params.rootpath = rootpath; ret = runtime_restart(id, runtime, &params); if (ret == -2) { goto out; } if (ret == 0) { container_restart_update_start_and_finish_time(cont->state, timebuffer); } if (container_state_to_disk(cont)) { ERROR("Failed to save container \"%s\" to disk", cont->common_config->id); ret = -1; goto out; } out: container_unlock(cont); return ret; } static uint32_t stop_and_start(container_t *cont, int timeout) { int ret = 0; uint32_t cc = ISULAD_SUCCESS; const char *console_fifos[3] = { NULL, NULL, NULL }; const char *id = cont->common_config->id; #ifdef ENABLE_NATIVE_NETWORK // skip remove network when restarting container set_container_skip_remove_network(cont); #endif ret = stop_container(cont, timeout, false, true); #ifdef ENABLE_NATIVE_NETWORK reset_container_skip_remove_network(cont); #endif if (ret != 0) { cc = ISULAD_ERR_EXEC; container_state_set_error(cont->state, (const char *)g_isulad_errmsg); goto out; } /* begin start container */ container_state_set_starting(cont->state); if (container_state_to_disk_locking(cont)) { ERROR("Failed to save container \"%s\" to disk", id); cc = ISULAD_ERR_EXEC; isulad_set_error_message("Failed to save container \"%s\" to disk", id); goto out; } if (container_is_running(cont->state)) { INFO("Container is already running"); goto out; } if (start_container(cont, console_fifos, true) != 0) { cc = ISULAD_ERR_EXEC; goto out; } out: container_state_reset_starting(cont->state); return cc; } static void pack_restart_response(container_restart_response *response, uint32_t cc, const char *id) { if (response == NULL) { return; } response->cc = cc; if (g_isulad_errmsg != NULL) { response->errmsg = util_strdup_s(g_isulad_errmsg); DAEMON_CLEAR_ERRMSG(); } if (id != NULL) { response->id = util_strdup_s(id); } } static uint32_t do_restart_container(container_t *cont, int timeout) { int ret = 0; ret = restart_container(cont); if (ret == -1) { container_state_set_error(cont->state, (const char *)g_isulad_errmsg); return ISULAD_ERR_EXEC; } else if (ret == RUNTIME_NOT_IMPLEMENT_RESET) { /* runtime don't implement restart, use stop and start */ return stop_and_start(cont, timeout); } return ISULAD_SUCCESS; } static int container_restart_cb(const container_restart_request *request, container_restart_response **response) { int timeout = 0; uint32_t cc = ISULAD_SUCCESS; char *name = NULL; char *id = NULL; container_t *cont = NULL; DAEMON_CLEAR_ERRMSG(); if (request == NULL || response == NULL) { ERROR("Invalid NULL input"); return -1; } *response = util_common_calloc_s(sizeof(container_restart_response)); if (*response == NULL) { ERROR("Out of memory"); cc = ISULAD_ERR_MEMOUT; goto pack_response; } name = request->id; timeout = request->timeout; if (!util_valid_container_id_or_name(name)) { cc = ISULAD_ERR_EXEC; ERROR("Invalid container name %s", name); isulad_set_error_message("Invalid container name %s", name); goto pack_response; } cont = containers_store_get(name); if (cont == NULL) { cc = ISULAD_ERR_EXEC; ERROR("No such container: %s", name); isulad_set_error_message("No such container:%s", name); goto pack_response; } id = cont->common_config->id; isula_libutils_set_log_prefix(id); EVENT("Event: {Object: %s, Type: restarting}", id); if (container_is_in_gc_progress(id)) { isulad_set_error_message("You cannot restart container %s in garbage collector progress.", id); ERROR("You cannot restart container %s in garbage collector progress.", id); cc = ISULAD_ERR_EXEC; goto pack_response; } cc = do_restart_container(cont, timeout); if (cc != ISULAD_SUCCESS) { goto pack_response; } EVENT("Event: {Object: %s, Type: Restarted}", id); (void)isulad_monitor_send_container_event(id, RESTART, -1, 0, NULL, NULL); pack_response: pack_restart_response(*response, cc, id); container_unref(cont); isula_libutils_free_log_prefix(); return (cc == ISULAD_SUCCESS) ? 0 : -1; } static void pack_stop_response(container_stop_response *response, uint32_t cc, const char *id) { if (response == NULL) { return; } response->cc = cc; if (g_isulad_errmsg != NULL) { response->errmsg = util_strdup_s(g_isulad_errmsg); DAEMON_CLEAR_ERRMSG(); } if (id != NULL) { response->id = util_strdup_s(id); } } static int container_stop_cb(const container_stop_request *request, container_stop_response **response) { int timeout = 0; bool force = false; char *name = NULL; char *id = NULL; uint32_t cc = ISULAD_SUCCESS; container_t *cont = NULL; DAEMON_CLEAR_ERRMSG(); if (request == NULL || response == NULL) { ERROR("Invalid NULL input"); return -1; } *response = util_common_calloc_s(sizeof(container_stop_response)); if (*response == NULL) { ERROR("Out of memory"); cc = ISULAD_ERR_MEMOUT; goto pack_response; } name = request->id; force = request->force; timeout = request->timeout; if (name == NULL) { ERROR("Stop: receive NULL id"); cc = ISULAD_ERR_INPUT; goto pack_response; } if (!util_valid_container_id_or_name(name)) { ERROR("Invalid container name %s", name); isulad_set_error_message("Invalid container name %s", name); cc = ISULAD_ERR_EXEC; goto pack_response; } cont = containers_store_get(name); if (cont == NULL) { ERROR("No such container:%s", name); isulad_set_error_message("No such container:%s", name); cc = ISULAD_ERR_EXEC; goto pack_response; } id = cont->common_config->id; isula_libutils_set_log_prefix(id); EVENT("Event: {Object: %s, Type: Stopping}", id); if (container_is_in_gc_progress(id)) { isulad_set_error_message("You cannot stop container %s in garbage collector progress.", id); ERROR("You cannot stop container %s in garbage collector progress.", id); cc = ISULAD_ERR_EXEC; goto pack_response; } if (stop_container(cont, timeout, force, false)) { cc = ISULAD_ERR_EXEC; container_state_set_error(cont->state, (const char *)g_isulad_errmsg); goto pack_response; } (void)isulad_monitor_send_container_event(id, STOP, -1, 0, NULL, NULL); EVENT("Event: {Object: %s, Type: Stopped}", id); pack_response: pack_stop_response(*response, cc, id); container_unref(cont); isula_libutils_free_log_prefix(); return (cc == ISULAD_SUCCESS) ? 0 : -1; } static void pack_kill_response(container_kill_response *response, uint32_t cc, const char *id) { if (response == NULL) { return; } response->cc = cc; if (g_isulad_errmsg != NULL) { response->errmsg = util_strdup_s(g_isulad_errmsg); DAEMON_CLEAR_ERRMSG(); } if (id != NULL) { response->id = util_strdup_s(id); } } static int container_kill_cb(const container_kill_request *request, container_kill_response **response) { int ret = 0; char *name = NULL; char *id = NULL; uint32_t signal = 0; uint32_t cc = ISULAD_SUCCESS; container_t *cont = NULL; DAEMON_CLEAR_ERRMSG(); if (request == NULL || response == NULL) { ERROR("Invalid NULL input"); return -1; } *response = util_common_calloc_s(sizeof(container_kill_response)); if (*response == NULL) { ERROR("Out of memory"); cc = ISULAD_ERR_MEMOUT; goto pack_response; } name = request->id; signal = request->signal; if (name == NULL) { ERROR("Kill: receive NULL id"); cc = ISULAD_ERR_INPUT; goto pack_response; } if (!util_valid_container_id_or_name(name)) { isulad_set_error_message("Invalid container name %s", name); ERROR("Invalid container name %s", name); cc = ISULAD_ERR_EXEC; goto pack_response; } if (!util_valid_signal((int)signal)) { isulad_set_error_message("Not supported signal %d", signal); ERROR("Not supported signal %d", signal); cc = ISULAD_ERR_EXEC; goto pack_response; } cont = containers_store_get(name); if (cont == NULL) { cc = ISULAD_ERR_EXEC; ERROR("No such container:%s", name); isulad_set_error_message("No such container:%s", name); goto pack_response; } id = cont->common_config->id; isula_libutils_set_log_prefix(id); EVENT("Event: {Object: %s, Type: Killing, Signal:%u}", id, signal); if (container_is_in_gc_progress(id)) { isulad_set_error_message("You cannot kill container %s in garbage collector progress.", id); ERROR("You cannot kill container %s in garbage collector progress.", id); cc = ISULAD_ERR_EXEC; goto pack_response; } ret = kill_container(cont, signal); if (ret != 0) { cc = ISULAD_ERR_EXEC; container_state_set_error(cont->state, (const char *)g_isulad_errmsg); goto pack_response; } EVENT("Event: {Object: %s, Type: Killed, Signal:%u}", id, signal); pack_response: pack_kill_response(*response, cc, id); container_unref(cont); isula_libutils_free_log_prefix(); return (cc == ISULAD_SUCCESS) ? 0 : -1; } static void pack_delete_response(container_delete_response *response, uint32_t cc, const char *id) { if (response == NULL) { return; } response->cc = cc; if (g_isulad_errmsg != NULL) { response->errmsg = util_strdup_s(g_isulad_errmsg); DAEMON_CLEAR_ERRMSG(); } if (id != NULL) { response->id = util_strdup_s(id); } } static int container_delete_cb(const container_delete_request *request, container_delete_response **response) { bool force = false; uint32_t cc = ISULAD_SUCCESS; char *name = NULL; char *id = NULL; container_t *cont = NULL; DAEMON_CLEAR_ERRMSG(); if (request == NULL || response == NULL) { ERROR("Invalid NULL input"); return -1; } *response = util_common_calloc_s(sizeof(container_delete_response)); if (*response == NULL) { ERROR("Out of memory"); cc = ISULAD_ERR_MEMOUT; goto pack_response; } name = request->id; force = request->force; if (!util_valid_container_id_or_name(name)) { ERROR("Invalid container name %s", name); isulad_set_error_message("Invalid container name %s", name); cc = ISULAD_ERR_INPUT; goto pack_response; } cont = containers_store_get(name); if (cont == NULL) { ERROR("No such container:%s", name); isulad_set_error_message("No such container:%s", name); cc = ISULAD_ERR_EXEC; goto pack_response; } id = cont->common_config->id; isula_libutils_set_log_prefix(id); EVENT("Event: {Object: %s, Type: Deleting}", id); container_lock(cont); int nret = set_container_to_removal(cont); container_unlock(cont); if (nret != 0) { ERROR("Failed to set container %s state to removal", id); cc = ISULAD_ERR_EXEC; goto pack_response; } cont->rm_anonymous_volumes = request->volumes; if (delete_container(cont, force)) { cc = ISULAD_ERR_EXEC; goto pack_response; } EVENT("Event: {Object: %s, Type: Deleted}", id); pack_response: pack_delete_response(*response, cc, id); container_unref(cont); isula_libutils_free_log_prefix(); return (cc == ISULAD_SUCCESS) ? 0 : -1; } static void pack_update_network_settings_response(container_update_network_settings_response *response, uint32_t cc, const char *id) { if (response == NULL) { return; } response->cc = cc; response->errmsg = util_strdup_s(g_isulad_errmsg); DAEMON_CLEAR_ERRMSG(); response->id = util_strdup_s(id); } static int update_container_network_setting_lock(container_t *cont, const char *setting_json) { int ret = 0; parser_error err = NULL; container_lock(cont); free_container_network_settings(cont->network_settings); cont->network_settings = container_network_settings_parse_data(setting_json, NULL, &err); if (cont->network_settings == NULL) { ERROR("Parse network settings failed: %s", err); ret = -1; goto out; } if (container_network_settings_to_disk(cont) != 0) { ERROR("Failed to save container '%s' network settings", cont->common_config->id); ret = -1; } out: container_unlock(cont); free(err); return ret; } static int container_update_network_settings_cb(const container_update_network_settings_request *request, container_update_network_settings_response **response) { uint32_t cc = ISULAD_SUCCESS; const char *name = NULL; const char *id = NULL; container_t *cont = NULL; if (request == NULL || response == NULL) { ERROR("Invalid NULL input"); return -1; } if (!util_valid_str(request->setting_json)) { DEBUG("Network setting is empty, no need to do anythin"); return 0; } DAEMON_CLEAR_ERRMSG(); *response = util_common_calloc_s(sizeof(container_update_network_settings_response)); if (*response == NULL) { ERROR("Out of memory"); cc = ISULAD_ERR_MEMOUT; goto pack_response; } name = request->id; if (!util_valid_container_id_or_name(name)) { ERROR("Invalid container name %s", name); isulad_set_error_message("Invalid container name %s", name); cc = ISULAD_ERR_INPUT; goto pack_response; } cont = containers_store_get(name); if (cont == NULL) { ERROR("No such container:%s", name); isulad_set_error_message("No such container:%s", name); cc = ISULAD_ERR_EXEC; goto pack_response; } id = cont->common_config->id; isula_libutils_set_log_prefix(id); EVENT("Event: {Object: %s, Type: Updating netorksettings}", id); if (update_container_network_setting_lock(cont, request->setting_json) != 0) { ERROR("Updated network settings to disk error"); cc = ISULAD_ERR_EXEC; goto pack_response; } EVENT("Event: {Object: %s, Type: Updated netorksettings}", id); pack_response: pack_update_network_settings_response(*response, cc, id); container_unref(cont); isula_libutils_free_log_prefix(); return (cc == ISULAD_SUCCESS) ? 0 : -1; } void container_callback_init(service_container_callback_t *cb) { cb->get_id = container_get_id_cb; cb->get_runtime = container_get_runtime_cb; cb->create = container_create_cb; cb->start = container_start_cb; cb->stop = container_stop_cb; cb->restart = container_restart_cb; cb->kill = container_kill_cb; cb->remove = container_delete_cb; cb->update_network_settings = container_update_network_settings_cb; container_information_callback_init(cb); container_stream_callback_init(cb); container_extend_callback_init(cb); }
jarekankowski/pegasus_spyware
sample4/recompiled_java/sources/com/lenovo/safecenter/mmsutils/PushReceiver.java
<filename>sample4/recompiled_java/sources/com/lenovo/safecenter/mmsutils/PushReceiver.java package com.lenovo.safecenter.mmsutils; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.Settings; import android.util.Log; import com.lenovo.lps.sus.a.a.a.b; import com.lenovo.performancecenter.framework.DatabaseTables; import com.lenovo.safecenter.floatwindow.util.SettingUtil; import java.io.UnsupportedEncodingException; public class PushReceiver extends BroadcastReceiver { public static final String BODY = "body"; public static final String CONTENT_MIME_TYPE_PUSH_MMS = "application/vnd.wap.mms-message"; public static final String CONTENT_MIME_TYPE_PUSH_SI = "application/vnd.wap.sic"; public static final String CONTENT_MIME_TYPE_PUSH_SL = "application/vnd.wap.slc"; public static final String DATE = "date"; public static final String ERR_TAG = "PushReceiver.java"; public static final String EXP = "exp"; public static final String M_CLS = "m_cls"; public static final String M_SIZE = "m_size"; public static final String M_TYPE = "m_type"; public static final String PHONE_NUMBER = "phone_number"; public static final String READ = "read"; public static final String SUB = "sub"; public static final String SUBJECT = "subject"; public static final String TAG = "Push Receiver"; public static final String TR_ID = "tr_id"; public static final String TYPE = "type"; public static final String V = "v"; public void onReceive(Context context, Intent intent) { UnsupportedEncodingException e; try { if ("android.provider.Telephony.WAP_PUSH_RECEIVED".equals(intent.getAction())) { byte[] pushData = intent.getByteArrayExtra(SettingUtil.DATA); HwDcdWapPushParser parser = new HwDcdWapPushParser(pushData); if (CONTENT_MIME_TYPE_PUSH_SL.equals(intent.getType())) { parser.parse(1).getAttributeValueString(HwDcdWapPushMsg.WAP_PUSH_PROJECTION_HREF); } else if (CONTENT_MIME_TYPE_PUSH_SI.equals(intent.getType())) { HwDcdWapPushMsg pushMsg = parser.parse(0); String str = pushMsg.getAttributeValueString(HwDcdWapPushMsg.WAP_PUSH_PROJECTION_SI_TEXT) + pushMsg.getAttributeValueString(HwDcdWapPushMsg.WAP_PUSH_PROJECTION_HREF); } else if ("application/vnd.wap.mms-message".equals(intent.getType())) { GenericPdu pdu = new TyuMMSParser(pushData).parse(); String val_from = pdu.getFrom().getString(); Log.i("messgae", "phone_number==" + val_from); ContentValues values = new ContentValues(); values.put("date", Long.valueOf(System.currentTimeMillis())); values.put(READ, (Integer) 1); switch (pdu.getMessageType()) { case 130: NotificationInd npdu = (NotificationInd) pdu; try { String location = new String(npdu.getContentLocation(), b.a); try { values.put("ct_l", location); Log.i("messgae", "body==" + location); try { String subject = npdu.getSubject().getString(); values.put(SUB, subject); Log.i("messgae", "sub==" + subject); } catch (Exception e1) { e1.printStackTrace(); } try { String transactionId = new String(npdu.getTransactionId(), b.a); values.put(TR_ID, transactionId); Log.i("messgae", "tr_id==" + transactionId); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } try { int v = npdu.getMmsVersion(); values.put(V, Integer.valueOf(v)); Log.i("messgae", "v==" + v); } catch (Exception e3) { e3.printStackTrace(); } try { long exp = npdu.getExpiry(); values.put(EXP, Long.valueOf(exp)); Log.i("messgae", "exp==" + exp); } catch (Exception e4) { e4.printStackTrace(); } try { long size = npdu.getMessageSize(); values.put(M_SIZE, Long.valueOf(size)); Log.i("messgae", "m_size==" + size); } catch (Exception e5) { e5.printStackTrace(); } try { String m_cls = new String(npdu.getMessageClass(), b.a); values.put(M_CLS, m_cls); Log.i("messgae", "m_cls==" + m_cls); } catch (UnsupportedEncodingException e6) { e6.printStackTrace(); } try { int messageType = npdu.getMessageType(); values.put(M_TYPE, Integer.valueOf(messageType)); Log.i("messgae", "m_type==" + messageType); } catch (Exception e7) { e7.printStackTrace(); } if (Settings.System.getInt(context.getContentResolver(), "guest_mode_on", 0) == 1) { abortBroadcast(); recoverData(context, val_from, values); } return; } catch (UnsupportedEncodingException e8) { e = e8; e.printStackTrace(); return; } } catch (UnsupportedEncodingException e9) { e = e9; e.printStackTrace(); return; } default: return; } } } } catch (Exception e10) { } } public static Uri recoverData(Context con, String address, ContentValues recover_values) { Uri data = null; int thread_id = 0; if (address != null) { try { ContentValues values = new ContentValues(); values.put("address", address); values.put("type", DatabaseTables.USER_MARK); values.put(READ, DatabaseTables.SYSTEM_MARK); values.put(BODY, "this is a test"); values.put("date", (Integer) 5211314); values.put("person", "test"); Uri sms_uri = con.getContentResolver().insert(Uri.parse("content://sms/inbox"), values); if (sms_uri != null) { String sms_id = sms_uri.toString().substring("content://sms/".length(), sms_uri.toString().length()); Cursor sms_cursor = con.getContentResolver().query(Uri.parse("content://sms"), new String[]{"thread_id"}, "_id=" + sms_id, null, null); if (sms_cursor != null && sms_cursor.getCount() > 0) { while (sms_cursor.moveToNext()) { thread_id = sms_cursor.getInt(0); } } if (sms_cursor != null) { sms_cursor.close(); } if (thread_id > 0) { recover_values.put("thread_id", Integer.valueOf(thread_id)); data = con.getContentResolver().insert(Uri.parse("content://mms/inbox"), recover_values); } con.getContentResolver().delete(Uri.parse("content://sms"), "_id=" + sms_id, null); } } catch (Exception e) { Log.i("test", e.toString()); con.getContentResolver().delete(Uri.parse("content://sms"), " date =5211314", null); } } return data; } }
tusharchoudhary0003/Custom-Football-Game
sources/com/google/android/gms/internal/ads/C9819xm.java
<reponame>tusharchoudhary0003/Custom-Football-Game package com.google.android.gms.internal.ads; /* renamed from: com.google.android.gms.internal.ads.xm */ final /* synthetic */ class C9819xm implements zzbal { /* renamed from: a */ private final zzczc f23475a; C9819xm(zzczc zzczc) { this.f23475a = zzczc; } /* renamed from: a */ public final zzbbh mo26658a(Object obj) { return zzbar.m26376a(this.f23475a.apply((Throwable) obj)); } }
st-a-novoseltcev/miet-patterns
interpreter/src/Corrector.java
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Corrector implements ICorrector { List<ICorrector> correctors; Corrector() { correctors = new LinkedList<>() {{ add(new DashCorrector()); add(new TabCorrector()); add(new QuoteCorrector()); add(new SpaceCorrector()); add(new EnterCorrector()); }}; } @Override public String execute(String context) { for (ICorrector corrector: correctors) { context = corrector.execute(context); } return context; } }
georgiannechifor/food-library
src/store/reducer/auth.js
import {handleActions} from 'redux-actions'; import {ActionTypes} from '../action/auth'; import {ActionTypes as AppActionTypes} from '../action/app'; const initialState = { isAuthenticated : false }; const setTokenReducer = (state, {payload : accessToken}) => ({ ...state, accessToken, isAuthenticated : true }); const cleanupReducer = () => initialState; const auth = handleActions({ [ActionTypes.SET_TOKEN] : setTokenReducer, [AppActionTypes.APP_CLEANUP] : cleanupReducer }, initialState); export default auth;
tomzhang/blackhole
src/tests/test_Attribute.cpp
<reponame>tomzhang/blackhole #include <blackhole/attribute.hpp> #include <blackhole/keyword/message.hpp> #include <blackhole/keyword/severity.hpp> #include <blackhole/keyword/timestamp.hpp> #include "global.hpp" using namespace blackhole; TEST(Attribute, CanMakeCustomAttribute) { auto attr = attribute::make<std::int32_t>("custom", 42); EXPECT_EQ("custom", attr.first); EXPECT_EQ(42, boost::get<std::int32_t>(attr.second.value)); }
natebeaty/onix
lib/onix/codelists/087.rb
# coding: utf-8 module ONIX; module CodeLists LIST_87 = { "CCL" => "Center column", "PGE" => "Page end", "SID" => "Side column", "VER" => "Verse end", "UNK" => "Unknown", "ZZZ" => "Other" } end; end
rcelebi/android-elfali
jni-build/jni/include/tensorflow/contrib/tensor_forest/core/ops/finished_nodes_op.cc
// Copyright 2016 The TensorFlow Authors. 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. // ============================================================================= // FinishedNodes returns a 1-D tensor listing the nodes that are finished // accumulating. #include "tensorflow/contrib/tensor_forest/core/ops/tree_utils.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/kernels/bounds_check.h" namespace tensorflow { using shape_inference::Dimension; using shape_inference::InferenceContext; using shape_inference::Shape; using tensorforest::CheckTensorBounds; using tensorforest::Sum; using tensorforest::BestSplitDominatesClassification; using tensorforest::BestSplitDominatesRegression; REGISTER_OP("FinishedNodes") .Attr("regression: bool = false") .Attr("num_split_after_samples: int") .Attr("min_split_samples: int") .Attr("dominate_fraction: float = 0.99") .Input("leaves: int32") .Input("node_to_accumulator: int32") .Input("split_sums: float") .Input("split_squares: float") .Input("accumulator_sums: float") .Input("accumulator_squares: float") .Input("birth_epochs: int32") .Input("current_epoch: int32") .Output("finished: int32") .Output("stale: int32") .SetShapeFn([](InferenceContext* c) { c->set_output(0, c->Vector(InferenceContext::kUnknownDim)); c->set_output(1, c->Vector(InferenceContext::kUnknownDim)); return Status::OK(); }) .Doc(R"doc( Determines which of the given leaf nodes are done accumulating. leaves:= A 1-d int32 tensor. Lists the nodes that are currently leaves. node_to_accumulator: If the i-th node is fertile, `node_to_accumulator[i]` is it's accumulator slot. Otherwise, `node_to_accumulator[i]` is -1. split_sums:= a 3-d tensor where `split_sums[a][s]` summarizes the training labels for examples that fall into the fertile node associated with accumulator slot s and have then taken the *left* branch of candidate split s. For a classification problem, `split_sums[a][s][c]` is the count of such examples with class c and for regression problems, `split_sums[a][s]` is the sum of the regression labels for such examples. split_squares: Same as split_sums, but it contains the sum of the squares of the regression labels. Only used for regression. For classification problems, pass a dummy tensor into this. accumulator_sums: For classification, `accumulator_sums[a][c]` records how many training examples have class c and have ended up in the fertile node associated with accumulator slot a. It has the total sum in entry 0 for convenience. For regression, it is the same except it contains the sum of the input labels that have been seen, and entry 0 contains the number of training examples that have been seen. accumulator_squares: Same as accumulator_sums, but it contains the sum of the squares of the regression labels. Only used for regression. For classification problems, pass a dummy tensor into this. birth_epochs:= A 1-d int32 tensor. `birth_epochs[i]` contains the epoch the i-th node was created in. current_epoch:= A 1-d int32 tensor with shape (1). `current_epoch[0]` stores the current epoch number. finished:= A 1-d int32 tensor containing the indices of the finished nodes. Nodes are finished if they have received at least num_split_after_samples samples, or if they have received min_split_samples and the best scoring split is sufficiently greater than the next best split. stale:= A 1-d int32 tensor containing the fertile nodes that were created two or more epochs ago. )doc"); class FinishedNodes : public OpKernel { public: explicit FinishedNodes(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, context->GetAttr( "regression", &regression_)); OP_REQUIRES_OK(context, context->GetAttr( "num_split_after_samples", &num_split_after_samples_)); OP_REQUIRES_OK(context, context->GetAttr( "min_split_samples", &min_split_samples_)); OP_REQUIRES_OK(context, context->GetAttr( "dominate_fraction", &dominate_fraction_)); } void Compute(OpKernelContext* context) override { const Tensor& leaf_tensor = context->input(0); const Tensor& node_to_accumulator = context->input(1); const Tensor& split_sums = context->input(2); const Tensor& split_squares = context->input(3); const Tensor& accumulator_sums = context->input(4); const Tensor& accumulator_squares = context->input(5); const Tensor& birth_epochs = context->input(6); const Tensor& current_epoch = context->input(7); OP_REQUIRES(context, leaf_tensor.shape().dims() == 1, errors::InvalidArgument( "leaf_tensor should be one-dimensional")); OP_REQUIRES(context, node_to_accumulator.shape().dims() == 1, errors::InvalidArgument( "node_to_accumulator should be one-dimensional")); OP_REQUIRES(context, split_sums.shape().dims() == 3, errors::InvalidArgument( "split_sums should be three-dimensional")); OP_REQUIRES(context, accumulator_sums.shape().dims() == 2, errors::InvalidArgument( "accumulator_sums should be two-dimensional")); OP_REQUIRES(context, birth_epochs.shape().dims() == 1, errors::InvalidArgument( "birth_epochs should be one-dimensional")); OP_REQUIRES( context, birth_epochs.shape().dim_size(0) == node_to_accumulator.shape().dim_size(0), errors::InvalidArgument( "birth_epochs and node_to_accumulator should be the same size.")); // Check tensor bounds. if (!CheckTensorBounds(context, leaf_tensor)) return; if (!CheckTensorBounds(context, node_to_accumulator)) return; if (!CheckTensorBounds(context, split_sums)) return; if (!CheckTensorBounds(context, split_squares)) return; if (!CheckTensorBounds(context, accumulator_sums)) return; if (!CheckTensorBounds(context, accumulator_squares)) return; if (!CheckTensorBounds(context, birth_epochs)) return; if (!CheckTensorBounds(context, current_epoch)) return; const auto leaves = leaf_tensor.unaligned_flat<int32>(); const auto node_map = node_to_accumulator.unaligned_flat<int32>(); const auto sums = accumulator_sums.tensor<float, 2>(); const auto start_epochs = birth_epochs.unaligned_flat<int32>(); const int32 epoch = current_epoch.unaligned_flat<int32>()(0); const int32 num_leaves = static_cast<int32>( leaf_tensor.shape().dim_size(0)); const int32 num_accumulators = static_cast<int32>( accumulator_sums.shape().dim_size(0)); std::vector<int32> finished_leaves; std::vector<int32> stale; for (int32 i = 0; i < num_leaves; i++) { const int32 leaf = internal::SubtleMustCopy(leaves(i)); OP_REQUIRES(context, FastBoundsCheck(leaf, node_map.size()), errors::InvalidArgument("leaf not in valid range.")) const int32 accumulator = internal::SubtleMustCopy(node_map(leaf)); if (accumulator < 0) { continue; } OP_REQUIRES(context, FastBoundsCheck(accumulator, num_accumulators), errors::InvalidArgument("accumulator not in valid range.")) // The first column holds the number of samples seen. // For classification, this should be the sum of the other columns. int32 count = sums(accumulator, 0); if (epoch > start_epochs(leaf) + 1) { if (count >= min_split_samples_) { finished_leaves.push_back(leaf); } else { stale.push_back(leaf); } continue; } if (count >= num_split_after_samples_) { finished_leaves.push_back(leaf); continue; } if (count < min_split_samples_) { continue; } bool finished = false; if (regression_) { finished = BestSplitDominatesRegression( accumulator_sums, accumulator_squares, split_sums, split_squares, accumulator); } else { finished = BestSplitDominatesClassification( accumulator_sums, split_sums, accumulator, dominate_fraction_); } if (finished) { finished_leaves.push_back(leaf); } } // Copy to output. Tensor* output_finished = nullptr; TensorShape finished_shape; finished_shape.AddDim(finished_leaves.size()); OP_REQUIRES_OK(context, context->allocate_output(0, finished_shape, &output_finished)); auto out_finished = output_finished->unaligned_flat<int32>(); for (int32 i = 0; i < finished_leaves.size(); i++) { out_finished(i) = finished_leaves[i]; } Tensor* output_stale = nullptr; TensorShape stale_shape; stale_shape.AddDim(stale.size()); OP_REQUIRES_OK(context, context->allocate_output(1, stale_shape, &output_stale)); auto out_stale = output_stale->unaligned_flat<int32>(); for (int32 i = 0; i < stale.size(); i++) { out_stale(i) = stale[i]; } } private: bool regression_; int32 num_split_after_samples_; int32 min_split_samples_; float dominate_fraction_; }; REGISTER_KERNEL_BUILDER(Name("FinishedNodes").Device(DEVICE_CPU), FinishedNodes); } // namespace tensorflow
shmoop207/rocket-engine
lib/loader/filesLoader.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FilesLoader = void 0; const tslib_1 = require("tslib"); const fs = require("fs"); const path = require("path"); const utils_1 = require("@appolo/utils"); class FilesLoader { static load(root, filesPath) { return tslib_1.__asyncGenerator(this, arguments, function* load_1() { var e_1, _a; if (!Array.isArray(filesPath)) { filesPath = [filesPath]; } try { for (var filesPath_1 = tslib_1.__asyncValues(filesPath), filesPath_1_1; filesPath_1_1 = yield tslib_1.__await(filesPath_1.next()), !filesPath_1_1.done;) { let filePath = filesPath_1_1.value; yield tslib_1.__await(yield* tslib_1.__asyncDelegator(tslib_1.__asyncValues(this._walk(path.join(root, filePath))))); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (filesPath_1_1 && !filesPath_1_1.done && (_a = filesPath_1.return)) yield tslib_1.__await(_a.call(filesPath_1)); } finally { if (e_1) throw e_1.error; } } }); } static _walk(dir) { return tslib_1.__asyncGenerator(this, arguments, function* _walk_1() { var e_2, _a; let [err, dirs] = yield tslib_1.__await(utils_1.Promises.to(fs.promises.opendir(dir))); if (err) { return yield tslib_1.__await(void 0); } try { for (var dirs_1 = tslib_1.__asyncValues(dirs), dirs_1_1; dirs_1_1 = yield tslib_1.__await(dirs_1.next()), !dirs_1_1.done;) { const d = dirs_1_1.value; const file = path.join(dir, d.name); if (d.isDirectory() && !file.startsWith("~")) { yield tslib_1.__await(yield* tslib_1.__asyncDelegator(tslib_1.__asyncValues(yield tslib_1.__await(this._walk(file))))); } else if (d.isFile() && file.endsWith(".js") && !file.startsWith("~")) { yield yield tslib_1.__await(file); } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (dirs_1_1 && !dirs_1_1.done && (_a = dirs_1.return)) yield tslib_1.__await(_a.call(dirs_1)); } finally { if (e_2) throw e_2.error; } } }); } } exports.FilesLoader = FilesLoader; //# sourceMappingURL=filesLoader.js.map
worrel/hydra
hydra-task/src/main/java/com/addthis/hydra/task/source/AggregateTaskDataSource.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.addthis.hydra.task.source; import java.util.LinkedList; import java.util.concurrent.atomic.AtomicBoolean; import com.addthis.bundle.channel.DataChannelError; import com.addthis.bundle.core.Bundle; import com.addthis.codec.Codec; import com.addthis.hydra.task.run.TaskRunConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This data source <span class="hydra-summary">aggregates data from one or more data sources</span>. * <p/> * <p>The user specifies an ordered sequence of data sources. The aggregate * data source first retrieves all the data from the first source. When the first * source has been exhausted, then the data is retrieved from the * second source. And so on and so forth until all the data has been retrieved. * <p/> * <p><b>CAUTION:</b> If the individual data sources have mark directories * then you must set these mark directories to be different locations for * each data source. Otherwise the mark information will end up in * an inconsistent state. The data team is working on enforcing this requirement * automatically.</p> * <p/> * <p>Example:</p> * <pre>source : { * type : "aggregate", * sources : [ * { * type : "stream2", * hash : true, * markDir : "markSource1", * source: { * ... * }, * factory: { * ... * } * }, * { * type : "mesh2", * markDir : "markSource2", * mesh : { * ... * }, * factory : { * ... * }, * } * ] * },</pre> * * @user-reference * @hydra-name aggregate */ public class AggregateTaskDataSource extends TaskDataSource { private static final Logger log = LoggerFactory.getLogger(AggregateTaskDataSource.class); /** * an ordered sequence of data sources. This field is required. */ @Codec.Set(codable = true, required = true) private TaskDataSource[] sources; private TaskDataSource currentSource; private final LinkedList<TaskDataSource> sourceList = new LinkedList<TaskDataSource>(); // to support test cases protected void setSources(TaskDataSource[] sources) { this.sources = sources; } @Override public boolean hadMoreData() { for (TaskDataSource source : sources) { if (source.hadMoreData()) { return true; } } return false; } @Override public void open(TaskRunConfig config, AtomicBoolean errored) { for (int i = 0; i < sources.length; i++) { TaskDataSource source = sources[i]; if (source.isEnabled()) { if (log.isDebugEnabled()) log.debug("open " + source); source.open(config, errored); sourceList.add(source); } else { if (log.isDebugEnabled()) log.debug("disabled " + source); } } requireValidSource(); } @Override public void close() { for (TaskDataSource source : sources) { if (source != null && source.isEnabled()) { if (log.isDebugEnabled()) log.debug("close " + source); source.close(); } } } private void resetCurrentSource() { if (log.isDebugEnabled()) log.debug("resetCurrentSource " + currentSource); currentSource = null; } private boolean requireValidSource() { while (currentSource == null && sourceList.size() > 0) { currentSource = sourceList.removeFirst(); if (log.isDebugEnabled()) log.debug("nextSource = " + currentSource); if (currentSource.peek() != null) { if (log.isDebugEnabled()) log.debug("setSource " + currentSource); return true; } currentSource = null; } return currentSource != null; } @Override public Bundle next() throws DataChannelError { while (requireValidSource()) { Bundle next = currentSource.next(); if (log.isDebugEnabled()) log.debug("next " + next); if (next != null) { return next; } resetCurrentSource(); } return null; } @Override public Bundle peek() throws DataChannelError { while (requireValidSource()) { Bundle peek = currentSource.peek(); if (log.isDebugEnabled()) log.debug("peek " + peek); if (peek != null) { return peek; } resetCurrentSource(); } return null; } }
gwilymhumphreys/botbuilder-js
samples/echobot-es6/echoBot.js
function createEchoBot(conversationState) { return async (context) => { if (context.activity.type === 'message') { const state = conversationState.get(context); const count = state.count === undefined ? state.count = 0 : ++state.count; await context.sendActivity(`${count}: You said "${context.activity.text}"`); } else { await context.sendActivity(`[${context.activity.type} event detected]`); } }; } module.exports = createEchoBot;
djeada/Nauka-programowania
src/Cpp/05_Petla_wyznaczanie_cyfr_liczby/Zad5.cpp
#include <iostream> int main() { // Dla pobranej liczby, sprawdz czy jest palindromem. std::cout << "Podaj liczbe" << std::endl; int a; std::cin >> a; int odwrocona = 0; int pom = a; while (pom > 0) { int cyfra = pom % 10; odwrocona = (odwrocona * 10 + cyfra); pom /= 10; } if (odwrocona == a) std::cout << "podana liczba jest palindromem" << std::endl; else std::cout << "podana liczba nie jest palindromem" << std::endl; return 0; }
nixcvf18/WorkTime
app/src/main/java/com/example/worktime/receiver/BootCompletedReceiver.java
package com.example.worktime.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.example.worktime.LoginActivity; public class BootCompletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. //throw new UnsupportedOperationException("Not yet implemented"); intent = new Intent(context, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startService(intent); } }
neontapir/managertools-logging
lib/path_string_extensions.rb
<filename>lib/path_string_extensions.rb # frozen_string_literal: true require 'namecase' # Splits path into team and member name components module PathStringExtensions refine Dir do # split_path() # Turn a relative path into an array of folders and the filename # # @example Parsing a path # Dir.new('foo/bar/baz.txt').split_path #=> ['foo', 'bar', 'baz.txt'] # @raise [ArgumentError] if path empty def split_path raise ArgumentError, 'Empty path' unless self Pathname.new(self).each_filename.to_a end end refine String do # split_path() # Turn a relative path into an array of folders and the filename # # @example Parsing a path # 'foo/bar/baz.txt'.split_path #=> ['foo', 'bar', 'baz.txt'] # @raise [ArgumentError] if path empty def split_path raise ArgumentError, 'Empty path' unless self Pathname.new(self).each_filename.to_a end # to_path() # Convert a titlecased string to a path name def to_path tr(' ', '-').downcase end # path_to_name() # Convert a path string to a title-cased name # @note Name case is needed for proper names # Titlecase is needed because name case doesn't handle prepositions, # which are sometimes found in team names def path_to_name NameCase(tr('_-', ' ').upcase).titlecase end end end
TimJSwan89/Java-Programs
ChessMaster/Bishop.java
import java.util.ArrayList; public class Bishop extends Piece { public Bishop(ChessBoard board, boolean white, Location location) { this.board = board; this.white = white; this.location = location; } public ArrayList<Location> getPossibleAttack() { ArrayList<Location> test = new ArrayList<Location>(); int i = 1; boolean works; do { Location loc = new Location(location.getX() + i, location.getY() + i); works = board.isValid(loc); if (works) { test.add(loc); i++; if (board.getPiece(loc) != null) works = false; } } while (works); i = 1; do { Location loc = new Location(location.getX() + i, location.getY() - i); works = board.isValid(loc); if (works) { test.add(loc); i++; if (board.getPiece(loc) != null) works = false; } } while (works); i = 1; do { Location loc = new Location(location.getX() - i, location.getY() + i); works = board.isValid(loc); if (works) { test.add(loc); i++; if (board.getPiece(loc) != null) works = false; } } while (works); i = 1; do { Location loc = new Location(location.getX() - i, location.getY() - i); works = board.isValid(loc); if (works) { test.add(loc); i++; if (board.getPiece(loc) != null) works = false; } } while (works); i = 1; return test; } public String toString() { return "Bishop"; } }
czurnieden/libczcomplex
mpc_pow.c
<gh_stars>0 #include <czcomplex.h> int mpc_pow(mp_complex * a, mp_complex * b, mp_complex * c) { int err; mp_complex t1; err = MP_OKAY; mpc_init(MPC_REAL(a).radix,&t1); mpc_log(a,&t1); mpc_mul(&t1,b,&t1); mpc_exp(&t1,c); _ERR: mpc_clear(&t1); return err; }
ganeshkamath89/redfish
hadoop/common.c
<reponame>ganeshkamath89/redfish /** * Copyright 2011-2012 the Redfish authors * * Licensed under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <errno.h> #include <jni.h> #include <stdint.h> #include "hadoop/common.h" #include "util/compiler.h" /** Class prefix for Redfish classes */ #define RF_CP "org/apache/hadoop/fs/redfish/" #define FSPERM_CP "org/apache/hadoop/fs/permission/FsPermission" #define PATH_CP "org/apache/hadoop/fs/Path" jfieldID g_fid_m_cli; jfieldID g_fid_rf_in_stream_m_ofe; jfieldID g_fid_rf_out_stream_m_ofe; jclass g_cls_file_status; jmethodID g_mid_file_status_ctor; jclass g_cls_fs_perm; jmethodID g_mid_fs_perm_ctor; jclass g_cls_path; jmethodID g_mid_path_ctor; jclass g_cls_rf_in_stream; jmethodID g_mid_rf_in_stream_ctor; jclass g_cls_rf_out_stream; jmethodID g_mid_rf_out_stream_ctor; jclass g_cls_block_loc; jmethodID g_mid_block_loc_ctor; jclass g_cls_string; static int cache_class_and_ctor(JNIEnv *jenv, const char *name, jclass *out_cls, jmethodID *out_ctor, const char *sig) { jclass cls; jmethodID ctor; cls = (*jenv)->FindClass(jenv, name); if (!cls) return -ENOENT; ctor = (*jenv)->GetMethodID(jenv, cls, "<init>", sig); if (!ctor) return -ENOENT; *out_cls = (*jenv)->NewWeakGlobalRef(jenv, cls); if (!(*out_cls)) return -ENOENT; *out_ctor = ctor; return 0; } static void uncache_class_and_ctor(JNIEnv *jenv, jclass *out_cls, jmethodID *out_ctor) { (*jenv)->DeleteGlobalRef(jenv, *out_cls); *out_cls = NULL; *out_ctor = NULL; } static int cache_redfish_client_fields(JNIEnv *jenv) { jclass cls; cls = (*jenv)->FindClass(jenv, RF_CP "RedfishClient"); if (!cls) return -ENOENT; g_fid_m_cli = (*jenv)->GetFieldID(jenv, cls, "m_cli", "J"); if (!g_fid_m_cli) return -ENOENT; return 0; } void redfish_throw(JNIEnv *jenv, const char *name, const char *msg) { jclass cls = (*jenv)->FindClass(jenv, name); if (!cls) { /* If !cls, we just raised a NoClassDefFound exception, or * similar. */ return; } (*jenv)->ThrowNew(jenv, cls, msg); (*jenv)->DeleteLocalRef(jenv, cls); } static int cache_redfish_input_stream_fields(JNIEnv *jenv) { int ret; ret = cache_class_and_ctor(jenv, RF_CP "RedfishDataInputStream", &g_cls_rf_in_stream, &g_mid_rf_in_stream_ctor, "(J)V"); if (ret) return -ENOENT; g_fid_rf_in_stream_m_ofe = (*jenv)->GetFieldID(jenv, g_cls_rf_in_stream, "m_ofe", "J"); if (!g_fid_rf_in_stream_m_ofe) return -ENOENT; return 0; } static int cache_redfish_output_stream_fields(JNIEnv *jenv) { int ret; ret = cache_class_and_ctor(jenv, RF_CP "RedfishDataOutputStream", &g_cls_rf_out_stream, &g_mid_rf_out_stream_ctor, "(J)V"); if (ret) return -ENOENT; g_fid_rf_out_stream_m_ofe = (*jenv)->GetFieldID(jenv, g_cls_rf_out_stream, "m_ofe", "J"); if (!g_fid_rf_out_stream_m_ofe) return -ENOENT; return 0; } static int cache_string_class(JNIEnv *jenv) { jclass cls; cls = (*jenv)->FindClass(jenv, "java/lang/String"); if (!cls) return -ENOENT; g_cls_string = (*jenv)->NewWeakGlobalRef(jenv, cls); if (!g_cls_string) return -ENOENT; return 0; } JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, POSSIBLY_UNUSED(void *reserved)) { int ret; JNIEnv *jenv = NULL; HJNI_DEBUG("libhfishc: entering JNI_OnLoad\n"); if ((*jvm)->GetEnv(jvm, (void **)&jenv, JNI_VERSION_1_2)) { return JNI_ERR; /* JNI version not supported */ } HJNI_DEBUG("libhfishc: caching client fields\n"); ret = cache_redfish_client_fields(jenv); if (ret) return JNI_ERR; HJNI_DEBUG("libhfishc: caching input stream fields\n"); ret = cache_redfish_input_stream_fields(jenv); if (ret) return JNI_ERR; HJNI_DEBUG("libhfishc: caching output stream fields\n"); ret = cache_redfish_output_stream_fields(jenv); if (ret) return JNI_ERR; HJNI_DEBUG("libhfishc: caching FilePermission\n"); ret = cache_class_and_ctor(jenv, FSPERM_CP, &g_cls_fs_perm, &g_mid_fs_perm_ctor, "(S)V"); if (ret) return JNI_ERR; HJNI_DEBUG("libhfishc: caching FileStatus\n"); ret = cache_class_and_ctor(jenv, "org/apache/hadoop/fs/FileStatus", &g_cls_file_status, &g_mid_file_status_ctor, "(JZIJJJL" FSPERM_CP ";Ljava/lang/String;" "Ljava/lang/String;L" PATH_CP ";)V"); if (ret) return JNI_ERR; HJNI_DEBUG("libhfishc: caching Path\n"); ret = cache_class_and_ctor(jenv, PATH_CP, &g_cls_path, &g_mid_path_ctor, "(Ljava/lang/String;)V"); if (ret) return JNI_ERR; HJNI_DEBUG("libhfishc: caching BlockLocation\n"); ret = cache_class_and_ctor(jenv, "org/apache/hadoop/fs/BlockLocation", &g_cls_block_loc, &g_mid_block_loc_ctor, "([Ljava/lang/String;[Ljava/lang/String;JJ)V"); if (ret) return JNI_ERR; HJNI_DEBUG("libhfishc: caching Java string class\n"); ret = cache_string_class(jenv); if (ret) return JNI_ERR; HJNI_DEBUG("libhfishc: JNI_OnLoad succeeded\n"); return JNI_VERSION_1_2; } JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *jvm, POSSIBLY_UNUSED(void *reserved)) { JNIEnv *jenv; HJNI_DEBUG("libhfishc: entering JNI_OnUnload\n"); if ((*jvm)->GetEnv(jvm, (void **)&jenv, JNI_VERSION_1_2)) { return; } g_fid_m_cli = 0; uncache_class_and_ctor(jenv, &g_cls_rf_in_stream, &g_mid_rf_in_stream_ctor); uncache_class_and_ctor(jenv, &g_cls_rf_out_stream, &g_mid_rf_out_stream_ctor); uncache_class_and_ctor(jenv, &g_cls_fs_perm, &g_mid_fs_perm_ctor); uncache_class_and_ctor(jenv, &g_cls_file_status, &g_mid_file_status_ctor); uncache_class_and_ctor(jenv, &g_cls_path, &g_mid_path_ctor); uncache_class_and_ctor(jenv, &g_cls_block_loc, &g_mid_block_loc_ctor); (*jenv)->DeleteGlobalRef(jenv, g_cls_string); HJNI_DEBUG("libhfishc: exiting JNI_OnUnload\n"); } jint validate_rw_params(JNIEnv *jenv, jbyteArray jarr, jint boff, jint blen) { /* TODO: we could probably skip at least some of this verification, * since a lot of the JNI functions, like SetByteArrayRegion, seem to * validate paramaters for us. It would have to be done carefully, * though, to avoid exposing us to mishaps elsewhere in the code or * implementation details of the various JNI implementations. */ int32_t alen; uint32_t end; if (boff < 0) { redfish_throw(jenv, "java/lang/IndexOutOfBoundsException", "boff < 0"); return -1; } if (blen < 0) { redfish_throw(jenv, "java/lang/IndexOutOfBoundsException", "blen < 0"); return -1; } if (jarr == NULL) { redfish_throw(jenv, "java/lang/NullPointerException", "buf == NULL"); return -1; } /* It's important to do the addition of boff and blen as an unsigned * operation, so that we don't get undefined behavior on integer * overflow. We do the comparison as a signed comparison, so that if * overflow did take place, we're comparing a positive number with a * negative one. * * Unlike C, Java defines integers as 4 bytes, no matter what the * underlying machine architecture may be. That's why we can ignore the * jint, etc typedefs and just use uint32_t and friends. */ alen = (*jenv)->GetArrayLength(jenv, jarr); end = ((uint32_t)boff) + ((uint32_t)blen); if (((int32_t)end) > alen) { redfish_throw(jenv, "java/lang/IndexOutOfBoundsException", "boff + blen > buf.length"); return -1; } return 0; } int jstr_to_cstr(JNIEnv *jenv, jstring jstr, char *cstr, size_t cstr_len) { char err[128]; size_t err_len = sizeof(err); int32_t jlen, clen; /* GetStringUTFLength is kind of a bizarre API. * * First, we have to supply the length of the region we want to get-- * but not in bytes, in UTF-8 characters! If you ask for too many, you * get an exception. How about having a simple API that just gets the * whole string; isn't that what 9999 people out of 10000 want? * But no, we have to make the extra function call every time. * * Secondly, it does no bounds checking. So we have to make another * extra function call here to find out what the length would be as a * UTF-8 string. The example in the JNI programmer's guide even omits * bounds checking-- they comment on ther omission, but don't fix it! * Somebody was not thinking clearly here. * * Despite all the warts, this API at least lets us avoid doing tons of * malloc()s, and that is a good thing. */ clen = (*jenv)->GetStringUTFLength(jenv, jstr); if (clen > (int32_t)cstr_len) { snprintf(err, err_len, "jstr_to_cstr: tried to load %d byte " "java string into %Zd byte C string\n", clen, cstr_len); redfish_throw(jenv, "java/lang/StringIndexOutOfBoundsException", err); return -ENAMETOOLONG; } jlen = (*jenv)->GetStringLength(jenv, jstr); (*jenv)->GetStringUTFRegion(jenv, jstr, 0, jlen, cstr); if ((*jenv)->ExceptionCheck(jenv)) return -EIO; return 0; }
vinniefalco/SimpleDJ
Extern/JUCE/modules/juce_gui_basics/commands/juce_KeyPressMappingSet.cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager& cm) : commandManager (cm) { Desktop::getInstance().addFocusChangeListener (this); } KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) : ChangeBroadcaster(), commandManager (other.commandManager) { Desktop::getInstance().addFocusChangeListener (this); } KeyPressMappingSet::~KeyPressMappingSet() { Desktop::getInstance().removeFocusChangeListener (this); } //============================================================================== Array<KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const { for (int i = 0; i < mappings.size(); ++i) if (mappings.getUnchecked(i)->commandID == commandID) return mappings.getUnchecked (i)->keypresses; return Array<KeyPress>(); } void KeyPressMappingSet::addKeyPress (const CommandID commandID, const KeyPress& newKeyPress, int insertIndex) { // If you specify an upper-case letter but no shift key, how is the user supposed to press it!? // Stick to lower-case letters when defining a keypress, to avoid ambiguity. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter()) && ! newKeyPress.getModifiers().isShiftDown())); if (findCommandForKeyPress (newKeyPress) != commandID) { if (newKeyPress.isValid()) { for (int i = mappings.size(); --i >= 0;) { if (mappings.getUnchecked(i)->commandID == commandID) { mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress); sendChangeMessage(); return; } } if (const ApplicationCommandInfo* const ci = commandManager.getCommandForID (commandID)) { CommandMapping* const cm = new CommandMapping(); cm->commandID = commandID; cm->keypresses.add (newKeyPress); cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0; mappings.add (cm); sendChangeMessage(); } } } } void KeyPressMappingSet::resetToDefaultMappings() { mappings.clear(); for (int i = 0; i < commandManager.getNumCommands(); ++i) { const ApplicationCommandInfo* const ci = commandManager.getCommandForIndex (i); for (int j = 0; j < ci->defaultKeypresses.size(); ++j) { addKeyPress (ci->commandID, ci->defaultKeypresses.getReference (j)); } } sendChangeMessage(); } void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) { clearAllKeyPresses (commandID); const ApplicationCommandInfo* const ci = commandManager.getCommandForID (commandID); for (int j = 0; j < ci->defaultKeypresses.size(); ++j) { addKeyPress (ci->commandID, ci->defaultKeypresses.getReference (j)); } } void KeyPressMappingSet::clearAllKeyPresses() { if (mappings.size() > 0) { sendChangeMessage(); mappings.clear(); } } void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) { for (int i = mappings.size(); --i >= 0;) { if (mappings.getUnchecked(i)->commandID == commandID) { mappings.remove (i); sendChangeMessage(); } } } void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) { if (keypress.isValid()) { for (int i = mappings.size(); --i >= 0;) { CommandMapping& cm = *mappings.getUnchecked(i); for (int j = cm.keypresses.size(); --j >= 0;) { if (keypress == cm.keypresses [j]) { cm.keypresses.remove (j); sendChangeMessage(); } } } } } void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex) { for (int i = mappings.size(); --i >= 0;) { if (mappings.getUnchecked(i)->commandID == commandID) { mappings.getUnchecked(i)->keypresses.remove (keyPressIndex); sendChangeMessage(); break; } } } //============================================================================== CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const noexcept { for (int i = 0; i < mappings.size(); ++i) if (mappings.getUnchecked(i)->keypresses.contains (keyPress)) return mappings.getUnchecked(i)->commandID; return 0; } bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const noexcept { for (int i = mappings.size(); --i >= 0;) if (mappings.getUnchecked(i)->commandID == commandID) return mappings.getUnchecked(i)->keypresses.contains (keyPress); return false; } void KeyPressMappingSet::invokeCommand (const CommandID commandID, const KeyPress& key, const bool isKeyDown, const int millisecsSinceKeyPressed, Component* const originatingComponent) const { ApplicationCommandTarget::InvocationInfo info (commandID); info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress; info.isKeyDown = isKeyDown; info.keyPress = key; info.millisecsSinceKeyPressed = millisecsSinceKeyPressed; info.originatingComponent = originatingComponent; commandManager.invoke (info, false); } //============================================================================== bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion) { if (xmlVersion.hasTagName ("KEYMAPPINGS")) { if (xmlVersion.getBoolAttribute ("basedOnDefaults", true)) { // if the XML was created as a set of differences from the default mappings, // (i.e. by calling createXml (true)), then we need to first restore the defaults. resetToDefaultMappings(); } else { // if the XML was created calling createXml (false), then we need to clear all // the keys and treat the xml as describing the entire set of mappings. clearAllKeyPresses(); } forEachXmlChildElement (xmlVersion, map) { const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32(); if (commandId != 0) { const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key"))); if (map->hasTagName ("MAPPING")) { addKeyPress (commandId, key); } else if (map->hasTagName ("UNMAPPING")) { for (int i = mappings.size(); --i >= 0;) if (mappings.getUnchecked(i)->commandID == commandId) mappings.getUnchecked(i)->keypresses.removeAllInstancesOf (key); } } } return true; } return false; } XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const { ScopedPointer <KeyPressMappingSet> defaultSet; if (saveDifferencesFromDefaultSet) { defaultSet = new KeyPressMappingSet (commandManager); defaultSet->resetToDefaultMappings(); } XmlElement* const doc = new XmlElement ("KEYMAPPINGS"); doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet); for (int i = 0; i < mappings.size(); ++i) { const CommandMapping& cm = *mappings.getUnchecked(i); for (int j = 0; j < cm.keypresses.size(); ++j) { if (defaultSet == nullptr || ! defaultSet->containsMapping (cm.commandID, cm.keypresses.getReference (j))) { XmlElement* const map = doc->createNewChildElement ("MAPPING"); map->setAttribute ("commandId", String::toHexString ((int) cm.commandID)); map->setAttribute ("description", commandManager.getDescriptionOfCommand (cm.commandID)); map->setAttribute ("key", cm.keypresses.getReference (j).getTextDescription()); } } } if (defaultSet != nullptr) { for (int i = 0; i < defaultSet->mappings.size(); ++i) { const CommandMapping& cm = *defaultSet->mappings.getUnchecked(i); for (int j = 0; j < cm.keypresses.size(); ++j) { if (! containsMapping (cm.commandID, cm.keypresses.getReference (j))) { XmlElement* const map = doc->createNewChildElement ("UNMAPPING"); map->setAttribute ("commandId", String::toHexString ((int) cm.commandID)); map->setAttribute ("description", commandManager.getDescriptionOfCommand (cm.commandID)); map->setAttribute ("key", cm.keypresses.getReference (j).getTextDescription()); } } } } return doc; } //============================================================================== bool KeyPressMappingSet::keyPressed (const KeyPress& key, Component* const originatingComponent) { bool commandWasDisabled = false; for (int i = 0; i < mappings.size(); ++i) { CommandMapping& cm = *mappings.getUnchecked(i); if (cm.keypresses.contains (key)) { if (const ApplicationCommandInfo* const ci = commandManager.getCommandForID (cm.commandID)) { if ((ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0) { ApplicationCommandInfo info (0); if (commandManager.getTargetForCommand (cm.commandID, info) != nullptr) { if ((info.flags & ApplicationCommandInfo::isDisabled) == 0) { invokeCommand (cm.commandID, key, true, 0, originatingComponent); return true; } else { commandWasDisabled = true; } } } } } } if (originatingComponent != nullptr && commandWasDisabled) originatingComponent->getLookAndFeel().playAlertSound(); return false; } bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent) { bool used = false; const uint32 now = Time::getMillisecondCounter(); for (int i = mappings.size(); --i >= 0;) { CommandMapping& cm = *mappings.getUnchecked(i); if (cm.wantsKeyUpDownCallbacks) { for (int j = cm.keypresses.size(); --j >= 0;) { const KeyPress key (cm.keypresses.getReference (j)); const bool isDown = key.isCurrentlyDown(); int keyPressEntryIndex = 0; bool wasDown = false; for (int k = keysDown.size(); --k >= 0;) { if (key == keysDown.getUnchecked(k)->key) { keyPressEntryIndex = k; wasDown = true; used = true; break; } } if (isDown != wasDown) { int millisecs = 0; if (isDown) { KeyPressTime* const k = new KeyPressTime(); k->key = key; k->timeWhenPressed = now; keysDown.add (k); } else { const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed; if (now > pressTime) millisecs = (int) (now - pressTime); keysDown.remove (keyPressEntryIndex); } invokeCommand (cm.commandID, key, isDown, millisecs, originatingComponent); used = true; } } } } return used; } void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent) { if (focusedComponent != nullptr) focusedComponent->keyStateChanged (false); }
yuneta/c-core
src/yuneta_register.c
<filename>src/yuneta_register.c /**************************************************************************** * YUNETA_REGISTER.C * Yuneta * * Copyright (c) 2014-2015 Niyamaka. * All Rights Reserved. ****************************************************************************/ #include "yuneta.h" #include "yuneta_register.h" /*************************************************************************** * Data ***************************************************************************/ /*************************************************************************** * Register internal yuno gclasses and services ***************************************************************************/ PUBLIC int yuneta_register_c_core(void) { static BOOL initialized = FALSE; if(initialized) { return -1; } /* * Services */ gobj_register_gclass(GCLASS_TREEDB); gobj_register_gclass(GCLASS_NODE); gobj_register_gclass(GCLASS_TRANGER); gobj_register_gclass(GCLASS_RESOURCE); gobj_register_gclass(GCLASS_IEVENT_SRV); gobj_register_gclass(GCLASS_IEVENT_CLI); // gobj_register_gclass(GCLASS_STORE); // gobj_register_gclass(GCLASS_SNMP); //gobj_register_gclass(GCLASS_DYNAGENT); /* * Gadgets */ gobj_register_gclass(GCLASS_MQIOGATE); gobj_register_gclass(GCLASS_QIOGATE); gobj_register_gclass(GCLASS_IOGATE); gobj_register_gclass(GCLASS_CHANNEL); gobj_register_gclass(GCLASS_COUNTER); gobj_register_gclass(GCLASS_TASK); gobj_register_gclass(GCLASS_DYNRULE); gobj_register_gclass(GCLASS_TIMETRANSITION); gobj_register_gclass(GCLASS_RSTATS); /* * Protocols */ gobj_register_gclass(GCLASS_CONNEX); gobj_register_gclass(GCLASS_GWEBSOCKET); gobj_register_gclass(GCLASS_PROT_HEADER4); gobj_register_gclass(GCLASS_PROT_RAW); gobj_register_gclass(GCLASS_PROT_HTTP); gobj_register_gclass(GCLASS_PROT_HTTP_SRV); gobj_register_gclass(GCLASS_PROT_HTTP_CLI); gobj_register_gclass(GCLASS_PROT_MODBUS_MASTER); gobj_register_gclass(GCLASS_SERIAL); /* * Mixin uv-gobj */ gobj_register_gclass(GCLASS_GSS_UDP_S0); gobj_register_gclass(GCLASS_TCP0); gobj_register_gclass(GCLASS_TCP_S0); gobj_register_gclass(GCLASS_UDP_S0); gobj_register_gclass(GCLASS_UDP0); gobj_register_gclass(GCLASS_TIMETRANSITION); gobj_register_gclass(GCLASS_TIMER); gobj_register_gclass(GCLASS_FS); register_ievent_answer_filter(); initialized = TRUE; return 0; }
jingcao80/Elastos
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/speech/SpeechRecognizer.h
<reponame>jingcao80/Elastos<filename>Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/speech/SpeechRecognizer.h //========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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. //========================================================================= #ifndef __ELASTOS_DROID_SPEECH_SPEECHRECOGNIZER_H__ #define __ELASTOS_DROID_SPEECH_SPEECHRECOGNIZER_H__ #include "elastos/droid/ext/frameworkdef.h" #include "elastos/core/Object.h" #include <elastos/utility/etl/List.h> #include "_Elastos.Droid.Speech.h" #include "Elastos.Droid.Content.h" #include "Elastos.Droid.Os.h" using Elastos::Utility::Etl::List; using Elastos::Droid::Os::IBundle; using Elastos::Droid::Os::IBinder; using Elastos::Droid::Content::IIntent; using Elastos::Droid::Content::IServiceConnection; using Elastos::Droid::Content::IComponentName; using Elastos::Droid::Content::IContext; using Elastos::Droid::Os::IMessage; using Elastos::Droid::Os::IHandler; namespace Elastos { namespace Droid { namespace Speech { /** * This class provides access to the speech recognition service. This service allows access to the * speech recognizer. Do not instantiate this class directly, instead, call * {@link SpeechRecognizer#createSpeechRecognizer(Context)}. This class's methods must be * invoked only from the main application thread. * * <p>The implementation of this API is likely to stream audio to remote servers to perform speech * recognition. As such this API is not intended to be used for continuous recognition, which would * consume a significant amount of battery and bandwidth. * * <p>Please note that the application must have {@link android.Manifest.permission#RECORD_AUDIO} * permission to use this class. */ //public class class SpeechRecognizer : public Object , public ISpeechRecognizer { private: class SpeechRecognizerHandler : public Object { public: SpeechRecognizerHandler(); SpeechRecognizerHandler( /* [in] */ SpeechRecognizer* sr); CARAPI HandleMessage( /* [in] */ IMessage* msg); private: SpeechRecognizer* mHost; }; friend class SpeechRecognizerHandler; private: /** * Basic ServiceConnection that records the mService variable. Additionally, on creation it * invokes the {@link IRecognitionService#startListening(Intent, IRecognitionListener)}. */ //private class class SpeechRecognizerConnection : public Object , public IServiceConnection { public: CAR_INTERFACE_DECL() SpeechRecognizerConnection(); virtual ~SpeechRecognizerConnection(); CARAPI constructor(); public: //public void CARAPI OnServiceConnected( /* [in] */ IComponentName* name, /* [in] */ /*IIBinder*/IBinder* service ); //public void CARAPI OnServiceDisconnected( /* [in] */ IComponentName* name); public: SpeechRecognizerConnection( /* [in] */ SpeechRecognizer* sr); private: SpeechRecognizer* mHost; }; friend class SpeechRecognizerConnection; private: /** * Internal wrapper of IRecognitionListener which will propagate the results to * RecognitionListener */ //private class class SpeechRecognizerInternalListener : public Object , public IIRecognitionListener { private: class SpeechRecognizerInternalListenerHandler : public Object { public: SpeechRecognizerInternalListenerHandler(); SpeechRecognizerInternalListenerHandler( /* [in] */ SpeechRecognizerInternalListener* sil); CARAPI HandleMessage( /* [in] */ IMessage* msg); private: SpeechRecognizerInternalListener* mHost; }; public: friend class SpeechRecognizerInternalListenerHandler; friend class SpeechRecognizer; public: CAR_INTERFACE_DECL() SpeechRecognizerInternalListener(); ~SpeechRecognizerInternalListener(); CARAPI constructor(); //public void CARAPI OnBeginningOfSpeech(); //public void CARAPI OnBufferReceived( /* [in] */ ArrayOf<Byte>* buffer); //public void CARAPI OnEndOfSpeech(); //public void CARAPI OnError( /* [in] */ Int32 error); //public void CARAPI OnReadyForSpeech( /* [in] */ IBundle* noiseParams); //public void CARAPI OnResults( /* [in] */ IBundle* results); //public void CARAPI OnPartialResults( /* [in] */ IBundle* results); //public void CARAPI OnRmsChanged( /* [in] */ Float rmsdB); //public void CARAPI OnEvent( /* [in] */ Int32 eventType, /* [in] */ IBundle* bParams); private: //private AutoPtr<IRecognitionListener> mInternalListener; //private final static const static Int32 MSG_BEGINNING_OF_SPEECH; // = 1; //private final static const static Int32 MSG_BUFFER_RECEIVED; // = 2; //private final static const static Int32 MSG_END_OF_SPEECH; // = 3; //private final static const static Int32 MSG_ERROR; // = 4; //private final static const static Int32 MSG_READY_FOR_SPEECH; // = 5; //private final static const static Int32 MSG_RESULTS; // = 6; //private final static const static Int32 MSG_PARTIAL_RESULTS; // = 7; //private final static const static Int32 MSG_RMS_CHANGED; // = 8; //private final static const static Int32 MSG_ON_EVENT; // = 9; private: //private final Handler AutoPtr<IHandler> mInternalHandler; // = new SpeechRecognizerInternalListenerHandler(); }; friend class SpeechRecognizerInternalListener; public: CAR_INTERFACE_DECL() SpeechRecognizer(); virtual ~SpeechRecognizer(); CARAPI constructor(); /** * The right way to create a {@code SpeechRecognizer} is by using * {@link #createSpeechRecognizer} static factory method */ CARAPI constructor( /* [in] */ IContext* context, /* [in] */ IComponentName* serviceComponent); /** * Checks whether a speech recognition service is available on the system. If this method * returns {@code false}, {@link SpeechRecognizer#createSpeechRecognizer(Context)} will * fail. * * @param context with which {@code SpeechRecognizer} will be created * @return {@code true} if recognition is available, {@code false} otherwise */ //public static CARAPI_(Boolean) IsRecognitionAvailable( /* [in] */ IContext* context); /** * Factory method to create a new {@code SpeechRecognizer}. Please note that * {@link #setRecognitionListener(RecognitionListener)} should be called before dispatching any * command to the created {@code SpeechRecognizer}, otherwise no notifications will be * received. * * @param context in which to create {@code SpeechRecognizer} * @return a new {@code SpeechRecognizer} */ //public static CARAPI_(AutoPtr<ISpeechRecognizer>) CreateSpeechRecognizer( /* [in] */ IContext* context); /** * Factory method to create a new {@code SpeechRecognizer}. Please note that * {@link #setRecognitionListener(RecognitionListener)} should be called before dispatching any * command to the created {@code SpeechRecognizer}, otherwise no notifications will be * received. * * Use this version of the method to specify a specific service to direct this * {@link SpeechRecognizer} to. Normally you would not use this; use * {@link #createSpeechRecognizer(Context)} instead to use the system default recognition * service. * * @param context in which to create {@code SpeechRecognizer} * @param serviceComponent the {@link ComponentName} of a specific service to direct this * {@code SpeechRecognizer} to * @return a new {@code SpeechRecognizer} */ //public static CARAPI_(AutoPtr<ISpeechRecognizer>) CreateSpeechRecognizer( /* [in] */ IContext* context, /* [in] */ IComponentName* serviceComponent); /** * Sets the listener that will receive all the callbacks. The previous unfinished commands will * be executed with the old listener, while any following command will be executed with the new * listener. * * @param listener listener that will receive all the callbacks from the created * {@link SpeechRecognizer}, this must not be null. */ //public CARAPI SetRecognitionListener( /* [in] */ IRecognitionListener* listener); /** * Starts listening for speech. Please note that * {@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise * no notifications will be received. * * @param recognizerIntent contains parameters for the recognition to be performed. The intent * may also contain optional extras, see {@link RecognizerIntent}. If these values are * not set explicitly, default values will be used by the recognizer. */ //public CARAPI StartListening( /* [in] */ IIntent* recognizerIntent); /** * Stops listening for speech. Speech captured so far will be recognized as if the user had * stopped speaking at this point. Note that in the default case, this does not need to be * called, as the speech endpointer will automatically stop the recognizer listening when it * determines speech has completed. However, you can manipulate endpointer parameters directly * using the intent extras defined in {@link RecognizerIntent}, in which case you may sometimes * want to manually call this method to stop listening sooner. Please note that * {@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise * no notifications will be received. */ //public CARAPI StopListening(); /** * Cancels the speech recognition. Please note that * {@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise * no notifications will be received. */ //public CARAPI Cancel(); /** * Destroys the {@code SpeechRecognizer} object. */ //public CARAPI Destroy(); protected: //private static CARAPI_(void) CheckIsCalledFromMainThread(); //private CARAPI_(void) PutMessage( /* [in] */ IMessage* msg); /** sends the actual message to the service */ //private CARAPI_(void) HandleStartListening( /* [in] */ IIntent* recognizerIntent); /** sends the actual message to the service */ //private CARAPI_(void) HandleStopMessage(); /** sends the actual message to the service */ //private CARAPI_(void) HandleCancelMessage(); //private CARAPI_(Boolean) CheckOpenConnection(); /** changes the listener */ //private CARAPI_(void) HandleChangeListener( /* [in] */ IRecognitionListener* listener); protected: /** DEBUG value to enable verbose debug prints */ //private final static static const Boolean DBG; // = FALSE; /** Log messages identifier */ //private static final static const String TAG; // = "SpeechRecognizer"; private: /** action codes */ //private final static static const Int32 MSG_START; // = 1; //private final static static const Int32 MSG_STOP; // = 2; //private final static static const Int32 MSG_CANCEL; // = 3; //private final static static const Int32 MSG_CHANGE_LISTENER; // = 4; /** The actual RecognitionService endpoint */ //private AutoPtr<IIRecognitionService> mService; /** The connection to the actual service */ //private AutoPtr<SpeechRecognizerConnection> mConnection; /** Context with which the manager was created */ //private final AutoPtr<IContext> mContext; /** Component to direct service intent to */ //private final AutoPtr<IComponentName> mServiceComponent; /** Handler that will execute the main tasks */ //private AutoPtr<IHandler> mHandler; // = new SpeechRecognizerHandler(); /** * Temporary queue, saving the messages until the connection will be established, afterwards, * only mHandler will receive the messages */ //private final Queue<Message> List< AutoPtr<IMessage> > mPendingTasks; // = new LinkedList<Message>(); /** The Listener that will receive all the callbacks */ //private final InternalListener AutoPtr<SpeechRecognizerInternalListener> mListener; // = new SpeechRecognizerInternalListener(); }; } // namespace Speech } // namepsace Droid } // namespace Elastos #endif // __ELASTOS_DROID_SPEECH_SPEECHRECOGNIZER_H__
csabaujvari/jackal
pkg/module/xep0280/carbons_test.go
// Copyright 2021 The jackal Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package xep0280 import ( "context" "testing" c2smodel "github.com/ortuman/jackal/pkg/model/c2s" "github.com/google/uuid" "github.com/jackal-xmpp/stravaganza/v2" "github.com/jackal-xmpp/stravaganza/v2/jid" "github.com/ortuman/jackal/pkg/hook" "github.com/ortuman/jackal/pkg/router" "github.com/ortuman/jackal/pkg/router/stream" "github.com/stretchr/testify/require" ) func TestCarbons_Enable(t *testing.T) { // given stmMock := &c2sStreamMock{} var setK string var setVal interface{} stmMock.SetInfoValueFunc = func(ctx context.Context, k string, val interface{}) error { setK = k setVal = val return nil } stmMock.InfoFunc = func() c2smodel.Info { return c2smodel.Info{} } c2sRouterMock := &c2sRouterMock{} c2sRouterMock.LocalStreamFunc = func(username string, resource string) stream.C2S { return stmMock } routerMock := &routerMock{} routerMock.C2SFunc = func() router.C2SRouter { return c2sRouterMock } var respStanzas []stravaganza.Stanza routerMock.RouteFunc = func(ctx context.Context, stanza stravaganza.Stanza) ([]jid.JID, error) { respStanzas = append(respStanzas, stanza) return nil, nil } hMock := &hostsMock{} hMock.IsLocalHostFunc = func(h string) bool { return h == "jackal.im" } c := &Carbons{ router: routerMock, hosts: hMock, hk: hook.NewHooks(), } // when setID := uuid.New().String() iq, _ := stravaganza.NewIQBuilder(). WithAttribute(stravaganza.ID, setID). WithAttribute(stravaganza.Type, stravaganza.SetType). WithAttribute(stravaganza.From, "<EMAIL>/yard"). WithAttribute(stravaganza.To, "<EMAIL>"). WithChild( stravaganza.NewBuilder("enable"). WithAttribute(stravaganza.Namespace, carbonsNamespace). Build(), ). BuildIQ() _ = c.ProcessIQ(context.Background(), iq) // then require.Equal(t, carbonsEnabledCtxKey, setK) require.Equal(t, true, setVal) require.Len(t, respStanzas, 1) require.Equal(t, stravaganza.IQName, respStanzas[0].Name()) require.Equal(t, setID, respStanzas[0].Attribute(stravaganza.ID)) require.Equal(t, stravaganza.ResultType, respStanzas[0].Attribute(stravaganza.Type)) } func TestCarbons_Disable(t *testing.T) { // given stmMock := &c2sStreamMock{} var setK string var setVal interface{} stmMock.SetInfoValueFunc = func(ctx context.Context, k string, val interface{}) error { setK = k setVal = val return nil } stmMock.InfoFunc = func() c2smodel.Info { return c2smodel.Info{} } c2sRouterMock := &c2sRouterMock{} c2sRouterMock.LocalStreamFunc = func(username string, resource string) stream.C2S { return stmMock } routerMock := &routerMock{} routerMock.C2SFunc = func() router.C2SRouter { return c2sRouterMock } var respStanzas []stravaganza.Stanza routerMock.RouteFunc = func(ctx context.Context, stanza stravaganza.Stanza) ([]jid.JID, error) { respStanzas = append(respStanzas, stanza) return nil, nil } hMock := &hostsMock{} hMock.IsLocalHostFunc = func(h string) bool { return h == "jackal.im" } c := &Carbons{ router: routerMock, hosts: hMock, hk: hook.NewHooks(), } // when setID := uuid.New().String() iq, _ := stravaganza.NewIQBuilder(). WithAttribute(stravaganza.ID, setID). WithAttribute(stravaganza.Type, stravaganza.SetType). WithAttribute(stravaganza.From, "ortuman@jackal.im/yard"). WithAttribute(stravaganza.To, "<EMAIL>"). WithChild( stravaganza.NewBuilder("disable"). WithAttribute(stravaganza.Namespace, carbonsNamespace). Build(), ). BuildIQ() _ = c.ProcessIQ(context.Background(), iq) // then require.Equal(t, carbonsEnabledCtxKey, setK) require.Equal(t, false, setVal) require.Len(t, respStanzas, 1) require.Equal(t, stravaganza.IQName, respStanzas[0].Name()) require.Equal(t, setID, respStanzas[0].Attribute(stravaganza.ID)) require.Equal(t, stravaganza.ResultType, respStanzas[0].Attribute(stravaganza.Type)) } func TestCarbons_SentCC(t *testing.T) { // given routerMock := &routerMock{} var respStanzas []stravaganza.Stanza routerMock.RouteFunc = func(ctx context.Context, stanza stravaganza.Stanza) ([]jid.JID, error) { respStanzas = append(respStanzas, stanza) return nil, nil } jd0, _ := jid.NewWithString("<EMAIL>/balcony", true) resManagerMock := &resourceManagerMock{} resManagerMock.GetResourcesFunc = func(ctx context.Context, username string) ([]c2smodel.Resource, error) { return []c2smodel.Resource{ {JID: jd0, Info: c2smodel.Info{M: map[string]string{carbonsEnabledCtxKey: "true"}}}, }, nil } hMock := &hostsMock{} hMock.IsLocalHostFunc = func(h string) bool { return h == "jackal.im" } hk := hook.NewHooks() c := &Carbons{ router: routerMock, resMng: resManagerMock, hosts: hMock, hk: hk, } b := stravaganza.NewMessageBuilder() b.WithAttribute("id", "i1234") b.WithAttribute("from", "<EMAIL>/yard") b.WithAttribute("to", "<EMAIL>/balcony") b.WithAttribute("type", "chat") b.WithChild( stravaganza.NewBuilder("body"). WithText("I'll give thee a wind."). Build(), ) msg, _ := b.BuildMessage() // when _ = c.Start(context.Background()) defer func() { _ = c.Stop(context.Background()) }() _, _ = hk.Run(context.Background(), hook.S2SInStreamMessageRouted, &hook.ExecutionContext{ Info: &hook.S2SStreamInfo{ Sender: "<EMAIL>", Target: "jabber.org", Element: msg, }, }) // then require.Len(t, respStanzas, 1) routedMsg := respStanzas[0] require.Equal(t, stravaganza.MessageName, routedMsg.Name()) require.Equal(t, "<EMAIL>", routedMsg.Attribute(stravaganza.From)) require.Equal(t, "<EMAIL>/balcony", routedMsg.Attribute(stravaganza.To)) require.NotNil(t, routedMsg.ChildNamespace("sent", carbonsNamespace)) } func TestCarbons_ReceivedCC(t *testing.T) { // given routerMock := &routerMock{} var respStanzas []stravaganza.Stanza routerMock.RouteFunc = func(ctx context.Context, stanza stravaganza.Stanza) ([]jid.JID, error) { respStanzas = append(respStanzas, stanza) return nil, nil } jd0, _ := jid.NewWithString("<EMAIL>/balcony", true) jd1, _ := jid.NewWithString("<EMAIL>/hall", true) jd2, _ := jid.NewWithString("<EMAIL>/chamber", true) resManagerMock := &resourceManagerMock{} resManagerMock.GetResourcesFunc = func(ctx context.Context, username string) ([]c2smodel.Resource, error) { return []c2smodel.Resource{ {JID: jd0, Info: c2smodel.Info{M: map[string]string{carbonsEnabledCtxKey: "true"}}}, {JID: jd1, Info: c2smodel.Info{M: map[string]string{carbonsEnabledCtxKey: "false"}}}, {JID: jd2, Info: c2smodel.Info{M: map[string]string{carbonsEnabledCtxKey: "true"}}}, }, nil } hMock := &hostsMock{} hMock.IsLocalHostFunc = func(h string) bool { return h == "jackal.im" } hk := hook.NewHooks() c := &Carbons{ router: routerMock, resMng: resManagerMock, hosts: hMock, hk: hk, } b := stravaganza.NewMessageBuilder() b.WithAttribute("id", "i1234") b.WithAttribute("from", "<EMAIL>/balcony") b.WithAttribute("to", "<EMAIL>/chamber") b.WithAttribute("type", "chat") b.WithChild( stravaganza.NewBuilder("body"). WithText("I'll give thee a wind."). Build(), ) msg, _ := b.BuildMessage() // when _ = c.Start(context.Background()) defer func() { _ = c.Stop(context.Background()) }() _, _ = hk.Run(context.Background(), hook.C2SStreamMessageRouted, &hook.ExecutionContext{ Info: &hook.C2SStreamInfo{ Targets: []jid.JID{*jd2}, Element: msg, }, }) // then require.Len(t, respStanzas, 1) routedMsg := respStanzas[0] require.Equal(t, stravaganza.MessageName, routedMsg.Name()) require.Equal(t, "<EMAIL>", routedMsg.Attribute(stravaganza.From)) require.Equal(t, "<EMAIL>/balcony", routedMsg.Attribute(stravaganza.To)) require.NotNil(t, routedMsg.ChildNamespace("received", carbonsNamespace)) } func TestCarbons_InterceptStanza(t *testing.T) { // given hk := hook.NewHooks() c := &Carbons{ hk: hk, } b := stravaganza.NewMessageBuilder() b.WithAttribute("from", "noelia@jackal.im/yard") b.WithAttribute("to", "<EMAIL>/balcony") b.WithChild( stravaganza.NewBuilder("body"). WithText("I'll give thee a wind."). Build(), ) b.WithChild( stravaganza.NewBuilder("private"). WithAttribute(stravaganza.Namespace, carbonsNamespace). Build(), ) msg, _ := b.BuildMessage() // when _ = c.Start(context.Background()) defer func() { _ = c.Stop(context.Background()) }() hInf := &hook.C2SStreamInfo{ Element: msg, } _, err := hk.Run(context.Background(), hook.C2SStreamWillRouteElement, &hook.ExecutionContext{ Info: hInf, }) // then require.Nil(t, err) require.Nil(t, hInf.Element.ChildNamespace("private", carbonsNamespace)) }
Marcusz97/CILP_Facilitatore_Audacity
lib-src/libnyquist/nyquist/nyqstk/src/Stk.cpp
/***************************************************/ /*! \class Stk \brief STK base class Nearly all STK classes inherit from this class. The global sample rate can be queried and modified via Stk. In addition, this class provides error handling and byte-swapping functions. by <NAME> and <NAME>, 1995 - 2005. */ /***************************************************/ #include "Stk.h" #include <stdlib.h> using namespace Nyq; StkFloat Stk :: srate_ = (StkFloat) SRATE; std::string Stk :: rawwavepath_ = RAWWAVE_PATH; const Stk::StkFormat Stk :: STK_SINT8 = 0x1; const Stk::StkFormat Stk :: STK_SINT16 = 0x2; const Stk::StkFormat Stk :: STK_SINT24 = 0x4; const Stk::StkFormat Stk :: STK_SINT32 = 0x8; const Stk::StkFormat Stk :: STK_FLOAT32 = 0x10; const Stk::StkFormat Stk :: STK_FLOAT64 = 0x20; bool Stk :: showWarnings_ = false; bool Stk :: printErrors_ = true; Stk :: Stk(void) { } Stk :: ~Stk(void) { } void Stk :: setRawwavePath( std::string path ) { if ( !path.empty() ) rawwavepath_ = path; // Make sure the path includes a "/" if ( rawwavepath_[rawwavepath_.length()-1] != '/' ) rawwavepath_ += "/"; } void Stk :: swap16(unsigned char *ptr) { register unsigned char val; // Swap 1st and 2nd bytes val = *(ptr); *(ptr) = *(ptr+1); *(ptr+1) = val; } void Stk :: swap32(unsigned char *ptr) { register unsigned char val; // Swap 1st and 4th bytes val = *(ptr); *(ptr) = *(ptr+3); *(ptr+3) = val; //Swap 2nd and 3rd bytes ptr += 1; val = *(ptr); *(ptr) = *(ptr+1); *(ptr+1) = val; } void Stk :: swap64(unsigned char *ptr) { register unsigned char val; // Swap 1st and 8th bytes val = *(ptr); *(ptr) = *(ptr+7); *(ptr+7) = val; // Swap 2nd and 7th bytes ptr += 1; val = *(ptr); *(ptr) = *(ptr+5); *(ptr+5) = val; // Swap 3rd and 6th bytes ptr += 1; val = *(ptr); *(ptr) = *(ptr+3); *(ptr+3) = val; // Swap 4th and 5th bytes ptr += 1; val = *(ptr); *(ptr) = *(ptr+1); *(ptr+1) = val; } #if (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) #include <unistd.h> #elif defined(__OS_WINDOWS__) #include <windows.h> #endif void Stk :: sleep(unsigned long milliseconds) { #if defined(__OS_WINDOWS__) Sleep((DWORD) milliseconds); #elif (defined(__OS_IRIX__) || defined(__OS_LINUX__) || defined(__OS_MACOSX__)) usleep( (unsigned long) (milliseconds * 1000.0) ); #endif } void Stk :: handleError( StkError::Type type ) { handleError( errorString_.str(), type ); errorString_.str( std::string() ); // reset the ostringstream buffer } void Stk :: handleError( const char *message, StkError::Type type ) { std::string msg( message ); handleError( msg, type ); } void Stk :: handleError( std::string message, StkError::Type type ) { if ( type == StkError::WARNING || type == StkError::STATUS ) { if ( !showWarnings_ ) return; std::cerr << '\n' << message << '\n' << std::endl; } else if (type == StkError::DEBUG_WARNING) { #if defined(_STK_DEBUG_) std::cerr << '\n' << message << '\n' << std::endl; #endif } else { if ( printErrors_ ) { // Print error message before throwing. std::cerr << '\n' << message << '\n' << std::endl; } throw StkError(message, type); } } // // StkFrames definitions // StkFrames :: StkFrames( unsigned int nFrames, unsigned int nChannels, bool interleaved ) : nFrames_( nFrames ), nChannels_( nChannels ), interleaved_( interleaved ) { size_ = nFrames_ * nChannels_; bufferSize_ = size_; if ( size_ > 0 ) { data_ = (StkFloat *) calloc( size_, sizeof( StkFloat ) ); #if defined(_STK_DEBUG_) if ( data_ == NULL ) { std::string error = "StkFrames: memory allocation error in constructor!"; Stk::handleError( error, StkError::MEMORY_ALLOCATION ); } #endif } else data_ = 0; dataRate_ = Stk::sampleRate(); } StkFrames :: StkFrames( const StkFloat& value, unsigned int nFrames, unsigned int nChannels, bool interleaved ) : nFrames_( nFrames ), nChannels_( nChannels ), interleaved_( interleaved ) { size_ = nFrames_ * nChannels_; bufferSize_ = size_; if ( size_ > 0 ) { data_ = (StkFloat *) malloc( size_ * sizeof( StkFloat ) ); #if defined(_STK_DEBUG_) if ( data_ == NULL ) { std::string error = "StkFrames: memory allocation error in constructor!"; Stk::handleError( error, StkError::MEMORY_ALLOCATION ); } #endif for ( long i=0; i<(long)size_; i++ ) data_[i] = value; } else data_ = 0; dataRate_ = Stk::sampleRate(); } StkFrames :: ~StkFrames() { if ( data_ ) free( data_ ); } bool StkFrames :: empty() const { if ( size_ > 0 ) return false; else return true; } void StkFrames :: resize( size_t nFrames, unsigned int nChannels ) { nFrames_ = nFrames; nChannels_ = nChannels; size_ = nFrames_ * nChannels_; if ( size_ > bufferSize_ ) { if ( data_ ) free( data_ ); data_ = (StkFloat *) malloc( size_ * sizeof( StkFloat ) ); #if defined(_STK_DEBUG_) if ( data_ == NULL ) { std::string error = "StkFrames::resize: memory allocation error!"; Stk::handleError( error, StkError::MEMORY_ALLOCATION ); } #endif bufferSize_ = size_; } } void StkFrames :: resize( size_t nFrames, unsigned int nChannels, StkFloat value ) { this->resize( nFrames, nChannels ); for ( size_t i=0; i<size_; i++ ) data_[i] = value; } StkFloat& StkFrames :: operator[] ( size_t n ) { #if defined(_STK_DEBUG_) if ( n >= size_ ) { std::ostringstream error; error << "StkFrames::operator[]: invalid index (" << n << ") value!"; Stk::handleError( error.str(), StkError::MEMORY_ACCESS ); } #endif return data_[n]; } StkFloat StkFrames :: operator[] ( size_t n ) const { #if defined(_STK_DEBUG_) if ( n >= size_ ) { std::ostringstream error; error << "StkFrames::operator[]: invalid index (" << n << ") value!"; Stk::handleError( error.str(), StkError::MEMORY_ACCESS ); } #endif return data_[n]; } StkFloat& StkFrames :: operator() ( size_t frame, unsigned int channel ) { #if defined(_STK_DEBUG_) if ( frame >= nFrames_ || channel >= nChannels_ ) { std::ostringstream error; error << "StkFrames::operator(): invalid frame (" << frame << ") or channel (" << channel << ") value!"; Stk::handleError( error.str(), StkError::MEMORY_ACCESS ); } #endif if ( interleaved_ ) return data_[ frame * nChannels_ + channel ]; else return data_[ channel * nFrames_ + frame ]; } StkFloat StkFrames :: operator() ( size_t frame, unsigned int channel ) const { #if defined(_STK_DEBUG_) if ( frame >= nFrames_ || channel >= nChannels_ ) { std::ostringstream error; error << "StkFrames::operator(): invalid frame (" << frame << ") or channel (" << channel << ") value!"; Stk::handleError( error.str(), StkError::MEMORY_ACCESS ); } #endif if ( interleaved_ ) return data_[ frame * nChannels_ + channel ]; else return data_[ channel * nFrames_ + frame ]; } StkFloat StkFrames :: interpolate( StkFloat frame, unsigned int channel ) const { #if defined(_STK_DEBUG_) if ( frame >= (StkFloat) nFrames_ || channel >= nChannels_ ) { std::ostringstream error; error << "StkFrames::interpolate: invalid frame (" << frame << ") or channel (" << channel << ") value!"; Stk::handleError( error.str(), StkError::MEMORY_ACCESS ); } #endif size_t iIndex = ( size_t ) frame; // integer part of index StkFloat output, alpha = frame - (StkFloat) iIndex; // fractional part of index if ( interleaved_ ) { iIndex = iIndex * nChannels_ + channel; output = data_[ iIndex ]; output += ( alpha * ( data_[ iIndex + nChannels_ ] - output ) ); } else { iIndex += channel * nFrames_; output = data_[ iIndex ]; output += ( alpha * ( data_[ iIndex++ ] - output ) ); } return output; }
metux/chromium-deb
third_party/WebKit/Source/core/editing/InlineBoxTraversal.h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef InlineBoxTraversal_h #define InlineBoxTraversal_h #include "platform/wtf/Allocator.h" namespace blink { class InlineBox; // This class provides common traveral functions on list of |InlineBox|. class InlineBoxTraversal final { STATIC_ONLY(InlineBoxTraversal); public: // TODO(yosin): We should take |bidi_level| from |InlineBox::BidiLevel()|, // once all call sites satisfy it. // Returns |InlineBox| which is less than or equal to |bidi_level| of // left/right of specified |InlineBox|. static InlineBox* FindLeftBidiRun(const InlineBox&, unsigned bidi_level); static InlineBox* FindRightBidiRun(const InlineBox&, unsigned bidi_level); // Find left boundary variations static InlineBox* FindLeftBoundaryOfBidiRunIgnoringLineBreak( const InlineBox&, unsigned bidi_level); static InlineBox* FindLeftBoundaryOfEntireBidiRun(const InlineBox&, unsigned bidi_level); static InlineBox* FindLeftBoundaryOfEntireBidiRunIgnoringLineBreak( const InlineBox&, unsigned bidi_level); // Find right boundary variations static InlineBox* FindRightBoundaryOfBidiRunIgnoringLineBreak( const InlineBox&, unsigned bidi_level); static InlineBox* FindRightBoundaryOfEntireBidiRun(const InlineBox&, unsigned bidi_level); static InlineBox* FindRightBoundaryOfEntireBidiRunIgnoringLineBreak( const InlineBox&, unsigned bidi_level); }; } // namespace blink #endif // InlineBoxTraversal_h
ice-blokk/FRC-4653-Code-2022
src/main/java/frc/robot/commands/defaultcommands/DefaultArcadeDrive.java
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands.defaultcommands; import java.util.function.BooleanSupplier; import java.util.function.DoubleSupplier; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Drivetrain; public class DefaultArcadeDrive extends CommandBase { private Drivetrain drivetrain; private DoubleSupplier speed, rotate; private BooleanSupplier invert; private double sign; public DefaultArcadeDrive(DoubleSupplier speed, DoubleSupplier rotate, BooleanSupplier invert, Drivetrain drivetrain) { this.drivetrain = drivetrain; addRequirements(drivetrain); this.speed = speed; this.rotate = rotate; this.invert = invert; sign = 1; } @Override public void initialize() {} @Override public void execute() { if(rotate.getAsDouble() > 0) { sign = 1; } else { sign = -1; } drivetrain.arcadeDrive(speed.getAsDouble(), rotate.getAsDouble() * rotate.getAsDouble() * sign * .55, invert.getAsBoolean()); SmartDashboard.putNumber("arcade drive turn", rotate.getAsDouble() * rotate.getAsDouble() * sign * .55); } @Override public void end(boolean interrupted) { drivetrain.arcadeDrive(0, 0); } @Override public boolean isFinished() { return false; } }
althink/hermes
hermes-common/src/main/java/pl/allegro/tech/hermes/domain/workload/constraints/TopicConstraintsDoNotExistException.java
package pl.allegro.tech.hermes.domain.workload.constraints; import pl.allegro.tech.hermes.api.ErrorCode; import pl.allegro.tech.hermes.api.TopicName; import pl.allegro.tech.hermes.common.exception.HermesException; import static pl.allegro.tech.hermes.api.ErrorCode.TOPIC_CONSTRAINTS_DO_NOT_EXIST; public class TopicConstraintsDoNotExistException extends HermesException { public TopicConstraintsDoNotExistException(TopicName topicName, Throwable cause) { super(String.format("Constraints for topic %s do not exist.", topicName.qualifiedName()), cause); } @Override public ErrorCode getCode() { return TOPIC_CONSTRAINTS_DO_NOT_EXIST; } }
willramanand/RamSkills
src/main/java/com/gmail/willramanand/RamSkills/listeners/DamageListener.java
package com.gmail.willramanand.RamSkills.listeners; import com.gmail.willramanand.RamSkills.RamSkills; import com.gmail.willramanand.RamSkills.events.CriticalStrikeEvent; import com.gmail.willramanand.RamSkills.mana.Ability; import com.gmail.willramanand.RamSkills.player.SkillPlayer; import com.gmail.willramanand.RamSkills.skills.Skills; import com.gmail.willramanand.RamSkills.stats.Stat; import com.gmail.willramanand.RamSkills.utils.ItemUtils; import org.bukkit.Bukkit; import org.bukkit.attribute.Attribute; import org.bukkit.enchantments.EnchantmentTarget; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.inventory.ItemStack; import java.util.Random; public class DamageListener implements Listener { private final RamSkills plugin; public DamageListener(RamSkills plugin) { this.plugin = plugin; } @EventHandler(priority = EventPriority.HIGH) public void damage(EntityDamageByEntityEvent event) { checkToughness(event); modifyPlayerDamage(event); } public void checkToughness(EntityDamageByEntityEvent event) { if (!(event.getEntity() instanceof Player player)) return; SkillPlayer skillPlayer = plugin.getPlayerManager().getPlayerData(player); double damageReduction = 1 - (skillPlayer.getStatPoint(Stat.TOUGHNESS) / (skillPlayer.getStatPoint(Stat.TOUGHNESS) + 100)); event.setDamage(Math.max(event.getFinalDamage() * damageReduction, 1.5)); } public void modifyPlayerDamage(EntityDamageByEntityEvent event) { double damage = event.getFinalDamage(); boolean isValid = false; Player player = null; if (event.getDamager() instanceof Player) { player = (Player) event.getDamager(); ItemStack playerItem = player.getInventory().getItemInMainHand(); if (!(EnchantmentTarget.TOOL.includes(playerItem)) && !(EnchantmentTarget.WEAPON.includes(playerItem))) return; isValid = true; } else if (event.getDamager() instanceof Projectile projectile) { if (projectile.getShooter() instanceof Player) { player = (Player) projectile.getShooter(); ItemStack playerItem = player.getInventory().getItemInMainHand(); if (!(EnchantmentTarget.BOW.includes(playerItem))) return; isValid = true; } } if (!isValid) return; double newDamage = calculateDamage(player, damage); if (ItemUtils.isSword(player.getInventory().getItemInMainHand()) && player.getMetadata("readied").get(0).asBoolean()) lifeStealAbility(player, newDamage); event.setDamage(newDamage); } public double calculateDamage(Player player, double originalDamage) { SkillPlayer skillPlayer = plugin.getPlayerManager().getPlayerData(player); double strengthCalc = 1 + (skillPlayer.getStatPoint(Stat.STRENGTH) / 100); double critDamage = 1.0; if (isCrit(skillPlayer)) { critDamage = 1 + (skillPlayer.getStatPoint(Stat.CRIT_DAMAGE) / 100); } double newDamage = originalDamage * strengthCalc * critDamage; if (critDamage > 1.0) { CriticalStrikeEvent event = new CriticalStrikeEvent(player); Bukkit.getPluginManager().callEvent(event); } return newDamage; } public boolean isCrit(SkillPlayer skillPlayer) { double randDouble = new Random().nextDouble(1.01); double critChance = skillPlayer.getStatPoint(Stat.CRIT_CHANCE) / 100; if (critChance >= randDouble) { plugin.getActionBar().sendAbilityActionBar(skillPlayer.getPlayer(), "Critical Strike!"); return true; } return false; } public void lifeStealAbility(Player player, double damage) { SkillPlayer skillPlayer = plugin.getPlayerManager().getPlayerData(player); double maxHealth = player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(); double baseSteal = 0.1; double manaCost = Ability.SOUL_STEAL.getManaCost(); double startHealth = player.getHealth(); if (skillPlayer.getSkillLevel(Skills.COMBAT) < Ability.SOUL_STEAL.getUnlock()) { return; } else if (skillPlayer.getSkillLevel(Skills.COMBAT) == Ability.SOUL_STEAL.getUpgrade()) { baseSteal = 0.25; manaCost = 0.3; } double heal = player.getHealth() + (baseSteal * damage); manaCost *= heal; if (!(plugin.getManaAbility().checkMana(skillPlayer, manaCost))) { plugin.getActionBar().sendAbilityActionBar(player, "&4Not enough mana!"); return; } if (heal >= maxHealth) { heal = maxHealth; } player.setHealth(heal); EntityRegainHealthEvent event = new EntityRegainHealthEvent(player, player.getHealth() - startHealth, EntityRegainHealthEvent.RegainReason.CUSTOM); Bukkit.getPluginManager().callEvent(event); plugin.getActionBar().sendAbilityActionBar(player, "Soul Steal Activated!"); } }
Kuxe/swordbow-magic
include/clientdisconnectedstate.hpp
<reponame>Kuxe/swordbow-magic<filename>include/clientdisconnectedstate.hpp<gh_stars>1-10 #ifndef CLIENTDISCONNECTEDSTATE_HPP #define CLIENTDISCONNECTEDSTATE_HPP #include "iclientstate.hpp" #include "messagetypes.hpp" #include "ipaddress.hpp" #include "packethandler.hpp" #include <mutex> class Client; class ClientDisconnectedState : public IClientState { private: Client* client; std::mutex forceDisconnectMutex; volatile bool forceDisconnectBool = false; void forceDisconnect(); void pollForceDisconnect(); public: ClientDisconnectedState(Client* client); void step(); void changeState(IClientState* state); void onChange(ClientDisconnectedState* state); void onChange(ClientReceiveInitialState* state); void onChange(ClientRunningState* state); std::string name() const override; void greet(IPacket* packet) override; void handle(const OutdatedData*) override; void handle(const DisconnectData*) override; void handle(const BeginTransmittingInitialComponentsData* data) override; void handle(const KeepAliveData*) override; void onEvent(const KeyEvent& evt); void onEvent(const MouseEvent& evt); }; #endif //CLIENTDISCONNECTEDSTATE_HPP
matthb2/ParaView-beforekitwareswtichedtogit
Servers/Filters/vtkDesktopDeliveryServer.h
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkDesktopDeliveryServer - An object for remote rendering. // // .SECTION Description // The two vtkDesktopDelivery objects (vtkDesktopDeliveryClient and // vtkDesktopDeliveryServer) work together to enable interactive viewing of // remotely rendered data. The server attaches itself to a vtkRenderWindow // and, optionally, another vtkParallelRenderManager. Whenever a new // rendering is requested, the client alerts the server, the server renders // a new frame, and ships the image back to the client, which will display // the image in the vtkRenderWindow. // // .SECTION note // // .SECTION see also // vtkDesktopDeliveryClient vtkMultiProcessController vtkRenderWindow // vtkParallelRenderManager #ifndef __vtkDesktopDeliveryServer_h #define __vtkDesktopDeliveryServer_h #include "vtkParallelRenderManager.h" class VTK_EXPORT vtkDesktopDeliveryServer : public vtkParallelRenderManager { public: vtkTypeRevisionMacro(vtkDesktopDeliveryServer, vtkParallelRenderManager); virtual void PrintSelf(ostream &os, vtkIndent indent); static vtkDesktopDeliveryServer *New(); // Description: // Set/Get the controller that is attached to a vtkDesktopDeliveryClient. // This object will assume that the controller has two processors, and // that the controller on the opposite side of the controller has been // given to the server object. virtual void SetController(vtkMultiProcessController *controller); // Description: // Set/Get a parallel render manager that is used for parallel rendering. // If not set or set to NULL, rendering is done on the render window // directly in single process mode. It will be assumed that the // ParallelRenderManager will have the final image stored at the local // processes. virtual void SetParallelRenderManager(vtkParallelRenderManager *prm); vtkGetObjectMacro(ParallelRenderManager, vtkParallelRenderManager); virtual void SetRenderWindow(vtkRenderWindow *renWin); // Description: // If on (the default) locally rendered images will be shipped back to // the client. To facilitate this, the local rendering windows will be // resized based on the remote window settings. If off, the images are // assumed to be displayed locally. The render window maintains its // current size. virtual void SetRemoteDisplay(int); vtkGetMacro(RemoteDisplay, int); vtkBooleanMacro(RemoteDisplay, int); //BTX enum Tags { IMAGE_TAG=12433, IMAGE_SIZE_TAG=12434, REMOTE_DISPLAY_TAG=834340, TIMING_METRICS_TAG=834341, SQUIRT_OPTIONS_TAG=834342, IMAGE_PARAMS_TAG=834343 }; struct TimingMetrics { double ImageProcessingTime; }; struct SquirtOptions { int Enabled; int CompressLevel; void Save(vtkMultiProcessStream& stream); bool Restore(vtkMultiProcessStream& stream); }; struct ImageParams { int RemoteDisplay; int SquirtCompressed; int NumberOfComponents; int BufferSize; int ImageSize[2]; }; enum TimingMetricSize { TIMING_METRICS_SIZE=sizeof(struct TimingMetrics)/sizeof(double) }; enum SquirtOptionSize { SQUIRT_OPTIONS_SIZE=sizeof(struct SquirtOptions)/sizeof(int) }; enum ImageParamsSize { IMAGE_PARAMS_SIZE=sizeof(struct ImageParams)/sizeof(int) }; //ETX protected: vtkDesktopDeliveryServer(); virtual ~vtkDesktopDeliveryServer(); virtual void PreRenderProcessing(); virtual void PostRenderProcessing(); virtual void LocalComputeVisiblePropBounds(vtkRenderer *ren, double bounds[6]); vtkParallelRenderManager *ParallelRenderManager; unsigned long StartParallelRenderTag; unsigned long EndParallelRenderTag; virtual void SetRenderWindowSize(); virtual void ReadReducedImage(); // Description: // Process window information for synchronizing windows on each frame. virtual bool ProcessWindowInformation(vtkMultiProcessStream&); int Squirt; int SquirtCompressionLevel; void SquirtCompress(vtkUnsignedCharArray *in, vtkUnsignedCharArray *out); int RemoteDisplay; vtkUnsignedCharArray *SquirtBuffer; private: vtkDesktopDeliveryServer(const vtkDesktopDeliveryServer &); //Not implemented void operator=(const vtkDesktopDeliveryServer &); //Not implemented }; #endif
devgrok/daml
ledger/sandbox-classic/src/test/suite/scala/platform/sandbox/auth/GetAuthenticatedUserAuthIT.scala
// Copyright (c) 2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.platform.sandbox.auth import java.util.UUID import com.daml.ledger.api.v1.admin.user_management_service.{ GetUserRequest, User, UserManagementServiceGrpc, } import org.scalatest.Assertion import scala.concurrent.Future /** Tests covering the special behaviour of GetUser wrt the authenticated user. */ class GetAuthenticatedUserAuthIT extends ServiceCallAuthTests { private val testId = UUID.randomUUID().toString override def serviceCallName: String = "UserManagementService#GetUser(<authenticated-user>)" override def serviceCallWithToken(token: Option[String]): Future[Any] = stub(UserManagementServiceGrpc.stub(channel), token).getUser(GetUserRequest()) private def expectUser(token: Option[String], expectedUser: User): Future[Assertion] = serviceCallWithToken(token).map(assertResult(expectedUser)(_)) private def getUser(token: Option[String], userId: String) = stub(UserManagementServiceGrpc.stub(channel), token).getUser(GetUserRequest(userId)) behavior of serviceCallName it should "deny unauthenticated access" in { expectUnauthenticated(serviceCallWithToken(None)) } it should "deny access for a standard token referring to an unknown user" in { expectPermissionDenied(serviceCallWithToken(canReadAsUnknownUserStandardJWT)) } it should "return the 'participant_admin' user when using its standard token" in { expectUser(canReadAsAdminStandardJWT, User("participant_admin", "")) } it should "return invalid argument for custom token" in { expectInvalidArgument(serviceCallWithToken(canReadAsAdmin)) } it should "allow access to a non-admin user's own user record" in { for { // admin creates user (alice, aliceToken) <- createUserByAdmin(testId + "-alice") // user accesses its own user record without specifying the id aliceRetrieved1 <- getUser(aliceToken, "") // user accesses its own user record with specifying the id aliceRetrieved2 <- getUser(aliceToken, alice.id) } yield assertResult((alice, alice))((aliceRetrieved1, aliceRetrieved2)) } }
CourtHive/tods-competition-factory
src/drawEngine/governors/queryGovernor/positionActions/actionPolicyUtils.js
<filename>src/drawEngine/governors/queryGovernor/positionActions/actionPolicyUtils.js import { getPolicyDefinitions } from '../../../../tournamentEngine/governors/queryGovernor/getPolicyDefinitions'; import { POLICY_TYPE_POSITION_ACTIONS } from '../../../../constants/policyConstants'; import { POLICY_POSITION_ACTIONS_DEFAULT } from '../../../../fixtures/policies/POLICY_POSITION_ACTIONS_DEFAULT'; export function getEnabledStructures({ policyDefinitions, tournamentRecord, drawDefinition, structure, event, }) { const { policyDefinitions: attachedPolicy } = getPolicyDefinitions({ policyTypes: [POLICY_TYPE_POSITION_ACTIONS], tournamentRecord, drawDefinition, event, }); policyDefinitions = policyDefinitions || attachedPolicy || POLICY_POSITION_ACTIONS_DEFAULT; const positionActionsPolicy = policyDefinitions[POLICY_TYPE_POSITION_ACTIONS]; const { enabledStructures, disabledStructures } = positionActionsPolicy || {}; const actionsDisabled = disabledStructures?.find( (structurePolicy) => structurePolicy.stages?.includes(structure.stage) && (!structurePolicy.stageSequences?.length || structurePolicy.stageSequences.includes(structure.stageSequence)) ); return { enabledStructures, actionsDisabled }; } export function getPolicyActions({ enabledStructures, structure }) { if (enabledStructures === false) return {}; if (!enabledStructures?.length) return { policyActions: { enabledActions: [], disabledActions: [] } }; const { stage, stageSequence } = structure || {}; const policyActions = enabledStructures.find((structurePolicy) => { const matchesStage = !structurePolicy.stages?.length || structurePolicy.stages.includes(stage); const matchesStageSequence = !structurePolicy.stageSequences?.length || structurePolicy.stageSequences.includes(stageSequence); if (structurePolicy && matchesStage && matchesStageSequence) { return true; } }); return { policyActions }; } export function isAvailableAction({ action, policyActions }) { const disabled = !policyActions?.enabledActions || (policyActions?.disabledActions?.length && policyActions.disabledActions.includes(action)); if (disabled) return false; const enabled = policyActions?.enabledActions.length === 0 || policyActions?.enabledActions.includes(action); return enabled && !disabled ? true : false; }
bannmann/stringtemplate4
src/main/java/org/puretemplate/ErrorManager.java
package org.puretemplate; import java.io.PrintWriter; import java.io.StringWriter; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.antlr.runtime.CharStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.Token; import org.puretemplate.error.ErrorListener; import org.puretemplate.error.ErrorType; import org.puretemplate.error.GroupCompilationMessage; import org.puretemplate.error.LexerMessage; import org.puretemplate.error.Message; import org.puretemplate.error.RuntimeMessage; import org.puretemplate.error.TemplateCompilationMessage; import org.puretemplate.misc.Location; @RequiredArgsConstructor class ErrorManager { @Getter @AllArgsConstructor private static class MessageImpl implements Message { protected final ErrorType error; protected final Location location; protected final Throwable cause; protected final Object arg; protected final Object arg2; protected final Object arg3; public MessageImpl(ErrorType error, Location location, Throwable cause) { this(error, location, cause, null, null, null); } public MessageImpl(ErrorType error, Location location, Throwable cause, Object arg) { this(error, location, cause, arg, null, null); } public MessageImpl(ErrorType error, Location location, Throwable cause, Object arg, Object arg2) { this(error, location, cause, arg, arg2, null); } @Override public String toString() { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String msg = String.format(error.getMessage(), arg, arg2, arg3); pw.print(msg); if (cause != null) { pw.print("\nCaused by: "); cause.printStackTrace(pw); } return sw.toString(); } } @Getter private static final class GroupCompilationMessageImpl extends MessageImpl implements GroupCompilationMessage { /** * token inside group file */ private final Token token; private final String sourceName; /** * Creates */ public GroupCompilationMessageImpl( ErrorType errorType, String sourceName, Token token, Throwable cause, Object arg) { super(errorType, null, cause, arg); this.token = token; this.sourceName = sourceName; } @Override public String toString() { RecognitionException re = (RecognitionException) cause; int line = 0; int charPos = -1; if (token != null) { line = token.getLine(); charPos = token.getCharPositionInLine(); } else if (re != null) { line = re.line; charPos = re.charPositionInLine; } String filepos = line + ":" + charPos; if (sourceName != null) { return sourceName + " " + filepos + ": " + String.format(error.getMessage(), arg, arg2); } return filepos + ": " + String.format(error.getMessage(), arg, arg2); } } @Getter private static final class LexerMessageImpl extends MessageImpl implements LexerMessage { private final String message; /** * overall token pulled from group file */ private final Token templateToken; private final String sourceName; public LexerMessageImpl(String sourceName, String message, Token templateToken, RecognitionException cause) { super(ErrorType.LEXER_ERROR, null, cause, null); this.message = message; this.templateToken = templateToken; this.sourceName = sourceName; } @Override public RecognitionException getCause() { return (RecognitionException) super.getCause(); } @Override public String toString() { RecognitionException re = getCause(); int line = re.line; int charPos = re.charPositionInLine; if (templateToken != null) { line += templateToken.getLine() - 1; charPos += templateToken.getCharPositionInLine() + Parsing.getTemplateDelimiterSize(templateToken); } String filepos = line + ":" + charPos; if (sourceName != null) { return sourceName + " " + filepos + ": " + String.format(error.getMessage(), message); } return filepos + ": " + String.format(error.getMessage(), message); } } private static final class RuntimeMessageImpl extends MessageImpl implements RuntimeMessage { public RuntimeMessageImpl(ErrorType error, Location location) { this(error, location, null); } public RuntimeMessageImpl(ErrorType error, Location location, Object arg) { this(error, location, null, arg, null); } public RuntimeMessageImpl(ErrorType error, Location location, Throwable e, Object arg) { this(error, location, e, arg, null); } public RuntimeMessageImpl(ErrorType error, Location location, Throwable e, Object arg, Object arg2) { this(error, location, e, arg, arg2, null); } public RuntimeMessageImpl(ErrorType error, Location location, Throwable e, Object arg, Object arg2, Object arg3) { super(error, location, e, arg, arg2, arg3); } @Override public String toString() { StringBuilder buf = new StringBuilder(); if (location != null) { buf.append("context [") .append(location.getCallHierarchy()) .append("]"); location.getCoordinates() .ifPresent(coordinate -> buf.append(" ") .append(coordinate)); } buf.append(" ") .append(super.toString()); return buf.toString(); } } @Getter public static final class TemplateCompilationMessageImpl extends MessageImpl implements TemplateCompilationMessage { /** * overall token pulled from group file */ private final Token templateToken; /** * token inside template */ private final Token token; private final String sourceName; public TemplateCompilationMessageImpl( ErrorType error, String sourceName, Token templateToken, Token t, Throwable cause, Object arg) { this(error, sourceName, templateToken, t, cause, arg, null); } public TemplateCompilationMessageImpl( ErrorType error, String sourceName, Token templateToken, Token t, Throwable cause, Object arg, Object arg2) { super(error, null, cause, arg, arg2); this.templateToken = templateToken; this.token = t; this.sourceName = sourceName; } @Override public String toString() { int line = 0; int charPos = -1; if (token != null) { line = token.getLine(); charPos = token.getCharPositionInLine(); // check the input streams - if different then token is embedded in templateToken and we need to adjust the offset if (templateToken != null && !templateToken.getInputStream() .equals(token.getInputStream())) { line += templateToken.getLine() - 1; charPos += templateToken.getCharPositionInLine() + Parsing.getTemplateDelimiterSize(templateToken); } } String filepos = line + ":" + charPos; if (sourceName != null) { return sourceName + " " + filepos + ": " + String.format(error.getMessage(), arg, arg2); } return filepos + ": " + String.format(error.getMessage(), arg, arg2); } } @NonNull public final ErrorListener listener; public void lexerError(String sourceName, String msg, Token templateToken, RecognitionException e) { if (sourceName != null) { sourceName = Misc.getFileName(sourceName); } listener.compileTimeError(new LexerMessageImpl(sourceName, msg, templateToken, e)); } public void compileTimeError(ErrorType error, Token templateToken, Token t) { String sourceName = getSourceName(t); String text = t.getText(); listener.compileTimeError(new TemplateCompilationMessageImpl(error, sourceName, templateToken, t, null, text)); } public void compileTimeError(ErrorType error, Token templateToken, Token t, Object arg) { String sourceName = getSourceName(t); listener.compileTimeError(new TemplateCompilationMessageImpl(error, sourceName, templateToken, t, null, arg)); } public void compileTimeError(ErrorType error, Token templateToken, Token t, Object arg, Object arg2) { String sourceName = getSourceName(t); listener.compileTimeError(new TemplateCompilationMessageImpl(error, sourceName, templateToken, t, null, arg, arg2)); } public void groupSyntaxError(ErrorType error, String sourceName, RecognitionException e, String msg) { Token token = getToken(e); listener.compileTimeError(new GroupCompilationMessageImpl(error, sourceName, token, e, msg)); } public void groupLexerError(ErrorType error, String sourceName, RecognitionException e, String msg) { Token token = getToken(e); listener.compileTimeError(new GroupCompilationMessageImpl(error, sourceName, token, e, msg)); } public void runTimeError(Location location, ErrorType error) { listener.runTimeError(new RuntimeMessageImpl(error, location)); } public void runTimeError(Location location, ErrorType error, Throwable e, Object arg) { listener.runTimeError(new RuntimeMessageImpl(error, location, e, arg)); } public void runTimeError(Location location, ErrorType error, Object arg) { listener.runTimeError(new RuntimeMessageImpl(error, location, arg)); } public void runTimeError(Location location, ErrorType error, Object arg, Object arg2) { listener.runTimeError(new RuntimeMessageImpl(error, location, null, arg, arg2)); } public void runTimeError(Location location, ErrorType error, Object arg, Object arg2, Object arg3) { listener.runTimeError(new RuntimeMessageImpl(error, location, null, arg, arg2, arg3)); } public void ioError(Location location, ErrorType error, Throwable e) { listener.ioError(new MessageImpl(error, location, e)); } public void ioError(Location location, ErrorType error, Throwable e, Object arg) { listener.ioError(new MessageImpl(error, location, e, arg)); } public void internalError(Location location, String msg, Throwable e) { listener.internalError(new MessageImpl(ErrorType.INTERNAL_ERROR, location, e, msg)); } private String getSourceName(Token t) { CharStream input = t.getInputStream(); if (input == null) { return null; } String sourceName = input.getSourceName(); if (sourceName != null) { sourceName = Misc.getFileName(sourceName); } return sourceName; } private Token getToken(RecognitionException e) { return e.token; } }
ancientmooner/DALI
dali/operators/ssd/box_encoder.h
<gh_stars>1-10 // Copyright (c) 2017-2018, NVIDIA CORPORATION. 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. #ifndef DALI_OPERATORS_SSD_BOX_ENCODER_H_ #define DALI_OPERATORS_SSD_BOX_ENCODER_H_ #include <algorithm> #include <cstring> #include <vector> #include <utility> #include "dali/core/cuda_utils.h" #include "dali/core/tensor_shape.h" #include "dali/pipeline/operator/operator.h" #include "dali/pipeline/util/bounding_box_utils.h" namespace dali { template<typename Backend> class BoxEncoder; template <> class BoxEncoder<CPUBackend>: public Operator<CPUBackend> { public: using BoundingBox = Box<2, float>; explicit BoxEncoder(const OpSpec &spec) : Operator<CPUBackend>(spec), criteria_(spec.GetArgument<float>("criteria")), offset_(spec.GetArgument<bool>("offset")), scale_(spec.GetArgument<float>("scale")) { DALI_ENFORCE( criteria_ >= 0.f, "Expected criteria >= 0, actual value = " + std::to_string(criteria_)); DALI_ENFORCE( criteria_ <= 1.f, "Expected criteria <= 1, actual value = " + std::to_string(criteria_)); auto anchors = spec.GetArgument<vector<float>>("anchors"); DALI_ENFORCE(anchors.size() % BoundingBox::size == 0, "Anchors size must be divisible by 4, actual value = " + std::to_string(anchors.size())); int nanchors = anchors.size() / BoundingBox::size; anchors_.resize(nanchors); ReadBoxes(make_span(anchors_), make_cspan(anchors), {}, {}); means_ = spec.GetArgument<vector<float>>("means"); DALI_ENFORCE(means_.size() == 4, "means size must be a list of 4 values."); stds_ = spec.GetArgument<vector<float>>("stds"); DALI_ENFORCE(stds_.size() == 4, "stds size must be a list of 4 values."); DALI_ENFORCE(std::find(stds_.begin(), stds_.end(), 0) == stds_.end(), "stds values must be != 0."); } ~BoxEncoder() override = default; DISABLE_COPY_MOVE_ASSIGN(BoxEncoder); protected: bool SetupImpl(std::vector<OutputDesc> &output_desc, const HostWorkspace &ws) override { return false; } void RunImpl(Workspace<CPUBackend> &ws) override; using Operator<CPUBackend>::RunImpl; private: const float criteria_; vector<BoundingBox> anchors_; bool offset_; vector<float> means_; vector<float> stds_; float scale_; vector<float> CalculateIous(const vector<BoundingBox> &boxes) const; void CalculateIousForBox(float *ious, const BoundingBox &box) const; void WriteAnchorsToOutput(float *out_boxes, int *out_labels) const; void WriteMatchesToOutput(const vector<std::pair<unsigned, unsigned>> matches, const vector<BoundingBox> &boxes, const int *labels, float *out_boxes, int *out_labels) const; vector<std::pair<unsigned, unsigned>> MatchBoxesWithAnchors( const vector<BoundingBox> &boxes) const; unsigned FindBestBoxForAnchor( unsigned anchor_idx, const vector<float> &ious, unsigned num_boxes) const; static const int kBoxesInId = 0; static const int kLabelsInId = 1; static const int kBoxesOutId = 0; static const int kLabelsOutId = 1; }; } // namespace dali #endif // DALI_OPERATORS_SSD_BOX_ENCODER_H_
tcpcloud/debian-cassandra-cpp-driver
test/unit_tests/src/test_class_type_parser.cpp
/* Copyright (c) 2014-2016 DataStax 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. */ #ifdef STAND_ALONE # define BOOST_TEST_MODULE cassandra #endif #include "data_type_parser.hpp" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(class_type_parser) BOOST_AUTO_TEST_CASE(simple) { cass::DataType::ConstPtr data_type; cass::NativeDataTypes native_types; native_types.init_class_names(); data_type = cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.InetAddressType", native_types); BOOST_CHECK(data_type->value_type() == CASS_VALUE_TYPE_INET); data_type = cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.UTF8Type)", native_types); BOOST_CHECK(data_type->value_type() == CASS_VALUE_TYPE_TEXT); data_type = cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.UTF8Type)", native_types); BOOST_REQUIRE(data_type->value_type() == CASS_VALUE_TYPE_LIST); cass::CollectionType::ConstPtr collection = static_cast<cass::CollectionType::ConstPtr>(data_type); BOOST_REQUIRE(collection->types().size() == 1); BOOST_CHECK(collection->types()[0]->value_type() == CASS_VALUE_TYPE_TEXT); } BOOST_AUTO_TEST_CASE(invalid) { cass_log_set_level(CASS_LOG_DISABLED); cass::NativeDataTypes native_types; native_types.init_class_names(); // Premature end of string BOOST_CHECK(!cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.UserType", native_types)); BOOST_CHECK(!cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.UserType(", native_types)); BOOST_CHECK(!cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.UserType(blah", native_types)); BOOST_CHECK(!cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.UserType(blah,", native_types)); // Empty BOOST_CHECK(!cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.UserType()", native_types)); // Invalid hex BOOST_CHECK(!cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.UserType(blah,ZZZZ", native_types)); // Missing ':' BOOST_CHECK(!cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.UserType(" "foo,61646472657373," "737472656574org.apache.cassandra.db.marshal.UTF8Type)", native_types)); // Premature end of string BOOST_CHECK(!cass::DataTypeClassNameParser::parse_with_composite("org.apache.cassandra.db.marshal.CompositeType", native_types)); BOOST_CHECK(!cass::DataTypeClassNameParser::parse_with_composite("org.apache.cassandra.db.marshal.CompositeType(", native_types)); BOOST_CHECK(!cass::DataTypeClassNameParser::parse_with_composite("org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type", native_types)); BOOST_CHECK(!cass::DataTypeClassNameParser::parse_with_composite("org.apache.cassandra.db.marshal.CompositeType(org.apache.cassandra.db.marshal.UTF8Type,", native_types)); // Empty BOOST_CHECK(!cass::DataTypeClassNameParser::parse_with_composite("org.apache.cassandra.db.marshal.CompositeType()", native_types)); } BOOST_AUTO_TEST_CASE(udt) { cass::NativeDataTypes native_types; native_types.init_class_names(); cass::DataType::ConstPtr data_type = cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.UserType(" "foo,61646472657373," "737472656574:org.apache.cassandra.db.marshal.UTF8Type," "7a6970636f6465:org.apache.cassandra.db.marshal.Int32Type," "70686f6e6573:org.apache.cassandra.db.marshal.SetType(" "org.apache.cassandra.db.marshal.UserType(foo,70686f6e65,6e616d65:org.apache.cassandra.db.marshal.UTF8Type,6e756d626572:org.apache.cassandra.db.marshal.UTF8Type)))", native_types); BOOST_REQUIRE(data_type->value_type() == CASS_VALUE_TYPE_UDT); // Check external UDT cass::UserType::ConstPtr udt(data_type); BOOST_CHECK(udt->keyspace() == "foo"); BOOST_CHECK(udt->type_name() == "address"); BOOST_REQUIRE(udt->fields().size() == 3); cass::UserType::FieldVec::const_iterator i; i = udt->fields().begin(); BOOST_CHECK(i->name == "street"); BOOST_CHECK(i->type->value_type() == CASS_VALUE_TYPE_TEXT); ++i; BOOST_CHECK(i->name == "zipcode"); BOOST_CHECK(i->type->value_type() == CASS_VALUE_TYPE_INT); ++i; BOOST_CHECK(i->name == "phones"); BOOST_REQUIRE(i->type->value_type() == CASS_VALUE_TYPE_SET); cass::CollectionType::ConstPtr collection = static_cast<cass::CollectionType::ConstPtr>(i->type); BOOST_REQUIRE(collection->types().size() == 1); BOOST_REQUIRE(collection->types()[0]->value_type() == CASS_VALUE_TYPE_UDT); // Check internal UDT udt = static_cast<cass::UserType::ConstPtr>(collection->types()[0]); BOOST_CHECK(udt->keyspace() == "foo"); BOOST_CHECK(udt->type_name() == "phone"); BOOST_REQUIRE(udt->fields().size() == 2); i = udt->fields().begin(); BOOST_CHECK(i->name == "name"); BOOST_CHECK(i->type->value_type() == CASS_VALUE_TYPE_TEXT); ++i; BOOST_CHECK(i->name == "number"); BOOST_CHECK(i->type->value_type() == CASS_VALUE_TYPE_TEXT); } BOOST_AUTO_TEST_CASE(tuple) { cass::NativeDataTypes native_types; native_types.init_class_names(); cass::DataType::ConstPtr data_type = cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.TupleType(" "org.apache.cassandra.db.marshal.Int32Type," "org.apache.cassandra.db.marshal.UTF8Type," "org.apache.cassandra.db.marshal.FloatType)", native_types); BOOST_REQUIRE(data_type->value_type() == CASS_VALUE_TYPE_TUPLE); cass::TupleType::ConstPtr tuple = static_cast<cass::TupleType::ConstPtr>(data_type); BOOST_REQUIRE(tuple->types().size() == 3); BOOST_REQUIRE(tuple->types()[0]->value_type() == CASS_VALUE_TYPE_INT); BOOST_REQUIRE(tuple->types()[1]->value_type() == CASS_VALUE_TYPE_TEXT); BOOST_REQUIRE(tuple->types()[2]->value_type() == CASS_VALUE_TYPE_FLOAT); } BOOST_AUTO_TEST_CASE(nested_collections) { cass::NativeDataTypes native_types; native_types.init_class_names(); cass::DataType::ConstPtr data_type = cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.MapType(" "org.apache.cassandra.db.marshal.UTF8Type," "org.apache.cassandra.db.marshal.FrozenType(" "org.apache.cassandra.db.marshal.MapType(" "org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.Int32Type)))", native_types); BOOST_REQUIRE(data_type->value_type() == CASS_VALUE_TYPE_MAP); cass::CollectionType::ConstPtr collection = static_cast<cass::CollectionType::ConstPtr>(data_type); BOOST_REQUIRE(collection->types().size() == 2); BOOST_CHECK(collection->types()[0]->value_type() == CASS_VALUE_TYPE_TEXT); BOOST_REQUIRE(collection->types()[1]->value_type() == CASS_VALUE_TYPE_MAP); cass::CollectionType::ConstPtr nested_collection = static_cast<cass::CollectionType::ConstPtr>(collection->types()[1]); BOOST_REQUIRE(nested_collection->types().size() == 2); BOOST_CHECK(nested_collection->types()[0]->value_type() == CASS_VALUE_TYPE_INT); BOOST_CHECK(nested_collection->types()[1]->value_type() == CASS_VALUE_TYPE_INT); } BOOST_AUTO_TEST_CASE(composite) { cass::NativeDataTypes native_types; native_types.init_class_names(); cass::SharedRefPtr<cass::ParseResult> result = cass::DataTypeClassNameParser::parse_with_composite("org.apache.cassandra.db.marshal.CompositeType(" "org.apache.cassandra.db.marshal.AsciiType," "org.apache.cassandra.db.marshal.Int32Type)", native_types); BOOST_CHECK(result->is_composite()); BOOST_REQUIRE(result->types().size() == 2); BOOST_CHECK(result->types()[0]->value_type() == CASS_VALUE_TYPE_ASCII); BOOST_CHECK(result->types()[1]->value_type() == CASS_VALUE_TYPE_INT); BOOST_REQUIRE(result->reversed().size() == 2); BOOST_CHECK(result->reversed()[0] == false); BOOST_CHECK(result->reversed()[1] == false); BOOST_CHECK(result->collections().empty()); } BOOST_AUTO_TEST_CASE(not_composite) { cass::NativeDataTypes native_types; native_types.init_class_names(); cass::SharedRefPtr<cass::ParseResult> result = cass::DataTypeClassNameParser::parse_with_composite("org.apache.cassandra.db.marshal.InetAddressType", native_types); BOOST_REQUIRE(result->types().size() == 1); BOOST_CHECK(result->types()[0]->value_type() == CASS_VALUE_TYPE_INET); BOOST_REQUIRE(result->reversed().size() == 1); BOOST_CHECK(result->reversed()[0] == false); } BOOST_AUTO_TEST_CASE(composite_with_reversed) { cass::NativeDataTypes native_types; native_types.init_class_names(); cass::SharedRefPtr<cass::ParseResult> result = cass::DataTypeClassNameParser::parse_with_composite("org.apache.cassandra.db.marshal.CompositeType(" "org.apache.cassandra.db.marshal.ReversedType(org.apache.cassandra.db.marshal.AsciiType)," "org.apache.cassandra.db.marshal.Int32Type)", native_types); BOOST_CHECK(result->is_composite()); BOOST_REQUIRE(result->types().size() == 2); BOOST_CHECK(result->types()[0]->value_type() == CASS_VALUE_TYPE_ASCII); BOOST_CHECK(result->types()[1]->value_type() == CASS_VALUE_TYPE_INT); BOOST_REQUIRE(result->reversed().size() == 2); BOOST_CHECK(result->reversed()[0] == true); BOOST_CHECK(result->reversed()[1] == false); BOOST_CHECK(result->collections().empty()); } BOOST_AUTO_TEST_CASE(composite_with_collections) { cass::NativeDataTypes native_types; native_types.init_class_names(); cass::SharedRefPtr<cass::ParseResult> result = cass::DataTypeClassNameParser::parse_with_composite("org.apache.cassandra.db.marshal.CompositeType(" "org.apache.cassandra.db.marshal.Int32Type, " "org.apache.cassandra.db.marshal.UTF8Type," "org.apache.cassandra.db.marshal.ColumnToCollectionType(" "6162:org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)," "4A4b4C4D4e4F:org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UTF8Type)," "6A6b6C6D6e6F:org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type, org.apache.cassandra.db.marshal.LongType)" "))", native_types); BOOST_CHECK(result->is_composite()); BOOST_REQUIRE(result->types().size() == 2); BOOST_CHECK(result->types()[0]->value_type() == CASS_VALUE_TYPE_INT); BOOST_CHECK(result->types()[1]->value_type() == CASS_VALUE_TYPE_TEXT); BOOST_REQUIRE(result->reversed().size() == 2); BOOST_CHECK(result->reversed()[0] == false); BOOST_CHECK(result->reversed()[1] == false); BOOST_REQUIRE(result->collections().size() == 3); cass::ParseResult::CollectionMap::const_iterator i; i = result->collections().find("ab"); cass::CollectionType::ConstPtr collection; BOOST_REQUIRE(i != result->collections().end()); BOOST_REQUIRE(i->second->value_type() == CASS_VALUE_TYPE_LIST); collection = static_cast<cass::CollectionType::ConstPtr>(i->second); BOOST_REQUIRE(collection->types().size() == 1); BOOST_CHECK(collection->types()[0]->value_type() == CASS_VALUE_TYPE_INT); i = result->collections().find("JKLMNO"); BOOST_REQUIRE(i != result->collections().end()); BOOST_CHECK(i->second->value_type() == CASS_VALUE_TYPE_SET); collection = static_cast<cass::CollectionType::ConstPtr>(i->second); BOOST_REQUIRE(collection->types().size() == 1); BOOST_CHECK(collection->types()[0]->value_type() == CASS_VALUE_TYPE_TEXT); i = result->collections().find("jklmno"); BOOST_REQUIRE(i != result->collections().end()); BOOST_CHECK(i->second->value_type() == CASS_VALUE_TYPE_MAP); collection = static_cast<cass::CollectionType::ConstPtr>(i->second); BOOST_REQUIRE(collection->types().size() == 2); BOOST_CHECK(collection->types()[0]->value_type() == CASS_VALUE_TYPE_TEXT); BOOST_CHECK(collection->types()[1]->value_type() == CASS_VALUE_TYPE_BIGINT); } BOOST_AUTO_TEST_CASE(frozen) { cass::DataType::ConstPtr data_type; cass::NativeDataTypes native_types; native_types.init_class_names(); data_type = cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.UTF8Type))", native_types); BOOST_REQUIRE(data_type->value_type() == CASS_VALUE_TYPE_LIST); BOOST_CHECK(data_type->is_frozen()); data_type = cass::DataTypeClassNameParser::parse_one("org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.UTF8Type)))", native_types); BOOST_REQUIRE(data_type->value_type() == CASS_VALUE_TYPE_LIST); BOOST_CHECK(!data_type->is_frozen()); cass::CollectionType::ConstPtr collection = static_cast<cass::CollectionType::ConstPtr>(data_type); BOOST_REQUIRE(collection->types().size() == 1); BOOST_CHECK(collection->types()[0]->value_type() == CASS_VALUE_TYPE_LIST); BOOST_CHECK(collection->types()[0]->is_frozen()); } BOOST_AUTO_TEST_SUITE_END()
microsoft/vOW4SIKE_on_HW
SIKE_vOW_hw-sw/ref_c/SIKE_vOW_software/src/prng.c
/******************************************************************************************** * PRNG based on AES *********************************************************************************************/ #include <string.h> #include "prng.h" void init_prng(prng_state_t *state, unsigned long seed) { #if defined(USE_AES_PRNG) unsigned char inp[16] = {0}, i; state->count = 0; for (i = 0; i < 4; i++) inp[i] = (seed >> 8 * i) & 0xFF; // Length of seed = 32 bits AES128_load_schedule(inp, state->aes_key_schedule); #else // POSIX.1-2001, see 'srand' man page state->A = 1103515245; state->B = 12345; state->rand_max = 32768; state->sampled = seed; #endif } void sample_prng(prng_state_t *state, unsigned char *buffer, unsigned long nbytes) { #if defined(USE_AES_PRNG) /* AES-CTR mode with plaintext = 0 */ /* Assumes that count doesn't exceed 64-bits */ unsigned char inp[16] = {0}; while (nbytes > 16) { *((uint64_t *)inp) = ++state->count; AES128_enc(inp, state->aes_key_schedule, buffer); nbytes -= 16; buffer += 16; } *((uint64_t *)inp) = ++state->count; AES128_enc(inp, state->aes_key_schedule, inp); memcpy(buffer, inp, nbytes); #else while (nbytes-- > 0) { state->sampled = state->sampled * state->A + state->B; buffer[nbytes] = (unsigned char)((unsigned)((state->sampled / state->rand_max) >> 1) % state->rand_max); } #endif } void XOF(unsigned char *output, unsigned char *input, unsigned long nbytes_output, unsigned long nbytes_input, unsigned long salt) { #ifdef USE_XXHASH_XOF // xxhash unsigned long long round_output = salt; int hash_round = 0; unsigned int i; for (i = 0; i < nbytes_output; i++) { switch (i & 7) { case 0: round_output = XXH64(input, nbytes_input, round_output); output[8 * hash_round] = ((unsigned char *)&round_output)[0]; break; case 1: output[8 * hash_round + 1] = ((unsigned char *)&round_output)[1]; break; case 2: output[8 * hash_round + 2] = ((unsigned char *)&round_output)[2]; break; case 3: output[8 * hash_round + 3] = ((unsigned char *)&round_output)[3]; break; case 4: output[8 * hash_round + 4] = ((unsigned char *)&round_output)[4]; break; case 5: output[8 * hash_round + 5] = ((unsigned char *)&round_output)[5]; break; case 6: output[8 * hash_round + 6] = ((unsigned char *)&round_output)[6]; break; case 7: output[8 * hash_round + 7] = ((unsigned char *)&round_output)[7]; hash_round++; break; } } #elif defined(USE_AES_XOF) (void)nbytes_input; /* AES-CBC mode */ unsigned char aes_key_schedule[16 * 11]; unsigned char key[16] = {0}, temp[32] = {0}; unsigned char* inp = &temp[16]; unsigned int nblocks = (unsigned int)(nbytes_input+15)/16; unsigned char j; for (int i = 0; i < 4; i++) key[i] = ((unsigned char *)&salt)[i]; // Set key AES128_load_schedule(key, aes_key_schedule); if (nbytes_input <= 16) { // Assumes nbytes_output <= 16 memcpy(inp, input, nbytes_input); AES128_enc(inp, aes_key_schedule, inp); memcpy(output, inp, nbytes_output); } else { // Assumes nbytes_output <= 32 memcpy(inp, input, 16); for (int i = 0; i < (int)nblocks-2; i++) { AES128_enc(inp, aes_key_schedule, temp); for (j = 0; j < 16; j++) inp[j] = input[j+16] ^ temp[j]; input += 16; } AES128_enc(inp, aes_key_schedule, temp); memset(inp, 0, 16); for (j = 0; j < nbytes_input-16*(nblocks-1); j++) inp[j] = input[j+16] ^ temp[j]; AES128_enc(inp, aes_key_schedule, inp); memcpy(output, temp, nbytes_output); } #endif }
AntonVolDev/Examples
Spring/GS_SubscriptionPortlet/src/main/java/com/geminisystems/subscription/job/SendMediaMailJob.java
package com.geminisystems.subscription.job; import com.geminisystems.subscription.dao.CategoryDao; import com.geminisystems.subscription.dao.SubscriptionDao; import com.geminisystems.subscription.domain.SBean; import com.geminisystems.subscription.domain.SCategory; import com.geminisystems.subscription.domain.SMediaContent; import com.geminisystems.subscription.domain.SType; import com.geminisystems.subscription.service.MailService; import com.geminisystems.subscription.service.MediaContentService; import org.apache.log4j.Logger; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; /** * Created by IntelliJ IDEA. * User: GGobozov * Date: 15.08.2012 * Time: 13:23:10 * To change this template use File | Settings | File Templates. */ public class SendMediaMailJob extends QuartzJobBean { private final static String PROP_DENY_JOBS_HOST = "subscr.deny.jobs.host"; private Logger logger = Logger.getLogger(SendMediaMailJob.class); private SubscriptionDao subscriptionDao; private MailService mailService; private CategoryDao categoryDao; private MediaContentService mediaContentService; private Properties configProperites; @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { try { String denyHost = configProperites.getProperty(PROP_DENY_JOBS_HOST); if (denyHost.equalsIgnoreCase(InetAddress.getLocalHost().getHostName())) { logger.info("ATTEMP TO RUN SEND MEDIA UPDATES JOB AT DENIED HOST : " + InetAddress.getLocalHost().getHostName()); return; } } catch (UnknownHostException e) { e.printStackTrace(); } logger.setLevel(Logger.getRootLogger().getLevel()); logger.info("================================================================================="); logger.info("Send MEDIA updates job started..."); logger.info("Get media content subscribers"); List<SBean> subscribers = subscriptionDao.getAllActive(SType.MEDIA); logger.info("Get media content from database"); List<SMediaContent> content = mediaContentService.getAll(); logger.info("Obtained " + content.size() + " media content items"); // create content map by category Map<String, List<String>> data = new HashMap<String, List<String>>(); for (SMediaContent smc : content) { if (data.get(smc.getTitle()) == null) { data.put(smc.getTitle(), new ArrayList<String>()); } // compose link String url = configProperites.getProperty("portal.host") + "/?urile=wcm:path:/" + smc.getUrl(); String link = "<a href='" + url + "'>" + smc.getText() + "</a><br/>" + smc.getDescription(); data.get(smc.getTitle()).add(link); } int count = 0; for (SBean b : subscribers) { Map<String, List<String>> userContent = new HashMap<String, List<String>>(); for (SCategory category : b.getCategories()) { category = categoryDao.getById(category.getCategoryId()); if (data.get(category.getTitle()) != null) { userContent.put(category.getTitle(), data.get(category.getTitle())); } } if (!userContent.isEmpty()) { logger.debug("Send mail to " + b.getEmail()); mailService.sendUpdatesMail(b, userContent); count++; } } logger.info("It was sent " + count + " MEDIA emails"); logger.info("Send MEDIA updates job finished..."); logger.info("================================================================================="); // delete all records mediaContentService.deleteAll(content); } public void setConfigProperites(Properties configProperites) { this.configProperites = configProperites; } public void setCategoryDao(CategoryDao categoryDao) { this.categoryDao = categoryDao; } public void setLogger(Logger logger) { this.logger = logger; } public void setMediaContentService(MediaContentService mediaContentService) { this.mediaContentService = mediaContentService; } public void setSubscriptionDao(SubscriptionDao subscriptionDao) { this.subscriptionDao = subscriptionDao; } public void setMailService(MailService mailService) { this.mailService = mailService; } private void printLogFooter(String error) { logger.info(error); logger.info("Send updates job finished..."); logger.info("================================================================================="); } }
markguozhiming/spheral
src/Material/PhysicalConstants.hh
<reponame>markguozhiming/spheral<gh_stars>1-10 //---------------------------------Spheral++----------------------------------// // PhysicalConstants -- Choose the physical units for a given Spheral run. // // Created by JMO, Mon Dec 6 21:36:45 PST 1999 //----------------------------------------------------------------------------// #ifndef __Spheral_PhysicalConstants_hh__ #define __Spheral_PhysicalConstants_hh__ namespace Spheral { class PhysicalConstants { public: //--------------------------- Public Interface ---------------------------// // You must provide the base mass, length, and time in MKS. PhysicalConstants(const double unitLm, const double unitMkg, const double unitTsec, const double unitTeK = 1.0, const double unitCcou = 1.0); // The fundamental independent quantities. double unitLengthMeters() const; double unitMassKg() const; double unitTimeSec() const; double unitTemperatureKelvin() const; double unitChargeCoulomb() const; // All the stuff we provide. double protonMass() const; double electronMass() const; double electronCharge() const; double G() const; double c() const; double kB() const; double Navogadro() const; double molarGasConstant() const; double kelvinsToEnergyPerMole() const; double unitMassDensity() const; double stefanBoltzmannConstant() const; double blackBodyConstant() const; double unitEnergyJ() const; private: //--------------------------- Private Interface ---------------------------// // Independent variables. double mUnitLm, mUnitMkg, mUnitTsec, mUnitTeK, mUnitCcou; // Dependent variables. const double UnitEnergyJ; const double ProtonMass; const double ElectronMass; const double ElectronCharge; const double GGravity; const double cLight; const double kBoltzmann; const double MolarGasConstant; const double KelvinsToEnergyPerMole; const double UnitMassDensity; const double Sigma; const double BlackBody; // The reference MKS data we base our values on. static const double mpMKS; static const double meMKS; static const double qeMKS; static const double GMKS; static const double cMKS; static const double kBMKS; static const double RgasMKS; static const double NAvogadro; static const double StefanBoltzmannMKS; }; } #include "PhysicalConstantsInline.hh" #else // Forward declaration. namespace Spheral { class PhysicalConstants; } #endif
Oriode/Simpleplusplus
Simple++/Graphic/Color.h
///@file Color.h ///@brief Basic for every type of color ///@author <NAME> ///@date 22/09/2016 (DMY) #pragma once #include "../Utility.h" #include "../String.h" namespace Graphic { enum class Format : unsigned int { R = 1, RGB = 3, RGBA = 4 }; ///@brief Struct used to retrieve the type compilation times informations template<typename T> struct _ColorHelper { typedef typename Utility::TypesInfos<typename Utility::TypesInfos<T>::Bigger>::Bigger Type; typedef float Float; constexpr static T getMax() { return Utility::TypesInfos<T>::getMax(); } }; template<> struct _ColorHelper<float> { typedef float Type; typedef float Float; constexpr static float getMax() { return 1.0f; } }; template<> struct _ColorHelper<double> { typedef double Type; typedef double Float; constexpr static double getMax() { return 1.0; } }; ///@brief Class representing a color of 1 component of type T template<typename T> class Color { public: ///@brief Type used to sum multiple pixels components typedef typename _ColorHelper<T>::Type SumType; ///@brief Type used to sum multiple pixels components multiplied with a negative value typedef typename Utility::TypesInfos<typename SumType>::Signed KernelType; ///@brief Floating point type typedef typename _ColorHelper<T>::Float Float; inline static void castComponent( float & comDest, const float & compSrc ); template<typename T1> inline static void castComponent( T1 & comDest, const T1 & compSrc ); template<typename T1, typename T2> inline static void castComponent( T1 & comDest, const T2 & compSrc ); template<typename U> inline static void castComponent( float & comDest, const U & compSrc ); template<typename U> inline static void castComponent( double & comDest, const U & compSrc ); template<typename U> inline static void castComponent( U & comDest, const float & compSrc ); template<typename U> inline static void castComponent( U & comDest, const double & compSrc ); constexpr static T getMin() { return T( 0 ); } static constexpr T getMax() { return _ColorHelper<T>::getMax(); } constexpr static T getMaxNbBits() { return Utility::TypesInfos<T>::getNbBits(); } }; template<typename T> void Color<T>::castComponent( float & comDest, const float & compSrc ) { comDest = ( compSrc ); } template<typename T> template<typename T1> void Color<T>::castComponent( T1 & comDest, const T1 & compSrc ) { comDest = ( compSrc ); } template<typename T> template<typename T1, typename T2> void Color<T>::castComponent( T1 & comDest, const T2 & compSrc ) { comDest = T1( compSrc ); } template<typename T> template<typename U> void Color<T>::castComponent( float & comDest, const U & compSrc ) { comDest = float( compSrc ) / float( ColorR<U>::getMax() ); } template<typename T> template<typename U> void Color<T>::castComponent( U & comDest, const float & compSrc ) { comDest = unsigned char( compSrc * float( ColorR<U>::getMax() ) ); } template<typename T> template<typename U> void Color<T>::castComponent( double & comDest, const U & compSrc ) { comDest = double( compSrc ) / double( ColorR<U>::getMax() ); } template<typename T> template<typename U> void Color<T>::castComponent( U & comDest, const double & compSrc ) { comDest = unsigned char( compSrc * double( ColorR<U>::getMax() ) ); } }
zhou-en/turf_portal
stock/migrations/0011_auto_20200913_2112.py
# Generated by Django 3.1.1 on 2020-09-13 21:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('stock', '0010_turfroll_delivered'), ] operations = [ migrations.RenameField( model_name='turfroll', old_name='delivered', new_name='total', ), migrations.RemoveField( model_name='turfroll', name='available', ), migrations.RemoveField( model_name='turfroll', name='reserved', ), ]
06needhamt/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/previewfeature/java.base/jdk.internal.javac/FirstPreviewFeatureReflective.java
<reponame>06needhamt/intellij-community package com.mycom; @jdk.internal.javac.PreviewFeature(feature = jdk.internal.javac.PreviewFeature.Feature.SEALED_CLASSES, reflective = true) public interface FirstPreviewFeatureReflective { public static final class Outer { public static final class Inner { public void z() {} } } void f(); static void g() {} public static final String KEY = "value"; }
Etxea/gestion_eide_web
clases/forms.py
<reponame>Etxea/gestion_eide_web<gh_stars>0 from django.forms import ModelForm from django import forms from models import * class ClaseForm(ModelForm): class Meta: model = Clase exclude = ["padre"] widgets = { "hora_inicio": forms.widgets.DateTimeInput(format='%Y-%m-%d %H:%M:%S'), "hora_fin": forms.widgets.DateTimeInput(format='%Y-%m-%d %H:%M:%S'), }
asm128/nwol
nwol/nwol_label_manager.h
<gh_stars>1-10 /// Copyright 2016-2017 - asm128 #include "nwol_unshrinkable_block_container.h" #ifndef NWOL_GLABELMANAGER_H_61596898798741996481968498 #define NWOL_GLABELMANAGER_H_61596898798741996481968498 namespace nwol { //#define MAX_LABELDATA_ARRAYS 16 class CLabelManager { static constexpr const uint32_t MAX_LABELDATA_ARRAYS = 16; ::nwol::unordered_string_set<char, 4096> LabelData [MAX_LABELDATA_ARRAYS] = {}; inline CLabelManager& operator= (const CLabelManager& other) = delete; public: //------------------------------------------------------ -------- ----- ::nwol::error_t AddLabel (const char* text, uint32_t maxReadSize, nwol::array_view<const char>& arrayView); static CLabelManager& get () { static CLabelManager globalLabelManager; return globalLabelManager; } }; CLabelManager* getLabelManager (); CLabelManager* getSystemLabelManager (); } // namespace #endif // NWOL_GLABELMANAGER_H_61596898798741996481968498