repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
stinsonga/geo-prime-workspace
work/exampleOAuY.js
<filename>work/exampleOAuY.js function my_function376(){ //37984557895029916748001204519028kdmUDJrxJrzUHNoNPzzlTMCmLGuvbyDR } function my_function033(){ //79334158616521852867777178335522ETKncXlUcLeDQeBIVfupJnFOrrepNuhg } function my_function293(){ //17517450847965549003072087682663WcRJhmoechQqeCbUiraAKHunJhiccqCy } function my_function649(){ //71215619901805601748469342206957CtmgQmfWRiSoYBXNkwhEqLJmXSgNmFrA } function my_function432(){ //60259213963838401859258435145934SmYJbpTRyXmPbvHEFnrcoEFjjfdUOHkV } function my_function959(){ //80710243915395929106633410871476qmgBWAGgIbLSYukPSfzEVknvBVfPFBLg } function my_function148(){ //73516250229300421011807048027552SFOOvTzPHNHLktZhmjltjdXHpjyEIBXN } function my_function565(){ //32526383844066008529559082682514effGnBVQfYIPZISMwElXKrVnzuSgQNZe } function my_function772(){ //48121140092115037927030048831134qFXVoJbsmYdSWotiaxLpLofOeqZUUjld } function my_function438(){ //20574377306634467835677046015162LxxGREwIYwBfdPITfNAklLYRjqsjOgqO } function my_function157(){ //24917693692898639135269868135022FuZHjwOnxtTGErTTrOsYoLDBpmfugZlq }
wangchong6808/dremio-oss
plugins/hive/src/test/java/com/dremio/exec/store/hive/exec/TestHiveRecordReaderIterator.java
<reponame>wangchong6808/dremio-oss /* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.exec.store.hive.exec; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.arrow.memory.ArrowBuf; import org.apache.arrow.memory.BufferAllocator; import org.apache.commons.lang3.tuple.Pair; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.dremio.common.AutoCloseables; import com.dremio.exec.store.CompositeColumnFilter; import com.dremio.exec.store.RecordReader; import com.dremio.exec.store.RuntimeFilter; import com.dremio.exec.store.SplitAndPartitionInfo; import com.dremio.exec.store.dfs.PrefetchingIterator; import com.dremio.exec.store.dfs.SplitReaderCreator; import com.dremio.exec.store.dfs.implicit.CompositeReaderConfig; import com.dremio.exec.store.dfs.implicit.ConstantColumnPopulators; import com.dremio.exec.store.dfs.implicit.NameValuePair; import com.dremio.exec.util.BloomFilter; import com.dremio.sabot.exec.context.OpProfileDef; import com.dremio.sabot.exec.context.OperatorContext; import com.dremio.sabot.exec.context.OperatorStats; import com.dremio.sabot.op.scan.ScanOperator; import com.dremio.service.namespace.dataset.proto.PartitionProtobuf; import com.dremio.test.AllocatorRule; /** * Tests for {@link HiveRecordReaderIterator} */ public class TestHiveRecordReaderIterator { private final static String TEST_NAME = "TestHiveRecordReaderIterator"; private BufferAllocator testAllocator; @Rule public final AllocatorRule allocatorRule = AllocatorRule.defaultAllocator(); @Before public void setupBeforeTest() { testAllocator = allocatorRule.newAllocator("test-hive-iterator", 0, Long.MAX_VALUE); } @After public void cleanupAfterTest() { testAllocator.close(); } @Test public void testIteratorWithoutFilter() { CompositeReaderConfig readerConfig = mock(CompositeReaderConfig.class); List<Pair<SplitAndPartitionInfo, RecordReader>> readers = getMockSplitReaders(10); HiveRecordReaderIterator it = new HiveRecordReaderIterator(getCtx(), readerConfig, withSupplier(readers)); for (int i = 0; i < readers.size(); i++) { RecordReader reader = readers.get(i).getRight(); assertTrue(it.hasNext()); assertEquals(reader, it.next()); } assertFalse(it.hasNext()); } @Test public void testIteratorWithFilterAddedInBetween() { CompositeReaderConfig readerConfig = mock(CompositeReaderConfig.class); when(readerConfig.getPartitionNVPairs(any(BufferAllocator.class), any(SplitAndPartitionInfo.class))) .thenReturn(getNonMatchingNameValuePairs()); List<Pair<SplitAndPartitionInfo, RecordReader>> readers = getMockSplitReaders(10); OperatorContext ctx = getCtx(); HiveRecordReaderIterator it = new HiveRecordReaderIterator(ctx, readerConfig, withSupplier(readers)); for (int i = 0; i < 5; i++) { RecordReader reader = readers.get(i).getRight(); assertTrue(it.hasNext()); assertEquals(reader, it.next()); } try (AutoCloseables.RollbackCloseable closer = new AutoCloseables.RollbackCloseable()) { RuntimeFilter filter = prepareRuntimeFilter(); closer.add(filter.getPartitionColumnFilter().getBloomFilter()); it.addRuntimeFilter(filter); assertFalse(it.hasNext()); assertEquals(5L, ctx.getStats().getLongStat(ScanOperator.Metric.NUM_PARTITIONS_PRUNED)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testIteratorWithFilterNothingSkipped() { CompositeReaderConfig readerConfig = mock(CompositeReaderConfig.class); when(readerConfig.getPartitionNVPairs(any(BufferAllocator.class), any(SplitAndPartitionInfo.class))) .thenReturn(getMatchingNameValuePairs()); List<Pair<SplitAndPartitionInfo, RecordReader>> readers = getMockSplitReaders(10); OperatorContext ctx = getCtx(); HiveRecordReaderIterator it = new HiveRecordReaderIterator(getCtx(), readerConfig, withSupplier(readers)); try (AutoCloseables.RollbackCloseable closer = new AutoCloseables.RollbackCloseable()) { RuntimeFilter filter = prepareRuntimeFilter(); closer.add(filter.getPartitionColumnFilter().getBloomFilter()); it.addRuntimeFilter(filter); for (int i = 0; i < readers.size(); i++) { RecordReader reader = readers.get(i).getRight(); assertTrue(it.hasNext()); assertEquals(reader, it.next()); } assertEquals(0L, ctx.getStats().getLongStat(ScanOperator.Metric.NUM_PARTITIONS_PRUNED)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testIteratorWithFilterAllSkipped() { CompositeReaderConfig readerConfig = mock(CompositeReaderConfig.class); when(readerConfig.getPartitionNVPairs(any(BufferAllocator.class), any(SplitAndPartitionInfo.class))) .thenReturn(getNonMatchingNameValuePairs()); List<Pair<SplitAndPartitionInfo, RecordReader>> readers = getMockSplitReaders(10); OperatorContext ctx = getCtx(); HiveRecordReaderIterator it = new HiveRecordReaderIterator(ctx, readerConfig, withSupplier(readers)); try (AutoCloseables.RollbackCloseable closer = new AutoCloseables.RollbackCloseable()) { RuntimeFilter filter = prepareRuntimeFilter(); closer.add(filter.getPartitionColumnFilter().getBloomFilter()); it.addRuntimeFilter(filter); assertFalse(it.hasNext()); assertEquals(10L, ctx.getStats().getLongStat(ScanOperator.Metric.NUM_PARTITIONS_PRUNED)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testIteratorWithFilterSomeSkipped() { Predicate<Integer> isSelectedSplit = i -> i==1 || i==3 || i==9; CompositeReaderConfig readerConfig = mock(CompositeReaderConfig.class); List<Pair<SplitAndPartitionInfo, RecordReader>> readers = getMockSplitReaders(10); List<RecordReader> selectedReaders = new ArrayList<>(); for (int i = 0; i < readers.size(); i++) { SplitAndPartitionInfo split = readers.get(i).getLeft(); if (isSelectedSplit.test(i)) { when(readerConfig.getPartitionNVPairs(any(BufferAllocator.class), eq(split))) .thenReturn(getMatchingNameValuePairs()); selectedReaders.add(readers.get(i).getRight()); } else { when(readerConfig.getPartitionNVPairs(any(BufferAllocator.class), eq(split))) .thenReturn(getNonMatchingNameValuePairs()); } } OperatorContext ctx = getCtx(); HiveRecordReaderIterator it = new HiveRecordReaderIterator(ctx, readerConfig, withSupplier(readers)); try (AutoCloseables.RollbackCloseable closer = new AutoCloseables.RollbackCloseable()) { RuntimeFilter filter = prepareRuntimeFilter(); closer.add(filter.getPartitionColumnFilter().getBloomFilter()); it.addRuntimeFilter(filter); for (int i = 0; i < selectedReaders.size(); i++) { RecordReader reader = selectedReaders.get(i); assertTrue(it.hasNext()); assertEquals(reader, it.next()); } assertEquals(7L, ctx.getStats().getLongStat(ScanOperator.Metric.NUM_PARTITIONS_PRUNED)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testMultipleFilters() { Predicate<Integer> isSelectedSplit1 = i -> i==1 || i==2 || i==3 || i==9; Predicate<Integer> isSelectedSplit2 = i -> i==3 || i==5 || i==9; CompositeReaderConfig readerConfig = mock(CompositeReaderConfig.class); List<Pair<SplitAndPartitionInfo, RecordReader>> readers = getMockSplitReaders(10); List<RecordReader> selectedReaders = new ArrayList<>(); final String secondColumnName = "partitionCol2"; for (int i = 0; i < readers.size(); i++) { SplitAndPartitionInfo split = readers.get(i).getLeft(); List<NameValuePair<?>> nvp = new ArrayList<>(); if (isSelectedSplit1.and(isSelectedSplit2).test(i)) { selectedReaders.add(readers.get(i).getRight()); nvp.addAll(getMatchingNameValuePairs()); nvp.addAll(getMatchingNameValuePairs1(secondColumnName)); } else if (isSelectedSplit1.test(i)) { nvp.addAll(getMatchingNameValuePairs()); nvp.addAll(getNonMatchingNameValuePairs1(secondColumnName)); } else if (isSelectedSplit2.test(i)) { nvp.addAll(getNonMatchingNameValuePairs()); nvp.addAll(getMatchingNameValuePairs1(secondColumnName)); } else { nvp.addAll(getNonMatchingNameValuePairs()); nvp.addAll(getNonMatchingNameValuePairs1(secondColumnName)); } when(readerConfig.getPartitionNVPairs(any(BufferAllocator.class), eq(split))) .thenReturn(nvp); } OperatorContext ctx = getCtx(); HiveRecordReaderIterator it = new HiveRecordReaderIterator(ctx, readerConfig, withSupplier(readers)); try (AutoCloseables.RollbackCloseable closer = new AutoCloseables.RollbackCloseable()) { RuntimeFilter filter1 = prepareRuntimeFilter(); closer.add(filter1.getPartitionColumnFilter().getBloomFilter()); it.addRuntimeFilter(filter1); RuntimeFilter filter2 = prepareRuntimeFilter(secondColumnName, 1, 2); closer.add(filter2.getPartitionColumnFilter().getBloomFilter()); it.addRuntimeFilter(filter2); for (int i = 0; i < selectedReaders.size(); i++) { RecordReader recordReader = selectedReaders.get(i); assertTrue(it.hasNext()); assertEquals(recordReader, it.next()); } assertEquals(8L , ctx.getStats().getLongStat(ScanOperator.Metric.NUM_PARTITIONS_PRUNED)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testIteratorEmpty() { CompositeReaderConfig readerConfig = mock(CompositeReaderConfig.class); when(readerConfig.getPartitionNVPairs(any(BufferAllocator.class), any(SplitAndPartitionInfo.class))) .thenReturn(getMatchingNameValuePairs()); List<SplitReaderCreator> creators = Collections.EMPTY_LIST; OperatorContext ctx = getCtx(); PrefetchingIterator<SplitReaderCreator> it = new PrefetchingIterator<>(ctx, readerConfig, creators); try (AutoCloseables.RollbackCloseable closer = new AutoCloseables.RollbackCloseable()) { RuntimeFilter filter = prepareRuntimeFilter(); closer.add(filter.getPartitionColumnFilter().getBloomFilter()); it.addRuntimeFilter(filter); assertFalse(it.hasNext()); assertEquals(0L, ctx.getStats().getLongStat(ScanOperator.Metric.NUM_PARTITIONS_PRUNED)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } private RuntimeFilter prepareRuntimeFilter() throws Exception { return prepareRuntimeFilter("partitionColumn", 1); } private RuntimeFilter prepareRuntimeFilter(String colName, int... value) throws Exception { try (AutoCloseables.RollbackCloseable rollbackCloseable = new AutoCloseables.RollbackCloseable(); ArrowBuf keyBuf = testAllocator.buffer(5)) { BloomFilter bloomFilter = new BloomFilter(testAllocator, TEST_NAME, 512); rollbackCloseable.add(bloomFilter); bloomFilter.setup(); keyBuf.setByte(0, 1); for (int v : value) { keyBuf.setInt(1, v); bloomFilter.put(keyBuf, 5); } rollbackCloseable.commit(); CompositeColumnFilter partitionColumnFilter = new CompositeColumnFilter.Builder() .setColumnsList(Collections.singletonList(colName)) .setBloomFilter(bloomFilter) .setFilterType(CompositeColumnFilter.RuntimeFilterType.BLOOM_FILTER) .build(); return new RuntimeFilter(partitionColumnFilter, null, ""); } } private List<NameValuePair<?>> getMatchingNameValuePairs() { return Collections.singletonList(new ConstantColumnPopulators.IntNameValuePair("partitionColumn", 1)); } private List<NameValuePair<?>> getMatchingNameValuePairs1(String colName) { return Collections.singletonList(new ConstantColumnPopulators.IntNameValuePair(colName, 2)); } private List<NameValuePair<?>> getNonMatchingNameValuePairs() { return Collections.singletonList(new ConstantColumnPopulators.IntNameValuePair("partitionColumn", 100)); } private List<NameValuePair<?>> getNonMatchingNameValuePairs1(String colName) { return Collections.singletonList(new ConstantColumnPopulators.IntNameValuePair(colName, 100)); } private List<Pair<SplitAndPartitionInfo, RecordReader>> getMockSplitReaders(int size) { final List<Pair<SplitAndPartitionInfo, RecordReader>> readerCreators = new ArrayList<>(size); for (int i = 0; i < size; i++) { SplitAndPartitionInfo split = mock(SplitAndPartitionInfo.class); PartitionProtobuf.NormalizedPartitionInfo partitionInfo = PartitionProtobuf .NormalizedPartitionInfo.newBuilder().build(); when(split.getPartitionInfo()).thenReturn(partitionInfo); RecordReader reader = mock(RecordReader.class); readerCreators.add(Pair.of(split, reader)); } return readerCreators; } private OperatorContext getCtx() { OpProfileDef prof = new OpProfileDef(1, 1, 1); final OperatorStats stats = new OperatorStats(prof, testAllocator); OperatorContext ctx = mock(OperatorContext.class); when(ctx.getStats()).thenReturn(stats); when(ctx.getAllocator()).thenReturn(testAllocator); return ctx; } private List<Pair<SplitAndPartitionInfo, Supplier<RecordReader>>> withSupplier(List<Pair<SplitAndPartitionInfo, RecordReader>> readers) { return readers.stream().map(p -> Pair.of(p.getLeft(), (Supplier<RecordReader>)(() -> p.getRight()))).collect(Collectors.toList()); } }
mk-prg-net/PlaygroundJS
HTML5/Scripts/JavaScriptLernen/Newton/Newton.Tests.js
<reponame>mk-prg-net/PlaygroundJS //<unit_header> //---------------------------------------------------------------- // // <NAME>: IT Beratung/Softwareentwicklung // Stuttgart, den 28.6.2015 // // Projekt.......: HTML5 // Name..........: Newtoon.Test.js // Aufgabe/Fkt...: Test der Newton- Bibliothek // // // // // //<unit_environment> //------------------------------------------------------------------ // Zielmaschine..: PC // Betriebssystem: Windows 7 mit .NET 4.5 // Werkzeuge.....: Visual Studio 2013 // Autor.........: <NAME> (mko) // Version 1.0...: // // </unit_environment> // //<unit_history> //------------------------------------------------------------------ // // Version.......: 1.1 // Autor.........: <NAME> (mko) // Datum.........: // Änderungen....: // //</unit_history> //</unit_header> QUnit.test("Newton Lib für Messwerte testen", function (assert) { var Meter5 = mko.newton.Meter(5); assert.equal(Meter5.Value, 5, "Meter5.Value unkorrekt"); assert.equal(Meter5.UnitSymbol, "m", "Meter5.UnitSymbol unkorrekt"); assert.equal(Meter5.GetUnit(), "m", "Meter5.Unit unkorrekt"); assert.equal(Meter5.toString(), "5 [m]", "Meter5.toString() unkorrekt"); var Cm500 = mko.newton.Centimeter(0).From(Meter5); assert.equal(Cm500.Value, 500, "Cm500.Value unkorrekt"); assert.equal(Cm500.UnitSymbol, "m", "Cm500.UnitSymbol unkorrekt"); assert.equal(Cm500.GetUnit(), "cm", "Cm500.Unit unkorrekt"); assert.equal(Cm500.toString(), "500 [cm]", "Cm500.toString() unkorrekt"); var Meter10 = mko.newton.Meter(10); var protoMeter5 = Object.getPrototypeOf(Meter5); var protoMeter10 = Object.getPrototypeOf(Meter10); if (protoMeter5 === protoMeter10) console.log("Prototypen verschiedener Meterobjekte sind gleich"); else console.log("Prototypen verschiedener Meterobjekte sind ungleich"); var protoCm500 = Object.getPrototypeOf(Cm500); if (protoMeter5 === protoCm500) console.log("Prototypen von Centimeter und Meter sind gleich"); else console.log("Prototypen von Centimeter und Meter sind ungleich"); var Len = mko.newton.Length(mko.newton.OrderOfMagnitude.One, 100); var protoLength = Object.getPrototypeOf(Len); if (protoMeter5 === protoLength) console.log("Prototypen von Meter und Length sind gleich"); else console.log("Prototypen von Meter und Length sind ungleich"); });
DimitrisJim/leetcode_solutions
Javascript/Algorithms/976.js
let largestPerimeter = (A) => { const lim = A.length - 2; A.sort((x, y) => y - x); for(let i = 0; i < lim; i++){ let [a, b, c] = [A[i], A[i+1], A[i+2]]; if (a + b > c && b + c > a && c + a > b) { return a + b + c; } } return 0; };
sturmianseq/demisto-sdk
demisto_sdk/commands/common/hook_validations/conf_json.py
import json from demisto_sdk.commands.common.constants import CONF_PATH, FileType from demisto_sdk.commands.common.errors import Errors from demisto_sdk.commands.common.hook_validations.base_validator import \ BaseValidator from demisto_sdk.commands.common.tools import _get_file_id class ConfJsonValidator(BaseValidator): """ConfJsonValidator has been designed to make sure we are following the standards for the conf.json file. Attributes: _is_valid (bool): Whether the conf.json file current state is valid or not. conf_data (dict): The data from the conf.json file in our repo. """ CONF_PATH = "./Tests/conf.json" def __init__(self, ignored_errors=None, print_as_warnings=False, suppress_print=False, json_file_path=None): super().__init__(ignored_errors=ignored_errors, print_as_warnings=print_as_warnings, suppress_print=suppress_print, json_file_path=json_file_path) self._is_valid = True self.conf_data = self.load_conf_file() def load_conf_file(self): with open(self.CONF_PATH) as data_file: return json.load(data_file) def is_valid_conf_json(self): """Validate the fields skipped_tests, skipped_integrations and unmockable_integrations in conf.json file.""" print('\nValidating conf.json') skipped_tests_conf = self.conf_data['skipped_tests'] skipped_integrations_conf = self.conf_data['skipped_integrations'] unmockable_integrations_conf = self.conf_data['unmockable_integrations'] self.is_valid_description_in_conf_dict(skipped_tests_conf) self.is_valid_description_in_conf_dict(skipped_integrations_conf) self.is_valid_description_in_conf_dict(unmockable_integrations_conf) return self._is_valid def is_valid_description_in_conf_dict(self, checked_dict): """Validate that the checked_dict has description for all it's fields. Args: checked_dict (dict): Dictionary from conf.json file. """ problematic_instances = [] for instance, description in checked_dict.items(): if description == "": problematic_instances.append(instance) if problematic_instances: error_message, error_code = Errors.description_missing_from_conf_json(problematic_instances) if self.handle_error(error_message, error_code, file_path=CONF_PATH): self._is_valid = False return self._is_valid def is_test_in_conf_json(self, file_id): """Check if the file_id(We get this ID only if it is a test) is located in the tests section in conf.json file. Args: file_id (string): the ID of the test we are looking for in the conf.json file. Returns: bool. Whether the test as been located in the conf.json file or not. """ conf_tests = self.conf_data['tests'] for test in conf_tests: playbook_id = test['playbookID'] if file_id == playbook_id: return True error_message, error_code = Errors.test_not_in_conf_json(file_id) if self.handle_error(error_message, error_code, file_path=CONF_PATH): return False return True def is_valid_file_in_conf_json(self, current_file, file_type, file_path): """Check if the file is valid in the conf.json""" entity_id = _get_file_id(file_type.value, current_file) if file_type in {FileType.INTEGRATION, FileType.BETA_INTEGRATION}: return self.integration_has_unskipped_test_playbook(current_file, entity_id, file_path) if file_type == FileType.SCRIPT: return self.has_unskipped_test_playbook(current_file=current_file, entity_id=entity_id, file_path=file_path) return True def has_unskipped_test_playbook(self, current_file, entity_id, file_path, test_playbook_ids: list = []): """Check if the content entity has at least one unskipped test playbook. Collect test playbook ids from the `tests` field in the file, merge them with provided test_playbook_ids and validate at least one is unskipped. Args: current_file: The file to check. entity_id: The id of the entity to check. file_path: The file path of the entity to check. test_playbook_ids: test_playbook_ids unrelated to `tests` field in the file. Retrun: True if the content entity has at least one unskipped test playbook. """ test_playbooks_unskip_status = {} all_test_playbook_ids = test_playbook_ids.copy() skipped_tests = self.conf_data.get('skipped_tests', {}) if isinstance(current_file.get('tests'), list): all_test_playbook_ids.extend(current_file.get('tests', [])) for test_playbook_id in set(all_test_playbook_ids): if skipped_tests and test_playbook_id in skipped_tests: test_playbooks_unskip_status[test_playbook_id] = False else: test_playbooks_unskip_status[test_playbook_id] = True if not any(test_playbooks_unskip_status.values()): error_message, error_code = Errors.all_entity_test_playbooks_are_skipped(entity_id) if self.handle_error(error_message, error_code, file_path=file_path): self._is_valid = False return self._is_valid def integration_has_unskipped_test_playbook(self, integration_data, integration_id, file_path): """Validate there is at least one unskipped test playbook.""" test_playbook_ids = [] conf_tests = self.conf_data.get('tests', []) for test in conf_tests: if 'integrations' in test: if (isinstance(test['integrations'], str) and integration_id == test['integrations']) or \ integration_id in list(test['integrations']): test_playbook_ids.append(test['playbookID']) return self.has_unskipped_test_playbook(integration_data, integration_id, file_path, test_playbook_ids)
ihmcrobotics/ihmc-open-robotics-software
ihmc-quadruped/src/footstep-planning-test/java/us/ihmc/quadrupedFootstepPlanning/pawPlanning/graphSearch/pawSnapping/PawNodeSnapperTest.java
package us.ihmc.quadrupedFootstepPlanning.pawPlanning.graphSearch.pawSnapping; import gnu.trove.map.hash.TIntObjectHashMap; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import us.ihmc.euclid.tools.EuclidCoreRandomTools; import us.ihmc.euclid.transform.RigidBodyTransform; import us.ihmc.euclid.tuple2D.interfaces.Point2DReadOnly; import us.ihmc.quadrupedFootstepPlanning.pawPlanning.graphSearch.graph.PawNode; import us.ihmc.robotics.geometry.PlanarRegion; import us.ihmc.robotics.geometry.PlanarRegionsList; import us.ihmc.robotics.robotSide.RobotQuadrant; import java.util.Random; import static us.ihmc.robotics.Assert.*; public class PawNodeSnapperTest { private final Random random = new Random(320L); private final double epsilon = 1e-8; private int[] frontLeftXIndices = new int[] {-30, 0, 23, 87, -100, 42}; private int[] frontRightXIndices = new int[] {-30, 0, 23, 87, -100, 42}; private int[] hindLeftXIndices = new int[] {-30, 0, 23, 87, -100, 42}; private int[] hindRightXIndices = new int[] {-30, 0, 23, 87, -100, 42}; private int[] frontLeftYIndices = new int[] {-35, 0, -777, 87, -50, 28}; private int[] frontRightYIndices = new int[] {-35, 0, -777, 87, -50, 28}; private int[] hindLeftYIndices = new int[] {-35, 0, -777, 87, -50, 28}; private int[] hindRightYIndices = new int[] {-35, 0, -777, 87, -50, 28}; @Disabled @Test public void testFootstepCacheing() { TestSnapper testSnapper = new TestSnapper(); PlanarRegionsList planarRegionsList = new PlanarRegionsList(new PlanarRegion()); testSnapper.setPlanarRegions(planarRegionsList); for (int i = 0; i < frontLeftXIndices.length; i++) { for (int j = 0; j < frontLeftYIndices.length; j++) { for (int k = 0; k < frontRightXIndices.length; k++) { for (int l = 0; l < frontRightYIndices.length; l++) { for (int m = 0; m < hindLeftXIndices.length; m++) { for (int n = 0; n < hindLeftYIndices.length; n++) { for (int o = 0; o < hindRightXIndices.length; o++) { for (int p = 0; p < hindRightYIndices.length; p++) { RobotQuadrant robotQuadrant = RobotQuadrant.generateRandomRobotQuadrant(random); double frontLeftX = PawNode.gridSizeXY * frontLeftXIndices[i]; double frontLeftY = PawNode.gridSizeXY * frontLeftYIndices[j]; double frontRightX = PawNode.gridSizeXY * frontRightXIndices[k]; double frontRightY = PawNode.gridSizeXY * frontRightYIndices[l]; double hindLeftX = PawNode.gridSizeXY * hindLeftXIndices[m]; double hindLeftY = PawNode.gridSizeXY * hindLeftYIndices[n]; double hindRightX = PawNode.gridSizeXY * hindRightXIndices[o]; double hindRightY = PawNode.gridSizeXY * hindRightYIndices[p]; double length = 1.0; double width = 0.5; int xIndex; int yIndex; switch (robotQuadrant) { case FRONT_LEFT: xIndex = PawNode.snapToGrid(frontLeftX); yIndex = PawNode.snapToGrid(frontLeftY); break; case FRONT_RIGHT: xIndex = PawNode.snapToGrid(frontRightX); yIndex = PawNode.snapToGrid(frontRightY); break; case HIND_LEFT: xIndex = PawNode.snapToGrid(hindLeftX); yIndex = PawNode.snapToGrid(hindLeftY); break; default: xIndex = PawNode.snapToGrid(hindRightX); yIndex = PawNode.snapToGrid(hindRightY); break; } testSnapper.dirtyBit = true; String string = "i " + i + " j " + j + " k " + k + " l " + l + " m " + m + " n " + n + " o " + o + " p " + p; testSnapper.snapPawNode(robotQuadrant, xIndex, yIndex, 0.0); assertTrue(string, testSnapper.dirtyBit); testSnapper.dirtyBit = false; testSnapper.snapPawNode(robotQuadrant, xIndex, yIndex, 0.0); assertFalse(string, testSnapper.dirtyBit); } } } } } } } } } @Test public void testWithoutPlanarRegions() { TestSnapper testSnapper = new TestSnapper(); for (int i = 0; i < frontLeftXIndices.length; i++) { for (int j = 0; j < frontLeftYIndices.length; j++) { for (int k = 0; k < frontRightXIndices.length; k++) { for (int l = 0; l < frontRightYIndices.length; l++) { for (int m = 0; m < hindLeftXIndices.length; m++) { for (int n = 0; n < hindLeftYIndices.length; n++) { for (int o = 0; o < hindRightXIndices.length; o++) { for (int p = 0; p < hindRightYIndices.length; p++) { RobotQuadrant newQuadrant = RobotQuadrant.generateRandomRobotQuadrant(random); double frontLeftX = PawNode.gridSizeXY * frontLeftXIndices[i]; double frontLeftY = PawNode.gridSizeXY * frontLeftYIndices[j]; double frontRightX = PawNode.gridSizeXY * frontRightXIndices[k]; double frontRightY = PawNode.gridSizeXY * frontRightYIndices[l]; double hindLeftX = PawNode.gridSizeXY * hindLeftXIndices[m]; double hindLeftY = PawNode.gridSizeXY * hindLeftYIndices[n]; double hindRightX = PawNode.gridSizeXY * hindRightXIndices[o]; double hindRightY = PawNode.gridSizeXY * hindRightYIndices[p]; double length = 1.0; double width = 0.5; int xIndex; int yIndex; switch (newQuadrant) { case FRONT_LEFT: xIndex = PawNode.snapToGrid(frontLeftX); yIndex = PawNode.snapToGrid(frontLeftY); break; case FRONT_RIGHT: xIndex = PawNode.snapToGrid(frontRightX); yIndex = PawNode.snapToGrid(frontRightY); break; case HIND_LEFT: xIndex = PawNode.snapToGrid(hindLeftX); yIndex = PawNode.snapToGrid(hindLeftY); break; default: xIndex = PawNode.snapToGrid(hindRightX); yIndex = PawNode.snapToGrid(hindRightY); break; } PawNodeSnapData snapData = testSnapper.snapPawNode(newQuadrant, xIndex, yIndex, 0.0); assertTrue(!testSnapper.dirtyBit); assertTrue(snapData.getSnapTransform().epsilonEquals(new RigidBodyTransform(), epsilon)); } } } } } } } } } @Test public void testHashMapStorage() { Random random = new Random(3823L); int numTrials = 100; PawNode nodeA, nodeB; for (int i = 0; i < numTrials; i++) { // test for exact same transform RobotQuadrant robotQuadrant = RobotQuadrant.FRONT_LEFT; Point2DReadOnly frontLeft = EuclidCoreRandomTools.nextPoint2D(random, 1.0); Point2DReadOnly frontRight = EuclidCoreRandomTools.nextPoint2D(random, 1.0); Point2DReadOnly otherFrontRight = EuclidCoreRandomTools.nextPoint2D(random, 1.0); Point2DReadOnly hindLeft = EuclidCoreRandomTools.nextPoint2D(random, 1.0); Point2DReadOnly otherHindLeft = EuclidCoreRandomTools.nextPoint2D(random, 1.0); Point2DReadOnly hindRight = EuclidCoreRandomTools.nextPoint2D(random, 1.0); Point2DReadOnly otherHindRight = EuclidCoreRandomTools.nextPoint2D(random, 1.0); double yaw = PawNode.computeNominalYaw(frontLeft.getX(), frontLeft.getY(), frontRight.getX(), frontRight.getY(), hindLeft.getX(), hindLeft.getY(), hindRight.getX(), hindRight.getY()); nodeA = new PawNode(robotQuadrant, frontLeft, frontRight, hindLeft, hindRight, yaw, 1.5, 0.5); nodeB = new PawNode(robotQuadrant, frontLeft, otherFrontRight, otherHindLeft, otherHindRight, yaw, 1.5, 0.5); TIntObjectHashMap<PawNodeSnapData> snapDataHolder = new TIntObjectHashMap<>(); assertFalse("number : " + i, snapDataHolder.containsKey(nodeB.hashCode())); snapDataHolder.put(nodeA.hashCode(), PawNodeSnapData.emptyData()); assertTrue("number : " + i, snapDataHolder.containsKey(nodeA.hashCode())); if (nodeA.getYawIndex() == nodeB.getYawIndex()) { assertEquals("number : " + i, nodeA.hashCode(), nodeB.hashCode()); assertTrue("number : " + i, snapDataHolder.containsKey(nodeB.hashCode())); } } } private class TestSnapper extends PawNodeSnapper { boolean dirtyBit = false; @Override protected PawNodeSnapData snapInternal(RobotQuadrant robotQuadrant, int xIndex, int yIndex, double yaw) { dirtyBit = true; return PawNodeSnapData.emptyData(); } } }
lintonv/aws-sdk-cpp
aws-cpp-sdk-connect/source/model/UpdateUserSecurityProfilesRequest.cpp
<filename>aws-cpp-sdk-connect/source/model/UpdateUserSecurityProfilesRequest.cpp<gh_stars>1-10 /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/connect/model/UpdateUserSecurityProfilesRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Connect::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateUserSecurityProfilesRequest::UpdateUserSecurityProfilesRequest() : m_securityProfileIdsHasBeenSet(false), m_userIdHasBeenSet(false), m_instanceIdHasBeenSet(false) { } Aws::String UpdateUserSecurityProfilesRequest::SerializePayload() const { JsonValue payload; if(m_securityProfileIdsHasBeenSet) { Array<JsonValue> securityProfileIdsJsonList(m_securityProfileIds.size()); for(unsigned securityProfileIdsIndex = 0; securityProfileIdsIndex < securityProfileIdsJsonList.GetLength(); ++securityProfileIdsIndex) { securityProfileIdsJsonList[securityProfileIdsIndex].AsString(m_securityProfileIds[securityProfileIdsIndex]); } payload.WithArray("SecurityProfileIds", std::move(securityProfileIdsJsonList)); } return payload.View().WriteReadable(); }
eagleeye1105/VForce
src/vision/matcher/Matcher.cpp
<filename>src/vision/matcher/Matcher.cpp // // Created by yongqi on 17-12-11. // #include "Matcher.hpp" #include <pcl/search/impl/kdtree.hpp> #include <pcl/io/pcd_io.h> #include <glog/logging.h> using namespace std; namespace VForce { double Matcher::CalculateMatchError(const PointTCloudPtr &model, const PointTCloudPtr &target, double max_dist) { if (model->size() == 0 || target->size() == 0) return 1; // initialize a Kd tree for searching pcl::search::KdTree<PointT> search; search.setInputCloud(target); vector<int> nn_indices; vector<float> nn_dists; set<int> indices; double fitness_score = 0; int nr = 0; // for each point, find the closest point in the other pointcloud for (PointT p: model->points) { search.nearestKSearch(p, 1, nn_indices, nn_dists); if (nn_dists[0] <= max_dist) { fitness_score += nn_dists[0]; nr++; } } if (nr > 0) return (fitness_score / (double) nr); else return (std::numeric_limits<double>::max()); } }
mtneug/mp4ff
hevc/hevc_test.go
<gh_stars>1-10 package hevc import ( "testing" "github.com/go-test/deep" ) func TestGetNaluTypes(t *testing.T) { testCases := []struct { name string input []byte wanted []NaluType }{ { "AUD", []byte{0, 0, 0, 2, 70, 0}, []NaluType{NALU_AUD}, }, { "AUD, VPS, SPS, PPS, and IDR ", []byte{ 0, 0, 0, 2, 70, 2, 0, 0, 0, 3, 64, 1, 1, 0, 0, 0, 3, 66, 2, 2, 0, 0, 0, 3, 68, 3, 3, 0, 0, 0, 3, 40, 4, 4}, []NaluType{NALU_AUD, NALU_VPS, NALU_SPS, NALU_PPS, NALU_IDR_N_LP}, }, } for _, tc := range testCases { got := FindNaluTypes(tc.input) if diff := deep.Equal(got, tc.wanted); diff != nil { t.Errorf("%s: %v", tc.name, diff) } } } func TestHasParameterSets(t *testing.T) { testCases := []struct { name string input []byte wanted bool }{ { "AUD", []byte{0, 0, 0, 2, 70, 0}, false, }, { "AUD, VPS, SPS, PPS, and IDR ", []byte{ 0, 0, 0, 2, 70, 2, 0, 0, 0, 3, 64, 1, 1, 0, 0, 0, 3, 66, 2, 2, 0, 0, 0, 3, 68, 3, 3, 0, 0, 0, 3, 40, 4, 4}, true, }, } for _, tc := range testCases { got := HasParameterSets(tc.input) if got != tc.wanted { t.Errorf("%s: got %t instead of %t", tc.name, got, tc.wanted) } } } func TestGetParameterSets(t *testing.T) { testCases := []struct { name string input []byte wantedVPS [][]byte wantedSPS [][]byte wantedPPS [][]byte }{ { "AUD", []byte{0, 0, 0, 2, 70, 0}, nil, nil, nil, }, { "AUD, VPS, SPS, PPS, and IDR ", []byte{ 0, 0, 0, 2, 70, 2, 0, 0, 0, 3, 64, 1, 1, 0, 0, 0, 3, 66, 2, 2, 0, 0, 0, 3, 68, 3, 3, 0, 0, 0, 3, 40, 4, 4}, [][]byte{{64, 1, 1}}, [][]byte{{66, 2, 2}}, [][]byte{{68, 3, 3}}, }, } for _, tc := range testCases { gotVPS, gotSPS, gotPPS := GetParameterSets(tc.input) if diff := deep.Equal(gotVPS, tc.wantedVPS); diff != nil { t.Errorf("%s VPS: %v", tc.name, diff) } if diff := deep.Equal(gotSPS, tc.wantedSPS); diff != nil { t.Errorf("%s SPS: %v", tc.name, diff) } if diff := deep.Equal(gotPPS, tc.wantedPPS); diff != nil { t.Errorf("%s PPS: %v", tc.name, diff) } } }
rfizzle/chef-center
api/app/contracts/empty_contract.rb
<filename>api/app/contracts/empty_contract.rb<gh_stars>0 # frozen_string_literal: true # Empty contract class EmptyContract < Dry::Validation::Contract params do end end
smiile8888/tabli
archive/src/js/components/MessageCard.js
import * as React from 'react' import * as styles from './cssStyles' import { cx, css } from 'emotion' import FlatButton from './FlatButton' const messageCardBaseStyle = css({ padding: 0 }) const messageCardStyle = cx(styles.tabWindow, styles.tabWindowFocused, messageCardBaseStyle) const cardActionsStyle = css({ display: 'inline-flex', flexDirection: 'row-reverse', paddingRight: 16, paddingBottom: 16, position: 'relative' }) /* * Layout / design based on Card from Material UI: * * http://www.material-ui.com/#/components/card */ class MessageCard extends React.Component { render () { const rawMarkup = { __html: this.props.content } return ( <div className={messageCardStyle}> <div className='cardContent' dangerouslySetInnerHTML={rawMarkup} /> <div className={cardActionsStyle}> <FlatButton label='GOT IT' onClick={this.props.onClick} /> </div> </div> ) } } export default MessageCard
densogiaichned/serenity
Kernel/Storage/NVMe/NVMeDefinitions.h
<filename>Kernel/Storage/NVMe/NVMeDefinitions.h<gh_stars>1-10 /* * Copyright (c) 2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/Endian.h> #include <AK/Types.h> struct ControllerRegister { u64 cap; u32 vs; u32 intms; u32 intmc; u32 cc; u32 rsvd1; u32 csts; u32 nssr; u32 aqa; u64 asq; u64 acq; u64 rsvd2[505]; }; struct IdentifyNamespace { u64 nsze; u64 ncap; u8 rsdv1[10]; u8 flbas; u8 rsvd2[100]; u32 lbaf[16]; u64 rsvd3[488]; }; // BAR static constexpr u32 BAR_ADDR_MASK = 0xFFFFFFF0; // DOORBELL static constexpr u32 REG_SQ0TDBL_START = 0x1000; static constexpr u32 REG_SQ0TDBL_END = 0x1003; static constexpr u8 DBL_REG_SIZE = 8; // CAP static constexpr u8 CAP_DBL_SHIFT = 32; static constexpr u8 CAP_DBL_MASK = 0xf; static constexpr u8 CAP_TO_SHIFT = 24; static constexpr u64 CAP_TO_MASK = 0xff << CAP_TO_SHIFT; static constexpr u16 MQES(u64 cap) { return (cap & 0xffff) + 1; } static constexpr u32 CAP_TO(u64 cap) { return (cap & CAP_TO_MASK) >> CAP_TO_SHIFT; } // CC – Controller Configuration static constexpr u8 CC_EN_BIT = 0x0; static constexpr u8 CSTS_RDY_BIT = 0x0; static constexpr u8 CSTS_SHST_SHIFT = 2; static constexpr u32 CSTS_SHST_MASK = 0x3 << CSTS_SHST_SHIFT; static constexpr u8 CC_IOSQES_BIT = 16; static constexpr u8 CC_IOCQES_BIT = 20; static constexpr u32 CSTS_SHST(u32 x) { return (x & CSTS_SHST_MASK) >> CSTS_SHST_SHIFT; } static constexpr u16 CC_AQA_MASK = (0xfff); static constexpr u16 ACQ_SIZE(u32 x) { return (x >> 16) & CC_AQA_MASK; } static constexpr u16 ASQ_SIZE(u32 x) { return x & CC_AQA_MASK; } static constexpr u8 CQ_WIDTH = 4; // CQ is 16 bytes(2^4) in size. static constexpr u8 SQ_WIDTH = 6; // SQ size is 64 bytes(2^6) in size. static constexpr u16 CQ_SIZE(u16 q_depth) { return q_depth << CQ_WIDTH; } static constexpr u16 SQ_SIZE(u16 q_depth) { return q_depth << SQ_WIDTH; } static constexpr u8 PHASE_TAG(u16 x) { return x & 0x1; } static constexpr u16 CQ_STATUS_FIELD_MASK = 0xfffe; static constexpr u16 CQ_STATUS_FIELD(u16 x) { return (x & CQ_STATUS_FIELD_MASK) >> 1; } static constexpr u16 IO_QUEUE_SIZE = 64; // TODO:Need to be configurable // IDENTIFY static constexpr u16 NVMe_IDENTIFY_SIZE = 4096; static constexpr u8 NVMe_CNS_ID_ACTIVE_NS = 0x2; static constexpr u8 NVMe_CNS_ID_NS = 0x0; static constexpr u8 FLBA_SIZE_INDEX = 26; static constexpr u8 FLBA_SIZE_MASK = 0xf; static constexpr u8 LBA_FORMAT_SUPPORT_INDEX = 128; static constexpr u32 LBA_SIZE_MASK = 0x00ff0000; // OPCODES // ADMIN COMMAND SET enum AdminCommandOpCode { OP_ADMIN_CREATE_COMPLETION_QUEUE = 0x5, OP_ADMIN_CREATE_SUBMISSION_QUEUE = 0x1, OP_ADMIN_IDENTIFY = 0x6, }; // IO opcodes enum IOCommandOpcode { OP_NVME_WRITE = 0x1, OP_NVME_READ = 0x2 }; // FLAGS static constexpr u8 QUEUE_PHY_CONTIGUOUS = (1 << 0); static constexpr u8 QUEUE_IRQ_ENABLED = (1 << 1); static constexpr u8 QUEUE_IRQ_DISABLED = (0 << 1); struct [[gnu::packed]] NVMeCompletion { LittleEndian<u32> cmd_spec; LittleEndian<u32> res; LittleEndian<u16> sq_head; /* how much of this queue may be reclaimed */ LittleEndian<u16> sq_id; /* submission queue that generated this entry */ u16 command_id; /* of the command which completed */ LittleEndian<u16> status; /* did the command fail, and if so, why? */ }; struct [[gnu::packed]] DataPtr { LittleEndian<u64> prp1; LittleEndian<u64> prp2; }; struct [[gnu::packed]] NVMeGenericCmd { LittleEndian<u32> nsid; LittleEndian<u64> rsvd; LittleEndian<u64> metadata; struct DataPtr data_ptr; LittleEndian<u32> cdw10; LittleEndian<u32> cdw11; LittleEndian<u32> cdw12; LittleEndian<u32> cdw13; LittleEndian<u32> cdw14; LittleEndian<u32> cdw15; }; struct [[gnu::packed]] NVMeRWCmd { LittleEndian<u32> nsid; LittleEndian<u64> rsvd; LittleEndian<u64> metadata; struct DataPtr data_ptr; LittleEndian<u64> slba; LittleEndian<u16> length; LittleEndian<u16> control; LittleEndian<u32> dsmgmt; LittleEndian<u32> reftag; LittleEndian<u16> apptag; LittleEndian<u16> appmask; }; struct [[gnu::packed]] NVMeIdentifyCmd { LittleEndian<u32> nsid; LittleEndian<u64> rsvd1[2]; struct DataPtr data_ptr; u8 cns; u8 rsvd2; LittleEndian<u16> ctrlid; u8 rsvd3[3]; u8 csi; u64 rsvd4[2]; }; struct [[gnu::packed]] NVMeCreateCQCmd { u32 rsvd1[5]; LittleEndian<u64> prp1; u64 rsvd2; LittleEndian<u16> cqid; LittleEndian<u16> qsize; LittleEndian<u16> cq_flags; LittleEndian<u16> irq_vector; u64 rsvd12[2]; }; struct [[gnu::packed]] NVMeCreateSQCmd { u32 rsvd1[5]; LittleEndian<u64> prp1; u64 rsvd2; LittleEndian<u16> sqid; LittleEndian<u16> qsize; LittleEndian<u16> sq_flags; LittleEndian<u16> cqid; u64 rsvd12[2]; }; struct [[gnu::packed]] NVMeSubmission { u8 op; u8 flags; LittleEndian<u16> cmdid; union [[gnu::packed]] { NVMeGenericCmd generic; NVMeIdentifyCmd identify; NVMeRWCmd rw; NVMeCreateCQCmd create_cq; NVMeCreateSQCmd create_sq; }; };
lukas-conka/mobile-app
Resources/iphone/database/ncm.js
function getTableNcm() { return "tb_ncm"; } function dbLoad() { var db = Ti.Database.open(Ti.App.Properties.getString(DATABASE_FILE)); return db; } function createNcm() { db = dbLoad(); db.execute("CREATE TABLE IF NOT EXISTS " + getTableNcm() + "(\n id INTEGER PRIMARY KEY, ncm_id INTEGER, ncm_numero TEXT, tb_numero TEXT, ep_id INTEGER\n );"); db.close(); } function dropNcm() { db = dbLoad(); db.execute("DROP TABLE IF EXISTS " + getTableNcm()); db.close(); } function insertNcm(ncm_id, ncm_numero, tb_numero, ep_id) { db = dbLoad(); db.execute("INSERT INTO " + getTableNcm() + " (\n ncm_id, ncm_numero, tb_numero, ep_id) \n VALUES (?,?,?,?)", ncm_id, ncm_numero, tb_numero, ep_id); db.close(); } function selectallNcm() { db = dbLoad(); var ncm = db.execute("SELECT * FROM" + getTableNcm()); "android" == Ti.Platform.osname && db.close(); return ncm; } function processNcm(jsonTxt) { dropNcm(); createNcm(); var jsonObject = JSON.parse(jsonTxt); for (var j = 0; j < jsonObject.length; j++) { var ncm_id = jsonObject[j].ncm_id; var ncm_numero = jsonObject[j].ncm_numero; var tb_numero = jsonObject[j].tb_numero; var ep_id = jsonObject[j].ep_id; insertNcm(ncm_id, ncm_numero, tb_numero, ep_id); } }
lemenendez/gotuto
github.com/lemenendez/gotuto/tuto/algo-02-maximum-value.go
<reponame>lemenendez/gotuto<filename>github.com/lemenendez/gotuto/tuto/algo-02-maximum-value.go<gh_stars>0 /* From: Graphic Go Algorithms Credits: <NAME> Name: Maximum Value Compare and swap elements in the array until the lastnumber in the array is the maximum */ package main import "fmt" func print(a[] int, count int) { for i:=0; i< count; i++ { if i==count-1 { fmt.Printf("%d\n", a[i]) } else { fmt.Printf("%d, ", a[i]) } } } func max(a []int, length int) int { for i := 0; i < length-1; i++ { if a[i] > a[i+1] { var temp = a[i] a[i] = a[i+1] a[i+1] = temp // print(a, length) } } max:=a[length-1] return max } func main() { var scores = []int{60, 50, 95, 80, 70} var length = len(scores) print(scores, length) var maxVal = max(scores, length) fmt.Printf("Max value = %d\n", maxVal) }
bianapis/sd-prospect-campaign-execution-v2
src/main/java/org/bian/dto/CRProspectCampaignProcedureRetrieveInputModelProspectCampaignProcedureInstanceReportRecord.java
<reponame>bianapis/sd-prospect-campaign-execution-v2<gh_stars>0 package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * CRProspectCampaignProcedureRetrieveInputModelProspectCampaignProcedureInstanceReportRecord */ public class CRProspectCampaignProcedureRetrieveInputModelProspectCampaignProcedureInstanceReportRecord { private String prospectCampaignProcedureInstanceReportReference = null; private String prospectCampaignProcedureInstanceReportType = null; private String prospectCampaignProcedureInstanceReportParameters = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the control record instance report * @return prospectCampaignProcedureInstanceReportReference **/ public String getProspectCampaignProcedureInstanceReportReference() { return prospectCampaignProcedureInstanceReportReference; } public void setProspectCampaignProcedureInstanceReportReference(String prospectCampaignProcedureInstanceReportReference) { this.prospectCampaignProcedureInstanceReportReference = prospectCampaignProcedureInstanceReportReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external report available * @return prospectCampaignProcedureInstanceReportType **/ public String getProspectCampaignProcedureInstanceReportType() { return prospectCampaignProcedureInstanceReportType; } public void setProspectCampaignProcedureInstanceReportType(String prospectCampaignProcedureInstanceReportType) { this.prospectCampaignProcedureInstanceReportType = prospectCampaignProcedureInstanceReportType; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The selection parameters for the report (e.g. period, content type) * @return prospectCampaignProcedureInstanceReportParameters **/ public String getProspectCampaignProcedureInstanceReportParameters() { return prospectCampaignProcedureInstanceReportParameters; } public void setProspectCampaignProcedureInstanceReportParameters(String prospectCampaignProcedureInstanceReportParameters) { this.prospectCampaignProcedureInstanceReportParameters = prospectCampaignProcedureInstanceReportParameters; } }
yahoo/ygloo-ymagine
jni/include/ymagine/ymagine.h
/** * Copyright 2013 Yahoo! Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. See accompanying LICENSE file. */ /** * @file ymagine.h * @addtogroup Ymagine * @brief Ymagine image decoding and processing */ #ifndef _YMAGINE_H #define _YMAGINE_H 1 #ifdef __cplusplus extern "C" { #endif /** * @defgroup Ymagine Ymagine * * This module provides an extended API for decoding, transforming * and processing images. It aims at being a fully portable, self-contained, * efficient native (C/C++) implementation of an alternative to BitmapFactory, * allowing executing faster and in a more memory-efficient way a batch of operation, * thanks to optimized processing pipeline. * * @{ */ #include "yosal/yosal.h" #define YMAGINE_OK ((int) 0) #define YMAGINE_ERROR ((int) -1) /** * scale and leave a letterbox (black bars) around the image */ #define YMAGINE_SCALE_LETTERBOX 0 /** * scale and crop parts of the image so that the image fills the * entire new size */ #define YMAGINE_SCALE_CROP 1 /** * scale and resize the image, modifying its aspect ratio if necessary */ #define YMAGINE_SCALE_FIT 2 /** * do not scale or resize */ #define YMAGINE_SCALE_NONE 10 /** * scale the image to half its width or height, ignoring 3 out of 4 pixels */ #define YMAGINE_SCALE_HALF_QUICK 11 /** * scale the image to half its width or height, averaging 4 pixels into 1 pixel */ #define YMAGINE_SCALE_HALF_AVERAGE 12 #include "ymagine/vbitmap.h" #include "ymagine/iosapi.h" #include "ymagine/filter.h" #include "ymagine/colorize.h" #include "ymagine/compose.h" #include "ymagine/color.h" #include "ymagine/pixelshader.h" #include "ymagine/transformer.h" #include "ymagine/draw.h" #include "ymagine/format.h" #include "ymagine/vformat.h" #include "ymagine/seam.h" #include "ymagine/design.h" #include "ymagine/simple.h" /** * @} */ #ifdef __cplusplus }; #endif #endif /* _YMAGINE_H */
NNSISA/BackIsa
src/main/java/com/contoller/DoctorController.java
<gh_stars>0 package com.contoller; import com.dto.PatientRatedClinicDTO; import com.dto.PatientRatedDoctorDTO; import com.model.*; import com.service.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @CrossOrigin(origins = "http://localhost:4200") @RestController public class DoctorController { @Autowired private AppointmentService as; @Autowired private PatientService ps; @Autowired private PatientRatedDoctorService prds; @Autowired private MedicalStaffService mss; @Autowired private PatientRatedClinicService prcs; @Autowired private ClinicService cs; //Dobavljanje doktora koji se mogu ocenjivati //Pregledi moraju biti zavrseni @CrossOrigin(origins = "http://localhost:4200") @RequestMapping(value = "/getDoctorsForRate/{username}", method = RequestMethod.GET) public List<Doctor> getDoctorsForRate(@PathVariable String username) { List<Appointment> pregledi = as.findAll(); List<Doctor> doctors = new ArrayList<>(); for (Appointment app : pregledi) { if (app.getPatient() != null) { if (app.getPatient().equals(username) && app.isFinished()) { doctors.add(app.getDoctor()); } } } return doctors; } //Ocenjivanje @CrossOrigin(origins = "http://localhost:4200") @RequestMapping(value = "/getRate/{username}", method = RequestMethod.GET) public List<PatientRatedDoctor> getRate(@PathVariable("username") String username) { List<Appointment> pregledi = as.findAll(); List<Doctor> doctors = new ArrayList<>(); List<Doctor> doctorsFromPrd = new ArrayList<>(); List<PatientRatedDoctor> ret = new ArrayList<>(); for (Appointment app : pregledi) { if (app.getPatient() != null) { if (app.getPatient().equals(username) && app.isFinished()) { doctors.add(app.getDoctor()); } } } Patient patient = ps.findByUsername(username); List<PatientRatedDoctor> prd = prds.findAll(); for (PatientRatedDoctor p1 : prd) { if (p1.getPatient() != null) { if (p1.getPatient().getUsername().equals(username)) { doctorsFromPrd.add(p1.getDoctor()); } } } for (Doctor doc : doctors) { if (!doctorsFromPrd.contains(doc)) { PatientRatedDoctor noviPrd = new PatientRatedDoctor(); noviPrd.setOcena(0); noviPrd.setPatient(patient); noviPrd.setDoctor(doc); prds.save(noviPrd); } } List<PatientRatedDoctor> prd1 = prds.findAll(); for (PatientRatedDoctor p : prd1) { if (p.getPatient().getUsername().equals(username)) { ret.add(p); } } return ret; } //Dobavljanje klinika koje se mogu ocenjivati //Pregledi moraju biti gotovi @CrossOrigin(origins = "http://localhost:4200") @RequestMapping(value = "/getClinicsForRate/{username}", method = RequestMethod.GET) public List<PatientRatedClinic> getClinicsForRate(@PathVariable("username") String username) { List<Appointment> pregledi = as.findAll(); List<Clinic> clinics = new ArrayList<>(); List<Clinic> clinicsFromPrclinic = new ArrayList<>(); List<PatientRatedClinic> ret = new ArrayList<>(); Patient patient = ps.findByUsername(username); for (Appointment app : pregledi) { if (app.getPatient() != null) { if (app.getPatient().equals(username) && app.isFinished()) { clinics.add(app.getDoctor().getClinic()); } } } List<PatientRatedClinic> prclinic = prcs.findAll(); for (PatientRatedClinic prclin : prclinic) { if (prclin.getPatient() != null) { if (prclin.getPatient().getUsername().equals(username)) { clinicsFromPrclinic.add(prclin.getClinic()); } } } for (Clinic c : clinics) { if (!clinicsFromPrclinic.contains(c)) { PatientRatedClinic noviPrclinic = new PatientRatedClinic(); noviPrclinic.setOcena(0); noviPrclinic.setPatient(patient); noviPrclinic.setClinic(c); prcs.save(noviPrclinic); } } List<PatientRatedClinic> prclinic1 = prcs.findAll(); for (PatientRatedClinic p : prclinic1) { if (p.getPatient().getUsername().equals(username)) { ret.add(p); } } return ret; } //Promena ocena doktora @CrossOrigin(origins = "http://localhost:4200") @RequestMapping(value = "/rateChange", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<PatientRatedDoctorDTO> rateChange( @RequestBody PatientRatedDoctorDTO patientRatedDoctorDTO) { List<PatientRatedDoctor> prd = prds.findAll(); Doctor doctor = (Doctor) mss.findByUsername(patientRatedDoctorDTO.getDoctorUsername()); int suma = 0; int kolikoIhIma = 0; for (PatientRatedDoctor p : prd) { if (p.getPatient().getUsername().equals(patientRatedDoctorDTO.getPatientUsername())) { if (p.getDoctor().getUsername().equals(patientRatedDoctorDTO.getDoctorUsername())) { p.setOcena(patientRatedDoctorDTO.getOcena()); prds.save(p); } } } for (PatientRatedDoctor p : prd) { if (p.getDoctor().getUsername().equals(patientRatedDoctorDTO.getDoctorUsername())) { suma += p.getOcena(); kolikoIhIma++; } } doctor.setReview(suma / kolikoIhIma); mss.save(doctor); return new ResponseEntity<>(patientRatedDoctorDTO, HttpStatus.OK); } //Promena ocena klinike @CrossOrigin(origins = "http://localhost:4200") @RequestMapping(value = "/rateChangeClinic", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity<PatientRatedClinicDTO> rateChangeClinic( @RequestBody PatientRatedClinicDTO patientRatedClinicDTO) { List<PatientRatedClinic> prclinic = prcs.findAll(); Clinic clinic = cs.findByName(patientRatedClinicDTO.getClinicName()); int suma = 0; int kolikoIhIma = 0; for (PatientRatedClinic p : prclinic) { if (p.getPatient().getUsername().equals(patientRatedClinicDTO.getPatientUsername())) { if (p.getClinic().getName().equals(patientRatedClinicDTO.getClinicName())) { p.setOcena(patientRatedClinicDTO.getOcena()); prcs.save(p); } } } for (PatientRatedClinic p : prclinic) { if (p.getClinic().getName().equals(patientRatedClinicDTO.getClinicName())) { suma += p.getOcena(); kolikoIhIma++; } } clinic.setRating(suma / kolikoIhIma); cs.save(clinic); return new ResponseEntity<>(patientRatedClinicDTO, HttpStatus.OK); } }
liuyangspace/java-test
src/javase/extension/system/process/inside/ProcessImpl.java
<gh_stars>0 package javase.extension.system.process.inside; /** * @see java.lang.ProcessImpl */ final class ProcessImpl { }
LeoRya/py-orbit
src/utils/integration/GaussLegendreIntegrator.cc
<filename>src/utils/integration/GaussLegendreIntegrator.cc //////////////////////////////// -*- C++ -*- ////////////////////////////// // // FILE NAME // GaussLegendreIntegrator.cc // // AUTHOR // <NAME> // // CREATED // 01/23/2013 // // DESCRIPTION // The integrator for the Gauss-Legendre schema. // /////////////////////////////////////////////////////////////////////////// #include "orbit_mpi.hh" #include "orbit_mpi.hh" #include "GaussLegendreIntegrator.hh" #include "gauss_legendre_points.hh" #include "OU_Function.hh" #include "OU_SplineCH.hh" #include <iomanip> using namespace OrbitUtils; GaussLegendreIntegrator::GaussLegendreIntegrator(): CppPyWrapper(NULL) { n_int_points = 1024; x0 = 0.; x1 = 1.; pw_finc = new Function(); gauss_legendre_generator(n_int_points,x0,x1,pw_finc); n_int_points = pw_finc->getSize(); } GaussLegendreIntegrator::GaussLegendreIntegrator(int nPoints): CppPyWrapper(NULL) { n_int_points = nPoints; x0 = 0.; x1 = 1.; pw_finc = new Function(); gauss_legendre_generator(n_int_points,x0,x1,pw_finc); n_int_points = pw_finc->getSize(); } GaussLegendreIntegrator::GaussLegendreIntegrator(int nPoints, double x_from, double x_to): CppPyWrapper(NULL) { n_int_points = nPoints; x0 = x_from; x1 = x_to; pw_finc = new Function(); gauss_legendre_generator(n_int_points,x0,x1,pw_finc); n_int_points = pw_finc->getSize(); } GaussLegendreIntegrator::~GaussLegendreIntegrator() { delete pw_finc; } void GaussLegendreIntegrator::setnPoints(int nPoints) { n_int_points = nPoints; gauss_legendre_generator(n_int_points,x0,x1,pw_finc); n_int_points = pw_finc->getSize(); } int GaussLegendreIntegrator::getnPoints() { return n_int_points; } void GaussLegendreIntegrator::setLimits(double x_from, double x_to) { x0 = x_from; x1 = x_to; gauss_legendre_generator(n_int_points,x0,x1,pw_finc); n_int_points = pw_finc->getSize(); } Function* GaussLegendreIntegrator::getPointsAndWeightFunc() { return pw_finc; } double GaussLegendreIntegrator::integral(Function* func) { double sum = 0.; for(int i = 0; i < n_int_points; i++){ sum += func->getY(pw_finc->x(i))*pw_finc->y(i); } return sum; } double GaussLegendreIntegrator::integral(SplineCH* spline) { double sum = 0.; for(int i = 0; i < n_int_points; i++){ sum += spline->getY(pw_finc->x(i))*pw_finc->y(i); } return sum; }
alejandroballestae/gmedchain-frontend
app/components/ProgressBar/index.js
import React, { Component, Fragment } from 'react'; import "./style.scss" class ProgressBar extends Component { constructor(props) { super(props); } render() { const parent = this.props; let values = parent.readings && parent.readings.length && parent.readings.map(function(item, i) { if(item.value > 0) { return ( <div className="value" style={{'color': item.color, 'width': item.value + '%'}} key={i}> <span>{item.value}%</span> </div> ) } }, this); let calibrations = parent.readings && parent.readings.length && parent.readings.map(function(item, i) { if(item.value > 0) { return ( <div className="graduation" style={{'color': item.color, 'width': item.value + '%'}} key={i}> <span>|</span> </div> ) } }, this); let bars = parent.readings && parent.readings.length && parent.readings.map(function(item, i) { if(item.value > 0) { return ( <div className="bar" style={{'backgroundColor': item.color, 'width': item.value + '%'}} key={i}> </div> ) } }, this); let legends = parent.readings && parent.readings.length && parent.readings.map(function(item, i) { if(item.value > 0) { return ( <div className="legend" key={i}> </div> ) } }, this); return ( <div className="multicolor-bar"> <div className="values"> {values == ''?'':values} </div> <div className="scale"> {calibrations == ''?'':calibrations} </div> <div className="bars"> {bars == ''?'':bars} </div> <div className="legends"> {legends == ''?'':legends} </div> </div> ); } } export default ProgressBar;
MuhammadAdeelUsman/kafka-connect
graphql/ws-client/src/main/java/io/debezium/examples/graphql/wsclient/GraphQLResponseReceiver.java
/* * Copyright Debezium Authors. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.debezium.examples.graphql.wsclient; @FunctionalInterface public interface GraphQLResponseReceiver { void messageReceived(GraphQLQueryResponse s); }
sevki/bazel
src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java
<filename>src/test/java/com/google/devtools/build/lib/bazel/repository/StripPrefixedPathTest.java<gh_stars>10-100 // Copyright 2014 The Bazel 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. package com.google.devtools.build.lib.bazel.repository; import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Optional; import com.google.devtools.build.lib.util.OS; import com.google.devtools.build.lib.vfs.PathFragment; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests {@link StripPrefixedPath}. */ @RunWith(JUnit4.class) public class StripPrefixedPathTest { @Test public void testStrip() { StripPrefixedPath result = StripPrefixedPath.maybeDeprefix("foo/bar", Optional.of("foo")); assertThat(PathFragment.create("bar")).isEqualTo(result.getPathFragment()); assertThat(result.foundPrefix()).isTrue(); assertThat(result.skip()).isFalse(); result = StripPrefixedPath.maybeDeprefix("foo", Optional.of("foo")); assertThat(result.skip()).isTrue(); result = StripPrefixedPath.maybeDeprefix("bar/baz", Optional.of("foo")); assertThat(result.foundPrefix()).isFalse(); result = StripPrefixedPath.maybeDeprefix("foof/bar", Optional.of("foo")); assertThat(result.foundPrefix()).isFalse(); } @Test public void testAbsolute() { StripPrefixedPath result = StripPrefixedPath.maybeDeprefix( "/foo/bar", Optional.<String>absent()); assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("foo/bar")); result = StripPrefixedPath.maybeDeprefix("///foo/bar/baz", Optional.<String>absent()); assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("foo/bar/baz")); result = StripPrefixedPath.maybeDeprefix("/foo/bar/baz", Optional.of("/foo")); assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("bar/baz")); } @Test public void testWindowsAbsolute() { if (OS.getCurrent() != OS.WINDOWS) { return; } StripPrefixedPath result = StripPrefixedPath.maybeDeprefix( "c:/foo/bar", Optional.<String>absent()); assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("foo/bar")); } @Test public void testNormalize() { StripPrefixedPath result = StripPrefixedPath.maybeDeprefix( "../bar", Optional.<String>absent()); assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("../bar")); result = StripPrefixedPath.maybeDeprefix("foo/../baz", Optional.<String>absent()); assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("baz")); result = StripPrefixedPath.maybeDeprefix("foo/../baz", Optional.of("foo")); assertThat(result.getPathFragment()).isEqualTo(PathFragment.create("baz")); } }
bugaoshuni/WeChatSportTweak
WeChatHeads/OfflineGetMsgResponse.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @class NSString; @interface OfflineGetMsgResponse : NSObject { int _pollTime; NSString *_ackKey; NSString *_appMsg; } @property(nonatomic) int pollTime; // @synthesize pollTime=_pollTime; @property(copy, nonatomic) NSString *appMsg; // @synthesize appMsg=_appMsg; @property(copy, nonatomic) NSString *ackKey; // @synthesize ackKey=_ackKey; - (void).cxx_destruct; @end
davidsandilands/control-repo-2
site-modules/enterprise_tasks/tasks/renew.rb
#!/opt/puppetlabs/puppet/bin/ruby # frozen_string_literal: true require_relative '../../ruby_task_helper/files/task_helper.rb' require 'puppet' require 'fileutils' require 'yaml' require 'open3' # Class for regenerating agent certs class Regen # Error class class Error < RuntimeError def initialize(kind, msg, details = nil) @kind = kind @details = details || {} super(msg) end def result { _error: { kind: @kind, msg: message, details: @details, } } end end def initialize(params) @params = JSON.parse(params) end def make_request setup unless @params['fetch_only'] reset_ssl create_attrs end request_certificate end def setup Puppet.initialize_settings Puppet::SSL::Oids.register_puppet_oids Puppet.settings.use(:main, :agent, :ssl) end def reset_ssl @cacert = @params['cacert'] certpath = Puppet[:localcacert] unless @params['trust_ca'] || @cacert # TODO: this should just use a fingerprint if File.readable?(certpath) @cacert = File.open(certpath) { |f| f.read } else raise Regen::Error.new('puppet_cert/missing_ca', "No ca certificate present at #{certpath} or provided in params") end end FileUtils.rm_rf(Puppet[:ssldir]) # Let Puppet recreate directories Puppet.settings.clear Puppet.settings.use(:main, :agent, :ssl) File.open(certpath, 'w') { |f| f.write(@cacert) } if @cacert # TODO: why does this cause a TypeError # Puppet::FileSystem.exclusive_create(certpath, 'w') { |f| f.write(cert) } end def create_attrs if attrs = @params['attrs'] File.open(Puppet[:csr_attributes], 'w') do |f| f.write(YAML.dump(attrs)) end end end def request_certificate(_wait = 0) host = Puppet::SSL::Host.new begin host.certificate rescue Puppet::Error => e raise Error.new('puppet_cert/request-failed', "Certificate request failed: #{e.message}") end # TODO: handle waiting # host.generate host end end class RenewCert < TaskHelper def task(**kwargs) regen = Regen.new(kwargs) host = regen.make_request output, status = Open3.capture2e('puppet ssl submit_request') if host.certificate.nil? raise TaskHelper::Error.new("Failed to generate certificate request on host #{host}", 'puppetlabs.certregen/regen-cert-failed', output) if status && status.exitstatus == 1 result = { signed: !host.certificate.nil? } result.to_json end end if __FILE__ == $PROGRAM_NAME begin CertRegen.run rescue Regen::Error => e puts e.result.to_json exit 1 end end
sskimdev/Jwt-Spring-Security-JPA
src/main/java/com/bithumbhomework/member/config/WebSecurityConfig.java
<reponame>sskimdev/Jwt-Spring-Security-JPA<filename>src/main/java/com/bithumbhomework/member/config/WebSecurityConfig.java package com.bithumbhomework.member.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.bithumbhomework.member.security.JwtAuthenticationEntryPoint; import com.bithumbhomework.member.security.JwtAuthenticationFilter; import com.bithumbhomework.member.service.CustomUserDetailsService; @Profile("!dev") @Configuration @EnableWebSecurity(debug = true) @EnableJpaRepositories(basePackages = "com.bithumbhomework.member.repository") @EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final CustomUserDetailsService userDetailsService; private final JwtAuthenticationEntryPoint jwtEntryPoint; @Autowired public WebSecurityConfig(CustomUserDetailsService userDetailsService, JwtAuthenticationEntryPoint jwtEntryPoint) { this.userDetailsService = userDetailsService; this.jwtEntryPoint = jwtEntryPoint; } @Override @Bean public AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override public void configure(WebSecurity web) { web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**"); } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(jwtEntryPoint).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests() .antMatchers("/", "/favicon.ico", "/**/*.json", "/**/*.xml", "/**/*.properties", "/**/*.woff2", "/**/*.woff", "/**/*.ttf", "/**/*.ttc", "/**/*.ico", "/**/*.bmp", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.jpeg", "/**/*.html", "/**/*.css", "/**/*.js") .permitAll().antMatchers("/**/api/auth/**", "/**/api/v1/auth/**").permitAll() .antMatchers("/v1/member/**", "/**/v1/member/**").permitAll().anyRequest().authenticated(); http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
Happy0/lila
modules/db/src/main/Env.scala
<reponame>Happy0/lila package lila.db import com.typesafe.config.Config import play.modules.reactivemongo.ReactiveMongoPlugin import reactivemongo.api.DB import Types._ final class Env(config: Config) { lazy val db = { import play.api.Play.current ReactiveMongoPlugin.db } def apply(name: String): Coll = db(name) } object Env { lazy val current = "[boot] db" describes new Env( lila.common.PlayApp loadConfig "mongodb") }
ilopezgp/human_impacts
anthro/tessellation.py
<filename>anthro/tessellation.py<gh_stars>1-10 import itertools import numpy from scipy.spatial import ConvexHull from matplotlib.collections import LineCollection from matplotlib import pyplot as plot import shapely.geometry # --- Misc. geometry code ----------------------------------------------------- ''' Pick N points uniformly from the unit disc This sampling algorithm does not use rejection sampling. ''' def disc_uniform_pick(N): angle = (2 * numpy.pi) * numpy.random.random(N) out = numpy.stack([numpy.cos(angle), numpy.sin(angle)], axis = 1) out *= numpy.sqrt(numpy.random.random(N))[:,None] return out def norm2(X): return numpy.sqrt(numpy.sum(X ** 2)) def normalized(X): return X / norm2(X) # --- Delaunay triangulation -------------------------------------------------- def get_triangle_normal(A, B, C): return normalized(numpy.cross(A, B) + numpy.cross(B, C) + numpy.cross(C, A)) def get_power_circumcenter(A, B, C): N = get_triangle_normal(A, B, C) return (-.5 / N[2]) * N[:2] def is_ccw_triangle(A, B, C): M = numpy.concatenate([numpy.stack([A, B, C]), numpy.ones((3, 1))], axis = 1) return numpy.linalg.det(M) > 0 def get_power_triangulation(S, R): # Compute the lifted weighted points S_norm = numpy.sum(S ** 2, axis = 1) - R S_lifted = numpy.concatenate([S, S_norm[:,None]], axis = 1) # Special case for 3 points if S.shape[0] == 3: if is_ccw_triangle(S[0], S[1], S[2]): return [[0, 1, 2]], numpy.array([get_power_circumcenter(*S_lifted)]) else: return [[0, 2, 1]], numpy.array([get_power_circumcenter(*S_lifted)]) # Compute the convex hull of the lifted weighted points hull = ConvexHull(S_lifted) # Extract the Delaunay triangulation from the lower hull tri_list = tuple([a, b, c] if is_ccw_triangle(S[a], S[b], S[c]) else [a, c, b] for (a, b, c), eq in zip(hull.simplices, hull.equations) if eq[2] <= 0) # Compute the Voronoi points V = numpy.array([get_power_circumcenter(*S_lifted[tri]) for tri in tri_list]) # Job done return tri_list, V # --- Compute Voronoi cells --------------------------------------------------- ''' Compute the segments and half-lines that delimits each Voronoi cell * The segments are oriented so that they are in CCW order * Each cell is a list of (i, j), (A, U, tmin, tmax) where * i, j are the indices of two ends of the segment. Segments end points are the circumcenters. If i or j is set to None, then it's an infinite end * A is the origin of the segment * U is the direction of the segment, as a unit vector * tmin is the parameter for the left end of the segment. Can be -1, for minus infinity * tmax is the parameter for the right end of the segment. Can be -1, for infinity * Therefore, the endpoints are [A + tmin * U, A + tmax * U] ''' def get_voronoi_cells(S, V, tri_list): # Keep track of which circles are included in the triangulation vertices_set = frozenset(itertools.chain(*tri_list)) # Keep track of which edge separate which triangles edge_map = { } for i, tri in enumerate(tri_list): for edge in itertools.combinations(tri, 2): edge = tuple(sorted(edge)) if edge in edge_map: edge_map[edge].append(i) else: edge_map[edge] = [i] # For each triangle voronoi_cell_map = { i : [] for i in vertices_set } for i, (a, b, c) in enumerate(tri_list): # For each edge of the triangle for u, v, w in ((a, b, c), (b, c, a), (c, a, b)): # Finite Voronoi edge edge = tuple(sorted((u, v))) if len(edge_map[edge]) == 2: j, k = edge_map[edge] if k == i: j, k = k, j # Compute the segment parameters U = V[k] - V[j] U_norm = norm2(U) # Add the segment voronoi_cell_map[u].append(((j, k), (V[j], U / U_norm, 0, U_norm))) else: # Infinite Voronoi edge # Compute the segment parameters A, B, C, D = S[u], S[v], S[w], V[i] U = normalized(B - A) I = A + numpy.dot(D - A, U) * U W = normalized(I - D) if numpy.dot(W, I - C) < 0: W = -W # Add the segment voronoi_cell_map[u].append(((edge_map[edge][0], -1), (D, W, 0, None))) voronoi_cell_map[v].append(((-1, edge_map[edge][0]), (D, -W, None, 0))) # Order the segments def order_segment_list(segment_list): # Pick the first element first = min((seg[0][0], i) for i, seg in enumerate(segment_list))[1] # In-place ordering segment_list[0], segment_list[first] = segment_list[first], segment_list[0] for i in range(len(segment_list) - 1): for j in range(i + 1, len(segment_list)): if segment_list[i][0][1] == segment_list[j][0][0]: segment_list[i+1], segment_list[j] = segment_list[j], segment_list[i+1] break # Job done return segment_list # Job done return { i : order_segment_list(segment_list) for i, segment_list in voronoi_cell_map.items() } def voronoi_to_polygons(vor, border, target_areas): # Plot the Voronoi cells edge_map = { } for segment_list in vor.values(): for edge, (A, U, tmin, tmax) in segment_list: edge = tuple(sorted(edge)) if edge not in edge_map: if tmax is None: tmax = 20 if tmin is None: tmin = -20 edge_map[edge] = (A + tmin * U, A + tmax * U) lines = [shapely.geometry.LineString(l) for l in edge_map.values()] polygons = border.difference(lines) # For each polygon in the object, compute props. cx, cy = [], [] areas = [] f_adapt = [] distance = [] for i, p in enumerate(polygons): cx.append(p.centroid.x) cy.append(p.centroid.y) areas.append(p.area) f_adapt.append(target_areas[i] / (p.area / border.area)) distance.append(p.exterior.distance(p.centroid)) return dict(centroids=numpy.stack([cx, cy], axis=1), areas=numpy.array(areas), f_adapt=numpy.array(f_adapt), polygon=polygons, distance=numpy.array(distance)) # --- Plot all the things ----------------------------------------------------- def display(S, R, tri_list, voronoi_cell_map): # Setup fig, ax = plot.subplots() plot.axis('equal') plot.axis('off') # Set min/max display size, as Matplotlib does it wrong min_corner = numpy.amin(S, axis = 0) - numpy.max(R) max_corner = numpy.amax(S, axis = 0) + numpy.max(R) plot.xlim((min_corner[0], max_corner[0])) plot.ylim((min_corner[1], max_corner[1])) # Plot the samples for Si, Ri in zip(S, R): ax.add_artist(plot.Circle(Si, Ri, fill = True, alpha = .4, lw = 0., color = '#8080f0', zorder = 1)) # Plot the power triangulation edge_set = frozenset(tuple(sorted(edge)) for tri in tri_list for edge in itertools.combinations(tri, 2)) line_list = LineCollection([(S[i], S[j]) for i, j in edge_set], lw = 1., colors = '.9') line_list.set_zorder(0) ax.add_collection(line_list) # Plot the Voronoi cells edge_map = { } for segment_list in voronoi_cell_map.values(): for edge, (A, U, tmin, tmax) in segment_list: edge = tuple(sorted(edge)) if edge not in edge_map: if tmax is None: tmax = 20 if tmin is None: tmin = -20 edge_map[edge] = (A + tmin * U, A + tmax * U) line_list = LineCollection(edge_map.values(), lw = 1., colors = 'k') line_list.set_zorder(0) ax.add_collection(line_list) # Job done plot.show() def compute_power_diagram(S, W, target, border): tri_list, V = get_power_triangulation(S, W) vor = get_voronoi_cells(S, V, tri_list) props = voronoi_to_polygons(vor, border, target) return [V, props, [vor, tri_list]] def adapt_position_weights(W, props): new_weights = [] for i, w in enumerate(W): min_val = numpy.min([numpy.sqrt(w), props['distance'][i]]) new_weights.append(min_val**2) return [props['centroids'], numpy.asarray(new_weights)] def adapt_weights(props, weights, err): sites = props['centroids'] new_weights = [] for i, s in enumerate(sites): other_sites = [tuple(s) for s_ in sites if tuple(s_) != tuple(s)] # Compute the nearest neighbor distance = [] for _s in other_sites: distance.append(numpy.sqrt((s[0] - _s[0])**2 + (s[1] - _s[1])**2)**2 - weights[i]) NN_dist = numpy.min(numpy.array(distance)) w_new = numpy.sqrt(weights[i]) * props['f_adapt'][i] w_max = numpy.abs(NN_dist) w_update = numpy.min([w_new, w_max])**2 w_update = numpy.max([w_update, err]) new_weights.append(w_update) return numpy.asarray(new_weights)
djxf/CampusAssi
app/src/main/java/cn/nicolite/huthelper/view/activity/ExamActivity.java
<reponame>djxf/CampusAssi package cn.nicolite.huthelper.view.activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.OrientationHelper; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import cn.nicolite.huthelper.R; import cn.nicolite.huthelper.base.BaseActivity; import cn.nicolite.huthelper.base.IBaseView; import cn.nicolite.huthelper.model.bean.Exam; import cn.nicolite.huthelper.presenter.ExamPresenter; import cn.nicolite.huthelper.utils.SnackbarUtils; import cn.nicolite.huthelper.view.adapter.ExamAdapter; import cn.nicolite.huthelper.view.iview.IExamView; import cn.nicolite.huthelper.view.customView.LoadingDialog; /** * 考试查询界面 * Created by nicolite on 17-11-1. */ public class ExamActivity extends BaseActivity<IBaseView, BaseActivity> implements IExamView { @BindView(R.id.toolbar_title) TextView toolbarTitle; @BindView(R.id.rv_exam) RecyclerView rvExam; @BindView(R.id.iv_empty) ImageView ivEmpty; @BindView(R.id.rl_empty) LinearLayout rlEmpty; @BindView(R.id.rootView) LinearLayout rootView; private ExamPresenter examPresenter; private LoadingDialog loadingDialog; private List<Exam> examList = new ArrayList<>(); private ExamAdapter adapter; @Override protected void initConfig(Bundle savedInstanceState) { setImmersiveStatusBar(true); setDeepColorStatusBar(true); setSlideExit(true); } @Override protected void initBundleData(Bundle bundle) { } @Override protected int setLayoutId() { return R.layout.activity_exam; } @Override protected void doBusiness() { toolbarTitle.setText("考试计划"); rvExam.setLayoutManager(new LinearLayoutManager(context, OrientationHelper.VERTICAL, false)); adapter = new ExamAdapter(context, examList); rvExam.setAdapter(adapter); examPresenter = new ExamPresenter(this, this); examPresenter.showExam(false); } @OnClick({R.id.toolbar_back, R.id.toolbar_menu}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.toolbar_back: finish(); break; case R.id.toolbar_menu: examPresenter.showExam(true); break; } } @Override public void showLoading() { if (loadingDialog == null){ loadingDialog = new LoadingDialog(context) .setLoadingText("查询中..."); } loadingDialog.show(); } @Override public void closeLoading() { if (loadingDialog != null) { loadingDialog.dismiss(); } } @Override public void showMessage(String msg) { SnackbarUtils.showShortSnackbar(rootView, msg); } @Override public void showExam(List<Exam> examList) { this.examList.clear(); this.examList.addAll(examList); adapter.notifyDataSetChanged(); } }
ngjaying/ojg
asm/delall_test.go
// Copyright (c) 2021, <NAME>, All rights reserved. package asm_test import ( "testing" "github.com/ngjaying/ojg/asm" "github.com/ngjaying/ojg/jp" "github.com/ngjaying/ojg/sen" "github.com/ngjaying/ojg/tt" ) func TestDelall(t *testing.T) { root := testPlan(t, `[ [{one:1 two:2 three:3}{one:4 two:5 three:6}] [delall "@.*.one"] [set $.asm @] [delall "$.asm.*.three"] ]`, "{src: [1 2 3]}", ) tt.Equal(t, "[{two:2}{two:5}]", sen.String(root["asm"])) } func TestDelallExprError(t *testing.T) { p := asm.NewPlan([]interface{}{ map[string]interface{}{}, []interface{}{"delall", jp.D()}, }) err := p.Execute(map[string]interface{}{}) tt.NotNil(t, err) } func TestDelallArgCount(t *testing.T) { p := asm.NewPlan([]interface{}{ []interface{}{"delall"}, }) err := p.Execute(map[string]interface{}{}) tt.NotNil(t, err) } func TestDelallArgNotExpr(t *testing.T) { p := asm.NewPlan([]interface{}{ []interface{}{"delall", 1}, }) err := p.Execute(map[string]interface{}{}) tt.NotNil(t, err) }
goubertbrent/oca-backend
src/rogerthat/migrations/put_all_models_by_kind.py
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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. # # @@license_version:1.7@@ from google.appengine.ext import db, ndb from google.appengine.ext.ndb.query import QueryOptions from rogerthat.bizz.job import run_job, MODE_BATCH from rogerthat.consts import MIGRATION_QUEUE from rogerthat.utils.transactions import run_in_transaction def job(cls): if issubclass(cls, db.Model): run_job(_qry_db, [cls], _worker_db, [], worker_queue=MIGRATION_QUEUE, mode=MODE_BATCH, batch_size=25) elif issubclass(cls, ndb.Model): run_job(_qry_ndb, [cls], _worker_ndb, [], worker_queue=MIGRATION_QUEUE, mode=MODE_BATCH, batch_size=25) def _qry_db(cls): return cls.all(keys_only=True) def _worker_db(keys): def trans(): db.put(db.get(keys)) run_in_transaction(trans, xg=True) def _qry_ndb(cls): return cls.query(default_options=QueryOptions(keys_only=True)) @ndb.transactional(xg=True) def _worker_ndb(keys): ndb.put_multi(ndb.get_multi(keys))
mespper/go-babylonjs
babylon/zzz_EdgesRenderer.go
// Code generated by docs2go. DO NOT EDIT. package babylon import ( "syscall/js" ) // EdgesRenderer represents a babylon.js EdgesRenderer. // This class is used to generate edges of the mesh that could then easily be rendered in a scene. type EdgesRenderer struct { p js.Value ctx js.Value } // JSObject returns the underlying js.Value. func (e *EdgesRenderer) JSObject() js.Value { return e.p } // EdgesRenderer returns a EdgesRenderer JavaScript class. func (ba *Babylon) EdgesRenderer() *EdgesRenderer { p := ba.ctx.Get("EdgesRenderer") return EdgesRendererFromJSObject(p, ba.ctx) } // EdgesRendererFromJSObject returns a wrapped EdgesRenderer JavaScript class. func EdgesRendererFromJSObject(p js.Value, ctx js.Value) *EdgesRenderer { return &EdgesRenderer{p: p, ctx: ctx} } // EdgesRendererArrayToJSArray returns a JavaScript Array for the wrapped array. func EdgesRendererArrayToJSArray(array []*EdgesRenderer) []interface{} { var result []interface{} for _, v := range array { result = append(result, v.JSObject()) } return result } // NewEdgesRendererOpts contains optional parameters for NewEdgesRenderer. type NewEdgesRendererOpts struct { Epsilon *float64 CheckVerticesInsteadOfIndices *bool GenerateEdgesLines *bool } // NewEdgesRenderer returns a new EdgesRenderer object. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#constructor func (ba *Babylon) NewEdgesRenderer(source *AbstractMesh, opts *NewEdgesRendererOpts) *EdgesRenderer { if opts == nil { opts = &NewEdgesRendererOpts{} } args := make([]interface{}, 0, 1+3) args = append(args, source.JSObject()) if opts.Epsilon == nil { args = append(args, js.Undefined()) } else { args = append(args, *opts.Epsilon) } if opts.CheckVerticesInsteadOfIndices == nil { args = append(args, js.Undefined()) } else { args = append(args, *opts.CheckVerticesInsteadOfIndices) } if opts.GenerateEdgesLines == nil { args = append(args, js.Undefined()) } else { args = append(args, *opts.GenerateEdgesLines) } p := ba.ctx.Get("EdgesRenderer").New(args...) return EdgesRendererFromJSObject(p, ba.ctx) } // Dispose calls the Dispose method on the EdgesRenderer object. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#dispose func (e *EdgesRenderer) Dispose() { e.p.Call("dispose") } // IsReady calls the IsReady method on the EdgesRenderer object. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#isready func (e *EdgesRenderer) IsReady() bool { retVal := e.p.Call("isReady") return retVal.Bool() } // Render calls the Render method on the EdgesRenderer object. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#render func (e *EdgesRenderer) Render() { e.p.Call("render") } // _generateEdgesLines calls the _generateEdgesLines method on the EdgesRenderer object. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#_generateedgeslines func (e *EdgesRenderer) _generateEdgesLines() { e.p.Call("_generateEdgesLines") } // EdgesWidthScalerForOrthographic returns the EdgesWidthScalerForOrthographic property of class EdgesRenderer. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#edgeswidthscalerfororthographic func (e *EdgesRenderer) EdgesWidthScalerForOrthographic() float64 { retVal := e.p.Get("edgesWidthScalerForOrthographic") return retVal.Float() } // SetEdgesWidthScalerForOrthographic sets the EdgesWidthScalerForOrthographic property of class EdgesRenderer. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#edgeswidthscalerfororthographic func (e *EdgesRenderer) SetEdgesWidthScalerForOrthographic(edgesWidthScalerForOrthographic float64) *EdgesRenderer { e.p.Set("edgesWidthScalerForOrthographic", edgesWidthScalerForOrthographic) return e } // EdgesWidthScalerForPerspective returns the EdgesWidthScalerForPerspective property of class EdgesRenderer. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#edgeswidthscalerforperspective func (e *EdgesRenderer) EdgesWidthScalerForPerspective() float64 { retVal := e.p.Get("edgesWidthScalerForPerspective") return retVal.Float() } // SetEdgesWidthScalerForPerspective sets the EdgesWidthScalerForPerspective property of class EdgesRenderer. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#edgeswidthscalerforperspective func (e *EdgesRenderer) SetEdgesWidthScalerForPerspective(edgesWidthScalerForPerspective float64) *EdgesRenderer { e.p.Set("edgesWidthScalerForPerspective", edgesWidthScalerForPerspective) return e } // IsEnabled returns the IsEnabled property of class EdgesRenderer. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#isenabled func (e *EdgesRenderer) IsEnabled() bool { retVal := e.p.Get("isEnabled") return retVal.Bool() } // SetIsEnabled sets the IsEnabled property of class EdgesRenderer. // // https://doc.babylonjs.com/api/classes/babylon.edgesrenderer#isenabled func (e *EdgesRenderer) SetIsEnabled(isEnabled bool) *EdgesRenderer { e.p.Set("isEnabled", isEnabled) return e }
BartoszJarocki/android-boilerpipe
src/main/java/mf/org/apache/xerces/xni/parser/XMLDTDContentModelSource.java
<reponame>BartoszJarocki/android-boilerpipe /* * 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 mf.org.apache.xerces.xni.parser; import mf.org.apache.xerces.xni.XMLDTDContentModelHandler; /** * Defines a DTD content model source. In other words, any object that * implements this interface is able to emit DTD content model "events" * to the registered DTD content model handler. These events could be * produced by parsing an XML document's internal or external subset, * could be generated from some other source, or could be created * programmatically. This interface does not say <em>how</em> the events * are created, only that the implementor is able to emit them. * * @author <NAME>, IBM * * @version $Id: XMLDTDContentModelSource.java 447244 2006-09-18 05:20:40Z mrglavas $ */ public interface XMLDTDContentModelSource { // // XMLDTDContentModelSource methods // /** Sets the DTD content model handler. */ public void setDTDContentModelHandler(XMLDTDContentModelHandler handler); /** Returns the DTD content model handler. */ public XMLDTDContentModelHandler getDTDContentModelHandler( ); } // interface XMLDTDContentModelSource
ipcraiurosario/dataverse-5.3-estadisticas
src/main/java/edu/harvard/iq/dataverse/SendFeedbackDialog.java
<filename>src/main/java/edu/harvard/iq/dataverse/SendFeedbackDialog.java package edu.harvard.iq.dataverse; import edu.harvard.iq.dataverse.branding.BrandingUtil; import edu.harvard.iq.dataverse.feedback.Feedback; import edu.harvard.iq.dataverse.feedback.FeedbackUtil; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; import edu.harvard.iq.dataverse.util.BundleUtil; import edu.harvard.iq.dataverse.util.MailUtil; import edu.harvard.iq.dataverse.util.SystemConfig; import java.util.List; import java.util.Random; import java.util.logging.Logger; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.validator.ValidatorException; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import javax.mail.internet.InternetAddress; import org.apache.commons.validator.routines.EmailValidator; @ViewScoped @Named public class SendFeedbackDialog implements java.io.Serializable { private static final Logger logger = Logger.getLogger(SendFeedbackDialog.class.getCanonicalName()); /** * The email address supplied by the person filling out the contact form. */ private String userEmail = ""; /** * Body of the message. */ private String userMessage = ""; /** * Becomes the subject of the email. */ private String messageSubject = ""; /** * First operand in addition problem. */ Long op1; /** * Second operand in addition problem. */ Long op2; /** * The guess the user makes in addition problem. */ Long userSum; /** * Either the dataverse or the dataset that the message is pertaining to. If * there is no recipient, this is a general feedback message. */ private DvObject recipient; /** * :SystemEmail (the main support address for an installation). */ private InternetAddress systemAddress; @EJB MailServiceBean mailService; @EJB SettingsServiceBean settingsService; @EJB DataverseServiceBean dataverseService; @EJB SystemConfig systemConfig; @Inject DataverseSession dataverseSession; public void setUserEmail(String uEmail) { userEmail = uEmail; } public String getUserEmail() { return userEmail; } public void initUserInput(ActionEvent ae) { userEmail = ""; userMessage = ""; messageSubject = ""; Random random = new Random(); op1 = new Long(random.nextInt(10)); op2 = new Long(random.nextInt(10)); userSum = null; String systemEmail = settingsService.getValueForKey(SettingsServiceBean.Key.SystemEmail); systemAddress = MailUtil.parseSystemAddress(systemEmail); } public Long getOp1() { return op1; } public void setOp1(Long op1) { this.op1 = op1; } public Long getOp2() { return op2; } public void setOp2(Long op2) { this.op2 = op2; } public Long getUserSum() { return userSum; } public void setUserSum(Long userSum) { this.userSum = userSum; } public String getMessageTo() { if (recipient == null) { <<<<<<< HEAD return BrandingUtil.getSupportTeamName(systemAddress, dataverseService.findRootDataverse().getName()); ======= return BrandingUtil.getSupportTeamName(systemAddress); >>>>>>> dataverse-5.3/master } else if (recipient.isInstanceofDataverse()) { return ((Dataverse) recipient).getDisplayName() + " " + BundleUtil.getStringFromBundle("contact.contact"); } else { return BundleUtil.getStringFromBundle("dataset") + " " + BundleUtil.getStringFromBundle("contact.contact"); } } public String getFormHeader() { if (recipient == null) { <<<<<<< HEAD return BrandingUtil.getContactHeader(systemAddress, dataverseService.findRootDataverse().getName()); ======= return BrandingUtil.getContactHeader(systemAddress); >>>>>>> dataverse-5.3/master } else if (recipient.isInstanceofDataverse()) { return BundleUtil.getStringFromBundle("contact.dataverse.header"); } else { return BundleUtil.getStringFromBundle("contact.dataset.header"); } } public void setUserMessage(String mess) { userMessage = mess; } public String getUserMessage() { return userMessage; } public void setMessageSubject(String messageSubject) { this.messageSubject = messageSubject; } public String getMessageSubject() { return messageSubject; } public boolean isLoggedIn() { return dataverseSession.getUser().isAuthenticated(); } public String loggedInUserEmail() { return dataverseSession.getUser().getDisplayInfo().getEmailAddress(); } public DvObject getRecipient() { return recipient; } public void setRecipient(DvObject recipient) { this.recipient = recipient; } public void validateUserSum(FacesContext context, UIComponent component, Object value) throws ValidatorException { if (op1 + op2 != (Long) value) { // TODO: Remove this English "Sum is incorrect" string. contactFormFragment.xhtml uses contact.sum.invalid instead. FacesMessage msg = new FacesMessage(BundleUtil.getStringFromBundle("contact.sum.invalid")); msg.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(msg); } } public void validateUserEmail(FacesContext context, UIComponent component, Object value) throws ValidatorException { if (!EmailValidator.getInstance().isValid((String) value)) { FacesMessage msg = new FacesMessage(BundleUtil.getStringFromBundle("oauth2.newAccount.emailInvalid")); msg.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(msg); } } public String sendMessage() { <<<<<<< HEAD // FIXME: move dataverseService.findRootDataverse() to init String rootDataverseName = dataverseService.findRootDataverse().getName(); String installationBrandName = BrandingUtil.getInstallationBrandName(rootDataverseName); String supportTeamName = BrandingUtil.getSupportTeamName(systemAddress, rootDataverseName); ======= String installationBrandName = BrandingUtil.getInstallationBrandName(); String supportTeamName = BrandingUtil.getSupportTeamName(systemAddress); >>>>>>> dataverse-5.3/master List<Feedback> feedbacks = FeedbackUtil.gatherFeedback(recipient, dataverseSession, messageSubject, userMessage, systemAddress, userEmail, systemConfig.getDataverseSiteUrl(), installationBrandName, supportTeamName); if (feedbacks.isEmpty()) { logger.warning("No feedback has been sent!"); return null; } for (Feedback feedback : feedbacks) { logger.fine("sending feedback: " + feedback); mailService.sendMail(feedback.getFromEmail(), feedback.getToEmail(), feedback.getSubject(), feedback.getBody()); } return null; } }
sapkra/rabbitmq-operator
rabbitmq-operator/src/main/java/com/indeed/operators/rabbitmq/OperatorException.java
<filename>rabbitmq-operator/src/main/java/com/indeed/operators/rabbitmq/OperatorException.java<gh_stars>10-100 package com.indeed.operators.rabbitmq; public class OperatorException extends RuntimeException { public OperatorException(final String description, final Throwable cause) { super(description, cause); } }
afeng11/tomato-arm
release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/leds/leds-regulator.c
/* * leds-regulator.c - LED class driver for regulator driven LEDs. * * Copyright (C) 2009 <NAME> <<EMAIL>> * * Inspired by leds-wm8350 driver. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/module.h> #include <linux/err.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/leds.h> #include <linux/leds-regulator.h> #include <linux/platform_device.h> #include <linux/regulator/consumer.h> #define to_regulator_led(led_cdev) \ container_of(led_cdev, struct regulator_led, cdev) struct regulator_led { struct led_classdev cdev; enum led_brightness value; int enabled; struct mutex mutex; struct work_struct work; struct regulator *vcc; }; static inline int led_regulator_get_max_brightness(struct regulator *supply) { int ret; int voltage = regulator_list_voltage(supply, 0); if (voltage <= 0) return 1; /* even if regulator can't change voltages, * we still assume it can change status * and the LED can be turned on and off. */ ret = regulator_set_voltage(supply, voltage, voltage); if (ret < 0) return 1; return regulator_count_voltages(supply); } static int led_regulator_get_voltage(struct regulator *supply, enum led_brightness brightness) { if (brightness == 0) return -EINVAL; return regulator_list_voltage(supply, brightness - 1); } static void regulator_led_enable(struct regulator_led *led) { int ret; if (led->enabled) return; ret = regulator_enable(led->vcc); if (ret != 0) { dev_err(led->cdev.dev, "Failed to enable vcc: %d\n", ret); return; } led->enabled = 1; } static void regulator_led_disable(struct regulator_led *led) { int ret; if (!led->enabled) return; ret = regulator_disable(led->vcc); if (ret != 0) { dev_err(led->cdev.dev, "Failed to disable vcc: %d\n", ret); return; } led->enabled = 0; } static void regulator_led_set_value(struct regulator_led *led) { int voltage; int ret; mutex_lock(&led->mutex); if (led->value == LED_OFF) { regulator_led_disable(led); goto out; } if (led->cdev.max_brightness > 1) { voltage = led_regulator_get_voltage(led->vcc, led->value); dev_dbg(led->cdev.dev, "brightness: %d voltage: %d\n", led->value, voltage); ret = regulator_set_voltage(led->vcc, voltage, voltage); if (ret != 0) dev_err(led->cdev.dev, "Failed to set voltage %d: %d\n", voltage, ret); } regulator_led_enable(led); out: mutex_unlock(&led->mutex); } static void led_work(struct work_struct *work) { struct regulator_led *led; led = container_of(work, struct regulator_led, work); regulator_led_set_value(led); } static void regulator_led_brightness_set(struct led_classdev *led_cdev, enum led_brightness value) { struct regulator_led *led = to_regulator_led(led_cdev); led->value = value; schedule_work(&led->work); } static int __devinit regulator_led_probe(struct platform_device *pdev) { struct led_regulator_platform_data *pdata = pdev->dev.platform_data; struct regulator_led *led; struct regulator *vcc; int ret = 0; if (pdata == NULL) { dev_err(&pdev->dev, "no platform data\n"); return -ENODEV; } vcc = regulator_get_exclusive(&pdev->dev, "vled"); if (IS_ERR(vcc)) { dev_err(&pdev->dev, "Cannot get vcc for %s\n", pdata->name); return PTR_ERR(vcc); } led = kzalloc(sizeof(*led), GFP_KERNEL); if (led == NULL) { ret = -ENOMEM; goto err_vcc; } led->cdev.max_brightness = led_regulator_get_max_brightness(vcc); if (pdata->brightness > led->cdev.max_brightness) { dev_err(&pdev->dev, "Invalid default brightness %d\n", pdata->brightness); ret = -EINVAL; goto err_led; } led->value = pdata->brightness; led->cdev.brightness_set = regulator_led_brightness_set; led->cdev.name = pdata->name; led->cdev.flags |= LED_CORE_SUSPENDRESUME; led->vcc = vcc; mutex_init(&led->mutex); INIT_WORK(&led->work, led_work); platform_set_drvdata(pdev, led); ret = led_classdev_register(&pdev->dev, &led->cdev); if (ret < 0) { cancel_work_sync(&led->work); goto err_led; } /* to expose the default value to userspace */ led->cdev.brightness = led->value; /* Set the default led status */ regulator_led_set_value(led); return 0; err_led: kfree(led); err_vcc: regulator_put(vcc); return ret; } static int __devexit regulator_led_remove(struct platform_device *pdev) { struct regulator_led *led = platform_get_drvdata(pdev); led_classdev_unregister(&led->cdev); cancel_work_sync(&led->work); regulator_led_disable(led); regulator_put(led->vcc); kfree(led); return 0; } static struct platform_driver regulator_led_driver = { .driver = { .name = "leds-regulator", .owner = THIS_MODULE, }, .probe = regulator_led_probe, .remove = __devexit_p(regulator_led_remove), }; static int __init regulator_led_init(void) { return platform_driver_register(&regulator_led_driver); } module_init(regulator_led_init); static void __exit regulator_led_exit(void) { platform_driver_unregister(&regulator_led_driver); } module_exit(regulator_led_exit); MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_DESCRIPTION("Regulator driven LED driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:leds-regulator");
sjyk/deeplens
depth_prediction/predictor.py
<reponame>sjyk/deeplens import argparse import os import sys import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from PIL import Image from urllib.request import urlretrieve import depth_prediction.models as models from main import utils import glob import logging logger = utils.get_logger(name=__name__) DEFAULT_MODEL_PATH = "../resources/models/depth_prediction/NYU_" \ "ResNet-UpProj.npy" DEFAULT_IMAGES_PATH = "../resources/demo/image.jpg" DEFAULT_BATCH_SIZE = 16 DEFAULT_LOG_FILE = "deeplens_depth_maps.log" IS_DEBUG = False """ author: <NAME> <EMAIL> based on: https://github.com/iro-cp/FCRN-DepthPrediction """ def show_figure(img): """ Plot the image as a figure. :param img: the input image """ fig = plt.figure() input_img = plt.imshow(img, interpolation='nearest') fig.colorbar(input_img) plt.show() def process_images(images_path, width, height): """ Process the image (e.g. resize). :param images_path: the path to the directory with images :param width: the width of the image expected by the model :param height: the height of the image expected by the model :return: the processed and resized images (the resized image can be used to plot is as an original input to the model) """ processed_imgs = [] resized_imgs = [] for image_path in images_path: img = Image.open(image_path) resized_img = img.resize([width, height], Image.ANTIALIAS) resized_imgs.append(resized_img) processed_img = np.array(resized_img).astype('float32') processed_imgs.append(processed_img) if logger.level == logging.DEBUG: for image in resized_imgs: show_figure(image) return processed_imgs, resized_imgs class Predictor(object): def __init__(self, model_path=DEFAULT_MODEL_PATH): """ Provides inference on arbitrary images. :param model_path: path to the model weights """ super(Predictor, self).__init__() self.model_path = model_path # Default input sizes self.height = 228 self.width = 304 self.channels = 3 self.batch_size = 1 # Create a placeholder for the input image self.input_node = tf.placeholder(tf.float32, shape=(None, self.height, self.width, self.channels)) # Construct the network self.net = models.ResNet50UpProj(inputs={'data': self.input_node}, batch=self.batch_size, keep_prob=1, is_training=False) self.session = tf.Session() self._load_model_weights() def __del__(self): """ Close the TensorFlow session. """ self.session.close() def _load_model_weights(self): """ Load the pre-trained model parameters (weights). """ logger.info('Loading pre-trained model weights') if self.model_path.endswith(".npy"): logger.debug("load the pre-trained model from npy file") if os.path.isfile(self.model_path) is False: # extract model folder by removing model file name from the end # of the path model_folder = self.model_path[:self.model_path.rfind("/")] if not os.path.exists(model_folder): os.makedirs(model_folder) model_url = "https://goo.gl/dt2geQ" logger.info( "Downloading the model weights to " + model_folder + "... (the file is about 243 MB big)") self.model_path = urlretrieve(model_url, self.model_path) logger.info("Model downloaded successfully") self.net.load(self.model_path, self.session) elif self.model_path.endswith(".ckpt"): # load the pre-trained model from ckpt file saver = tf.train.Saver() saver.restore(self.session, self.model_path) else: raise ValueError("Not known saved model weights' extension: " "Expected: .npy or .ckpt, but given file: " + self.model_path) logger.debug("model loaded") def predict_depth(self, images_path, batch_size=DEFAULT_BATCH_SIZE): """ For each image return its depth map. For the provided paths to images (it can be a single image path) returns maps of the predicted depths. :param images_path: path to the directory with images (it can be also a single path to an image) :param batch_size: batch size for the image inference :return: map of the predicted depths and the re-sized input images """ logger.debug("predict depth") if os.path.isfile(images_path): images_path = [images_path] else: # extract the whole content from the directory images_path = glob.glob(images_path + "/*") # retain only files images_path = [image_path for image_path in images_path if os.path.isfile(image_path)] processed_imgs, resized_imgs = process_images( images_path=images_path, width=self.width, height=self.height) processed_imgs = np.array(processed_imgs) # adjust the batch size self.net.batch_size = min(len(images_path), batch_size) # Evaluate the network for the given images predicted_depths = self.session.run( self.net.get_output(), feed_dict={self.input_node: processed_imgs}) return predicted_depths[..., 0], resized_imgs def main(model_path=DEFAULT_MODEL_PATH, images_path=DEFAULT_IMAGES_PATH): """ Main and self-contained method to predict the images. :param model_path: the path to the pre-trained model parameters :param images_path: the path to the directory with images or a single image path """ predictor = Predictor(model_path) predicted_depths, resized_imgs = predictor.predict_depth( images_path=images_path) # Plot result fig = plt.figure() columns = 2 rows = len(resized_imgs) logger.debug("number of processed images:" + str(rows)) for counter in range(rows): first_index = 2 * counter + 1 ax1 = fig.add_subplot(rows, columns, first_index) input_img = plt.imshow(resized_imgs[counter], interpolation='nearest') fig.colorbar(input_img) ax1.title.set_text("resized input image " + str(counter)) second_index = 2 * counter + 2 ax2 = fig.add_subplot(rows, columns, second_index) prediction_img = plt.imshow(predicted_depths[counter], interpolation='nearest') fig.colorbar(prediction_img) ax2.title.set_text("depth map " + str(counter)) fig.tight_layout() img_folder = images_path[:images_path.rfind("/")] depth_folder = img_folder + "/image_depths/" if not os.path.exists(depth_folder): os.makedirs(depth_folder) fig.savefig(depth_folder + "/image_depths.png") plt.show(block=True) plt.close(fig) if __name__ == '__main__': # Parse arguments parser = argparse.ArgumentParser() parser.add_argument('-m', '--model_path', default=DEFAULT_MODEL_PATH, help='Converted parameters for the model') parser.add_argument('-i', '--image_path', default=DEFAULT_IMAGES_PATH, help='Image path or directory of images to predict ' 'their depth maps') parser.add_argument("-l", "--log_file", default=DEFAULT_LOG_FILE, help="The name of the log file.") parser.add_argument("-b", "--batch_size", default=DEFAULT_BATCH_SIZE, type=int, help="the batch size for inference") parser.add_argument("-g", "--is_debug", default=IS_DEBUG, type=bool, help="is it the debug mode execution") args = parser.parse_args(args=sys.argv[1:]) log_file = args.log_file IS_DEBUG = args.is_debug utils.set_up_logging(log_file=log_file, is_debug=args.is_debug) logger = utils.get_logger(name=__name__) if IS_DEBUG: logger.setLevel(logging.DEBUG) logger.debug("current working directory: " + os.getcwd()) # predict the depth maps main(model_path=args.model_path, images_path=args.image_path)
rzeh4n/psp-validator
sharedModule/src/main/java/nkp/pspValidator/shared/engine/validationFunctions/VfCheckInfoFileItemlistReferencesAllFiles.java
<gh_stars>1-10 package nkp.pspValidator.shared.engine.validationFunctions; import nkp.pspValidator.shared.engine.*; import nkp.pspValidator.shared.engine.exceptions.ContractException; import nkp.pspValidator.shared.engine.exceptions.InvalidPathException; import nkp.pspValidator.shared.engine.exceptions.InvalidXPathExpressionException; import nkp.pspValidator.shared.engine.exceptions.XmlFileParsingException; import nkp.pspValidator.shared.engine.params.ValueParam; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by <NAME> on 1.11.16. */ public class VfCheckInfoFileItemlistReferencesAllFiles extends ValidationFunction { public static final String PARAM_INFO_FILE = "info_file"; public static final String PARAM_LEVEL = "level"; public static final String PARAM_FILE = "file"; public static final String PARAM_FILES = "files"; public VfCheckInfoFileItemlistReferencesAllFiles(String name, Engine engine) { super(name, engine, new Contract() .withValueParam(PARAM_INFO_FILE, ValueType.FILE, 1, 1) .withValueParam(PARAM_LEVEL, ValueType.LEVEL, 1, 1) .withValueParam(PARAM_FILE, ValueType.FILE, 0, null) .withValueParam(PARAM_FILES, ValueType.FILE_LIST, 0, null) ); } @Override public ValidationResult validate() { try { checkContractCompliance(); ValueEvaluation paramInfoFile = valueParams.getParams(PARAM_INFO_FILE).get(0).getEvaluation(); File infoFile = (File) paramInfoFile.getData(); if (infoFile == null) { return invalidValueParamNull(PARAM_INFO_FILE, paramInfoFile); } else if (infoFile.isDirectory()) { return singlErrorResult(invalidFileIsDir(infoFile)); } else if (!infoFile.canRead()) { return singlErrorResult(invalidCannotReadDir(infoFile)); } ValueEvaluation paramLevel = valueParams.getParams(PARAM_LEVEL).get(0).getEvaluation(); Level level = (Level) paramLevel.getData(); if (level == null) { return invalidValueParamNull(PARAM_LEVEL, paramLevel); } Set<File> expectedFiles = new HashSet<>(); List<ValueParam> fileParams = valueParams.getParams(PARAM_FILE); for (ValueParam fileParam : fileParams) { ValueEvaluation fileEvaluation = fileParam.getEvaluation(); File file = (File) fileEvaluation.getData(); if (file == null) { return invalidValueParamNull(PARAM_FILE, fileEvaluation); } else { expectedFiles.add(file.getAbsoluteFile()); } } List<ValueParam> filesParams = valueParams.getParams(PARAM_FILES); for (ValueParam fileParam : filesParams) { ValueEvaluation filesEvaluation = fileParam.getEvaluation(); List<File> files = (List<File>) filesEvaluation.getData(); if (files == null) { //ignore //return invalidValueParamNull(PARAM_FILES, filesEvaluation); } else { for (File file : files) { expectedFiles.add(file.getAbsoluteFile()); } } } return validate(infoFile, expectedFiles, level); } catch (ContractException e) { return invalidContractNotMet(e); } catch (Throwable e) { return invalidUnexpectedError(e); } } private ValidationResult validate(File infoFile, Set<File> expectedFiles, Level level) { ValidationResult result = new ValidationResult(); try { Document infoDoc = engine.getXmlDocument(infoFile, false); XPathExpression exp = engine.buildXpath("/info/itemlist/item"); NodeList nodes = (NodeList) exp.evaluate(infoDoc, XPathConstants.NODESET); File rootDir = infoFile.getParentFile(); List<File> foundFilesList = new ArrayList<>(nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String path = node.getTextContent().trim(); try { File file = Utils.buildAbsoluteFile(rootDir, path); foundFilesList.add(file); } catch (InvalidPathException e) { result.addError(invalid(e)); } } Set<File> foundFiles = new HashSet<>(foundFilesList.size()); foundFiles.addAll(foundFilesList); if (!foundFiles.equals(expectedFiles)) {//something is different for (File foundFile : foundFiles) { if (!expectedFiles.contains(foundFile)) { result.addError(invalid(level, "soubor INFO se odkazuje na neočekávaný soubor %s", foundFile.getAbsolutePath())); } } for (File expectedFile : expectedFiles) { if (!foundFiles.contains(expectedFile)) { result.addError(invalid(level, "soubor INFO se neodkazuje na očekávaný soubor %s", expectedFile.getAbsolutePath())); } } } } catch (XmlFileParsingException e) { result.addError(invalid(e)); } catch (InvalidXPathExpressionException e) { result.addError(invalid(e)); } catch (XPathExpressionException e) { result.addError(invalid(e)); } finally { return result; } } }
ishlandbukkit/CubicChunks
src/main/java/io/github/opencubicchunks/cubicchunks/mixin/core/client/server/MixinIntegratedServer.java
<reponame>ishlandbukkit/CubicChunks package io.github.opencubicchunks.cubicchunks.mixin.core.client.server; import java.util.function.BooleanSupplier; import io.github.opencubicchunks.cubicchunks.CubicChunks; import io.github.opencubicchunks.cubicchunks.chunk.IVerticalView; import net.minecraft.client.Minecraft; import net.minecraft.client.server.IntegratedServer; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(IntegratedServer.class) public class MixinIntegratedServer { @Shadow @Final private Minecraft minecraft; @Inject(method = "tickServer", at = @At(value = "INVOKE", target = "Ljava/lang/Math;max(II)I"), cancellable = true) private void tickServer(BooleanSupplier shouldKeepTicking, CallbackInfo ci) { int horizontalViewDistance = Math.max(2, this.minecraft.options.renderDistance + -1); int verticalViewDistance = Math.max(2, CubicChunks.config().client.verticalViewDistance + -1); int currentVerticalViewDistance1 = ((IVerticalView) ((IntegratedServer) (Object) this).getPlayerList()).getVerticalViewDistance(); if (verticalViewDistance != currentVerticalViewDistance1) { CubicChunks.LOGGER.info("Changing vertical view distance to {}, from {}", verticalViewDistance, currentVerticalViewDistance1); ((IVerticalView) ((IntegratedServer) (Object) this).getPlayerList()).setIncomingVerticalViewDistance(verticalViewDistance); ((IntegratedServer) (Object) this).getPlayerList().setViewDistance(horizontalViewDistance); } } }
westernmarslab/tanager-feeder
tanager_feeder/dialogs/change_ip_dialog.py
<reponame>westernmarslab/tanager-feeder<filename>tanager_feeder/dialogs/change_ip_dialog.py from tkinter import Frame, Label, Entry, LEFT from tanager_feeder.dialogs.dialog import Dialog from tanager_feeder.utils import CompyTypes, ConnectionManager class ChangeIPDialog(Dialog): def __init__( self, connection_manager: ConnectionManager, title: str, label: str, which_compy: str, config_loc: str ): buttons = { "ok": { self.ok: [], }, "cancel": { self.cancel: [], }, } super().__init__(None, title, label, buttons, allow_exit=False, start_mainloop=False) self.connection_manager = connection_manager self.entry_frame = Frame(self.top, bg=self.tk_format.bg) self.entry_frame.pack(pady=(10, 20)) frame = Frame(self.entry_frame, bg=self.tk_format.bg) frame.pack(pady=(5, 5)) change_label = Label(frame, text="IP address: ", fg=self.tk_format.textcolor, bg=self.tk_format.bg) change_label.pack(side=LEFT) self.ip_entry = Entry( frame, bg=self.tk_format.entry_background, selectbackground=self.tk_format.selectbackground, selectforeground=self.tk_format.selectforeground, ) if which_compy == CompyTypes.SPEC_COMPY.value: print("spec ip") print(self.connection_manager.spec_ip) self.ip_entry.insert(0, self.connection_manager.spec_ip) else: self.ip_entry.insert(0, self.connection_manager.pi_ip) self.ip_entry.pack(side=LEFT) self.which_compy = which_compy self.config_loc = config_loc self.top.mainloop() def ok(self): if self.which_compy == CompyTypes.SPEC_COMPY.value: self.connection_manager.spec_ip = self.ip_entry.get() print(self.connection_manager.spec_ip) elif self.which_compy == CompyTypes.PI.value: self.connection_manager.pi_ip = self.ip_entry.get() with open(self.config_loc + "ip_addresses.txt", "w+") as f: if self.connection_manager.spec_ip != "": print("writing ip! ") print("spec ip") print(self.connection_manager.spec_ip) f.write(self.connection_manager.spec_ip + "\n") else: f.write("spec_compy_ip\n") if self.connection_manager.spec_ip != "": print("writing pi_pi") print(self.connection_manager.pi_ip) f.write(self.connection_manager.pi_ip) else: f.write("raspberrypi") self.top.destroy() def cancel(self): self.top.destroy()
ufoscout/jpattern
core/src/test/java/com/jpattern/service/log/reader/MessageReaderTest.java
package com.jpattern.service.log.reader; import com.jpattern.core.BaseApplicationTest; import com.jpattern.service.log.reader.IQueueMessages; import com.jpattern.service.log.reader.MessageReader; import com.jpattern.service.log.reader.QueueMessages; /** * * @author <NAME>' * * 09/apr/2010 */ public class MessageReaderTest extends BaseApplicationTest { public void testMessageReader1() throws Exception { IQueueMessages messageQueue = new QueueMessages(50); MessageReader messageReader = new MessageReader(messageQueue); MessageFilteredReader messageStringNullFilteredReader = new MessageFilteredReader(messageReader, new NullMessageFilter()); MessageFilteredReader messageStringEmptyFilteredReader = new MessageFilteredReader(messageReader, new MessageFilter("")); MessageFilteredReader messageStringFilteredReader = new MessageFilteredReader(messageReader, new MessageFilter("2")); messageQueue.offer("messaggio 1"); messageQueue.offer("messaggio 2"); messageQueue.offer("messaggio 3"); assertEquals( "messaggio 1", messageReader.read().getMessage()); assertEquals( "messaggio 1", messageReader.read(0).getMessage()); assertEquals( "messaggio 2", messageReader.read(1).getMessage()); assertEquals( "messaggio 3", messageReader.read(2).getMessage()); assertEquals( "messaggio 1", messageStringNullFilteredReader.read().getMessage()); assertEquals( "messaggio 1", messageStringNullFilteredReader.read(0).getMessage()); assertEquals( "messaggio 2", messageStringNullFilteredReader.read(1).getMessage()); assertEquals( "messaggio 3", messageStringNullFilteredReader.read(2).getMessage()); assertEquals( "messaggio 1", messageStringEmptyFilteredReader.read().getMessage()); assertEquals( "messaggio 1", messageStringEmptyFilteredReader.read(0).getMessage()); assertEquals( "messaggio 2", messageStringEmptyFilteredReader.read(1).getMessage()); assertEquals( "messaggio 3", messageStringEmptyFilteredReader.read(2).getMessage()); assertEquals( "", messageStringFilteredReader.read().getMessage()); assertEquals( "", messageStringFilteredReader.read(0).getMessage()); assertEquals( "messaggio 2", messageStringFilteredReader.read(1).getMessage()); assertEquals( "", messageStringFilteredReader.read(2).getMessage()); } }
lizzzcai/leetcode-go
solutions/0329_Longest_Increasing_Path_in_a_Matrix/0329_Longest_Increasing_Path_in_a_Matrix_test.go
<gh_stars>0 package leetcode import ( "fmt" "testing" ) func TestLongestIncreasingPath(t *testing.T) { var tests = []struct { matrix [][]int want int }{ {[][]int{[]int{9, 9, 4}, []int{6, 6, 8}, []int{2, 1, 1}}, 4}, {[][]int{[]int{3, 4, 5}, []int{3, 2, 6}, []int{2, 2, 1}}, 4}, } for _, tt := range tests { testname := fmt.Sprintf("%v", tt.matrix) t.Run(testname, func(t *testing.T) { ans := longestIncreasingPath(tt.matrix) if ans != tt.want { t.Errorf("got %v, want %v", ans, tt.want) } }) } }
syncrou/catalog-ui
src/helpers/share/share-helper.js
import { getAxiosInstance, getPortfolioApi } from '../shared/user-login'; import { CATALOG_API_BASE } from '../../utilities/constants'; const axiosInstance = getAxiosInstance(); const userApi = getPortfolioApi(); export async function getShareInfo(portfolioId) { return await axiosInstance.get(`${CATALOG_API_BASE}/portfolios/${portfolioId}/share_info`); } export async function sharePortfolio(data) { let policy = { permissions: data.permissions.split(','), group_uuids: [ data.group_uuid ]}; return await userApi.sharePortfolio(data.id, policy); } export async function unsharePortfolio(data) { let policy = { permissions: data.permissions, group_uuids: [ data.group_uuid ]}; return await userApi.unsharePortfolio(data.id, policy); }
stavanmehta/leetcode
python/562.longest-line-of-consecutive-one-in-matrix.py
<gh_stars>0 class Solution: def longestLine(self, M: List[List[int]]) -> int:
AnyBitIO/anybit-Android
app/src/main/java/com/bitcoin/common/Json.java
<reponame>AnyBitIO/anybit-Android<gh_stars>10-100 package com.bitcoin.common; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public class Json { private static final Logger LOGGER = LoggerFactory.getLogger(Json.class); /** * Convert a JSON string to the object that it represents. * * @param objectType Class that we're converting this string to. * @param str String containing the JSON representation. * @return Object that was reconstructed from the JSON. */ public static Object objectifyString(Class objectType, String str) { try { JsonFactory jsonFact = new JsonFactory(); JsonParser jsonParser = jsonFact.createParser(str); return new ObjectMapper().readValue(jsonParser, objectType); } catch (IOException e) { LOGGER.warn(null, e); return null; } } /** * Convert an object to a JSON representation of itself. * * @param objectType Object type we're writing. * @param obj Object we're writing. * @return JSON representation of the object. */ public static String stringifyObject(Class objectType, Object obj) { try { JsonFactory jsonFact = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(jsonFact); ObjectWriter writer = mapper.writerFor(objectType); return writer.writeValueAsString(obj); } catch (IOException e) { LOGGER.error(null, e); return ""; } } }
nickgros/SynapseWebClient
src/main/java/org/sagebionetworks/web/client/presenter/MapPresenter.java
package org.sagebionetworks.web.client.presenter; import org.sagebionetworks.web.client.view.MapView; import org.sagebionetworks.web.client.widget.googlemap.GoogleMap; import org.sagebionetworks.web.client.widget.team.TeamBadge; import com.google.gwt.activity.shared.AbstractActivity; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.inject.Inject; public class MapPresenter extends AbstractActivity implements Presenter<org.sagebionetworks.web.client.place.MapPlace>, MapView.Presenter { public static final String ALL_USERS = "all"; GoogleMap map; MapView view; TeamBadge teamBadge; @Inject public MapPresenter(MapView view, GoogleMap map, TeamBadge teamBadge) { this.view = view; this.map = map; this.teamBadge = teamBadge; view.setPresenter(this); view.setMap(map.asWidget()); view.setTeamBadge(teamBadge.asWidget()); } @Override public void start(AcceptsOneWidget panel, EventBus eventBus) { panel.setWidget(view.asWidget()); } @Override public void setPlace(org.sagebionetworks.web.client.place.MapPlace place) { String teamId = place.getTeamId(); map.setHeight((view.getClientHeight() - 300) + "px"); if (ALL_USERS.equalsIgnoreCase(teamId)) { map.configure(); view.setAllUsersTitleVisible(true); view.setTeamBadgeVisible(false); } else { teamBadge.configure(teamId); map.configure(teamId); view.setAllUsersTitleVisible(false); view.setTeamBadgeVisible(true); } } @Override public String mayStop() { return null; } }
aldopain/DevExtreme
testing/tests/DevExpress.viz.vectorMap/mapLayer_new.tests.js
const $ = require('jquery'); const vizMocks = require('../../helpers/vizMocks.js'); const loadingIndicatorModule = require('viz/core/loading_indicator'); const titleModule = require('viz/core/title'); const projectionEnginesModule = require('viz/vector_map/projection'); const controlBarModule = require('viz/vector_map/control_bar'); const legendModule = require('viz/vector_map/legend'); const tooltipModule = require('viz/core/tooltip'); const tooltipViewerModule = require('viz/vector_map/tooltip_viewer'); const dataSourceModule = require('data/data_source/data_source'); const exportMenuModule = require('viz/core/export'); // TODO maybe if you test layer - you should create exact layer? const rendererModule = require('viz/core/renderers/renderer'); require('viz/vector_map/vector_map'); $('#qunit-fixture').append('<div id="container" style="width: 1200px; height: 600px;"></div>'); titleModule.Title = vizMocks.stubClass(titleModule.Title, { }); tooltipModule.Tooltip = vizMocks.stubClass(tooltipModule.Tooltip); exportMenuModule.ExportMenu = vizMocks.stubClass(exportMenuModule.ExportMenu); // TODO maybe if you test layer - you should create exact layer? loadingIndicatorModule.LoadingIndicator = vizMocks.stubClass(loadingIndicatorModule.LoadingIndicator); controlBarModule.ControlBar = vizMocks.stubClass(controlBarModule.ControlBar); legendModule.LegendsControl = vizMocks.stubClass(legendModule.LegendsControl); tooltipViewerModule.TooltipViewer = vizMocks.stubClass(tooltipViewerModule.TooltipViewer); const simpleProjection = projectionEnginesModule.projection({ aspectRatio: 4 / 3, to: function(coordinates) { return [ (coordinates[0] - 200) / 200, (coordinates[1] - 150) / 150 ]; }, from: function(coordinates) { return [ (coordinates[0] + 1) * 200, (coordinates[1] + 1) * 150 ]; } }); const createData = function(featureType, items) { return { type: 'FeatureCollection', features: $.map(items, function(item) { return { type: 'Feature', geometry: { type: featureType, coordinates: item.coordinates ? item.coordinates : item }, properties: item.properties || {} }; }) }; }; const environment = { beforeEach: function() { const renderer = this.renderer = new vizMocks.Renderer(); rendererModule.Renderer = function() { return renderer; }; }, createLayer: function(options) { return $('#container').dxVectorMap({ projection: simpleProjection, layers: options }).dxVectorMap('instance').getLayers()[0]; }, getArea: function(index) { return this.renderer.path.getCall(0 + index).returnValue; }, getLine: function(index) { return this.renderer.path.getCall(0 + index).returnValue; }, getMarker: function(index) { return this.renderer.g.getCall(2 + index).returnValue; }, getLabel: function(index) { return this.renderer.text.getCall(index).returnValue; } }; QUnit.module('Elements positioning', environment); QUnit.test('Areas (Polygon)', function(assert) { this.createLayer({ dataSource: createData('Polygon', [ [ [[100, 50], [200, 50], [200, 200], [100, 200]] ], [ [[200, 100], [400, 0], [400, 300]], [[0, 0], [0, 300], [400, 300], [400, 0]] ], [] ]) }); assert.strictEqual(this.getArea(0).attr.getCall(1).args[0]['class'], 'dxm-area', 'type'); assert.deepEqual(this.getArea(0).attr.getCall(0).args, [{ points: [ [400, 500, 600, 500, 600, 200, 400, 200] ] }], 'area 1 (simple)'); assert.deepEqual(this.getArea(1).attr.getCall(0).args, [{ points: [ [600, 400, 1000, 600, 1000, 0], [200, 600, 200, 0, 1000, 0, 1000, 600] ] }], 'area 2 (complex)'); assert.deepEqual(this.getArea(2).attr.getCall(0).args, [{ points: [] }], 'area 3 (degenerate)'); }); QUnit.test('Areas (Multipolygon)', function(assert) { this.createLayer({ dataSource: createData('MultiPolygon', [ [ [ [[100, 50], [200, 50], [200, 200], [100, 200]] ] ], [ [ [[200, 100], [400, 0], [400, 300]] ], [ [[0, 0], [0, 300], [400, 300], [400, 0]], [[200, 100], [300, 100], [250, 200]] ] ], [] ]) }); assert.strictEqual(this.getArea(0).attr.getCall(1).args[0]['class'], 'dxm-area', 'type'); assert.deepEqual(this.getArea(0).attr.getCall(0).args, [{ points: [ [400, 500, 600, 500, 600, 200, 400, 200] ] }], 'area 1 (simple)'); assert.deepEqual(this.getArea(1).attr.getCall(0).args, [{ points: [ [600, 400, 1000, 600, 1000, 0], [200, 600, 200, 0, 1000, 0, 1000, 600], [600, 400, 800, 400, 700, 200] ] }], 'area 2 (complex)'); assert.deepEqual(this.getArea(2).attr.getCall(0).args, [{ points: [] }], 'area 3 (degenerate)'); }); QUnit.test('Areas (simple data source)', function(assert) { this.createLayer({ dataSource: [ { coordinates: [ [[100, 50], [200, 50], [200, 200], [100, 200]] ] }, { coordinates: [ [[200, 100], [400, 0], [400, 300]], [[0, 0], [0, 300], [400, 300], [400, 0]] ] }, { coordinates: [] } ] }); assert.strictEqual(this.getArea(0).attr.getCall(1).args[0]['class'], 'dxm-area', 'type'); assert.deepEqual(this.getArea(0).attr.getCall(0).args, [{ points: [ [400, 500, 600, 500, 600, 200, 400, 200] ] }], 'area 1 (simple)'); assert.deepEqual(this.getArea(1).attr.getCall(0).args, [{ points: [ [600, 400, 1000, 600, 1000, 0], [200, 600, 200, 0, 1000, 0, 1000, 600] ] }], 'area 2 (complex)'); assert.deepEqual(this.getArea(2).attr.getCall(0).args, [{ points: [] }], 'area 3 (degenerate)'); }); QUnit.test('Lines (LineString)', function(assert) { this.createLayer({ dataSource: createData('LineString', [ [[100, 200], [300, 300], [400, 0]], [] ]) }); assert.strictEqual(this.getArea(0).attr.getCall(1).args[0]['class'], 'dxm-line', 'type'); assert.deepEqual(this.getLine(0).attr.getCall(0).args, [{ points: [[400, 200, 800, 0, 1000, 600]] }], 'line 1 (common)'); assert.deepEqual(this.getLine(1).attr.getCall(0).args, [{ points: [[]] // TODO: Investigate }], 'line 2 (degenerate)'); }); QUnit.test('Lines (MultiPoint)', function(assert) { this.createLayer({ dataSource: createData('MultiPoint', [ [[100, 200], [300, 300], [400, 0]], [] ]) }); assert.strictEqual(this.getArea(0).attr.getCall(1).args[0]['class'], 'dxm-line', 'type'); assert.deepEqual(this.getLine(0).attr.getCall(0).args, [{ points: [[400, 200, 800, 0, 1000, 600]] }], 'line 1 (common)'); assert.deepEqual(this.getLine(1).attr.getCall(0).args, [{ points: [[]] // TODO: Investigate }], 'line 2 (degenerate)'); }); QUnit.test('Lines (MultiLineString)', function(assert) { this.createLayer({ dataSource: createData('MultiLineString', [ [ [[100, 50], [200, 50], [200, 200], [100, 200]] ], [ [[200, 100], [400, 0], [400, 300]], [[0, 0], [0, 300], [400, 300], [400, 0]] ], [] ]) }); assert.strictEqual(this.getArea(0).attr.getCall(1).args[0]['class'], 'dxm-line', 'type'); assert.deepEqual(this.getLine(0).attr.getCall(0).args, [{ points: [ [400, 500, 600, 500, 600, 200, 400, 200] ] }], 'line 1 (simple)'); assert.deepEqual(this.getLine(1).attr.getCall(0).args, [{ points: [ [600, 400, 1000, 600, 1000, 0], [200, 600, 200, 0, 1000, 0, 1000, 600] ] }], 'line 2 (complex)'); assert.deepEqual(this.getLine(2).attr.getCall(0).args, [{ points: [] }], 'line 3 (degenerate)'); }); QUnit.test('Lines (simple data source)', function(assert) { this.createLayer({ dataSource: [ { coordinates: [[100, 200], [300, 300], [400, 0]] }, { coordinates: [] } ] }); assert.strictEqual(this.getArea(0).attr.getCall(1).args[0]['class'], 'dxm-line', 'type'); assert.deepEqual(this.getLine(0).attr.getCall(0).args, [{ points: [ [400, 200, 800, 0, 1000, 600] ] }], 'line 1 (common)'); assert.deepEqual(this.getLine(1).attr.getCall(0).args, [{ points: [ [] // TODO: Investigate (should be points: []) ] }], 'line 2 (degenerate)'); }); QUnit.test('Markers (Point)', function(assert) { this.createLayer({ dataSource: createData('Point', [ [0, 100], [200, 200], [] ]) }); assert.strictEqual(this.getMarker(0).attr.getCall(1).args[0]['class'], 'dxm-marker', 'type'); assert.deepEqual(this.getMarker(0).attr.getCall(0).args, [{ translateX: 200, translateY: 400 }], 'Marker 1 (common)'); assert.deepEqual(this.getMarker(1).attr.getCall(0).args, [{ translateX: 600, translateY: 200 }], 'Marker 2 (common)'); assert.deepEqual(this.getMarker(2).attr.getCall(0).args, [{ translateX: NaN, translateY: NaN }], 'Marker 3 (degenerate)'); }); QUnit.test('Markers (simple data source)', function(assert) { this.createLayer({ dataSource: [ { coordinates: [0, 100] }, { coordinates: [200, 200] }, { coordinates: [] } ] }); assert.strictEqual(this.getMarker(0).attr.getCall(1).args[0]['class'], 'dxm-marker', 'type'); assert.deepEqual(this.getMarker(0).attr.getCall(0).args, [{ translateX: 200, translateY: 400 }], 'Marker 1 (common)'); assert.deepEqual(this.getMarker(1).attr.getCall(0).args, [{ translateX: 600, translateY: 200 }], 'Marker 2 (common)'); assert.deepEqual(this.getMarker(2).attr.getCall(0).args, [{ translateX: NaN, translateY: NaN }], 'Marker 3 (degenerate)'); }); QUnit.test('Area labels', function(assert) { this.renderer.bBoxTemplate = { x: 0, y: -15, width: 40, height: 20 }; this.createLayer({ dataSource: createData('Polygon', [ { coordinates: [ [[200, 100], [400, 100], [400, 150], [300, 200]] ], properties: { text: 'Item 1' } }, { coordinates: [ [[100, 50], [100, 150], [200, 150], [200, 50], [100, 50]], [[200, 200], [200, 220], [240, 220], [240, 200]] ], properties: { text: 'Item 2' } }, { coordinates: [ [[100, 100], [300, 100], [100, 100]] // T344899 ], properties: { text: 'Item 3' } }, { coordinates: [], // T344899 properties: { text: 'Item 4' } } ]), label: { enabled: true, dataField: 'text' } }); assert.deepEqual(getLabelPosition(this.getLabel(0)), [853, 353], 'label 1'); assert.deepEqual(getLabelPosition(this.getLabel(1)), [500, 400], 'label 2'); assert.deepEqual(getLabelPosition(this.getLabel(2)), [NaN, NaN], 'label 3 (degenerate)'); assert.deepEqual(getLabelPosition(this.getLabel(3)), [NaN, NaN], 'label 4 (degenerate)'); function getLabelPosition(label) { const arg = label.attr.getCall(1).args[0]; return [Math.round(arg.translateX), Math.round(arg.translateY)]; } }); QUnit.test('Line labels', function(assert) { this.createLayer({ dataSource: createData('LineString', [ { coordinates: [[100, 200], [300, 300], [400, 0]], properties: { text: 'Item 1' } }, { coordinates: [], // T344899 properties: { text: 'Item 2' } } ]), label: { enabled: true, dataField: 'text' } }); assert.deepEqual(getLabelPosition(this.getLabel(0)), [842, 125], 'label 1'); assert.deepEqual(getLabelPosition(this.getLabel(1)), [NaN, NaN], 'label 2 (degenerate)'); function getLabelPosition(label) { const arg = label.attr.getCall(1).args[0]; return [Math.round(arg.translateX), Math.round(arg.translateY)]; } }); QUnit.module('Layers management', { beforeEach: function() { const renderer = this.renderer = new vizMocks.Renderer(); rendererModule.Renderer = function() { return renderer; }; }, createLayers: function(options) { return $('#container').dxVectorMap({ layers: options }).dxVectorMap('instance'); } }); QUnit.test('Array option', function(assert) { const map = this.createLayers([ { name: 'layer-a' }, {}, { name: 'layer-b' }, {} ]); const layers = map.getLayers(); assert.strictEqual(layers.length, 4, 'count'); assert.strictEqual(layers[0].name, 'layer-a', 'layer 1 name'); assert.strictEqual(layers[1].name, 'map-layer-1', 'layer 2 name'); assert.strictEqual(layers[2].name, 'layer-b', 'layer 3 name'); assert.strictEqual(layers[3].name, 'map-layer-3', 'layer 4 name'); }); QUnit.test('Object option', function(assert) { const map = this.createLayers({ name: 'layer' }); const layers = map.getLayers(); assert.strictEqual(layers.length, 1, 'count'); assert.strictEqual(layers[0].name, 'layer', 'layer 1 name'); }); QUnit.test('Empty option', function(assert) { const map = this.createLayers(); assert.deepEqual(map.getLayers(), []); }); QUnit.test('Change option - increase layers count', function(assert) { const map = this.createLayers([ { name: 'layer-1' }, { name: 'layer-2' } ]); map.option('layers', [ {}, {}, { name: 'layer-3' } ]); const layers = map.getLayers(); assert.strictEqual(layers.length, 3, 'count'); assert.strictEqual(layers[0].name, 'map-layer-0', 'layer 1 name'); assert.strictEqual(layers[1].name, 'map-layer-1', 'layer 2 name'); assert.strictEqual(layers[2].name, 'layer-3', 'layer 3 name'); }); QUnit.test('Change option - decrease layers count', function(assert) { const map = this.createLayers([ { name: 'layer-1' }, { name: 'layer-2' }, { name: 'layer-3' } ]); map.option('layers', [ {}, {} ]); const layers = map.getLayers(); assert.strictEqual(layers.length, 2, 'count'); assert.strictEqual(layers[0].name, 'map-layer-0', 'layer 1 name'); assert.strictEqual(layers[1].name, 'map-layer-1', 'layer 2 name'); }); QUnit.test('Change name of one layer', function(assert) { const map = this.createLayers([ { name: 'layer-1' }, { name: 'layer-2' }, { name: 'layer-3' } ]); const oldLayers = map.getLayers(); map.option('layers', [ { name: 'layer-1' }, { name: 'new_layer-2' }, { name: 'layer-3' } ]); const updatedLayers = map.getLayers(); updatedLayers.forEach(function(l, i) { assert.ok(l !== oldLayers[i]); }); }); QUnit.test('Layers shouldn\'t be created on updating when name not set', function(assert) { const map = this.createLayers([ { color: 'some_color_1' } ]); const oldLayer = map.getLayers()[0]; map.option('layers', [{ color: 'some_color_1' }]); assert.ok(map.getLayers()[0] === oldLayer); }); QUnit.test('No crush on updating when on of layer in null', function(assert) { const map = this.createLayers([ { color: 'some_color_1' } ]); map.option('layers', [null]); assert.strictEqual(map.getLayers().length, 1); }); QUnit.test('Get layer by name', function(assert) { const map = this.createLayers([ { name: 'layer-a' }, {}, { name: 'layer-b' } ]); const layers = map.getLayers(); assert.strictEqual(map.getLayerByName('layer-a'), layers[0], 'layer 1'); assert.strictEqual(map.getLayerByName('map-layer-1'), layers[1], 'layer 2'); assert.strictEqual(map.getLayerByName('layer-b'), layers[2], 'layer 3'); assert.strictEqual(map.getLayerByName('test'), null, 'unknown name'); }); QUnit.test('Get layer by index', function(assert) { const map = this.createLayers([ {}, {}, {} ]); const layers = map.getLayers(); assert.strictEqual(map.getLayerByIndex(0), layers[0], 'layer 1'); assert.strictEqual(map.getLayerByIndex(1), layers[1], 'layer 2'); assert.strictEqual(map.getLayerByIndex(2), layers[2], 'layer 3'); assert.strictEqual(map.getLayerByIndex(3), null, 'not valid index'); }); QUnit.test('Change layer name', function(assert) { const map = this.createLayers([ { name: 'layer-1' }, {} ]); map.option('layers', [ { name: 'layer-2' }, {} ]); assert.ok(map.getLayerByName('layer-2'), 'get by new name'); assert.ok(!map.getLayerByName('layer-1'), 'get by old name'); const layers = map.getLayers(); assert.strictEqual(layers.length, 2, 'count'); assert.strictEqual(layers[0].name, 'layer-2', 'layer 1 name'); assert.strictEqual(layers[1].name, 'map-layer-1', 'layer 2 name'); }); QUnit.test('getDataSource method', function(assert) { const map = this.createLayers({ dataSource: createData('Polygon', [ [ [[100, 50], [200, 50], [200, 200], [100, 200]] ], [ [[200, 100], [400, 0], [400, 300]], [[0, 0], [0, 300], [400, 300], [400, 0]] ], [] ]) }); assert.ok(map.getLayers()[0].getDataSource() instanceof dataSourceModule.DataSource); }); QUnit.test('Bounds calculation', function(assert) { const map = this.createLayers({ dataSource: createData('Polygon', [ [ [[100, 50], [200, 50], [200, 200], [100, 200]] ], [ [[200, 100], [400, 0], [400, 300]], [[0, 0], [0, 300], [400, 300], [400, 0]] ], [] ]) }); const bounds = map.getLayers()[0].getBounds(); assert.deepEqual(bounds, [0, 0, 400, 300]); });
RyPC/FTCUltimateGoal
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/timeAutons/RebAubtob.java
package org.firstinspires.ftc.teamcode.timeAutons; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import org.firstinspires.ftc.teamcode.Constants; import org.firstinspires.ftc.teamcode.RobotHardware; @Autonomous(name="Reb Bowel", group="Auton") @Disabled public class RebAubtob extends LinearOpMode { RobotHardware robotHardware = new RobotHardware(this, telemetry); Constants constants = new Constants(); @Override public void runOpMode() { robotHardware.init(hardwareMap, true); waitForStart(); //start shooter robotHardware.shooter.setVelocity(constants.shooterPower); robotHardware.sleep(250); //drive to shoot pos robotHardware.drive(0.25, 1500); robotHardware.strafe(-0.25, 2000); robotHardware.sleep(500); //shoot power shots //1 robotHardware.turnTo(-9, 1); robotHardware.sleep(1500); robotHardware.cleanser.setPower(0.25); robotHardware.intake.setPower(0.4); robotHardware.shooter.setVelocity(1350); robotHardware.sleep(750); robotHardware.cleanser.setPower(0); robotHardware.intake.setPower(0); robotHardware.sleep(500); //2 robotHardware.shooter.setVelocity(1450); robotHardware.turnTo(-7, 1); robotHardware.cleanser.setPower(0.25); robotHardware.intake.setPower(0.4); robotHardware.sleep(700); robotHardware.cleanser.setPower(0); robotHardware.intake.setPower(0); robotHardware.sleep(500); //3 robotHardware.turnTo(-5, 1); robotHardware.cleanser.setPower(0.25); robotHardware.intake.setPower(0.4); robotHardware.sleep(1200); robotHardware.strafe(0.25,250); //last 0-4 rings //reverse intake robotHardware.shooter.setVelocity(constants.shooterPower); robotHardware.intake.setPower(-0.25); robotHardware.drive(0.15, 2000); robotHardware.intake.setPower(0.35); robotHardware.sleep(500); robotHardware.turnTo(5, 1); for(int i = 0; i < 6; i++) { robotHardware.drive(0.1, 1000); robotHardware.intake.setPower(-0.35); robotHardware.drive(0.1, 125); robotHardware.intake.setPower(0.35); } robotHardware.sleep(1000); robotHardware.shooter.setVelocity(0); robotHardware.cleanser.setPower(0); robotHardware.drive(0.5, 750); robotHardware.turnTo(-90, 1); robotHardware.wobbleArm.setPosition(constants.armDown); robotHardware.wobbleClamp.setPosition(constants.clampClosed); robotHardware.wobbleArm.setPosition(constants.armUp); robotHardware.strafe(-1, 250); robotHardware.turnTo(0, 1); } }
NReilingh/flux
stdlib/contrib/tomhollingworth/events/flux_gen.go
<filename>stdlib/contrib/tomhollingworth/events/flux_gen.go // DO NOT EDIT: This file is autogenerated via the builtin command. package events import ( ast "github.com/influxdata/flux/ast" runtime "github.com/influxdata/flux/runtime" ) func init() { runtime.RegisterPackage(pkgAST) } var pkgAST = &ast.Package{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: nil, }, Files: []*ast.File{&ast.File{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 17, Line: 14, }, File: "duration.flux", Source: "package events\n\n\n// duration will calculate the duration between records\n// for each record. The duration calculated is between\n// the current record and the next. The last record will\n// compare against either the stopColum (default: _stop)\n// or a stop timestamp value.\n//\n// `timeColumn` - Optional string. Default '_time'. The value used to calculate duration\n// `columnName` - Optional string. Default 'duration'. The name of the result column\n// `stopColumn` - Optional string. Default '_stop'. The name of the column to compare the last record on\n// `stop` - Optional Time. Use a fixed time to compare the last record against instead of stop column.\nbuiltin duration", Start: ast.Position{ Column: 1, Line: 1, }, }, }, Body: []ast.Statement{&ast.BuiltinStatement{ BaseNode: ast.BaseNode{ Comments: []ast.Comment{ast.Comment{Text: "// duration will calculate the duration between records\n"}, ast.Comment{Text: "// for each record. The duration calculated is between\n"}, ast.Comment{Text: "// the current record and the next. The last record will\n"}, ast.Comment{Text: "// compare against either the stopColum (default: _stop)\n"}, ast.Comment{Text: "// or a stop timestamp value.\n"}, ast.Comment{Text: "//\n"}, ast.Comment{Text: "// `timeColumn` - Optional string. Default '_time'. The value used to calculate duration\n"}, ast.Comment{Text: "// `columnName` - Optional string. Default 'duration'. The name of the result column\n"}, ast.Comment{Text: "// `stopColumn` - Optional string. Default '_stop'. The name of the column to compare the last record on\n"}, ast.Comment{Text: "// `stop` - Optional Time. Use a fixed time to compare the last record against instead of stop column.\n"}}, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 17, Line: 14, }, File: "duration.flux", Source: "builtin duration", Start: ast.Position{ Column: 1, Line: 14, }, }, }, Colon: nil, ID: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 17, Line: 14, }, File: "duration.flux", Source: "duration", Start: ast.Position{ Column: 9, Line: 14, }, }, }, Name: "duration", }, Ty: ast.TypeExpression{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 14, Line: 23, }, File: "duration.flux", Source: "(\n <-tables: [A],\n ?unit: duration,\n ?timeColumn: string,\n ?columnName: string,\n ?stopColumn: string,\n ?stop: time,\n) => [B] where\n A: Record,\n B: Record", Start: ast.Position{ Column: 20, Line: 14, }, }, }, Constraints: []*ast.TypeConstraint{&ast.TypeConstraint{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 14, Line: 22, }, File: "duration.flux", Source: "A: Record", Start: ast.Position{ Column: 5, Line: 22, }, }, }, Kinds: []*ast.Identifier{&ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 14, Line: 22, }, File: "duration.flux", Source: "Record", Start: ast.Position{ Column: 8, Line: 22, }, }, }, Name: "Record", }}, Tvar: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 6, Line: 22, }, File: "duration.flux", Source: "A", Start: ast.Position{ Column: 5, Line: 22, }, }, }, Name: "A", }, }, &ast.TypeConstraint{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 14, Line: 23, }, File: "duration.flux", Source: "B: Record", Start: ast.Position{ Column: 5, Line: 23, }, }, }, Kinds: []*ast.Identifier{&ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 14, Line: 23, }, File: "duration.flux", Source: "Record", Start: ast.Position{ Column: 8, Line: 23, }, }, }, Name: "Record", }}, Tvar: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 6, Line: 23, }, File: "duration.flux", Source: "B", Start: ast.Position{ Column: 5, Line: 23, }, }, }, Name: "B", }, }}, Ty: &ast.FunctionType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 9, Line: 21, }, File: "duration.flux", Source: "(\n <-tables: [A],\n ?unit: duration,\n ?timeColumn: string,\n ?columnName: string,\n ?stopColumn: string,\n ?stop: time,\n) => [B]", Start: ast.Position{ Column: 20, Line: 14, }, }, }, Parameters: []*ast.ParameterType{&ast.ParameterType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 18, Line: 15, }, File: "duration.flux", Source: "<-tables: [A]", Start: ast.Position{ Column: 5, Line: 15, }, }, }, Kind: "Pipe", Name: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 13, Line: 15, }, File: "duration.flux", Source: "tables", Start: ast.Position{ Column: 7, Line: 15, }, }, }, Name: "tables", }, Ty: &ast.ArrayType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 18, Line: 15, }, File: "duration.flux", Source: "[A]", Start: ast.Position{ Column: 15, Line: 15, }, }, }, ElementType: &ast.TvarType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 17, Line: 15, }, File: "duration.flux", Source: "A", Start: ast.Position{ Column: 16, Line: 15, }, }, }, ID: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 17, Line: 15, }, File: "duration.flux", Source: "A", Start: ast.Position{ Column: 16, Line: 15, }, }, }, Name: "A", }, }, }, }, &ast.ParameterType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 20, Line: 16, }, File: "duration.flux", Source: "?unit: duration", Start: ast.Position{ Column: 5, Line: 16, }, }, }, Kind: "Optional", Name: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 10, Line: 16, }, File: "duration.flux", Source: "unit", Start: ast.Position{ Column: 6, Line: 16, }, }, }, Name: "unit", }, Ty: &ast.NamedType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 20, Line: 16, }, File: "duration.flux", Source: "duration", Start: ast.Position{ Column: 12, Line: 16, }, }, }, ID: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 20, Line: 16, }, File: "duration.flux", Source: "duration", Start: ast.Position{ Column: 12, Line: 16, }, }, }, Name: "duration", }, }, }, &ast.ParameterType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 24, Line: 17, }, File: "duration.flux", Source: "?timeColumn: string", Start: ast.Position{ Column: 5, Line: 17, }, }, }, Kind: "Optional", Name: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 16, Line: 17, }, File: "duration.flux", Source: "timeColumn", Start: ast.Position{ Column: 6, Line: 17, }, }, }, Name: "timeColumn", }, Ty: &ast.NamedType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 24, Line: 17, }, File: "duration.flux", Source: "string", Start: ast.Position{ Column: 18, Line: 17, }, }, }, ID: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 24, Line: 17, }, File: "duration.flux", Source: "string", Start: ast.Position{ Column: 18, Line: 17, }, }, }, Name: "string", }, }, }, &ast.ParameterType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 24, Line: 18, }, File: "duration.flux", Source: "?columnName: string", Start: ast.Position{ Column: 5, Line: 18, }, }, }, Kind: "Optional", Name: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 16, Line: 18, }, File: "duration.flux", Source: "columnName", Start: ast.Position{ Column: 6, Line: 18, }, }, }, Name: "columnName", }, Ty: &ast.NamedType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 24, Line: 18, }, File: "duration.flux", Source: "string", Start: ast.Position{ Column: 18, Line: 18, }, }, }, ID: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 24, Line: 18, }, File: "duration.flux", Source: "string", Start: ast.Position{ Column: 18, Line: 18, }, }, }, Name: "string", }, }, }, &ast.ParameterType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 24, Line: 19, }, File: "duration.flux", Source: "?stopColumn: string", Start: ast.Position{ Column: 5, Line: 19, }, }, }, Kind: "Optional", Name: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 16, Line: 19, }, File: "duration.flux", Source: "stopColumn", Start: ast.Position{ Column: 6, Line: 19, }, }, }, Name: "stopColumn", }, Ty: &ast.NamedType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 24, Line: 19, }, File: "duration.flux", Source: "string", Start: ast.Position{ Column: 18, Line: 19, }, }, }, ID: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 24, Line: 19, }, File: "duration.flux", Source: "string", Start: ast.Position{ Column: 18, Line: 19, }, }, }, Name: "string", }, }, }, &ast.ParameterType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 16, Line: 20, }, File: "duration.flux", Source: "?stop: time", Start: ast.Position{ Column: 5, Line: 20, }, }, }, Kind: "Optional", Name: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 10, Line: 20, }, File: "duration.flux", Source: "stop", Start: ast.Position{ Column: 6, Line: 20, }, }, }, Name: "stop", }, Ty: &ast.NamedType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 16, Line: 20, }, File: "duration.flux", Source: "time", Start: ast.Position{ Column: 12, Line: 20, }, }, }, ID: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 16, Line: 20, }, File: "duration.flux", Source: "time", Start: ast.Position{ Column: 12, Line: 20, }, }, }, Name: "time", }, }, }}, Return: &ast.ArrayType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 9, Line: 21, }, File: "duration.flux", Source: "[B]", Start: ast.Position{ Column: 6, Line: 21, }, }, }, ElementType: &ast.TvarType{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 8, Line: 21, }, File: "duration.flux", Source: "B", Start: ast.Position{ Column: 7, Line: 21, }, }, }, ID: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 8, Line: 21, }, File: "duration.flux", Source: "B", Start: ast.Position{ Column: 7, Line: 21, }, }, }, Name: "B", }, }, }, }, }, }}, Eof: nil, Imports: nil, Metadata: "parser-type=rust", Name: "duration.flux", Package: &ast.PackageClause{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 15, Line: 1, }, File: "duration.flux", Source: "package events", Start: ast.Position{ Column: 1, Line: 1, }, }, }, Name: &ast.Identifier{ BaseNode: ast.BaseNode{ Comments: nil, Errors: nil, Loc: &ast.SourceLocation{ End: ast.Position{ Column: 15, Line: 1, }, File: "duration.flux", Source: "events", Start: ast.Position{ Column: 9, Line: 1, }, }, }, Name: "events", }, }, }}, Package: "events", Path: "contrib/tomhollingworth/events", }
ik-wmua/wmua-finance
app/org/intracer/finance/slick/Projects.scala
package org.intracer.finance.slick import org.intracer.finance.Project import slick.driver.H2Driver.api._ class Projects(tag: Tag) extends Table[Project](tag, "project") { def id = column[Int]("id", O.PrimaryKey, O.AutoInc) def name = column[String]("name") def nameIndex = index("project_name", name, unique = true) def * = (id.?, name) <> (Project.tupled, Project.unapply) }
MarcusTw/tp
src/test/java/atas/storage/StorageManagerTest.java
<filename>src/test/java/atas/storage/StorageManagerTest.java package atas.storage; import static atas.testutil.TypicalMemos.SAMPLE_MEMO_ONE; import static atas.testutil.TypicalStudents.getTypicalStudentList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.nio.file.Path; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import atas.commons.core.GuiSettings; import atas.model.UserPrefs; import atas.model.memo.Memo; import atas.model.student.ReadOnlyStudentList; import atas.model.student.StudentList; public class StorageManagerTest { @TempDir public Path testFolder; private StorageManager storageManager; @BeforeEach public void setUp() { JsonSessionListStorage sessionListStorage = new JsonSessionListStorage(getTempFilePath("sl")); JsonAtasStorage studentListStorage = new JsonAtasStorage(getTempFilePath("ab")); JsonUserPrefsStorage userPrefsStorage = new JsonUserPrefsStorage(getTempFilePath("prefs")); TxtMemoStorage memoStorage = new TxtMemoStorage(getTempFilePath("memo")); storageManager = new StorageManager(sessionListStorage, studentListStorage, userPrefsStorage, memoStorage); } private Path getTempFilePath(String fileName) { return testFolder.resolve(fileName); } @Test public void prefsReadSave() throws Exception { /* * Note: This is an integration test that verifies the StorageManager is properly wired to the * {@link JsonUserPrefsStorage} class. * More extensive testing of UserPref saving/reading is done in {@link JsonUserPrefsStorageTest} class. */ UserPrefs original = new UserPrefs(); original.setGuiSettings(new GuiSettings(300, 600, 4, 6)); storageManager.saveUserPrefs(original); UserPrefs retrieved = storageManager.readUserPrefs().get(); assertEquals(original, retrieved); } @Test public void studentListReadSave() throws Exception { /* * Note: This is an integration test that verifies the StorageManager is properly wired to the * {@link JsonStudentListStorage} class. * More extensive testing of UserPref saving/reading is done in {@link JsonStudentListStorageTest} class. */ StudentList original = getTypicalStudentList(); storageManager.saveStudentList(original); ReadOnlyStudentList retrieved = storageManager.readStudentList().get(); assertEquals(original, new StudentList(retrieved)); } @Test public void getStudentListFilePath() { assertNotNull(storageManager.getStudentListFilePath()); } @Test public void testSaveMemo() throws Exception { Memo original = SAMPLE_MEMO_ONE; storageManager.saveMemo(original); String retrieved = storageManager.readMemo(); assertEquals(original, new Memo(retrieved)); } @Test public void getMemoFilePath() { assertNotNull(storageManager.getMemoFilePath()); } }
airbug/bugcore
libraries/bugcore/js/test/flow/FlowsTests.js
/* * Copyright (c) 2016 airbug Inc. http://airbug.com * * bugcore may be freely distributed under the MIT license. */ //------------------------------------------------------------------------------- // Annotations //------------------------------------------------------------------------------- //@TestFile //@Require('Class') //@Require('Flows') //@Require('Promise') //@Require('Promises') //@Require('TypeUtil') //@Require('bugmeta.BugMeta') //@Require('bugunit.TestTag') //------------------------------------------------------------------------------- // Context //------------------------------------------------------------------------------- require('bugpack').context("*", function(bugpack) { //------------------------------------------------------------------------------- // BugPack //------------------------------------------------------------------------------- var Class = bugpack.require('Class'); var Flows = bugpack.require('Flows'); var Promise = bugpack.require('Promise'); var Promises = bugpack.require('Promises'); var TypeUtil = bugpack.require('TypeUtil'); var BugMeta = bugpack.require('bugmeta.BugMeta'); var TestTag = bugpack.require('bugunit.TestTag'); //------------------------------------------------------------------------------- // Simplify References //------------------------------------------------------------------------------- var bugmeta = BugMeta.context(); var test = TestTag.test; //------------------------------------------------------------------------------- // Declare Tests //------------------------------------------------------------------------------- /** * This tests.. * 1) Adding a callback to end of series * 2) Returning a promise from task within series * 3) Ensuring that callback receives values resolved by last task in series */ var flowsResolveSeriesWithPromiseToCallbackTest = { async: true, // Setup Test //------------------------------------------------------------------------------- setup: function(test) { var _this = this; this.testValue = "TestValue"; this.testDeferred = Promises.deferred(); this.testSeries = Flows.$series([ function() { setTimeout(function() { _this.testDeferred.resolve(_this.testValue); }, 0); return _this.testDeferred.promise(); } ]); test.completeSetup(); }, // Run Test //------------------------------------------------------------------------------- test: function(test) { var _this = this; this.testSeries.callback(function(throwable, value) { if (!throwable) { test.assertEqual(value, _this.testValue, "Assert value received in callback is equal to testValue"); } else { test.error(throwable); } test.completeTest(); }) } }; /** * This tests.. * 1) Adding a callback to end of series * 2) Returning a promise from task within series * 3) Ensuring that callback receives values resolved by last task in series */ var flowsResolveSeriesWithPromiseToForwardPromiseTest = { async: true, // Setup Test //------------------------------------------------------------------------------- setup: function(test) { var _this = this; this.testValue = "TestValue"; this.testDeferred = Promises.deferred(); this.testSeries = Flows.$series([ function() { setTimeout(function() { _this.testDeferred.resolve(_this.testValue); }, 0); return _this.testDeferred.promise(); } ]); test.completeSetup(); }, // Run Test //------------------------------------------------------------------------------- test: function(test) { var _this = this; var forwardPromise = this.testSeries.callback(); test.assertTrue(Class.doesExtend(forwardPromise, Promise), "Assert Series.callback method returns a promise"); if (Class.doesExtend(forwardPromise, Promise)) { forwardPromise .then(function(value) { //TEST console.log("Type:", TypeUtil.toType(_this.testValue), " testValue:", _this.testValue); console.log("Type:", TypeUtil.toType(value), " value:", value); test.assertEqual(value, _this.testValue, "Assert value received in forwardPromise.then is equal to testValue"); }) .catch(function(throwable) { test.error(throwable); }) .finally(function() { test.completeTest(); }); } else { test.completeTest(); } } }; /** * This tests.. * 1) Returning a promise from Task * 2) Ensuring that callback receives values resolved by Promise returned from Task */ var flowsResolveTaskWithPromiseTest = { async: true, // Setup Test //------------------------------------------------------------------------------- setup: function(test) { var _this = this; this.testValue = "TestValue"; this.testDeferred = Promises.deferred(); this.testTask = Flows.$task(function() { setTimeout(function() { _this.testDeferred.resolve(_this.testValue); }, 0); return _this.testDeferred.promise(); }); test.completeSetup(); }, // Run Test //------------------------------------------------------------------------------- test: function(test) { var _this = this; this.testTask.execute(function(throwable, value) { test.assertEqual(value, _this.testValue, "Assert value received in callback is equal to testValue"); test.completeTest(); }) } }; //------------------------------------------------------------------------------- // BugMeta //------------------------------------------------------------------------------- bugmeta.tag(flowsResolveSeriesWithPromiseToCallbackTest).with( test().name("Flows - resolve Series with Promise to callback test") ); bugmeta.tag(flowsResolveSeriesWithPromiseToForwardPromiseTest).with( test().name("Flows - resolve Series with Promise to forward Promise test") ); bugmeta.tag(flowsResolveTaskWithPromiseTest).with( test().name("Flows - resolve Task with Promise test") ); });
anterostecnologia/anterosrestdocmavenplugin
src/main/java/br/com/anteros/restdoc/maven/plugin/doclet/writer/swagger/model/Operation.java
/******************************************************************************* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package br.com.anteros.restdoc.maven.plugin.doclet.writer.swagger.model; import java.util.Collection; import static br.com.anteros.restdoc.maven.plugin.util.CommonUtils.isEmpty; public class Operation { private final String method; private final String nickname; private final String notes; private final String summary; private final String type; private final Collection<String> produces; private final Collection<String> consumes; private final Collection<Parameter> parameters; public Operation(String method, String nickname, String notes, String summary, String type, Collection<String> produces, Collection<String> consumes, Collection<Parameter> parameters) { this.method = method; this.nickname = nickname; this.notes = notes; this.summary = summary; this.type = type; this.produces = (isEmpty(produces) ? null : produces); this.consumes = (isEmpty(consumes) ? null : consumes); this.parameters = (isEmpty(parameters) ? null : parameters); } public String getMethod() { return method; } public String getNickname() { return nickname; } public String getNotes() { return notes; } public String getSummary() { return summary; } public String getType() { return type; } public Collection<String> getProduces() { return produces; } public Collection<String> getConsumes() { return consumes; } public Collection<Parameter> getParameters() { return parameters; } }
realDragon11/Trawel-Text
Dragon's Trawel/src/trawel/QuestR.java
<gh_stars>1-10 package trawel; import java.io.Serializable; public abstract class QuestR implements Serializable { /** * */ private static final long serialVersionUID = 1L; public abstract String getName(); public abstract boolean go(); public Quest overQuest; public Town locationT; public Feature locationF; public void cleanup() { locationF.removeQR(this); } }
vishnudevk/MiBandDecompiled
Original Files/source/src/com/sina/weibo/sdk/constant/WBConstants.java
<reponame>vishnudevk/MiBandDecompiled // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.sina.weibo.sdk.constant; public class WBConstants { public static final String ACTION_WEIBO_REGISTER = "com.sina.weibo.sdk.Intent.ACTION_WEIBO_REGISTER"; public static final String ACTION_WEIBO_RESPONSE = "com.sina.weibo.sdk.Intent.ACTION_WEIBO_RESPONSE"; public static final String ACTION_WEIBO_SDK_PERMISSION = "com.sina.weibo.permission.WEIBO_SDK_PERMISSION"; public static final String ACTIVITY_REQ_SDK = "com.sina.weibo.sdk.action.ACTION_SDK_REQ_ACTIVITY"; public static final String ACTIVITY_RESP_SDK = "com.sina.weibo.sdk.action.ACTION_SDK_RESP_ACTIVITY"; public static final String ACTIVITY_WEIBO = "com.sina.weibo.sdk.action.ACTION_WEIBO_ACTIVITY"; public static final String AUTH_PARAMS_CLIENT_ID = "client_id"; public static final String AUTH_PARAMS_CLIENT_SECRET = "client_secret"; public static final String AUTH_PARAMS_CODE = "code"; public static final String AUTH_PARAMS_DISPLAY = "display"; public static final String AUTH_PARAMS_GRANT_TYPE = "grant_type"; public static final String AUTH_PARAMS_KEY_HASH = "key_hash"; public static final String AUTH_PARAMS_PACKAGE_NAME = "packagename"; public static final String AUTH_PARAMS_REDIRECT_URL = "redirect_uri"; public static final String AUTH_PARAMS_RESPONSE_TYPE = "response_type"; public static final String AUTH_PARAMS_SCOPE = "scope"; public static final int COMMAND_FROM_WEIBO = 2; public static final int COMMAND_SSO = 3; public static final int COMMAND_TO_WEIBO = 1; public static final String COMMAND_TYPE_KEY = "_weibo_command_type"; public static final int SDK_ACTIVITY_FOR_RESULT_CODE = 765; public static final String SIGN = "_weibo_sign"; public static final String SSO_APP_KEY = "appKey"; public static final String SSO_KEY_HASH = "key_hash"; public static final String SSO_PACKAGE_NAME = "packagename"; public static final String SSO_REDIRECT_URL = "redirectUri"; public static final String SSO_USER_SCOPE = "scope"; public static final String TRAN = "_weibo_transaction"; public static final String WEIBO_DOWNLOAD_URL = "http://app.sina.cn/appdetail.php?appID=84560"; public static final int WEIBO_FLAG_SDK = 0x20130329; public static final int WEIBO_SDK_VERSION = 22; public static final String WEIBO_SDK_VERSION_NAME = "2.2"; public WBConstants() { } }
cycere/quid
src/Common/ConsoleTools.h
// Copyright (c) 2011-2016 The Cryptonote developers // Copyright (c) 2017-2021 The Cycere developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <cstdint> namespace Common { namespace Console { enum class Color : uint8_t { Default, Blue, Green, Red, Yellow, White, Cyan, Magenta, BrightBlue, BrightGreen, BrightRed, BrightYellow, BrightWhite, BrightCyan, BrightMagenta }; void setTextColor(Color color); bool isConsoleTty(); }}
samuelsilvadev/react-projects
instagram-copy/client/src/components/App.js
<gh_stars>1-10 import React from 'react'; import { ApolloProvider } from 'react-apollo'; import ApolloClient from 'apollo-boost'; import { Main } from './App.style'; import Header from './header'; import Posts from './posts'; const client = new ApolloClient({ uri: `${process.env.SERVER_URI}graphql`, }); const App = () => ( <ApolloProvider client={client}> <Header /> <Main> <Posts /> </Main> </ApolloProvider> ); export default App;
make-sans/developool
client/src/constants/Skills.js
export const SKILLS = [ 'C#', 'JavaScript', 'React.js', 'Node.js', 'Kotlin', 'HTML/CSS', 'Android', 'Java', 'iOS', 'Objective C', 'Swift', 'React Native', 'Flutter', 'Ionic', 'Cordova', 'Ruby', 'PHP', 'Python', 'Django', 'Flask', 'MySQL', 'SQL', 'Postgres', 'SQLite', 'Mongo', 'VueJS', 'AngularJS', 'Docker', 'Kubernetes' ];
TimSnedden138/CodeDesignAndStructure
FactoryPattern/IFactory.h
#pragma once #include "IBox.h" #include <iostream> class IFactory { public: //Make sure that all derived classes HAVE a create method virtual IBox* Create(std::string type) = 0; };
Aurorasic/Swiftglobal
blockchain-app/src/main/java/com/higgsblock/global/chain/app/task/InventoryTask.java
<reponame>Aurorasic/Swiftglobal package com.higgsblock.global.chain.app.task; import com.higgsblock.global.chain.app.blockchain.BlockIndex; import com.higgsblock.global.chain.app.blockchain.IBlockChainService; import com.higgsblock.global.chain.app.blockchain.listener.MessageCenter; import com.higgsblock.global.chain.app.service.impl.BlockIndexService; import com.higgsblock.global.chain.app.sync.message.Inventory; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; /** * @author baizhengwen * @date 2018/3/23 */ @Slf4j @Component public class InventoryTask extends BaseTask { @Autowired private MessageCenter messageCenter; @Autowired private IBlockChainService blockChainService; @Autowired private BlockIndexService blockIndexService; @Override protected void task() { long height = blockChainService.getMaxHeight(); BlockIndex blockIndex = blockIndexService.getBlockIndexByHeight(height); if (blockIndex != null && CollectionUtils.isNotEmpty(blockIndex.getBlockHashs())) { Set<String> set = new HashSet<>(blockIndex.getBlockHashs()); Inventory inventory = new Inventory(height, set); messageCenter.broadcast(inventory); } } @Override protected long getPeriodMs() { return TimeUnit.SECONDS.toMillis(3); } }
FAD95/NEXT.JS-Course
node_modules/@iconify/icons-mdi/src/nix.js
<filename>node_modules/@iconify/icons-mdi/src/nix.js let data = { "body": "<path d=\"M9.9 8.7L5 17.2l-1.1-1.9L5.2 13H2.6L2 12l.6-1h3.7l1.3-2.3h2.3m.3 6.8h9.7l-1.1 1.9h-2.6l1.3 2.3l-.6 1h-1.1L14 17.4h-2.7l-1.1-1.9m5.7-3.7L11 3.3h2.2l1.3 2.3l1.3-2.3h1.1l.6 1l-1.9 3.2L17 9.8l-1.1 2m-2.1-3.3H4l1.1-1.9h2.6L6.4 4.3l.6-1h1.1L10 6.5h2.7l1.1 2m.3 6.8L19 6.8l1.1 1.9l-1.3 2.3h2.6l.6 1l-.6 1h-3.7l-1.3 2.3h-2.3m-6-3.1l4.9 8.4h-2.2l-1.3-2.3l-1.1 2.3H7.1l-.6-1l1.9-3.2L7 14.2l1.1-2z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; export default data;
commercetools/commercetools-payment-integration-java
payone-adapter/src/test/java/io/sphere/sdk/carts/CartTestImpl.java
package io.sphere.sdk.carts; import com.neovisionaries.i18n.CountryCode; import io.sphere.sdk.cartdiscounts.CartDiscount; import io.sphere.sdk.customergroups.CustomerGroup; import io.sphere.sdk.discountcodes.DiscountCodeInfo; import io.sphere.sdk.models.Address; import io.sphere.sdk.models.KeyReference; import io.sphere.sdk.models.Reference; import io.sphere.sdk.stores.Store; import io.sphere.sdk.types.CustomFields; import javax.annotation.Nullable; import javax.money.MonetaryAmount; import java.time.ZonedDateTime; import java.util.List; import java.util.Locale; /** * <i>KISS</i> implementation of {@link Cart} interface for tests purpose: * it has public properties for all the interface methods, so may be easily changed during the tests. * <p> * <b>Developers</b>: the implementation is not completely finished, so add required getters' properties * when you need them. * </p> */ public class CartTestImpl implements Cart { // Dummy Interface implementation. Look for related properties at the bottom of the class. @Override public CartState getCartState() { return null; } @Override public InventoryMode getInventoryMode() { return null; } @Nullable @Override public CartShippingInfo getShippingInfo() { return null; } @Nullable @Override public Address getBillingAddress() { return null; } @Nullable @Override public CountryCode getCountry() { return null; } @Nullable @Override public String getCustomerEmail() { return null; } @Nullable @Override public Reference<CustomerGroup> getCustomerGroup() { return null; } @Nullable @Override public String getCustomerId() { return null; } @Override public List<CustomLineItem> getCustomLineItems() { return null; } @Override public List<LineItem> getLineItems() { return null; } @Nullable @Override public Address getShippingAddress() { return null; } @Nullable @Override public TaxedPrice getTaxedPrice() { return null; } @Override public TaxCalculationMode getTaxCalculationMode() { return null; } @Override public MonetaryAmount getTotalPrice() { return totalPrice; } @Override public List<DiscountCodeInfo> getDiscountCodes() { return null; } @Nullable @Override public CustomFields getCustom() { return null; } @Nullable @Override public PaymentInfo getPaymentInfo() { return null; } @Override public TaxMode getTaxMode() { return null; } @Nullable @Override public String getAnonymousId() { return null; } @Nullable @Override public Locale getLocale() { return locale; } @Override public String getId() { return null; } @Override public Long getVersion() { return null; } @Override public ZonedDateTime getCreatedAt() { return null; } @Override public ZonedDateTime getLastModifiedAt() { return null; } @Nullable @Override public Integer getDeleteDaysAfterLastModification() { return null; } @Override public RoundingMode getTaxRoundingMode() { return null; } @Nullable @Override public List<Reference<CartDiscount>> getRefusedGifts() { return null; } @Nullable @Override public ShippingRateInput getShippingRateInput() { return null; } @Override public CartOrigin getOrigin() { return null; } @Override public List<Address> getItemShippingAddresses() { return null; } @Nullable @Override public KeyReference<Store> getStore() { return null; } // Put the properties for the getters here // we keep them public for easy mocking public MonetaryAmount totalPrice; public Locale locale; }
BIJOY-SUST/ACM---ICPC
Competitive Programing Problem Solutions/Graph Theory/Rope in the labi/Rope in the Labyrinth.cpp
<reponame>BIJOY-SUST/ACM---ICPC ///Problem = Timus Online Judge/1145. Rope in the Labyrinth/ট্রি ডায়ামিটার #include<bits/stdc++.h> using namespace std; int fx[]={1,-1,0,0}; int fy[]={0,0,1,-1}; int mr,mc,mx=0; char w[1000][1000];///The Input array............... int d[1000][1000];///d == Distance................... int r,c; void BFS(int x,int y,int dep) { queue<pair<int,int> >q; q.push(make_pair(x,y)); memset(d,100,sizeof(d)); d[x][y]=0; while(!q.empty()){ pair<int,int>top=q.front(); q.pop(); if(d[top.first][top.second]>mx){ mx=d[top.first][top.second]; mr=top.first; mc=top.second; } for(int k=0;k<4;k++){ int tx=top.first+fx[k]; int ty=top.second+fy[k]; if(tx>=0 && tx<r && ty>=0 && ty<c && w[tx][ty]=='.' && d[top.first][top.second]+1<d[tx][ty]){ q.push(make_pair(tx,ty)); d[tx][ty]=d[top.first][top.second]+1; } } } } int main(){ int sx,sy,cc=0; cin>>r>>c; swap(r,c); for(int i=0;i<r;i++){ cin>>w[i]; } for(int i=0;i<r;i++){ for(int j=0;j<c;j++){ if(w[i][j]=='.'){ sx=i;sy=j;cc++; } } } //cout<<sx<<sy<<mx<<endl; BFS(sx,sy,0); mx=0; //out<<mr<<mc<<mx<<endl; BFS(mr,mc,0); //cout<<mr<<mc<<mx<<endl; if(cc==1){ mx=0; } cout<<mx<<endl; return 0; }
Bahmni-Covid19/health-information-user
src/test/java/in/org/projecteka/hiu/dataflow/HealthInfoControllerTest.java
package in.org.projecteka.hiu.dataflow; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.nimbusds.jose.jwk.JWKSet; import in.org.projecteka.hiu.Caller; import in.org.projecteka.hiu.DestinationsConfig; import in.org.projecteka.hiu.common.Authenticator; import in.org.projecteka.hiu.consent.ConceptValidator; import in.org.projecteka.hiu.consent.PatientConsentRepository; import in.org.projecteka.hiu.dataflow.model.PatientDataRequestMapping; import in.org.projecteka.hiu.dataflow.model.DataPartDetail; import in.org.projecteka.hiu.dataflow.model.HealthInfoStatus; import in.org.projecteka.hiu.dataflow.model.PatientHealthInfoStatus; import in.org.projecteka.hiu.dataflow.model.DataRequestStatus; import in.org.projecteka.hiu.dataflow.model.DataRequestStatusResponse; import in.org.projecteka.hiu.dataflow.model.DataRequestStatusCheckRequest; import in.org.projecteka.hiu.dataprocessor.DataAvailabilityListener; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import static in.org.projecteka.hiu.common.Constants.API_PATH_FETCH_PATIENT_HEALTH_INFO; import static in.org.projecteka.hiu.common.Constants.API_PATH_GET_HEALTH_INFO_STATUS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import static reactor.core.publisher.Mono.just; @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureWebTestClient class HealthInfoControllerTest { @MockBean @Qualifier("userAuthenticator") private Authenticator authenticator; @SuppressWarnings("unused") @MockBean @Qualifier("centralRegistryJWKSet") private JWKSet centralRegistryJWKSet; @SuppressWarnings("unused") @MockBean @Qualifier("identityServiceJWKSet") private JWKSet identityServiceJWKSet; @SuppressWarnings("unused") @MockBean private DataAvailabilityListener dataAvailabilityListener; @SuppressWarnings("unused") @MockBean private DestinationsConfig destinationsConfig; @SuppressWarnings("unused") @MockBean private DataFlowRequestListener dataFlowRequestListener; @SuppressWarnings("unused") @MockBean private DataFlowDeleteListener dataFlowDeleteListener; @Autowired private WebTestClient webTestClient; @MockBean private DataFlowServiceProperties serviceProperties; @MockBean private PatientConsentRepository patientConsentRepository; @MockBean private DataFlowRepository dataFlowRepository; @MockBean private HealthInformationRepository healthInformationRepository; @SuppressWarnings("unused") @MockBean private ConceptValidator conceptValidator; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); when(serviceProperties.getDefaultPageSize()).thenReturn(20); when(serviceProperties.getMaxPageSize()).thenReturn(20); when(serviceProperties.getDataFlowRequestWaitTime()).thenReturn(2); when(serviceProperties.getDataPartWaitTime()).thenReturn(2); } @Test void shouldFetchDataPartDetails() { ArgumentCaptor<List<String>> transactionIdsCaptor = ArgumentCaptor.forClass(List.class); var token = TestBuilders.string(); var requester = "some<EMAIL>"; var caller = new Caller(requester, false, null, true); var healthInfoRequest = TestBuilders.healthInformationRequest().limit(10).build(); var dataRequestMappings = TestBuilders.dataRequestMappings(2).stream() .map(PatientDataRequestMapping.PatientDataRequestMappingBuilder::build) .collect(Collectors.toList()); var consentRequestIds = dataRequestMappings.stream().map(PatientDataRequestMapping::getConsentRequestId).collect(Collectors.toList()); var dataPartDetails = TestBuilders.dataPartDetails(2, requester, HealthInfoStatus.SUCCEEDED) .stream().map(DataPartDetail.DataPartDetailBuilder::build).collect(Collectors.toList()); var transactionIds = dataPartDetails.stream().map(DataPartDetail::getTransactionId).collect(Collectors.toList()); List<Map<String, Object>> healthInfo = List.of(Map.of( "data", JsonNodeFactory.instance.objectNode(), "status", "SUCCEEDED", "transaction_id", transactionIds.get(0), "doc_id", "1.v1", "doc_origin", "hip1d-11")); when(authenticator.verify(token)).thenReturn(just(caller)); when(patientConsentRepository.fetchConsentRequestIds(healthInfoRequest.getRequestIds())).thenReturn(Flux.fromIterable(dataRequestMappings)); when(dataFlowRepository.fetchDataPartDetails(consentRequestIds)).thenReturn(Flux.fromIterable(dataPartDetails)); when(healthInformationRepository.getHealthInformation(transactionIdsCaptor.capture(), eq(healthInfoRequest.getLimit()), eq(healthInfoRequest.getOffset()))) .thenReturn(Flux.fromIterable(healthInfo)); when(healthInformationRepository.getTotalCountOfEntries(transactionIdsCaptor.capture())).thenReturn(Mono.just(100)); webTestClient .post() .uri(API_PATH_FETCH_PATIENT_HEALTH_INFO) .header("Authorization", token) .contentType(MediaType.APPLICATION_JSON) .bodyValue(healthInfoRequest) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus() .isOk(); assertEquals(Set.copyOf(transactionIds), Set.copyOf(transactionIdsCaptor.getValue())); } private void assertHealthInfoStatus(String token, DataRequestStatusCheckRequest request, DataRequestStatusResponse expectedResponse) throws JsonProcessingException { webTestClient .post() .uri(API_PATH_GET_HEALTH_INFO_STATUS) .header("Authorization", token) .contentType(MediaType.APPLICATION_JSON) .bodyValue(request) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus() .isOk() .expectBody() .json(new ObjectMapper() .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .writeValueAsString(expectedResponse)); } @Test void shouldReturnSucceededStatusForGivenDataRequestIds() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail().dataPartStatus(HealthInfoStatus.SUCCEEDED).patientId(requester).build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.SUCCEEDED) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnPartialStatusForGivenDataRequestIds() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail().dataPartStatus(HealthInfoStatus.PARTIAL).patientId(requester).build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.PARTIAL) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnProcessingStatusWhenDataPartIsBeingProcessed() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail().dataPartStatus(HealthInfoStatus.PROCESSING).patientId(requester).build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.PROCESSING) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnErroredStatusWhenDataPartHasAllEntriesErrored() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail().dataPartStatus(HealthInfoStatus.ERRORED).patientId(requester).build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.ERRORED) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnProcessingStatusWhenConsentRequestIsNotCreatedAndWaitingTimeIsNotPassed() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail() .consentRequestId(null) .patientDataRequestedAt(LocalDateTime.now(ZoneOffset.UTC)) .patientId(requester) .build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.PROCESSING) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnProcessingStatusWhenConsentArtefactIsNotReachedAndWaitingTimeIsNotPassed() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail() .consentArtefactId(null) .patientId(requester) .patientDataRequestedAt(LocalDateTime.now(ZoneOffset.UTC).minusMinutes(1)) .build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.PROCESSING) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnProcessingStatusWhenDataFlowIsNotReachedAndWaitingTimeIsNotPassed() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@<EMAIL>"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail() .dataPartStatus(null) .dataFlowRequestedAt(LocalDateTime.now(ZoneOffset.UTC)) .patientId(requester) .build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.PROCESSING) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnErroredStatusWhenDataFlowIsNotReachedWithinWatingTimeLimit() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail() .dataPartStatus(null) .patientId(requester) .dataFlowRequestedAt(LocalDateTime.now(ZoneOffset.UTC).minusMinutes(5)) .build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.ERRORED) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnErroredStatusWhenConsentArtefactNotReachedWithinWatingTimeLimit() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail() .consentArtefactId(null) .patientDataRequestedAt(LocalDateTime.now(ZoneOffset.UTC).minusMinutes(5)) .patientId(requester) .build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.ERRORED) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnErroredStatusWhenConsentRequestIsNotCreatedWithinWatingTimeLimit() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail() .consentRequestId(null) .patientDataRequestedAt(LocalDateTime.now(ZoneOffset.UTC).minusMinutes(5)) .patientId(requester) .build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); var expectedResponse = DataRequestStatusResponse.builder().statuses( List.of(PatientHealthInfoStatus.builder() .hipId(dataRequestDetail.getHipId()) .requestId(dataRequestDetail.getDataRequestId()) .status(DataRequestStatus.ERRORED) .build())).build(); assertHealthInfoStatus(token, dataStatusCheckRequest, expectedResponse); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } @Test void shouldReturnEmptyStatusesDataRequestIdDoesntBelongToRequester() throws JsonProcessingException { var token = TestBuilders.string(); var requester = "someone@ncg"; var caller = new Caller(requester, false, null, true); var dataRequestIds = List.of(UUID.randomUUID().toString()); var dataStatusCheckRequest = DataRequestStatusCheckRequest.builder().requestIds(dataRequestIds).build(); ArgumentCaptor<Set<String>> dataRequestIdsCaptor = ArgumentCaptor.forClass(Set.class); var dataRequestDetail = TestBuilders.patientDataRequestDetail() .consentRequestId(null) .patientDataRequestedAt(LocalDateTime.now(ZoneOffset.UTC).minusMinutes(5)) .patientId("some-other-request@ncg") .build(); when(authenticator.verify(token)).thenReturn(just(caller)); when(dataFlowRepository.fetchPatientDataRequestDetails(dataRequestIdsCaptor.capture())).thenReturn(Flux.just(dataRequestDetail)); assertHealthInfoStatus(token, dataStatusCheckRequest, new DataRequestStatusResponse(List.of())); assertEquals(dataRequestIdsCaptor.getValue(), Set.copyOf(dataRequestIds)); } }
lofunz/mieme
Reloaded/trunk/src/mame/drivers/playmark.c
<gh_stars>10-100 /*************************************************************************** Big Twins World Beach Volley Excelsior Hot Mind Hard Times driver by <NAME> and <NAME> The games run on different, but similar, hardware. The sprite system is the same (almost - the tile size is different). Even if some games are from the same year, World Beach Volley is much more advanced - more colourful, and stores setting in an EEPROM. An interesting thing about this hardware is that the same gfx ROMs are used to generate both 8x8 and 16x16 tiles for different tilemaps. Hard Times and Hot Mind have different tilemaps layout than the other ones. Hard Times was hacked from Blood Bros. program code. Hot Mind is a romswap kit for Hard Times pcb, in fact it was found in a pcb marked as HARD TIMES 28-06-94. Original Bugs: - World Beach Volley histogram functions don't work. TODO: - World Beach Volley sound is controlled by a pic16c57 whose ROM is missing for this game. - One stage in Hard Times has large white blocks instead of GFX in places, are they using an invalid tile number that should be invisible? - In Hard Times the last boss appears on left side of screen as it scrolls into view, are we missing part of the X co-ordinate? ***************************************************************************/ #include "emu.h" #include "cpu/m68000/m68000.h" #include "machine/eeprom.h" #include "cpu/pic16c5x/pic16c5x.h" #include "sound/okim6295.h" #include "includes/playmark.h" static WRITE16_HANDLER( coinctrl_w ) { if (ACCESSING_BITS_8_15) { coin_counter_w(space->machine, 0, data & 0x0100); coin_counter_w(space->machine, 1, data & 0x0200); } if (data & 0xfcff) logerror("Writing %04x to unknown coin control bits\n", data); } /*************************************************************************** EEPROM ***************************************************************************/ static const eeprom_interface eeprom_intf = { 6, /* address bits */ 16, /* data bits */ "*110", /* read command */ "*101", /* write command */ 0, /* erase command */ "*10000xxxx", /* lock command */ "*10011xxxx", /* unlock command */ 0, /* enable_multi_read */ 5 /* reset_delay (otherwise wbeachvl will hang when saving settings) */ }; static WRITE16_HANDLER( wbeachvl_coin_eeprom_w ) { playmark_state *state = space->machine->driver_data<playmark_state>(); if (ACCESSING_BITS_0_7) { /* bits 0-3 are coin counters? (only 0 used?) */ coin_counter_w(space->machine, 0, data & 0x01); coin_counter_w(space->machine, 1, data & 0x02); coin_counter_w(space->machine, 2, data & 0x04); coin_counter_w(space->machine, 3, data & 0x08); /* bits 5-7 control EEPROM */ eeprom_set_cs_line(state->eeprom, (data & 0x20) ? CLEAR_LINE : ASSERT_LINE); eeprom_write_bit(state->eeprom, data & 0x80); eeprom_set_clock_line(state->eeprom, (data & 0x40) ? CLEAR_LINE : ASSERT_LINE); } } static WRITE16_HANDLER( hotmind_coin_eeprom_w ) { playmark_state *state = space->machine->driver_data<playmark_state>(); if (ACCESSING_BITS_0_7) { coin_counter_w(space->machine, 0,data & 0x20); eeprom_set_cs_line(state->eeprom, (data & 1) ? CLEAR_LINE : ASSERT_LINE); eeprom_write_bit(state->eeprom, data & 4); eeprom_set_clock_line(state->eeprom, (data & 2) ? ASSERT_LINE : CLEAR_LINE ); } } static WRITE16_HANDLER( hrdtimes_coin_w ) { coin_counter_w(space->machine, 0, data & 0x01); coin_counter_w(space->machine, 1, data & 0x02); } static WRITE16_HANDLER( playmark_snd_command_w ) { playmark_state *state = space->machine->driver_data<playmark_state>(); if (ACCESSING_BITS_0_7) { state->snd_command = (data & 0xff); state->snd_flag = 1; cpu_yield(space->cpu); } } static READ8_HANDLER( playmark_snd_command_r ) { playmark_state *state = space->machine->driver_data<playmark_state>(); int data = 0; if ((state->oki_control & 0x38) == 0x30) { data = state->snd_command; // logerror("PC$%03x PortB reading %02x from the 68K\n", cpu_get_previouspc(space->cpu), data); } else if ((state->oki_control & 0x38) == 0x28) { data = (okim6295_r(state->oki, 0) & 0x0f); // logerror("PC$%03x PortB reading %02x from the OKI status port\n", cpu_get_previouspc(space->cpu), data); } return data; } static READ8_HANDLER( playmark_snd_flag_r ) { playmark_state *state = space->machine->driver_data<playmark_state>(); if (state->snd_flag) { state->snd_flag = 0; return 0x00; } return 0x40; } static WRITE8_DEVICE_HANDLER( playmark_oki_banking_w ) { playmark_state *state = device->machine->driver_data<playmark_state>(); if (state->old_oki_bank != (data & 7)) { state->old_oki_bank = data & 7; if (((state->old_oki_bank - 1) * 0x40000) < memory_region_length(device->machine, "oki")) { downcast<okim6295_device *>(device)->set_bank_base(0x40000 * (state->old_oki_bank - 1)); } } } static WRITE8_HANDLER( playmark_oki_w ) { playmark_state *state = space->machine->driver_data<playmark_state>(); state->oki_command = data; } static WRITE8_DEVICE_HANDLER( playmark_snd_control_w ) { playmark_state *state = device->machine->driver_data<playmark_state>(); // const address_space *space = cputag_get_address_space(device->machine, "audiocpu", ADDRESS_SPACE_PROGRAM); /* This port controls communications to and from the 68K, and the OKI device. bit legend 7w ??? (No read or writes to Port B) 6r Flag from 68K to notify the PIC that a command is coming 5w Latch write data to OKI? (active low) 4w Activate read signal to OKI? (active low) 3w Set Port 1 to read sound to play command from 68K. (active low) 2w ??? (Read Port B) 1 Not used 0 Not used */ state->oki_control = data; if ((data & 0x38) == 0x18) { // logerror("PC$%03x Writing %02x to OKI1, PortC=%02x, Code=%02x\n",cpu_get_previouspc(space->cpu),playmark_oki_command,playmark_oki_control,playmark_snd_command); okim6295_w(device, 0, state->oki_command); } } static READ8_HANDLER( PIC16C5X_T0_clk_r ) { return 0; } /***************************** 68000 Memory Maps ****************************/ static ADDRESS_MAP_START( bigtwin_main_map, ADDRESS_SPACE_PROGRAM, 16 ) AM_RANGE(0x000000, 0x0fffff) AM_ROM AM_RANGE(0x304000, 0x304001) AM_NOP /* watchdog? irq ack? */ AM_RANGE(0x440000, 0x4403ff) AM_RAM AM_BASE_SIZE_MEMBER(playmark_state, spriteram, spriteram_size) AM_RANGE(0x500000, 0x500fff) AM_WRITE(wbeachvl_fgvideoram_w) AM_BASE_MEMBER(playmark_state, videoram2) AM_RANGE(0x501000, 0x501fff) AM_WRITENOP /* unused RAM? */ AM_RANGE(0x502000, 0x503fff) AM_WRITE(wbeachvl_txvideoram_w) AM_BASE_MEMBER(playmark_state, videoram1) AM_RANGE(0x504000, 0x50ffff) AM_WRITENOP /* unused RAM? */ AM_RANGE(0x510000, 0x51000b) AM_WRITE(bigtwin_scroll_w) AM_RANGE(0x51000c, 0x51000d) AM_WRITENOP /* always 3? */ AM_RANGE(0x600000, 0x67ffff) AM_RAM AM_BASE_MEMBER(playmark_state, bgvideoram) AM_RANGE(0x700010, 0x700011) AM_READ_PORT("SYSTEM") AM_RANGE(0x700012, 0x700013) AM_READ_PORT("P1") AM_RANGE(0x700014, 0x700015) AM_READ_PORT("P2") AM_RANGE(0x700016, 0x700017) AM_WRITE(coinctrl_w) AM_RANGE(0x70001a, 0x70001b) AM_READ_PORT("DSW1") AM_RANGE(0x70001c, 0x70001d) AM_READ_PORT("DSW2") AM_RANGE(0x70001e, 0x70001f) AM_WRITE(playmark_snd_command_w) AM_RANGE(0x780000, 0x7807ff) AM_WRITE(bigtwin_paletteram_w) AM_BASE_GENERIC(paletteram) // AM_RANGE(0xe00000, 0xe00001) ?? written on startup AM_RANGE(0xff0000, 0xffffff) AM_RAM ADDRESS_MAP_END static ADDRESS_MAP_START( wbeachvl_main_map, ADDRESS_SPACE_PROGRAM, 16 ) AM_RANGE(0x000000, 0x07ffff) AM_ROM AM_RANGE(0x440000, 0x440fff) AM_RAM AM_BASE_SIZE_MEMBER(playmark_state, spriteram, spriteram_size) AM_RANGE(0x500000, 0x501fff) AM_RAM_WRITE(wbeachvl_bgvideoram_w) AM_BASE_MEMBER(playmark_state, videoram3) AM_RANGE(0x504000, 0x505fff) AM_RAM_WRITE(wbeachvl_fgvideoram_w) AM_BASE_MEMBER(playmark_state, videoram2) AM_RANGE(0x508000, 0x509fff) AM_RAM_WRITE(wbeachvl_txvideoram_w) AM_BASE_MEMBER(playmark_state, videoram1) AM_RANGE(0x50f000, 0x50ffff) AM_RAM AM_BASE_MEMBER(playmark_state, rowscroll) AM_RANGE(0x510000, 0x51000b) AM_WRITE(wbeachvl_scroll_w) AM_RANGE(0x51000c, 0x51000d) AM_WRITENOP /* 2 and 3 */ // AM_RANGE(0x700000, 0x700001) ?? written on startup AM_RANGE(0x710010, 0x710011) AM_READ_PORT("SYSTEM") AM_RANGE(0x710012, 0x710013) AM_READ_PORT("P1") AM_RANGE(0x710014, 0x710015) AM_READ_PORT("P2") AM_RANGE(0x710016, 0x710017) AM_WRITE(wbeachvl_coin_eeprom_w) AM_RANGE(0x710018, 0x710019) AM_READ_PORT("P3") AM_RANGE(0x71001a, 0x71001b) AM_READ_PORT("P4") // AM_RANGE(0x71001c, 0x71001d) AM_READ(playmark_snd_status???) // AM_RANGE(0x71001e, 0x71001f) AM_WRITENOP//playmark_snd_command_w }, AM_RANGE(0x780000, 0x780fff) AM_WRITE(paletteram16_RRRRRGGGGGBBBBBx_word_w) AM_BASE_GENERIC(paletteram) AM_RANGE(0xff0000, 0xffffff) AM_RAM ADDRESS_MAP_END static ADDRESS_MAP_START( excelsr_main_map, ADDRESS_SPACE_PROGRAM, 16 ) AM_RANGE(0x000000, 0x2fffff) AM_ROM AM_RANGE(0x304000, 0x304001) AM_WRITENOP /* watchdog? irq ack? */ AM_RANGE(0x440000, 0x440cff) AM_RAM AM_BASE_SIZE_MEMBER(playmark_state, spriteram, spriteram_size) AM_RANGE(0x500000, 0x500fff) AM_RAM_WRITE(wbeachvl_fgvideoram_w) AM_BASE_MEMBER(playmark_state, videoram2) AM_RANGE(0x501000, 0x501fff) AM_RAM_WRITE(wbeachvl_txvideoram_w) AM_BASE_MEMBER(playmark_state, videoram1) AM_RANGE(0x510000, 0x51000b) AM_WRITE(excelsr_scroll_w) AM_RANGE(0x51000c, 0x51000d) AM_WRITENOP /* 2 and 3 */ AM_RANGE(0x600000, 0x67ffff) AM_RAM AM_BASE_MEMBER(playmark_state, bgvideoram) AM_RANGE(0x700010, 0x700011) AM_READ_PORT("SYSTEM") AM_RANGE(0x700012, 0x700013) AM_READ_PORT("P1") AM_RANGE(0x700014, 0x700015) AM_READ_PORT("P2") AM_RANGE(0x700016, 0x700017) AM_WRITE(coinctrl_w) AM_RANGE(0x70001a, 0x70001b) AM_READ_PORT("DSW1") AM_RANGE(0x70001c, 0x70001d) AM_READ_PORT("DSW2") AM_RANGE(0x70001e, 0x70001f) AM_WRITE(playmark_snd_command_w) AM_RANGE(0x780000, 0x7807ff) AM_RAM_WRITE(bigtwin_paletteram_w) AM_BASE_GENERIC(paletteram) AM_RANGE(0xff0000, 0xffffff) AM_RAM ADDRESS_MAP_END static ADDRESS_MAP_START( hotmind_main_map, ADDRESS_SPACE_PROGRAM, 16 ) AM_RANGE(0x000000, 0x03ffff) AM_ROM AM_RANGE(0x100000, 0x103fff) AM_RAM_WRITE(hrdtimes_bgvideoram_w) AM_BASE_MEMBER(playmark_state, videoram3) AM_RANGE(0x104000, 0x107fff) AM_RAM_WRITE(hrdtimes_fgvideoram_w) AM_BASE_MEMBER(playmark_state, videoram2) AM_RANGE(0x108000, 0x10ffff) AM_RAM_WRITE(hrdtimes_txvideoram_w) AM_BASE_MEMBER(playmark_state, videoram1) AM_RANGE(0x110000, 0x11000d) AM_WRITE(hrdtimes_scroll_w) AM_RANGE(0x200000, 0x200fff) AM_RAM AM_BASE_SIZE_MEMBER(playmark_state, spriteram, spriteram_size) AM_RANGE(0x280000, 0x2807ff) AM_RAM_WRITE(bigtwin_paletteram_w) AM_BASE_GENERIC(paletteram) AM_RANGE(0x300010, 0x300011) AM_READ_PORT("SYSTEM") AM_RANGE(0x300012, 0x300013) AM_READ_PORT("P1") AM_RANGE(0x300014, 0x300015) AM_READ_PORT("P2") AM_WRITE(hotmind_coin_eeprom_w) AM_RANGE(0x30001a, 0x30001b) AM_READ_PORT("DSW1") AM_RANGE(0x30001c, 0x30001d) AM_READ_PORT("DSW2") AM_RANGE(0x30001e, 0x30001f) AM_WRITE(playmark_snd_command_w) AM_RANGE(0x304000, 0x304001) AM_WRITENOP /* watchdog? irq ack? */ AM_RANGE(0xff0000, 0xffffff) AM_RAM ADDRESS_MAP_END static ADDRESS_MAP_START( hrdtimes_main_map, ADDRESS_SPACE_PROGRAM, 16 ) AM_RANGE(0x000000, 0x07ffff) AM_ROM AM_RANGE(0x080000, 0x0bffff) AM_RAM AM_RANGE(0x0c0000, 0x0fffff) AM_ROM AM_REGION("maincpu", 0x0c0000) AM_RANGE(0x100000, 0x103fff) AM_RAM_WRITE(hrdtimes_bgvideoram_w) AM_BASE_MEMBER(playmark_state, videoram3) AM_RANGE(0x104000, 0x107fff) AM_RAM_WRITE(hrdtimes_fgvideoram_w) AM_BASE_MEMBER(playmark_state, videoram2) AM_RANGE(0x108000, 0x10ffff) AM_RAM_WRITE(hrdtimes_txvideoram_w) AM_BASE_MEMBER(playmark_state, videoram1) AM_RANGE(0x110000, 0x11000d) AM_WRITE(hrdtimes_scroll_w) AM_RANGE(0x200000, 0x200fff) AM_RAM AM_BASE_SIZE_MEMBER(playmark_state, spriteram, spriteram_size) AM_RANGE(0x280000, 0x2807ff) AM_RAM_WRITE(bigtwin_paletteram_w) AM_BASE_GENERIC(paletteram) AM_RANGE(0x280800, 0x280fff) AM_RAM // unused AM_RANGE(0x300010, 0x300011) AM_READ_PORT("SYSTEM") AM_RANGE(0x300012, 0x300013) AM_READ_PORT("P1") AM_RANGE(0x300014, 0x300015) AM_READ_PORT("P2") AM_RANGE(0x300016, 0x300017) AM_WRITE(hrdtimes_coin_w) AM_RANGE(0x30001a, 0x30001b) AM_READ_PORT("DSW1") AM_RANGE(0x30001c, 0x30001d) AM_READ_PORT("DSW2") AM_RANGE(0x30001e, 0x30001f) AM_WRITENOP //(playmark_snd_command_w) AM_RANGE(0x304000, 0x304001) AM_WRITENOP /* watchdog? irq ack? */ ADDRESS_MAP_END /***************************** PIC16C57 Memory Map **************************/ /* $000 - 7FF PIC16C57 Internal Program ROM. Note: code is 12bits wide */ /* $000 - 07F PIC16C57 Internal Data RAM */ static ADDRESS_MAP_START( playmark_sound_io_map, ADDRESS_SPACE_IO, 8 ) AM_RANGE(0x00, 0x00) AM_DEVWRITE("oki", playmark_oki_banking_w) AM_RANGE(0x01, 0x01) AM_READWRITE(playmark_snd_command_r, playmark_oki_w) AM_RANGE(0x02, 0x02) AM_READ(playmark_snd_flag_r) AM_DEVWRITE("oki", playmark_snd_control_w) AM_RANGE(PIC16C5x_T0, PIC16C5x_T0) AM_READ(PIC16C5X_T0_clk_r) ADDRESS_MAP_END static INPUT_PORTS_START( bigtwin ) PORT_START("SYSTEM") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("P1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 ) PORT_START("P2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 ) PORT_START("DSW1") PORT_DIPNAME( 0x01, 0x00, DEF_STR( Language ) ) PORT_DIPSETTING( 0x00, DEF_STR( English ) ) PORT_DIPSETTING( 0x01, DEF_STR( Italian ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x00, "Censor Pictures" ) PORT_DIPSETTING( 0x00, DEF_STR( No ) ) PORT_DIPSETTING( 0x04, DEF_STR( Yes ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x30, 0x00, DEF_STR( Difficulty ) ) // PORT_DIPSETTING( 0x20, DEF_STR( Easy ) ) /* Seems same as Medium */ PORT_DIPSETTING( 0x30, DEF_STR( Medium ) ) PORT_DIPSETTING( 0x10, DEF_STR( Hard ) ) PORT_DIPSETTING( 0x00, DEF_STR( Hardest ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Allow_Continue ) ) PORT_DIPSETTING( 0x00, DEF_STR( No ) ) PORT_DIPSETTING( 0x40, DEF_STR( Yes ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START("DSW2") PORT_DIPNAME( 0x01, 0x01, "Coin Mode" ) PORT_DIPSETTING( 0x01, "Mode 1" ) PORT_DIPSETTING( 0x00, "Mode 2" ) PORT_DIPNAME( 0x1e, 0x1e, "Coinage Mode 1" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_EQUALS, 0x01) PORT_DIPSETTING( 0x14, DEF_STR( 6C_1C ) ) PORT_DIPSETTING( 0x16, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x18, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x1a, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 8C_3C ) ) PORT_DIPSETTING( 0x1c, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 5C_3C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x1e, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x12, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) PORT_DIPNAME( 0x06, 0x06, "Coin A Mode 2" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_NOTEQUALS, 0x01) PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 1C_1C ) ) PORT_DIPNAME( 0x18, 0x18, "Coin B Mode 2" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_NOTEQUALS, 0x01) PORT_DIPSETTING( 0x18, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x20, 0x20, "Minimum Credits to Start" ) PORT_DIPSETTING( 0x20, "1" ) PORT_DIPSETTING( 0x00, "2" ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END static INPUT_PORTS_START( wbeachvl ) PORT_START("SYSTEM") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_COIN2 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_COIN3 ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_COIN4 ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_SERVICE1 ) PORT_SERVICE_NO_TOGGLE(0x20, IP_ACTIVE_LOW) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_SPECIAL ) /* ?? see code at 746a. sound status? */ PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_SPECIAL ) PORT_READ_LINE_DEVICE("eeprom", eeprom_read_bit) /* EEPROM data */ PORT_START("P1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 ) PORT_START("P2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 ) PORT_START("P3") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(3) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(3) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(3) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(3) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(3) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START3 ) PORT_START("P4") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(4) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(4) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(4) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(4) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(4) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(4) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(4) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START4 ) INPUT_PORTS_END static INPUT_PORTS_START( excelsr ) PORT_START("SYSTEM") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("P1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 ) PORT_START("P2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 ) PORT_START("DSW1") PORT_DIPNAME( 0x03, 0x03, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "1" ) PORT_DIPSETTING( 0x02, "2" ) PORT_DIPSETTING( 0x03, "3" ) PORT_DIPSETTING( 0x01, "4" ) PORT_DIPNAME( 0x0c, 0x00, "Censor Pictures" ) PORT_DIPSETTING( 0x00, DEF_STR( No ) ) // PORT_DIPSETTING( 0x04, DEF_STR( No ) ) PORT_DIPSETTING( 0x08, "50%" ) PORT_DIPSETTING( 0x0c, "100%" ) PORT_DIPNAME( 0x30, 0x20, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x30, DEF_STR( Easy ) ) PORT_DIPSETTING( 0x20, DEF_STR( Normal ) ) PORT_DIPSETTING( 0x10, DEF_STR( Medium ) ) PORT_DIPSETTING( 0x00, DEF_STR( Hard ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Allow_Continue ) ) PORT_DIPSETTING( 0x00, DEF_STR( No ) ) PORT_DIPSETTING( 0x40, DEF_STR( Yes ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START("DSW2") PORT_DIPNAME( 0x01, 0x01, "Coin Mode" ) PORT_DIPSETTING( 0x01, "Mode 1" ) PORT_DIPSETTING( 0x00, "Mode 2" ) PORT_DIPNAME( 0x1e, 0x1e, "Coinage Mode 1" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_EQUALS, 0x01) PORT_DIPSETTING( 0x14, DEF_STR( 6C_1C ) ) PORT_DIPSETTING( 0x16, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x18, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x1a, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 8C_3C ) ) PORT_DIPSETTING( 0x1c, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 5C_3C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x1e, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x12, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) PORT_DIPNAME( 0x06, 0x06, "Coin A Mode 2" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_NOTEQUALS, 0x01) PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 1C_1C ) ) PORT_DIPNAME( 0x18, 0x18, "Coin B Mode 2" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_NOTEQUALS, 0x01) PORT_DIPSETTING( 0x18, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x20, 0x20, "Minimum Credits to Start" ) PORT_DIPSETTING( 0x20, "1" ) PORT_DIPSETTING( 0x00, "2" ) PORT_DIPNAME( 0x40, 0x40, "Percentage to Reveal" ) PORT_DIPSETTING( 0x40, "80%" ) PORT_DIPSETTING( 0x00, "90%" ) PORT_SERVICE( 0x80, IP_ACTIVE_LOW ) INPUT_PORTS_END static INPUT_PORTS_START( hotmind ) PORT_START("SYSTEM") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("P1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("P2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_VBLANK ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_SPECIAL ) PORT_READ_LINE_DEVICE("eeprom", eeprom_read_bit) /* EEPROM data */ PORT_START("DSW1") PORT_DIPNAME( 0x07, 0x07, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x00, "Very Hard 5" ) PORT_DIPSETTING( 0x01, "Very Hard 4" ) PORT_DIPSETTING( 0x02, "Very Hard 3" ) PORT_DIPSETTING( 0x03, "Very Hard 2" ) PORT_DIPSETTING( 0x04, "Very Hard 1" ) PORT_DIPSETTING( 0x05, DEF_STR( Hard ) ) PORT_DIPSETTING( 0x06, DEF_STR( Normal ) ) PORT_DIPSETTING( 0x07, DEF_STR( Easy ) ) PORT_SERVICE( 0x08, IP_ACTIVE_LOW ) PORT_DIPNAME( 0x10, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, "Erogatore Gettoni" ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, "Erogatore Ticket" ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, "Clear Memory" ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START("DSW2") PORT_DIPNAME( 0x01, 0x01, "Coin Mode" ) PORT_DIPSETTING( 0x01, "Mode 1" ) PORT_DIPSETTING( 0x00, "Mode 2" ) PORT_DIPNAME( 0x1e, 0x1e, "Coinage Mode 1" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_EQUALS, 0x01) PORT_DIPSETTING( 0x14, DEF_STR( 6C_1C ) ) PORT_DIPSETTING( 0x16, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x18, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x1a, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 8C_3C ) ) PORT_DIPSETTING( 0x1c, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 5C_3C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x1e, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x12, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) PORT_DIPNAME( 0x06, 0x06, "Coin A Mode 2" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_NOTEQUALS, 0x01) PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 1C_1C ) ) PORT_DIPNAME( 0x18, 0x18, "Coin B Mode 2" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_NOTEQUALS, 0x01) PORT_DIPSETTING( 0x18, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) INPUT_PORTS_END static INPUT_PORTS_START( hrdtimes ) PORT_START("SYSTEM") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("P1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 ) PORT_START("P2") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 ) PORT_START("DSW1") PORT_DIPNAME( 0x03, 0x03, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "1" ) PORT_DIPSETTING( 0x02, "2" ) PORT_DIPSETTING( 0x03, "3" ) PORT_DIPSETTING( 0x01, "5" ) PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0c, "Every 300k - 500k" ) PORT_DIPSETTING( 0x08, "Every 500k - 500k" ) PORT_DIPSETTING( 0x04, "Only 500k" ) PORT_DIPSETTING( 0x00, DEF_STR( No ) ) PORT_DIPNAME( 0x30, 0x30, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x20, DEF_STR( Easy ) ) PORT_DIPSETTING( 0x30, DEF_STR( Normal ) ) PORT_DIPSETTING( 0x10, DEF_STR( Hard ) ) PORT_DIPSETTING( 0x00, DEF_STR( Very_Hard ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Allow_Continue ) ) PORT_DIPSETTING( 0x00, DEF_STR( No ) ) PORT_DIPSETTING( 0x40, DEF_STR( Yes ) ) PORT_DIPNAME( 0x80, 0x00, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START("DSW2") PORT_DIPNAME( 0x01, 0x01, "Coin Mode" ) PORT_DIPSETTING( 0x01, "Mode 1" ) PORT_DIPSETTING( 0x00, "Mode 2" ) PORT_DIPNAME( 0x1e, 0x1e, "Coinage Mode 1" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_EQUALS, 0x01) PORT_DIPSETTING( 0x14, DEF_STR( 6C_1C ) ) PORT_DIPSETTING( 0x16, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x18, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x1a, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 8C_3C ) ) PORT_DIPSETTING( 0x1c, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 5C_3C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x1e, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x12, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) PORT_DIPNAME( 0x06, 0x06, "Coin A Mode 2" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_NOTEQUALS, 0x01) PORT_DIPSETTING( 0x00, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x04, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 1C_1C ) ) PORT_DIPNAME( 0x18, 0x18, "Coin B Mode 2" ) PORT_CONDITION("DSW2", 0x01, PORTCOND_NOTEQUALS, 0x01) PORT_DIPSETTING( 0x18, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x20, 0x20, "Minimum Credits to Start" ) PORT_DIPSETTING( 0x20, "1" ) PORT_DIPSETTING( 0x00, "2" ) PORT_DIPNAME( 0x40, 0x40, "1 Life If Continue" ) PORT_DIPSETTING( 0x40, DEF_STR( No ) ) PORT_DIPSETTING( 0x00, DEF_STR( Yes ) ) PORT_SERVICE( 0x80, IP_ACTIVE_LOW ) INPUT_PORTS_END static const gfx_layout charlayout = { 8,8, RGN_FRAC(1,4), 4, { RGN_FRAC(3,4), RGN_FRAC(2,4), RGN_FRAC(1,4), RGN_FRAC(0,4) }, { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 32*8 }; static const gfx_layout tilelayout = { 16,16, RGN_FRAC(1,4), 4, { RGN_FRAC(3,4), RGN_FRAC(2,4), RGN_FRAC(1,4), RGN_FRAC(0,4) }, { 0, 1, 2, 3, 4, 5, 6, 7, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 }, 32*8 }; static const gfx_layout spritelayout = { 32,32, RGN_FRAC(1,4), 4, { RGN_FRAC(3,4), RGN_FRAC(2,4), RGN_FRAC(1,4), RGN_FRAC(0,4) }, { 0, 1, 2, 3, 4, 5, 6, 7, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7, 32*8+0, 32*8+1, 32*8+2, 32*8+3, 32*8+4, 32*8+5, 32*8+6, 32*8+7, 48*8+0, 48*8+1, 48*8+2, 48*8+3, 48*8+4, 48*8+5, 48*8+6, 48*8+7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8, 64*8, 65*8, 66*8, 67*8, 68*8, 69*8, 70*8, 71*8, 72*8, 73*8, 74*8, 75*8, 76*8, 77*8, 78*8, 79*8 }, 128*8 }; static GFXDECODE_START( playmark ) GFXDECODE_ENTRY( "gfx2", 0, spritelayout, 0x200, 16 ) /* colors 0x200-0x2ff */ GFXDECODE_ENTRY( "gfx1", 0, tilelayout, 0x000, 8 ) /* colors 0x000-0x07f */ GFXDECODE_ENTRY( "gfx1", 0, charlayout, 0x080, 8 ) /* colors 0x080-0x0ff */ /* background bitmap uses colors 0x100-0x1ff */ GFXDECODE_END static const gfx_layout wcharlayout = { 8,8, RGN_FRAC(1,6), 6, { RGN_FRAC(5,6), RGN_FRAC(4,6), RGN_FRAC(3,6), RGN_FRAC(2,6), RGN_FRAC(1,6), RGN_FRAC(0,6) }, { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 }; static const gfx_layout wtilelayout = { 16,16, RGN_FRAC(1,6), 6, { RGN_FRAC(5,6), RGN_FRAC(4,6), RGN_FRAC(3,6), RGN_FRAC(2,6), RGN_FRAC(1,6), RGN_FRAC(0,6) }, { 0, 1, 2, 3, 4, 5, 6, 7, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 }, 32*8 }; /* tiles are 6 bpp, sprites only 5bpp */ static const gfx_layout wspritelayout = { 16,16, RGN_FRAC(1,6), 5, { RGN_FRAC(4,6), RGN_FRAC(3,6), RGN_FRAC(2,6), RGN_FRAC(1,6), RGN_FRAC(0,6) }, { 0, 1, 2, 3, 4, 5, 6, 7, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 }, 32*8 }; static GFXDECODE_START( wbeachvl ) GFXDECODE_ENTRY( "gfx1", 0, wspritelayout, 0x600, 16 ) /* colors 0x600-0x7ff */ GFXDECODE_ENTRY( "gfx1", 0, wtilelayout, 0x000, 16 ) /* colors 0x000-0x3ff */ GFXDECODE_ENTRY( "gfx1", 0, wcharlayout, 0x400, 8 ) /* colors 0x400-0x5ff */ GFXDECODE_END static GFXDECODE_START( excelsr ) GFXDECODE_ENTRY( "gfx2", 0, tilelayout, 0x200, 16 ) /* colors 0x200-0x2ff */ GFXDECODE_ENTRY( "gfx1", 0, tilelayout, 0x000, 8 ) /* colors 0x000-0x07f */ GFXDECODE_ENTRY( "gfx1", 0, tilelayout, 0x080, 8 ) /* colors 0x080-0x0ff */ /* background bitmap uses colors 0x100-0x1ff */ GFXDECODE_END static const gfx_layout hrdtimes_tilelayout = { 16,16, RGN_FRAC(1,2), 4, { RGN_FRAC(2,4)+8, RGN_FRAC(2,4), RGN_FRAC(0,4)+8, RGN_FRAC(0,4) }, { 0, 1, 2, 3, 4, 5, 6, 7, 16*16+0, 16*16+1, 16*16+2, 16*16+3, 16*16+4, 16*16+5, 16*16+6, 16*16+7 }, { 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16 }, 32*16 }; static const gfx_layout hrdtimes_charlayout = { 8,8, RGN_FRAC(1,2), 4, { RGN_FRAC(2,4)+8, RGN_FRAC(2,4), RGN_FRAC(0,4)+8, RGN_FRAC(0,4) }, { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16 }, 8*16 }; static GFXDECODE_START( hrdtimes ) GFXDECODE_ENTRY( "gfx2", 0, hrdtimes_tilelayout, 0x200, 32 ) /* colors 0x200-0x2ff */ GFXDECODE_ENTRY( "gfx1", 0, hrdtimes_tilelayout, 0x000, 16 ) /* colors 0x000-0x0ff */ GFXDECODE_ENTRY( "gfx1", 0, hrdtimes_charlayout, 0x100, 8 ) /* colors 0x100-0x17f */ GFXDECODE_END static MACHINE_START( playmark ) { playmark_state *state = machine->driver_data<playmark_state>(); state->oki = machine->device("oki"); state->eeprom = machine->device("eeprom"); state_save_register_global(machine, state->bgscrollx); state_save_register_global(machine, state->bgscrolly); state_save_register_global(machine, state->bg_enable); state_save_register_global(machine, state->bg_full_size); state_save_register_global(machine, state->fgscrollx); state_save_register_global(machine, state->fg_rowscroll_enable); state_save_register_global_array(machine, state->scroll); state_save_register_global(machine, state->snd_command); state_save_register_global(machine, state->snd_flag); state_save_register_global(machine, state->oki_control); state_save_register_global(machine, state->oki_command); state_save_register_global(machine, state->old_oki_bank); } static MACHINE_RESET( playmark ) { playmark_state *state = machine->driver_data<playmark_state>(); state->bgscrollx = 0; state->bgscrolly = 0; state->bg_enable = 0; state->bg_full_size = 0; state->fgscrollx = 0; state->fg_rowscroll_enable = 0; memset(state->scroll, 0, ARRAY_LENGTH(state->scroll)); state->snd_command = 0; state->oki_control = 0; state->oki_command = 0; state->old_oki_bank = 0; } static MACHINE_DRIVER_START( bigtwin ) /* driver data */ MDRV_DRIVER_DATA(playmark_state) /* basic machine hardware */ MDRV_CPU_ADD("maincpu", M68000, 12000000) /* 12 MHz */ MDRV_CPU_PROGRAM_MAP(bigtwin_main_map) MDRV_CPU_VBLANK_INT("screen", irq2_line_hold) MDRV_CPU_ADD("audiocpu", PIC16C57, 12000000) /* 3MHz */ /* Program and Data Maps are internal to the MCU */ MDRV_CPU_IO_MAP(playmark_sound_io_map) MDRV_MACHINE_START(playmark) MDRV_MACHINE_RESET(playmark) /* video hardware */ MDRV_SCREEN_ADD("screen", RASTER) MDRV_SCREEN_REFRESH_RATE(58) MDRV_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0)) MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MDRV_SCREEN_SIZE(64*8, 64*8) MDRV_SCREEN_VISIBLE_AREA(0*8, 40*8-1, 2*8, 32*8-1) MDRV_GFXDECODE(playmark) MDRV_PALETTE_LENGTH(1024) MDRV_VIDEO_START(bigtwin) MDRV_VIDEO_UPDATE(bigtwin) /* sound hardware */ MDRV_SPEAKER_STANDARD_MONO("mono") MDRV_OKIM6295_ADD("oki", 1000000, OKIM6295_PIN7_HIGH) MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MACHINE_DRIVER_END static MACHINE_DRIVER_START( wbeachvl ) /* driver data */ MDRV_DRIVER_DATA(playmark_state) /* basic machine hardware */ MDRV_CPU_ADD("maincpu", M68000, 12000000) /* 12 MHz */ MDRV_CPU_PROGRAM_MAP(wbeachvl_main_map) MDRV_CPU_VBLANK_INT("screen", irq2_line_hold) // MDRV_CPU_ADD("audiocpu", PIC16C57, 12000000) /* 3MHz */ /* Program and Data Maps are internal to the MCU */ // MDRV_CPU_IO_MAP(playmark_sound_io_map) MDRV_EEPROM_ADD("eeprom", eeprom_intf) MDRV_EEPROM_DEFAULT_VALUE(0) MDRV_MACHINE_START(playmark) MDRV_MACHINE_RESET(playmark) /* video hardware */ MDRV_SCREEN_ADD("screen", RASTER) MDRV_SCREEN_REFRESH_RATE(58) MDRV_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500) /* not accurate */) MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MDRV_SCREEN_SIZE(64*8, 64*8) MDRV_SCREEN_VISIBLE_AREA(0*8, 40*8-1, 2*8, 32*8-1) MDRV_GFXDECODE(wbeachvl) MDRV_PALETTE_LENGTH(2048) MDRV_VIDEO_START(wbeachvl) MDRV_VIDEO_UPDATE(wbeachvl) /* sound hardware */ MDRV_SPEAKER_STANDARD_MONO("mono") MDRV_OKIM6295_ADD("oki", 1000000, OKIM6295_PIN7_HIGH) MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MACHINE_DRIVER_END static MACHINE_DRIVER_START( excelsr ) /* driver data */ MDRV_DRIVER_DATA(playmark_state) /* basic machine hardware */ MDRV_CPU_ADD("maincpu", M68000, 12000000) /* 12 MHz */ MDRV_CPU_PROGRAM_MAP(excelsr_main_map) MDRV_CPU_VBLANK_INT("screen", irq2_line_hold) MDRV_CPU_ADD("audiocpu", PIC16C57, 12000000) /* 3MHz */ /* Program and Data Maps are internal to the MCU */ MDRV_CPU_IO_MAP(playmark_sound_io_map) MDRV_MACHINE_START(playmark) MDRV_MACHINE_RESET(playmark) /* video hardware */ MDRV_SCREEN_ADD("screen", RASTER) MDRV_SCREEN_REFRESH_RATE(58) MDRV_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0)) MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MDRV_SCREEN_SIZE(64*8, 64*8) MDRV_SCREEN_VISIBLE_AREA(0*8, 40*8-1, 2*8, 32*8-1) MDRV_GFXDECODE(excelsr) MDRV_PALETTE_LENGTH(1024) MDRV_VIDEO_START(excelsr) MDRV_VIDEO_UPDATE(excelsr) /* sound hardware */ MDRV_SPEAKER_STANDARD_MONO("mono") MDRV_OKIM6295_ADD("oki", 1000000, OKIM6295_PIN7_HIGH) MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MACHINE_DRIVER_END static MACHINE_DRIVER_START( hotmind ) /* driver data */ MDRV_DRIVER_DATA(playmark_state) /* basic machine hardware */ MDRV_CPU_ADD("maincpu", M68000, XTAL_24MHz/2) /* verified on pcb */ MDRV_CPU_PROGRAM_MAP(hotmind_main_map) MDRV_CPU_VBLANK_INT("screen", irq2_line_hold) MDRV_CPU_ADD("audiocpu", PIC16C57, XTAL_24MHz/2) /* verified on pcb */ /* Program and Data Maps are internal to the MCU */ MDRV_CPU_IO_MAP(playmark_sound_io_map) MDRV_EEPROM_ADD("eeprom", eeprom_intf) MDRV_EEPROM_DEFAULT_VALUE(0) MDRV_MACHINE_START(playmark) MDRV_MACHINE_RESET(playmark) /* video hardware */ MDRV_SCREEN_ADD("screen", RASTER) MDRV_SCREEN_REFRESH_RATE(58) MDRV_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500) /* not accurate */) MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MDRV_SCREEN_SIZE(64*8, 64*8) MDRV_SCREEN_VISIBLE_AREA(0*8, 40*8-1, 2*8, 30*8-1) MDRV_GFXDECODE(hrdtimes) MDRV_PALETTE_LENGTH(1024) MDRV_VIDEO_START(hotmind) MDRV_VIDEO_UPDATE(hrdtimes) /* sound hardware */ MDRV_SPEAKER_STANDARD_MONO("mono") MDRV_OKIM6295_ADD("oki", XTAL_1MHz, OKIM6295_PIN7_HIGH) /* verified on pcb */ MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MACHINE_DRIVER_END static MACHINE_DRIVER_START( hrdtimes ) /* driver data */ MDRV_DRIVER_DATA(playmark_state) /* basic machine hardware */ MDRV_CPU_ADD("maincpu", M68000, XTAL_24MHz/2) /* verified on pcb */ MDRV_CPU_PROGRAM_MAP(hrdtimes_main_map) MDRV_CPU_VBLANK_INT("screen", irq6_line_hold) // MDRV_CPU_ADD("audiocpu", PIC16C57, XTAL_24MHz/2) /* verified on pcb */ /* Program and Data Maps are internal to the MCU */ // MDRV_CPU_IO_MAP(playmark_sound_io_map) MDRV_MACHINE_START(playmark) MDRV_MACHINE_RESET(playmark) /* video hardware */ MDRV_SCREEN_ADD("screen", RASTER) MDRV_SCREEN_REFRESH_RATE(58) MDRV_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0)) MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MDRV_SCREEN_SIZE(64*8, 64*8) MDRV_SCREEN_VISIBLE_AREA(0*8, 40*8-1, 2*8, 30*8-1) MDRV_GFXDECODE(hrdtimes) MDRV_PALETTE_LENGTH(1024) MDRV_VIDEO_START(hrdtimes) MDRV_VIDEO_UPDATE(hrdtimes) /* sound hardware */ MDRV_SPEAKER_STANDARD_MONO("mono") MDRV_OKIM6295_ADD("oki", XTAL_1MHz, OKIM6295_PIN7_HIGH) /* verified on pcb */ MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MACHINE_DRIVER_END /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( bigtwin ) ROM_REGION( 0x100000, "maincpu", 0 ) /* 68000 code */ ROM_LOAD16_BYTE( "2.302", 0x000000, 0x80000, CRC(e6767f60) SHA1(ec0ba1c786e6fde04601c2f3f619e3c6545f9239) ) ROM_LOAD16_BYTE( "3.301", 0x000001, 0x80000, CRC(5aba6990) SHA1(4f664a91819fdd27821fa607425701d83fcbd8ce) ) ROM_REGION( 0x1000, "audiocpu", ROMREGION_ERASE00 ) /* sound (PIC16C57) */ // ROM_LOAD( "16c57hs.bin", 0x0000, 0x1000, CRC(b4c95cc3) SHA1(7fc9b141e7782aa5c17310ee06db99d884537c30) ) /* ROM will be copied here by the init code from "user1" */ ROM_REGION( 0x3000, "user1", 0 ) ROM_LOAD( "16c57hs.015", 0x0000, 0x2d4c, CRC(c07e9375) SHA1(7a6714ab888ea6e37bc037bc7419f0998868cfce) ) /* 16C57 .HEX dump, to be converted */ ROM_REGION( 0x100000, "gfx1", 0 ) ROM_LOAD( "4.311", 0x00000, 0x40000, CRC(6f628fbc) SHA1(51cdee457aef79fef5d89d30a173afdf13fbb2ef) ) ROM_LOAD( "5.312", 0x40000, 0x40000, CRC(6a9b1752) SHA1(7c78157cd6b3d631704d2aca1a5756c69c87d581) ) ROM_LOAD( "6.313", 0x80000, 0x40000, CRC(411cf852) SHA1(1b66cec672b6ec6974d9e82afc6ec58b78c92ee4) ) ROM_LOAD( "7.314", 0xc0000, 0x40000, CRC(635c81fd) SHA1(64c787a37fcd1ba7c747ec25ff5b949aad3914ec) ) ROM_REGION( 0x80000, "gfx2", 0 ) ROM_LOAD( "8.321", 0x00000, 0x20000, CRC(2749644d) SHA1(f506ed1a14ee411eda8a7e639f5572e35b89b13f) ) ROM_LOAD( "9.322", 0x20000, 0x20000, CRC(1d1897af) SHA1(0ad00906b94443d7ceef383717b39c6aa8cca241) ) ROM_LOAD( "10.323", 0x40000, 0x20000, CRC(2a03432e) SHA1(44722b83093211d88460cbcd9e9c0b638d24ad3e) ) ROM_LOAD( "11.324", 0x60000, 0x20000, CRC(2c980c4c) SHA1(77af29a1f5d4302650915f4a7daf2918a2519a6e) ) ROM_REGION( 0x40000, "oki", 0 ) /* OKIM6295 samples */ ROM_LOAD( "1.013", 0x00000, 0x40000, CRC(ff6671dc) SHA1(517941946a3edfc2da0b7aa8a106ebb4ae849beb) ) ROM_END ROM_START( wbeachvl ) ROM_REGION( 0x80000, "maincpu", 0 ) /* 68000 code */ ROM_LOAD16_BYTE( "wbv_02.bin", 0x000000, 0x40000, CRC(c7cca29e) SHA1(03af361081d688c4204a95f7f5babcc598b72c23) ) ROM_LOAD16_BYTE( "wbv_03.bin", 0x000001, 0x40000, CRC(db4e69d5) SHA1(119bf35a463d279ddde67ab08f6f1bab9f05cf0c) ) ROM_REGION( 0x1000, "audiocpu", ROMREGION_ERASE00 ) /* sound (missing) */ ROM_LOAD( "pic16c57", 0x0000, 0x1000, NO_DUMP ) ROM_REGION( 0x600000, "gfx1", 0 ) ROM_LOAD( "wbv_10.bin", 0x000000, 0x80000, CRC(50680f0b) SHA1(ed76ef6ced70ba7e9558162aa94bbe9f19bbabe6) ) ROM_LOAD( "wbv_04.bin", 0x080000, 0x80000, CRC(df9cbff1) SHA1(7197939d9c4e8666d37266b6326134cfb4c761da) ) ROM_LOAD( "wbv_11.bin", 0x100000, 0x80000, CRC(e59ad0d1) SHA1(70dfc1ea45246fc8e24c96550563ab7a983f3824) ) ROM_LOAD( "wbv_05.bin", 0x180000, 0x80000, CRC(51245c3c) SHA1(5ac27d6fc22555766b4cdd532210199f4d7bd8bb) ) ROM_LOAD( "wbv_12.bin", 0x200000, 0x80000, CRC(36b87d0b) SHA1(702b8139d150c7cc9399dfa38536567aab40dcef) ) ROM_LOAD( "wbv_06.bin", 0x280000, 0x80000, CRC(9eb808ef) SHA1(0e46557665f1acef0606f22f043a391d1086cfce) ) ROM_LOAD( "wbv_13.bin", 0x300000, 0x80000, CRC(7021107b) SHA1(088fe3060dbb196e8000a3b4db1cfa3cb0c4b677) ) ROM_LOAD( "wbv_07.bin", 0x380000, 0x80000, CRC(4fff9fe8) SHA1(e29d3b4895692fd8559c9018432f32170aecdcc3) ) ROM_LOAD( "wbv_14.bin", 0x400000, 0x80000, CRC(0595e675) SHA1(82aebaedc919fa51b71f5519ee765ce9953d613a) ) ROM_LOAD( "wbv_08.bin", 0x480000, 0x80000, CRC(07e4b416) SHA1(a780ef0bd11897ab437359985f6e4852030ddbbf) ) ROM_LOAD( "wbv_15.bin", 0x500000, 0x80000, CRC(4e1a82d2) SHA1(9e66b52ba8e8144f772183396fc1a2fbb37ed2bc) ) ROM_LOAD( "wbv_09.bin", 0x580000, 0x20000, CRC(894ce354) SHA1(331aeabbe10cd645776da2dc0829acc2275e72dc) ) /* 5a0000-5fffff is empty */ ROM_REGION( 0x100000, "user2", 0 ) /* OKIM6295 samples */ ROM_LOAD( "wbv_01.bin", 0x00000, 0x100000, CRC(ac33f25f) SHA1(5d9ed16650aeb297d565376a99b31c88ab611668) ) /* $00000-$20000 stays the same in all sound banks, */ /* the second half of the bank is what gets switched */ ROM_REGION( 0x1c0000, "oki", 0 ) /* Samples */ ROM_COPY( "user2", 0x000000, 0x000000, 0x020000) ROM_COPY( "user2", 0x020000, 0x020000, 0x020000) ROM_COPY( "user2", 0x000000, 0x040000, 0x020000) ROM_COPY( "user2", 0x040000, 0x060000, 0x020000) ROM_COPY( "user2", 0x000000, 0x080000, 0x020000) ROM_COPY( "user2", 0x060000, 0x0a0000, 0x020000) ROM_COPY( "user2", 0x000000, 0x0c0000, 0x020000) ROM_COPY( "user2", 0x080000, 0x0e0000, 0x020000) ROM_COPY( "user2", 0x000000, 0x100000, 0x020000) ROM_COPY( "user2", 0x0a0000, 0x120000, 0x020000) ROM_COPY( "user2", 0x000000, 0x140000, 0x020000) ROM_COPY( "user2", 0x0c0000, 0x160000, 0x020000) ROM_COPY( "user2", 0x000000, 0x180000, 0x020000) ROM_COPY( "user2", 0x0e0000, 0x1a0000, 0x020000) ROM_END ROM_START( wbeachvl2 ) ROM_REGION( 0x80000, "maincpu", 0 ) /* 68000 code */ ROM_LOAD16_BYTE( "2.bin", 0x000000, 0x40000, CRC(8993487e) SHA1(c927ae655807f9046f66ff96a30bd2c6fa671566) ) ROM_LOAD16_BYTE( "3.bin", 0x000001, 0x40000, CRC(15904789) SHA1(640c80bbf7302529e1a39c2ae60e018ecb176478) ) ROM_REGION( 0x1000, "audiocpu", ROMREGION_ERASE00 ) /* sound (missing) */ ROM_LOAD( "pic16c57", 0x0000, 0x1000, NO_DUMP ) ROM_REGION( 0x600000, "gfx1", 0 ) ROM_LOAD( "wbv_10.bin", 0x000000, 0x80000, CRC(50680f0b) SHA1(ed76ef6ced70ba7e9558162aa94bbe9f19bbabe6) ) ROM_LOAD( "wbv_04.bin", 0x080000, 0x80000, CRC(df9cbff1) SHA1(7197939d9c4e8666d37266b6326134cfb4c761da) ) ROM_LOAD( "wbv_11.bin", 0x100000, 0x80000, CRC(e59ad0d1) SHA1(70dfc1ea45246fc8e24c96550563ab7a983f3824) ) ROM_LOAD( "wbv_05.bin", 0x180000, 0x80000, CRC(51245c3c) SHA1(5ac27d6fc22555766b4cdd532210199f4d7bd8bb) ) ROM_LOAD( "wbv_12.bin", 0x200000, 0x80000, CRC(36b87d0b) SHA1(702b8139d150c7cc9399dfa38536567aab40dcef) ) ROM_LOAD( "wbv_06.bin", 0x280000, 0x80000, CRC(9eb808ef) SHA1(0e46557665f1acef0606f22f043a391d1086cfce) ) ROM_LOAD( "wbv_13.bin", 0x300000, 0x80000, CRC(7021107b) SHA1(088fe3060dbb196e8000a3b4db1cfa3cb0c4b677) ) ROM_LOAD( "wbv_07.bin", 0x380000, 0x80000, CRC(4fff9fe8) SHA1(e29d3b4895692fd8559c9018432f32170aecdcc3) ) ROM_LOAD( "wbv_14.bin", 0x400000, 0x80000, CRC(0595e675) SHA1(82aebaedc919fa51b71f5519ee765ce9953d613a) ) ROM_LOAD( "wbv_08.bin", 0x480000, 0x80000, CRC(07e4b416) SHA1(a780ef0bd11897ab437359985f6e4852030ddbbf) ) ROM_LOAD( "wbv_15.bin", 0x500000, 0x80000, CRC(4e1a82d2) SHA1(9e66b52ba8e8144f772183396fc1a2fbb37ed2bc) ) ROM_LOAD( "wbv_09.bin", 0x580000, 0x20000, CRC(894ce354) SHA1(331aeabbe10cd645776da2dc0829acc2275e72dc) ) /* 5a0000-5fffff is empty */ ROM_REGION( 0x100000, "user2", 0 ) /* OKIM6295 samples */ ROM_LOAD( "wbv_01.bin", 0x00000, 0x100000, CRC(ac33f25f) SHA1(5d9ed16650aeb297d565376a99b31c88ab611668) ) /* $00000-$20000 stays the same in all sound banks, */ /* the second half of the bank is what gets switched */ ROM_REGION( 0x1c0000, "oki", 0 ) /* Samples */ ROM_COPY( "user2", 0x000000, 0x000000, 0x020000) ROM_COPY( "user2", 0x020000, 0x020000, 0x020000) ROM_COPY( "user2", 0x000000, 0x040000, 0x020000) ROM_COPY( "user2", 0x040000, 0x060000, 0x020000) ROM_COPY( "user2", 0x000000, 0x080000, 0x020000) ROM_COPY( "user2", 0x060000, 0x0a0000, 0x020000) ROM_COPY( "user2", 0x000000, 0x0c0000, 0x020000) ROM_COPY( "user2", 0x080000, 0x0e0000, 0x020000) ROM_COPY( "user2", 0x000000, 0x100000, 0x020000) ROM_COPY( "user2", 0x0a0000, 0x120000, 0x020000) ROM_COPY( "user2", 0x000000, 0x140000, 0x020000) ROM_COPY( "user2", 0x0c0000, 0x160000, 0x020000) ROM_COPY( "user2", 0x000000, 0x180000, 0x020000) ROM_COPY( "user2", 0x0e0000, 0x1a0000, 0x020000) ROM_END ROM_START( excelsr ) ROM_REGION( 0x300000, "maincpu", 0 ) /* 68000 code */ ROM_LOAD16_BYTE( "22.u301", 0x000001, 0x80000, CRC(f0aa1c1b) SHA1(5ed68181defe6cde6f4979508f0cfce9e9743912) ) ROM_LOAD16_BYTE( "19.u302", 0x000000, 0x80000, CRC(9a8acddc) SHA1(c7868317998bb98c630685a0b242ffd1fbdc54ed) ) ROM_LOAD16_BYTE( "21.u303", 0x100001, 0x80000, CRC(fdf9bd64) SHA1(783e3b8b70f8751915715e2455990c1c8eec6a71) ) ROM_LOAD16_BYTE( "18.u304", 0x100000, 0x80000, CRC(fe517e0e) SHA1(fa074c3848046b59f1026f9ce1f264b49560668d) ) ROM_LOAD16_BYTE( "20.u305", 0x200001, 0x80000, CRC(8692afe9) SHA1(b4411bad64a9a6efd8eb13dcf7c5eebfb5681f3d) ) ROM_LOAD16_BYTE( "17.u306", 0x200000, 0x80000, CRC(978f9a6b) SHA1(9514b97f071fd20740218a58af877765beffedad) ) ROM_REGION( 0x1000, "audiocpu", ROMREGION_ERASE00 ) /* sound (PIC16C57) */ /* ROM will be copied here by the init code from "user1" */ ROM_REGION( 0x3000, "user1", 0 ) ROM_LOAD( "pic16c57-hs.i015", 0x0000, 0x2d4c, CRC(022c6941) SHA1(8ead40bfa7aa783b1ce62bd6cfa673cb876e29e7) ) ROM_REGION( 0x200000, "gfx1", 0 ) ROM_LOAD( "26.u311", 0x000000, 0x80000, CRC(c171c059) SHA1(7bc45ef1d588f5f55a461adb91bca382155c1059) ) ROM_LOAD( "30.u312", 0x080000, 0x80000, CRC(b4a4c510) SHA1(07951a4c18bb25b10f650fd85b6bab566d0ef971) ) ROM_LOAD( "25.u313", 0x100000, 0x80000, CRC(667eec1b) SHA1(9e5ed82a4966244a97d18c27466179771012b305) ) ROM_LOAD( "29.u314", 0x180000, 0x80000, CRC(4acb0745) SHA1(6b5feaa5aa088f0cc5799f73ee5f90ed390165a9) ) ROM_REGION( 0x200000, "gfx2", 0 ) ROM_LOAD( "24.u321", 0x000000, 0x80000, CRC(17f46825) SHA1(6ac0e71498ac668641c0b7134ddd19cc4cc97005) ) ROM_LOAD( "28.u322", 0x080000, 0x80000, CRC(a823f2bd) SHA1(c7f1b1ee8f7069522787b6916b8c6e4591b55782) ) ROM_LOAD( "23.u323", 0x100000, 0x80000, CRC(d8e1453b) SHA1(a3edb05abe486d4cce30f5caf14be619b6886f7c) ) ROM_LOAD( "27.u324", 0x180000, 0x80000, CRC(eca2c079) SHA1(a07957b427d55c8ca1efb0e83ee3b603f06bed58) ) ROM_REGION( 0x80000, "user2", 0 ) /* OKIM6295 samples */ ROM_LOAD( "16.i013", 0x000000, 0x80000, CRC(7ed9da5d) SHA1(352f1e89613feb1902b6d87adb996ed1c1d8108e) ) /* $00000-$20000 stays the same in all sound banks, */ /* the second half of the bank is what gets switched */ ROM_REGION( 0xc0000, "oki", 0 ) /* Samples */ ROM_COPY( "user2", 0x000000, 0x000000, 0x020000) ROM_COPY( "user2", 0x020000, 0x020000, 0x020000) ROM_COPY( "user2", 0x000000, 0x040000, 0x020000) ROM_COPY( "user2", 0x040000, 0x060000, 0x020000) ROM_COPY( "user2", 0x000000, 0x080000, 0x020000) ROM_COPY( "user2", 0x060000, 0x0a0000, 0x020000) ROM_END /* Hot Mind Playmark, 1995 PCB Layout ---------- HARD TIMES 28-06-94 |---------------------------------------------------------| | ROM20 | | PAL | | M6295 PAL ROM23 ROM27 | | 1MHz PAL ROM24 ROM28 | |-----| PIC16C57 62256 | | | 62256 | |93C46|J 6116 ROM25 ROM29 | | |A 6116 |--------| ROM26 ROM30 | | |M |TPC1020 | | |J |M |AFN-084C| | |A |A | | | |M | 26MHz |--------| | |M | | |A | DSW1 | | | | | | DSW2 PAL | | | | |-----| 68000 6116 | | 6116 6116 | | 62256 62256 6116 PAL | | 24MHz 6116 | | ROM21 ROM22 6116 | |---------------------------------------------------------| Notes: 68000 CPU clock - 12.000MHz [24/2] M6295 clock - 1.000MHz. Sample rate = 1000000/132 PIC16C57 clock - OCS1/CLKIN 12.000MHz (on pin 27, but internally divided by 4 at 3.000MHz) Note PIC is secured, contents can not be read out. VSync - 58Hz HSync - 14.25kHz */ ROM_START( hotmind ) ROM_REGION( 0x40000, "maincpu", 0 ) /* 68000 code */ ROM_LOAD16_BYTE( "21.u87", 0x00000, 0x20000, CRC(e9000f7f) SHA1(c19fee7b774d3f30f4d4025a63ec396ec119c855) ) ROM_LOAD16_BYTE( "22.u68", 0x00001, 0x20000, CRC(2c518ec5) SHA1(6d9e81ddb5793d64e22dc0254519b947f6ec6954) ) ROM_REGION( 0x1000, "audiocpu", ROMREGION_ERASE00 ) /* sound (PIC16C57) */ /* ROM will be copied here by the init code from "user1" */ /* original PIC (which is the one from Hard Times) was protected, but it works with the Excelsior one because it uses only 1 bank of samples */ ROM_REGION( 0x3000, "user1", 0 ) ROM_LOAD( "pic16c57-hs.i015", 0x0000, 0x2d4c, BAD_DUMP CRC(022c6941) SHA1(8ead40bfa7aa783b1ce62bd6cfa673cb876e29e7) ) ROM_REGION( 0x200000, "gfx1", 0 ) ROM_LOAD16_BYTE( "23.u36", 0x000000, 0x10000, CRC(ddcf60b9) SHA1(0c0fbc44131cb7d36c21bf5aead87b498c5684f5) ) ROM_CONTINUE( 0x080000, 0x10000 ) ROM_LOAD16_BYTE( "27.u42", 0x000001, 0x10000, CRC(413bbcf4) SHA1(d82ae9d26df1a69b760b3025048e47ab757d9175) ) ROM_CONTINUE( 0x080001, 0x10000 ) ROM_LOAD16_BYTE( "24.u39", 0x100000, 0x10000, CRC(4baa5b4c) SHA1(ee953ed9a4a45715d1ae39b5bb8b9b6505a4e95d) ) ROM_CONTINUE( 0x180000, 0x10000 ) ROM_LOAD16_BYTE( "28.u49", 0x100001, 0x10000, CRC(8df34d6a) SHA1(ca0d2ca7e0f2a302bc8b1a03c0c18ac72fe105ac) ) ROM_CONTINUE( 0x180001, 0x10000 ) ROM_REGION( 0x80000, "gfx2", 0 ) ROM_LOAD16_BYTE( "26.u34", 0x00000, 0x20000, CRC(ff8d3b75) SHA1(5427b70a61dee4c125877e040be21cb1cadb1af5) ) ROM_LOAD16_BYTE( "30.u85", 0x00001, 0x20000, CRC(87a640c7) SHA1(818ff3243cb3ed0189988348e6c2e954f0d3dd4f) ) ROM_LOAD16_BYTE( "25.u35", 0x40000, 0x20000, CRC(c4fd4445) SHA1(ab0c5a328a312740595b5c92a1050527140518f3) ) ROM_LOAD16_BYTE( "29.u83", 0x40001, 0x20000, CRC(0bebfb53) SHA1(d4342f808141b70af98c370004153a31d120e2a4) ) ROM_REGION( 0xc0000, "oki", 0 ) /* Samples */ ROM_LOAD( "20.io13", 0x00000, 0x40000, CRC(0bf3a3e5) SHA1(2ae06f37a6bcd20bc5fbaa90d970aba2ebf3cf5a) ) ROM_END ROM_START( hrdtimes ) ROM_REGION( 0x100000, "maincpu", 0 ) /* 68000 code */ ROM_LOAD16_BYTE( "31.u67", 0x00000, 0x80000, CRC(53eb041b) SHA1(7437da1ceb26e9518a3085560b8a42f37e77ace9) ) ROM_LOAD16_BYTE( "32.u66", 0x00001, 0x80000, CRC(f2c6b382) SHA1(d73affed091a261c4bfe17f409657e0a46b6c163) ) ROM_REGION( 0x1000, "audiocpu", ROMREGION_ERASE00 ) /* sound (PIC16C57) */ ROM_LOAD( "pic16c57", 0x0000, 0x1000, NO_DUMP ) ROM_REGION( 0x200000, "gfx1", 0 ) ROM_LOAD16_BYTE( "33.u36", 0x000000, 0x80000, CRC(d1239ce5) SHA1(8e966a39a47f66c5e904ec4357c751e896ed47cb) ) ROM_LOAD16_BYTE( "37.u42", 0x000001, 0x80000, CRC(aa692005) SHA1(1e274da358a25ceebdc71cb8f7228ef39348a895) ) ROM_LOAD16_BYTE( "34.u39", 0x100000, 0x80000, CRC(e4108c59) SHA1(15f7b53a7bbdc4aefdae31a00be64c419326bfd1) ) ROM_LOAD16_BYTE( "38.u45", 0x100001, 0x80000, CRC(ff7cacf3) SHA1(5ed93e86fe3b0b594bdd62e314cd9e2ffd3c2a2a) ) ROM_REGION( 0x200000, "gfx2", 0 ) ROM_LOAD16_BYTE( "36.u86", 0x000000, 0x80000, CRC(f2fc1ca3) SHA1(f70913d9b89338932e62ca6bb60e5f5e412d7f64) ) ROM_LOAD16_BYTE( "40.u85", 0x000001, 0x80000, CRC(368c15f4) SHA1(8ae95fd672448921964c4d0312d7366903362e27) ) ROM_LOAD16_BYTE( "35.u84", 0x100000, 0x80000, CRC(7bde46ec) SHA1(1d26d268e1fc937e23ae7d93a1f86386b899a0c2) ) ROM_LOAD16_BYTE( "39.u83", 0x100001, 0x80000, CRC(a0bae586) SHA1(0b2bb0c5c51b2717b820f0176d5775df21652667) ) ROM_REGION( 0x80000, "user2", 0 ) /* OKIM6295 samples */ ROM_LOAD( "30.id13", 0x00000, 0x80000, CRC(fa5e50ae) SHA1(f3bd87c83fca9269cc2f19db1fbf55540c96f931) ) /* $00000-$20000 stays the same in all sound banks, */ /* the second half of the bank is what gets switched */ ROM_REGION( 0xc0000, "oki", 0 ) /* Samples */ ROM_COPY( "user2", 0x000000, 0x000000, 0x020000) ROM_COPY( "user2", 0x020000, 0x020000, 0x020000) ROM_COPY( "user2", 0x000000, 0x040000, 0x020000) ROM_COPY( "user2", 0x040000, 0x060000, 0x020000) ROM_COPY( "user2", 0x000000, 0x080000, 0x020000) ROM_COPY( "user2", 0x060000, 0x0a0000, 0x020000) ROM_END /* Different revision of the PCB, uses larger gfx ROMs, however the content is the same */ ROM_START( hrdtimesa ) ROM_REGION( 0x100000, "maincpu", 0 ) /* 68000 code */ ROM_LOAD16_BYTE( "u67.bin", 0x00000, 0x80000, CRC(3e1334cb) SHA1(9523c04f92371a35c297280b42b1604e23790a1e) ) ROM_LOAD16_BYTE( "u66.bin", 0x00001, 0x80000, CRC(041ec30a) SHA1(00476ebd0a64cbd027be159cae7666d2df6d11ba) ) ROM_REGION( 0x1000, "audiocpu", ROMREGION_ERASE00 ) /* sound (PIC16C57) */ ROM_LOAD( "pic16c57", 0x0000, 0x1000, NO_DUMP ) ROM_REGION( 0x200000, "gfx1", 0 ) ROM_LOAD( "fh1_playmark_ht", 0x000000, 0x100000, CRC(3cca02b0) SHA1(22c57f4192bf81dd26caa6adfb1c80665bdc305c) ) ROM_LOAD( "fh2_playmark_th", 0x100000, 0x100000, CRC(ed699acd) SHA1(23cf1da4e7462f7434e946a80bdd6df0395b3059) ) ROM_REGION( 0x200000, "gfx2", 0 ) ROM_LOAD( "mh1_playmark_ht", 0x000000, 0x100000, CRC(927e5989) SHA1(b01444a3ff57cc2e10594e23c0343c956ed3ee32) ) ROM_LOAD( "mh2_playmark_ht", 0x100000, 0x100000, CRC(e76f001b) SHA1(217c06ca3618275c22e33cfe318ec6c970d4862c) ) ROM_REGION( 0x80000, "user2", 0 ) /* OKIM6295 samples */ ROM_LOAD( "io13.bin", 0x00000, 0x80000, CRC(fa5e50ae) SHA1(f3bd87c83fca9269cc2f19db1fbf55540c96f931) ) /* $00000-$20000 stays the same in all sound banks, */ /* the second half of the bank is what gets switched */ ROM_REGION( 0xc0000, "oki", 0 ) /* Samples */ ROM_COPY( "user2", 0x000000, 0x000000, 0x020000) ROM_COPY( "user2", 0x020000, 0x020000, 0x020000) ROM_COPY( "user2", 0x000000, 0x040000, 0x020000) ROM_COPY( "user2", 0x040000, 0x060000, 0x020000) ROM_COPY( "user2", 0x000000, 0x080000, 0x020000) ROM_COPY( "user2", 0x060000, 0x0a0000, 0x020000) ROM_END static UINT8 playmark_asciitohex(UINT8 data) { /* Convert ASCII data to HEX */ if ((data >= 0x30) && (data < 0x3a)) data -= 0x30; data &= 0xdf; /* remove case sensitivity */ if ((data >= 0x41) && (data < 0x5b)) data -= 0x37; return data; } static DRIVER_INIT( bigtwin ) { playmark_state *state = machine->driver_data<playmark_state>(); UINT8 *playmark_PICROM_HEX = memory_region(machine, "user1"); UINT16 *playmark_PICROM = (UINT16 *)memory_region(machine, "audiocpu"); INT32 offs, data; UINT16 src_pos = 0; UINT16 dst_pos = 0; UINT8 data_hi, data_lo; state->snd_flag = 0; /**** Convert the PIC16C57 ASCII HEX dumps to pure HEX ****/ do { if ((playmark_PICROM_HEX[src_pos + 0] == ':') && (playmark_PICROM_HEX[src_pos + 1] == '1') && (playmark_PICROM_HEX[src_pos + 2] == '0')) { src_pos += 9; for (offs = 0; offs < 32; offs += 4) { data_hi = playmark_asciitohex((playmark_PICROM_HEX[src_pos + offs + 0])); data_lo = playmark_asciitohex((playmark_PICROM_HEX[src_pos + offs + 1])); if ((data_hi <= 0x0f) && (data_lo <= 0x0f)) { data = (data_hi << 4) | (data_lo << 0); data_hi = playmark_asciitohex((playmark_PICROM_HEX[src_pos + offs + 2])); data_lo = playmark_asciitohex((playmark_PICROM_HEX[src_pos + offs + 3])); if ((data_hi <= 0x0f) && (data_lo <= 0x0f)) { data |= (data_hi << 12) | (data_lo << 8); playmark_PICROM[dst_pos] = data; dst_pos += 1; } } } src_pos += 32; } /* Get the PIC16C57 Config register data */ if ((playmark_PICROM_HEX[src_pos + 0] == ':') && (playmark_PICROM_HEX[src_pos + 1] == '0') && (playmark_PICROM_HEX[src_pos + 2] == '2') && (playmark_PICROM_HEX[src_pos + 3] == '1')) { src_pos += 9; data_hi = playmark_asciitohex((playmark_PICROM_HEX[src_pos + 0])); data_lo = playmark_asciitohex((playmark_PICROM_HEX[src_pos + 1])); data = (data_hi << 4) | (data_lo << 0); data_hi = playmark_asciitohex((playmark_PICROM_HEX[src_pos + 2])); data_lo = playmark_asciitohex((playmark_PICROM_HEX[src_pos + 3])); data |= (data_hi << 12) | (data_lo << 8); pic16c5x_set_config(machine->device("audiocpu"), data); src_pos = 0x7fff; /* Force Exit */ } src_pos += 1; } while (src_pos < 0x2d4c); /* 0x2d4c is the size of the HEX rom loaded */ } GAME( 1995, bigtwin, 0, bigtwin, bigtwin, bigtwin, ROT0, "Playmark", "Big Twin", GAME_NO_COCKTAIL | GAME_SUPPORTS_SAVE ) GAME( 1995, wbeachvl, 0, wbeachvl, wbeachvl, 0, ROT0, "Playmark", "World Beach Volley (set 1)", GAME_NO_COCKTAIL | GAME_NO_SOUND | GAME_SUPPORTS_SAVE ) GAME( 1995, wbeachvl2, wbeachvl, wbeachvl, wbeachvl, 0, ROT0, "Playmark", "World Beach Volley (set 2)", GAME_NO_COCKTAIL | GAME_NO_SOUND | GAME_SUPPORTS_SAVE ) GAME( 1996, excelsr, 0, excelsr, excelsr, bigtwin, ROT0, "Playmark", "Excelsior", GAME_SUPPORTS_SAVE ) GAME( 1995, hotmind, 0, hotmind, hotmind, bigtwin, ROT0, "Playmark", "Hot Mind", GAME_SUPPORTS_SAVE ) GAME( 1994, hrdtimes, 0, hrdtimes, hrdtimes, 0, ROT0, "Playmark", "Hard Times (set 1)", GAME_NO_SOUND | GAME_SUPPORTS_SAVE ) GAME( 1994, hrdtimesa, hrdtimes, hrdtimes, hrdtimes, 0, ROT0, "Playmark", "Hard Times (set 2)", GAME_NO_SOUND | GAME_SUPPORTS_SAVE )
likebot0/core.h
include/core/meta/is_struct.h
#ifndef _core_meta_is_struct #define _core_meta_is_struct core_::core_meta_is_struct template<typename A> struct core_meta_is_struct_; template<typename A> inline constexpr auto core_meta_is_struct = core_meta_is_struct_<A>::value; #include <core/False.type.h> #include <core/Nullptr.type.h> #include <core/Remove_all_qualifiers.type.h> #include <core/True.type.h> #if __has_include(<type_traits>) #include <type_traits> #endif #if __has_include(<type_traits>) template<typename A> struct core_meta_is_struct_ { static constexpr auto value = [] () constexpr { if constexpr (std::is_class_v<A>) return _core_True{}; else return _core_False{}; }(); }; #endif template<> struct core_meta_is_struct_<_core_Nullptr> { static constexpr auto value = _core_True{}; }; #endif
wuzhongtuniu/adhoc-all
adhoc-solr/src/main/java/org/apache/lucene/store/LinkMMapDirectory.java
package org.apache.lucene.store; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Method; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; public class LinkMMapDirectory extends LinkFSDirectory{ private boolean useUnmapHack = MMapDirectory.UNMAP_SUPPORTED; private int chunkSizePower; public void setUseUnmap(final boolean useUnmapHack) { if (useUnmapHack && !MMapDirectory.UNMAP_SUPPORTED) throw new IllegalArgumentException("Unmap hack not supported on this platform!"); this.useUnmapHack=useUnmapHack; } public boolean getUseUnmap() { return useUnmapHack; } final void cleanMapping(final ByteBuffer buffer) throws IOException { if (useUnmapHack) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { final Method getCleanerMethod = buffer.getClass() .getMethod("cleaner"); getCleanerMethod.setAccessible(true); final Object cleaner = getCleanerMethod.invoke(buffer); if (cleaner != null) { cleaner.getClass().getMethod("clean") .invoke(cleaner); } return null; } }); } catch (PrivilegedActionException e) { final IOException ioe = new IOException("unable to unmap the mapped buffer"); ioe.initCause(e.getCause()); throw ioe; } } } public final void setMaxChunkSize(final int maxChunkSize) { if (maxChunkSize <= 0) throw new IllegalArgumentException("Maximum chunk size for mmap must be >0"); this.chunkSizePower = 31 - Integer.numberOfLeadingZeros(maxChunkSize); assert this.chunkSizePower >= 0 && this.chunkSizePower <= 30; } public final int getMaxChunkSize() { return 1 << chunkSizePower; } public LinkMMapDirectory(File path, LockFactory lockFactory) throws IOException { super(path, lockFactory); setMaxChunkSize(MMapDirectory.DEFAULT_MAX_BUFF); } /** Create a new MMapDirectory for the named location and {@link NativeFSLockFactory}. * * @param path the path of the directory * @throws IOException */ public LinkMMapDirectory(File path) throws IOException { super(path, null); setMaxChunkSize(MMapDirectory.DEFAULT_MAX_BUFF); } public IndexInput openInput(String name, int bufferSize) throws IOException { File file=null; if (!this.links.containsKey(name)) { file=new File(directory, name); }else{ file = this.links.get(name); } RandomAccessFile raf = new RandomAccessFile(file, "r"); try { return new LinkMMapIndexInput("MMapIndexInput(path=\"" + file + "\")", raf, chunkSizePower); } finally { raf.close(); } } private final class LinkMMapIndexInput extends IndexInput { private ByteBuffer[] buffers; private final long length, chunkSizeMask, chunkSize; private final int chunkSizePower; private int curBufIndex; private ByteBuffer curBuf; // redundant for speed: buffers[curBufIndex] private boolean isClone = false; LinkMMapIndexInput(String resourceDescription, RandomAccessFile raf, int chunkSizePower) throws IOException { super(resourceDescription); this.length = raf.length(); this.chunkSizePower = chunkSizePower; this.chunkSize = 1L << chunkSizePower; this.chunkSizeMask = chunkSize - 1L; if (chunkSizePower < 0 || chunkSizePower > 30) throw new IllegalArgumentException("Invalid chunkSizePower used for ByteBuffer size: " + chunkSizePower); if ((length >>> chunkSizePower) >= Integer.MAX_VALUE) throw new IllegalArgumentException("RandomAccessFile too big for chunk size: " + raf.toString()); // we always allocate one more buffer, the last one may be a 0 byte one final int nrBuffers = (int) (length >>> chunkSizePower) + 1; //System.out.println("length="+length+", chunkSizePower=" + chunkSizePower + ", chunkSizeMask=" + chunkSizeMask + ", nrBuffers=" + nrBuffers); this.buffers = new ByteBuffer[nrBuffers]; long bufferStart = 0L; FileChannel rafc = raf.getChannel(); for (int bufNr = 0; bufNr < nrBuffers; bufNr++) { int bufSize = (int) ( (length > (bufferStart + chunkSize)) ? chunkSize : (length - bufferStart) ); this.buffers[bufNr] = rafc.map(MapMode.READ_ONLY, bufferStart, bufSize); bufferStart += bufSize; } seek(0L); } @Override public byte readByte() throws IOException { try { return curBuf.get(); } catch (BufferUnderflowException e) { do { curBufIndex++; if (curBufIndex >= buffers.length) { throw new IOException("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.position(0); } while (!curBuf.hasRemaining()); return curBuf.get(); } } @Override public void readBytes(byte[] b, int offset, int len) throws IOException { try { curBuf.get(b, offset, len); } catch (BufferUnderflowException e) { int curAvail = curBuf.remaining(); while (len > curAvail) { curBuf.get(b, offset, curAvail); len -= curAvail; offset += curAvail; curBufIndex++; if (curBufIndex >= buffers.length) { throw new IOException("read past EOF: " + this); } curBuf = buffers[curBufIndex]; curBuf.position(0); curAvail = curBuf.remaining(); } curBuf.get(b, offset, len); } } @Override public int readInt() throws IOException { try { return curBuf.getInt(); } catch (BufferUnderflowException e) { return super.readInt(); } } @Override public long readLong() throws IOException { try { return curBuf.getLong(); } catch (BufferUnderflowException e) { return super.readLong(); } } @Override public long getFilePointer() { return (((long) curBufIndex) << chunkSizePower) + curBuf.position(); } @Override public void seek(long pos) throws IOException { // we use >> here to preserve negative, so we will catch AIOOBE: final int bi = (int) (pos >> chunkSizePower); try { final ByteBuffer b = buffers[bi]; b.position((int) (pos & chunkSizeMask)); // write values, on exception all is unchanged this.curBufIndex = bi; this.curBuf = b; } catch (ArrayIndexOutOfBoundsException aioobe) { if (pos < 0L) { throw new IllegalArgumentException("Seeking to negative position: " + this); } throw new IOException("seek past EOF"); } catch (IllegalArgumentException iae) { if (pos < 0L) { throw new IllegalArgumentException("Seeking to negative position: " + this); } throw new IOException("seek past EOF: " + this); } } @Override public long length() { return length; } @Override public Object clone() { if (buffers == null) { throw new AlreadyClosedException("MMapIndexInput already closed: " + this); } final LinkMMapIndexInput clone = (LinkMMapIndexInput)super.clone(); clone.isClone = true; clone.buffers = new ByteBuffer[buffers.length]; // Since most clones will use only one buffer, duplicate() could also be // done lazy in clones, e.g. when adapting curBuf. for (int bufNr = 0; bufNr < buffers.length; bufNr++) { clone.buffers[bufNr] = buffers[bufNr].duplicate(); } try { clone.seek(getFilePointer()); } catch(IOException ioe) { throw new RuntimeException("Should never happen: " + this, ioe); } return clone; } @Override public void close() throws IOException { try { if (isClone || buffers == null) return; for (int bufNr = 0; bufNr < buffers.length; bufNr++) { try { cleanMapping(buffers[bufNr]); } finally { buffers[bufNr] = null; } } } finally { buffers = null; } } } }
ElderDeveloper/UnrealExtendedFramework
Source/UnrealExtendedFramework/AI/BTService/Distance/EFBTServiceDistanceBetweenActors.cpp
<reponame>ElderDeveloper/UnrealExtendedFramework // Fill out your copyright notice in the Description page of Project Settings. #include "EFBTServiceDistanceBetweenActors.h" #include "AIController.h" #include "BehaviorTree/BlackboardComponent.h" // Sets default values UEFBTServiceDistanceBetweenActors::UEFBTServiceDistanceBetweenActors() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. bNotifyTick = true; } void UEFBTServiceDistanceBetweenActors::TickNode(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds) { Super::TickNode(OwnerComp, NodeMemory, DeltaSeconds); if (auto const AIController = Cast<AAIController>(OwnerComp.GetOwner())) { const auto OwnerActor = Cast<AActor>(AIController->GetBlackboardComponent()->GetValueAsObject(OwnerActorKey.SelectedKeyName)); const auto TargetActor = Cast<AActor>(AIController->GetBlackboardComponent()->GetValueAsObject(OwnerTargetKey.SelectedKeyName)); if (OwnerActor && TargetActor) { AIController->GetBlackboardComponent()->SetValueAsFloat(DistanceKey.SelectedKeyName,FVector(OwnerActor->GetActorLocation()-TargetActor->GetActorLocation()).Size()); return; } AIController->GetBlackboardComponent()->SetValueAsFloat(DistanceKey.SelectedKeyName,-1.f); } }
tharakamd/integration-studio
components/bps-tools/plugins/org.eclipse.bpel.model/src/org/eclipse/bpel/model/impl/ToImpl.java
/** * <copyright> * Copyright (c) 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * </copyright> * * $Id: ToImpl.java,v 1.14 2011/03/30 18:54:25 rbrodt Exp $ */ package org.eclipse.bpel.model.impl; import org.eclipse.bpel.model.AbstractAssignBound; import org.eclipse.bpel.model.BPELPackage; import org.eclipse.bpel.model.Expression; import org.eclipse.bpel.model.PartnerLink; import org.eclipse.bpel.model.Query; import org.eclipse.bpel.model.To; import org.eclipse.bpel.model.Variable; import org.eclipse.bpel.model.messageproperties.Property; import org.eclipse.bpel.model.proxy.PartProxy; import org.eclipse.bpel.model.util.BPELConstants; import org.eclipse.bpel.model.util.ReconciliationHelper; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.wst.wsdl.Message; import org.eclipse.wst.wsdl.Part; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>To</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.bpel.model.impl.ToImpl#getVariable <em>Variable</em>}</li> * <li>{@link org.eclipse.bpel.model.impl.ToImpl#getPart <em>Part</em>}</li> * <li>{@link org.eclipse.bpel.model.impl.ToImpl#getPartnerLink <em>Partner Link</em>}</li> * <li>{@link org.eclipse.bpel.model.impl.ToImpl#getProperty <em>Property</em>}</li> * <li>{@link org.eclipse.bpel.model.impl.ToImpl#getQuery <em>Query</em>}</li> * <li>{@link org.eclipse.bpel.model.impl.ToImpl#getExpression <em>Expression</em>}</li> * </ul> * </p> * * @generated */ public class ToImpl extends BPELExtensibleElementImpl implements To { /** * The cached value of the '{@link #getVariable() <em>Variable</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getVariable() * @generated * @ordered */ protected Variable variable; /** * The cached value of the '{@link #getPart() <em>Part</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPart() * @generated * @ordered */ protected Part part; /** * The deserialized value of the part name. * @customized */ protected String partName = null; /** * The cached value of the '{@link #getPartnerLink() <em>Partner Link</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPartnerLink() * @generated * @ordered */ protected PartnerLink partnerLink; /** * The cached value of the '{@link #getProperty() <em>Property</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getProperty() * @generated * @ordered */ protected Property property; /** * The cached value of the '{@link #getQuery() <em>Query</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getQuery() * @generated * @ordered */ protected Query query; /** * The cached value of the '{@link #getExpression() <em>Expression</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getExpression() * @generated * @ordered */ protected Expression expression; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ToImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return BPELPackage.Literals.TO; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Variable getVariable() { if (variable != null && variable.eIsProxy()) { InternalEObject oldVariable = (InternalEObject) variable; variable = (Variable) eResolveProxy(oldVariable); if (variable != oldVariable) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, BPELPackage.TO__VARIABLE, oldVariable, variable)); } } return variable; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Variable basicGetVariable() { return variable; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> */ public void setVariable(Variable newVariable) { Variable oldVariable = variable; if (!isReconciling) { ReconciliationHelper.replaceAttribute(this, BPELConstants.AT_VARIABLE, newVariable == null ? null : newVariable.getName()); } variable = newVariable; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BPELPackage.TO__VARIABLE, oldVariable, variable)); } /** * Customizes {@link #getPartGen()} to lazy-resolve the part name. * @customized */ public Part getPart() { if (part == null && partName != null) { Variable aVar = getVariable(); if (variable != null) { Message message = aVar.getMessageType(); if (message != null) { // Create an part proxy with the deserialized part name. part = new PartProxy(eResource(), message, partName); partName = null; } } } return getPartGen(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Part getPartGen() { if (part != null && part.eIsProxy()) { InternalEObject oldPart = (InternalEObject) part; part = (Part) eResolveProxy(oldPart); if (part != oldPart) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, BPELPackage.TO__PART, oldPart, part)); } } return part; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Part basicGetPart() { return part; } /** * Set the deserialized value of the part name. * @customized */ public void setPartName(String newPartName) { partName = newPartName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> */ public void setPart(Part newPart) { Part oldPart = part; if (!isReconciling) { ReconciliationHelper.replaceAttribute(this, BPELConstants.AT_PART, newPart == null ? null : newPart.getName()); } part = newPart; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BPELPackage.TO__PART, oldPart, part)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PartnerLink getPartnerLink() { if (partnerLink != null && partnerLink.eIsProxy()) { InternalEObject oldPartnerLink = (InternalEObject) partnerLink; partnerLink = (PartnerLink) eResolveProxy(oldPartnerLink); if (partnerLink != oldPartnerLink) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, BPELPackage.TO__PARTNER_LINK, oldPartnerLink, partnerLink)); } } return partnerLink; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PartnerLink basicGetPartnerLink() { return partnerLink; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> */ public void setPartnerLink(PartnerLink newPartnerLink) { PartnerLink oldPartnerLink = partnerLink; if (!isReconciling) { ReconciliationHelper.replaceAttribute(this, BPELConstants.AT_PARTNER_LINK, newPartnerLink == null ? null : newPartnerLink.getName()); } partnerLink = newPartnerLink; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BPELPackage.TO__PARTNER_LINK, oldPartnerLink, partnerLink)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Property getProperty() { if (property != null && property.eIsProxy()) { InternalEObject oldProperty = (InternalEObject) property; property = (Property) eResolveProxy(oldProperty); if (property != oldProperty) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, BPELPackage.TO__PROPERTY, oldProperty, property)); } } return property; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Property basicGetProperty() { return property; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> */ public void setProperty(Property newProperty) { Property oldProperty = property; if (!isReconciling) { ReconciliationHelper.replaceAttribute(this, BPELConstants.AT_PROPERTY, newProperty == null ? null : newProperty.getQName()); } property = newProperty; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BPELPackage.TO__PROPERTY, oldProperty, property)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Query getQuery() { return query; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> */ public NotificationChain basicSetQuery(Query newQuery, NotificationChain msgs) { Query oldQuery = query; if (!isReconciling) { ReconciliationHelper.replaceChild(this, oldQuery, newQuery); } query = newQuery; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, BPELPackage.TO__QUERY, oldQuery, newQuery); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setQuery(Query newQuery) { if (newQuery != query) { NotificationChain msgs = null; if (query != null) msgs = ((InternalEObject) query).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - BPELPackage.TO__QUERY, null, msgs); if (newQuery != null) msgs = ((InternalEObject) newQuery).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - BPELPackage.TO__QUERY, null, msgs); msgs = basicSetQuery(newQuery, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BPELPackage.TO__QUERY, newQuery, newQuery)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Expression getExpression() { return expression; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> */ public NotificationChain basicSetExpression(Expression newExpression, NotificationChain msgs) { Expression oldExpression = expression; if (!isReconciling) { ReconciliationHelper.replaceExpression(this, newExpression); } expression = newExpression; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, BPELPackage.TO__EXPRESSION, oldExpression, newExpression); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setExpression(Expression newExpression) { if (newExpression != expression) { NotificationChain msgs = null; if (expression != null) msgs = ((InternalEObject) expression).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - BPELPackage.TO__EXPRESSION, null, msgs); if (newExpression != null) msgs = ((InternalEObject) newExpression).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - BPELPackage.TO__EXPRESSION, null, msgs); msgs = basicSetExpression(newExpression, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BPELPackage.TO__EXPRESSION, newExpression, newExpression)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case BPELPackage.TO__QUERY: return basicSetQuery(null, msgs); case BPELPackage.TO__EXPRESSION: return basicSetExpression(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case BPELPackage.TO__VARIABLE: if (resolve) return getVariable(); return basicGetVariable(); case BPELPackage.TO__PART: if (resolve) return getPart(); return basicGetPart(); case BPELPackage.TO__PARTNER_LINK: if (resolve) return getPartnerLink(); return basicGetPartnerLink(); case BPELPackage.TO__PROPERTY: if (resolve) return getProperty(); return basicGetProperty(); case BPELPackage.TO__QUERY: return getQuery(); case BPELPackage.TO__EXPRESSION: return getExpression(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case BPELPackage.TO__VARIABLE: setVariable((Variable) newValue); return; case BPELPackage.TO__PART: setPart((Part) newValue); return; case BPELPackage.TO__PARTNER_LINK: setPartnerLink((PartnerLink) newValue); return; case BPELPackage.TO__PROPERTY: setProperty((Property) newValue); return; case BPELPackage.TO__QUERY: setQuery((Query) newValue); return; case BPELPackage.TO__EXPRESSION: setExpression((Expression) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case BPELPackage.TO__VARIABLE: setVariable((Variable) null); return; case BPELPackage.TO__PART: setPart((Part) null); return; case BPELPackage.TO__PARTNER_LINK: setPartnerLink((PartnerLink) null); return; case BPELPackage.TO__PROPERTY: setProperty((Property) null); return; case BPELPackage.TO__QUERY: setQuery((Query) null); return; case BPELPackage.TO__EXPRESSION: setExpression((Expression) null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case BPELPackage.TO__VARIABLE: return variable != null; case BPELPackage.TO__PART: return part != null; case BPELPackage.TO__PARTNER_LINK: return partnerLink != null; case BPELPackage.TO__PROPERTY: return property != null; case BPELPackage.TO__QUERY: return query != null; case BPELPackage.TO__EXPRESSION: return expression != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) { if (baseClass == AbstractAssignBound.class) { switch (derivedFeatureID) { case BPELPackage.TO__VARIABLE: return BPELPackage.ABSTRACT_ASSIGN_BOUND__VARIABLE; case BPELPackage.TO__PART: return BPELPackage.ABSTRACT_ASSIGN_BOUND__PART; case BPELPackage.TO__PARTNER_LINK: return BPELPackage.ABSTRACT_ASSIGN_BOUND__PARTNER_LINK; case BPELPackage.TO__PROPERTY: return BPELPackage.ABSTRACT_ASSIGN_BOUND__PROPERTY; case BPELPackage.TO__QUERY: return BPELPackage.ABSTRACT_ASSIGN_BOUND__QUERY; case BPELPackage.TO__EXPRESSION: return BPELPackage.ABSTRACT_ASSIGN_BOUND__EXPRESSION; default: return -1; } } return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) { if (baseClass == AbstractAssignBound.class) { switch (baseFeatureID) { case BPELPackage.ABSTRACT_ASSIGN_BOUND__VARIABLE: return BPELPackage.TO__VARIABLE; case BPELPackage.ABSTRACT_ASSIGN_BOUND__PART: return BPELPackage.TO__PART; case BPELPackage.ABSTRACT_ASSIGN_BOUND__PARTNER_LINK: return BPELPackage.TO__PARTNER_LINK; case BPELPackage.ABSTRACT_ASSIGN_BOUND__PROPERTY: return BPELPackage.TO__PROPERTY; case BPELPackage.ABSTRACT_ASSIGN_BOUND__QUERY: return BPELPackage.TO__QUERY; case BPELPackage.ABSTRACT_ASSIGN_BOUND__EXPRESSION: return BPELPackage.TO__EXPRESSION; default: return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass); } } //ToImpl
SeanCode/CQUPT-JWZX-Jsoup
app/src/main/java/me/xyp/app/network/service/JwzxService.java
<reponame>SeanCode/CQUPT-JWZX-Jsoup package me.xyp.app.network.service; import me.xyp.app.config.Const; import okhttp3.ResponseBody; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; import retrofit2.http.Url; import rx.Observable; /** * Created by cc on 16/4/23. */ public interface JwzxService { @GET(Const.INDEX) Observable<ResponseBody> index(); @GET(Const.LOGIN) Observable<ResponseBody> login(); @FormUrlEncoded @POST(Const.LOGIN) Observable<ResponseBody> loginWithForm(@Field("id") String stuNum, @Field("psw") String psw, @Field("validationCode") String code); @GET(Const.PUBLIC_STU_COURSE_SCHEDULE) Observable<ResponseBody> pubStuCourseSchedule(@Query("xh") String xh); @GET(Const.COURSE_SCHEDULE) Observable<ResponseBody> courseSchedule(); @GET(Const.STU_EXAM_SCHEDULE) Observable<ResponseBody> examSchedule(); @GET(Const.STU_EXAM_SCHEDULE_MAKE_UP) Observable<ResponseBody> makeUpSchedule(); @GET(Const.STU_GRADE) Observable<ResponseBody> gradeList(); @GET(Const.STU_GRADE_ALL) Observable<ResponseBody> gradleListAll(); @GET(Const.STU_INFO) Observable<ResponseBody> studentInfo(); @GET(Const.ARTICLE_LIST) Observable<ResponseBody> articleList(@Query("dirId") String dirId); @GET(Const.ARTICLE_CONTENT) Observable<ResponseBody> articleContent(@Query("id") String id); }
EulerFormula/Java8InAction
src/main/java/algorithm/stack/LinkStack.java
<filename>src/main/java/algorithm/stack/LinkStack.java package algorithm.stack; /** * 链栈 */ public class LinkStack { private StackNode top; public void display(String msg) { System.out.println("=====" + msg + "====="); StackNode p = top; while (p != null) { System.out.print(String.format("%3c", p.getData())); p = p.getNext(); if (p != null) { System.out.print("->"); } } System.out.println(); } /** * 判栈空 */ public boolean isEmpty() { return top == null; } /** * 进栈 */ public StackNode push(char x) { //申请新结点 StackNode stackNode = new StackNode(); stackNode.setData(x); //将新结点插入栈顶 stackNode.setNext(top); //使top指向新的栈顶 top = stackNode; //返回栈顶指针 return top; } /** * 退栈 */ public Character pop() { StackNode p = top; if (isEmpty()) { System.out.println("stack empty"); return null; } else { //栈顶指针指向下一个结点 top = top.getNext(); Character ch = p.getData(); //删除p指向的结点 p = null; return ch; } } /** * 取栈顶元素 */ public Character getTop() { if (isEmpty()) { System.out.println("stack empty"); return null; } else { return top.getData(); } } public static void main(String[] args) { LinkStack linkStack = new LinkStack(); linkStack.push('t'); linkStack.push('e'); linkStack.push('s'); linkStack.push('t'); linkStack.display("进栈后当前元素"); linkStack.pop(); linkStack.pop(); linkStack.display("出栈后当前元素"); linkStack.pop(); linkStack.pop(); linkStack.pop(); } }
LaceyHyde/dsw-site
db/migrate/20130116164738_create_cmsimple_pages.cmsimple.rb
# This migration comes from cmsimple (originally 20120201221410) class CreateCmsimplePages < ActiveRecord::Migration[4.2] def change create_table :cmsimple_pages do |t| t.string :path, :null => false t.string :template t.text :content end add_index :cmsimple_pages, :path end end
fredyw/leetcode
src/main/java/leetcode/Problem225.java
package leetcode; import java.util.LinkedList; import java.util.Queue; /** * https://leetcode.com/problems/implement-stack-using-queues/ */ public class Problem225 { static class MyStack { private Queue<Integer> list1 = new LinkedList<>(); private Queue<Integer> list2 = new LinkedList<>(); // Push element x onto stack. public void push(int x) { while (!list1.isEmpty()) { list2.add(list1.remove()); } list1.add(x); while (!list2.isEmpty()) { list1.add(list2.remove()); } } // Removes the element on top of the stack. public void pop() { list1.remove(); } // Get the top element. public int top() { return list1.peek(); } // Return whether the stack is empty. public boolean empty() { return list1.isEmpty(); } } }
HgeX/Hazelnut
core/src/main/java/hazelnut/core/protocol/Heartbeat.java
<reponame>HgeX/Hazelnut package hazelnut.core.protocol; import hazelnut.core.Message; import org.jetbrains.annotations.NotNull; public class Heartbeat implements Message<Heartbeat> { @Override public @NotNull Class<Heartbeat> type() { return Heartbeat.class; } }
MarginC/kame
netbsd/sys/dev/i2c/at24cxx.c
/* $NetBSD: at24cxx.c,v 1.2 2004/03/11 15:11:53 christos Exp $ */ /* * Copyright (c) 2003 Wasabi Systems, Inc. * All rights reserved. * * Written by <NAME> and <NAME> for Wasabi Systems, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed for the NetBSD Project by * Wasabi Systems, Inc. * 4. The name of Wasabi Systems, Inc. may not be used to endorse * or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WASABI SYSTEMS, INC * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/device.h> #include <sys/kernel.h> #include <sys/fcntl.h> #include <sys/uio.h> #include <sys/conf.h> #include <sys/proc.h> #include <sys/event.h> #include <machine/bus.h> #include <dev/i2c/i2cvar.h> #include <dev/i2c/at24cxxvar.h> /* * AT24Cxx EEPROM I2C address: * * 101 0xxx */ #define AT24CXX_ADDRMASK 0x78 #define AT24CXX_ADDR 0x50 #define AT24CXX_WRITE_CYCLE_MS 10 #define AT24CXX_ADDR_HI(a) (((a) >> 8) & 0x1f) #define AT24CXX_ADDR_LO(a) ((a) & 0xff) #include "seeprom.h" #if NSEEPROM > 0 struct seeprom_softc { struct device sc_dev; i2c_tag_t sc_tag; int sc_address; int sc_size; int sc_cmdlen; int sc_open; }; static int seeprom_match(struct device *, struct cfdata *, void *); static void seeprom_attach(struct device *, struct device *, void *); CFATTACH_DECL(seeprom, sizeof(struct seeprom_softc), seeprom_match, seeprom_attach, NULL, NULL); extern struct cfdriver seeprom_cd; dev_type_open(seeprom_open); dev_type_close(seeprom_close); dev_type_read(seeprom_read); dev_type_write(seeprom_write); const struct cdevsw seeprom_cdevsw = { seeprom_open, seeprom_close, seeprom_read, seeprom_write, noioctl, nostop, notty, nopoll, nommap, nokqfilter }; static int seeprom_wait_idle(struct seeprom_softc *); static int seeprom_match(struct device *parent, struct cfdata *cf, void *aux) { struct i2c_attach_args *ia = aux; if ((ia->ia_addr & AT24CXX_ADDRMASK) == AT24CXX_ADDR) return (1); return (0); } static void seeprom_attach(struct device *parent, struct device *self, void *aux) { struct seeprom_softc *sc = (struct seeprom_softc *)self; struct i2c_attach_args *ia = aux; sc->sc_tag = ia->ia_tag; sc->sc_address = ia->ia_addr; aprint_naive(": EEPROM\n"); aprint_normal(": AT24Cxx EEPROM\n"); /* * The AT24C01A/02/04/08/16 EEPROMs use a 1 byte command * word to select the offset into the EEPROM page. The * AT24C04/08/16 decode fewer of the i2c address bits, * using the bottom 1, 2, or 3 to select the 256-byte * super-page. * * The AT24C32/64 EEPROMs use a 2 byte command word and * decode all of the i2c address bits. */ sc->sc_size = ia->ia_size; switch (sc->sc_size) { case 128: /* 1Kbit */ case 256: /* 2Kbit */ case 512: /* 4Kbit */ case 1024: /* 8Kbit */ case 2048: /* 16Kbit */ sc->sc_cmdlen = 1; break; case 4096: /* 32Kbit */ case 8192: /* 64Kbit */ sc->sc_cmdlen = 2; break; default: /* * Default to 2KB. If we happen to have a 2KB * EEPROM this will allow us to access it. If we * have a smaller one, the worst that can happen * is that we end up trying to read a different * EEPROM on the bus when accessing it. * * Obviously this will not work for 4KB or 8KB * EEPROMs, but them's the breaks. */ aprint_error("%s: invalid size specified; " "assuming 2KB (16Kb)\n", sc->sc_dev.dv_xname); sc->sc_size = 2048; sc->sc_cmdlen = 1; } sc->sc_open = 0; } /*ARGSUSED*/ int seeprom_open(dev_t dev, int flag, int fmt, struct proc *p) { struct seeprom_softc *sc; if ((sc = device_lookup(&seeprom_cd, minor(dev))) == NULL) return (ENXIO); /* XXX: Locking */ if (sc->sc_open) return (EBUSY); sc->sc_open = 1; return (0); } /*ARGSUSED*/ int seeprom_close(dev_t dev, int flag, int fmt, struct proc *p) { struct seeprom_softc *sc; if ((sc = device_lookup(&seeprom_cd, minor(dev))) == NULL) return (ENXIO); sc->sc_open = 0; return (0); } /*ARGSUSED*/ int seeprom_read(dev_t dev, struct uio *uio, int flags) { struct seeprom_softc *sc; i2c_addr_t addr; u_int8_t ch, cmdbuf[2]; int a, error; if ((sc = device_lookup(&seeprom_cd, minor(dev))) == NULL) return (ENXIO); if (uio->uio_offset >= sc->sc_size) return (EINVAL); if ((error = iic_acquire_bus(sc->sc_tag, 0)) != 0) return (error); /* * Even though the AT24Cxx EEPROMs support sequential * reads within a page, some I2C controllers do not * support anything other than single-byte transfers, * so we're stuck with this lowest-common-denominator. */ while (uio->uio_resid > 0 && uio->uio_offset < sc->sc_size) { a = (int)uio->uio_offset; if (sc->sc_cmdlen == 1) { addr = sc->sc_address + (a >> 8); cmdbuf[0] = a & 0xff; } else { addr = sc->sc_address; cmdbuf[0] = AT24CXX_ADDR_HI(a); cmdbuf[1] = AT24CXX_ADDR_LO(a); } if ((error = iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, addr, cmdbuf, sc->sc_cmdlen, &ch, 1, 0)) != 0) { iic_release_bus(sc->sc_tag, 0); printf("%s: seeprom_read: byte read failed at 0x%x\n", sc->sc_dev.dv_xname, a); return (error); } if ((error = uiomove(&ch, 1, uio)) != 0) { iic_release_bus(sc->sc_tag, 0); return (error); } } iic_release_bus(sc->sc_tag, 0); return (0); } /*ARGSUSED*/ int seeprom_write(dev_t dev, struct uio *uio, int flags) { struct seeprom_softc *sc; i2c_addr_t addr; u_int8_t ch, cmdbuf[2]; int a, error; if ((sc = device_lookup(&seeprom_cd, minor(dev))) == NULL) return (ENXIO); if (uio->uio_offset >= sc->sc_size) return (EINVAL); if ((error = iic_acquire_bus(sc->sc_tag, 0)) != 0) return (error); /* * See seeprom_read() for why we don't use sequential * writes within a page. */ while (uio->uio_resid > 0 && uio->uio_offset < sc->sc_size) { a = (int)uio->uio_offset; if (sc->sc_cmdlen == 1) { addr = sc->sc_address + (a >> 8); cmdbuf[0] = a & 0xff; } else { addr = sc->sc_address; cmdbuf[0] = AT24CXX_ADDR_HI(a); cmdbuf[1] = AT24CXX_ADDR_LO(a); } if ((error = uiomove(&ch, 1, uio)) != 0) { iic_release_bus(sc->sc_tag, 0); return (error); } if ((error = iic_exec(sc->sc_tag, I2C_OP_WRITE_WITH_STOP, addr, cmdbuf, sc->sc_cmdlen, &ch, 1, 0)) != 0) { iic_release_bus(sc->sc_tag, 0); printf("%s: seeprom_write: byte write failed at 0x%x\n", sc->sc_dev.dv_xname, a); return (error); } /* Wait until the device commits the byte. */ if ((error = seeprom_wait_idle(sc)) != 0) { iic_release_bus(sc->sc_tag, 0); return (error); } } iic_release_bus(sc->sc_tag, 0); return (0); } static int seeprom_wait_idle(struct seeprom_softc *sc) { uint8_t cmdbuf[2] = { 0, 0 }; int rv, timeout; u_int8_t dummy; timeout = (1000 / hz) / AT24CXX_WRITE_CYCLE_MS; if (timeout == 0) timeout = 1; delay(10); /* * Read the byte at address 0. This is just a dummy * read to wait for the EEPROM's write cycle to complete. */ while (iic_exec(sc->sc_tag, I2C_OP_READ_WITH_STOP, sc->sc_address, cmdbuf, sc->sc_cmdlen, &dummy, 1, 0)) { rv = tsleep(sc, PRIBIO | PCATCH, "seepromwr", timeout); if (rv != EWOULDBLOCK) return (rv); } return (0); } #endif /* NSEEPROM > 0 */ int seeprom_bootstrap_read(i2c_tag_t tag, int i2caddr, int offset, int devsize, u_int8_t *rvp, size_t len) { i2c_addr_t addr; int cmdlen; uint8_t cmdbuf[2]; if (len == 0) return (0); /* We are very forgiving about devsize during bootstrap. */ cmdlen = (devsize >= 4096) ? 2 : 1; if (iic_acquire_bus(tag, I2C_F_POLL) != 0) return (-1); while (len) { if (cmdlen == 1) { addr = i2caddr + (offset >> 8); cmdbuf[0] = offset & 0xff; } else { addr = i2caddr; cmdbuf[0] = AT24CXX_ADDR_HI(offset); cmdbuf[1] = AT24CXX_ADDR_LO(offset); } /* Read a single byte. */ if (iic_exec(tag, I2C_OP_READ_WITH_STOP, addr, cmdbuf, cmdlen, rvp, 1, I2C_F_POLL)) { iic_release_bus(tag, I2C_F_POLL); return (-1); } len--; rvp++; offset++; } iic_release_bus(tag, I2C_F_POLL); return (0); }
aic-sri-international/aic-util
src/main/java/com/sri/ai/util/graph2d/api/variables/Value.java
<filename>src/main/java/com/sri/ai/util/graph2d/api/variables/Value.java package com.sri.ai.util.graph2d.api.variables; /** * The value of a variable; can represent any Java object but typically this will be numbers and strings. */ public interface Value { static Value value(Object value) { DefaultValue defaultValue = new DefaultValue(value); return defaultValue; } String stringValue(); int intValue(); double doubleValue(); }
bgalloway1/enroll
spec/models/rule_set/coverage_household/individual_market_verification_spec.rb
require "rails_helper" if ExchangeTestingConfigurationHelper.individual_market_is_enabled? describe RuleSet::CoverageHousehold::IndividualMarketVerification do subject { RuleSet::CoverageHousehold::IndividualMarketVerification.new(coverage_household) } let(:coverage_household) { instance_double(CoverageHousehold, :active_individual_enrollments => active_individual_policies) } describe "in a coverage household with no active individual policies" do let(:active_individual_policies) { [] } it "should not be applicable" do expect(subject.applicable?).to eq false end end describe "in a coverage household with active individual policies" do let(:enrollment_members) { [] } let(:active_individual_policy) { instance_double(HbxEnrollment, :hbx_enrollment_members => enrollment_members) } let(:active_individual_policies) { [active_individual_policy] } it "should be applicable" do expect(subject.applicable?).to eq true end describe "in a coverage household with 2 members" do let(:consumer_role_1) { instance_double(ConsumerRole) } let(:person_1) { instance_double(Person, :consumer_role => consumer_role_1) } let(:member_1) { instance_double(HbxEnrollmentMember, :person => person_1) } let(:consumer_role_2) { instance_double(ConsumerRole) } let(:person_2) { instance_double(Person, :consumer_role => consumer_role_2) } let(:member_2) { instance_double(HbxEnrollmentMember, :person => person_2) } describe "where both of the members are enrolled" do describe "where one of the members is pending and the other has passed validation" do let(:enrollment_members) { [member_1, member_2] } before :each do allow(consumer_role_1).to receive(:ssa_pending?).and_return(false) allow(consumer_role_2).to receive(:ssa_pending?).and_return(true) end it "should recommend the unverified state" do expect(subject.determine_next_state).to eq(:move_to_pending!) end end describe "where one of the members is pending and the other has failed validation" do let(:enrollment_members) { [member_1, member_2] } before :each do allow(consumer_role_1).to receive(:ssa_pending?).and_return(true) allow(consumer_role_2).to receive(:ssa_pending?).and_return(false) end it "should recommend the unverified state" do expect(subject.determine_next_state).to eq(:move_to_pending!) end end describe "where one of the members is verified and the other has failed validation" do let(:enrollment_members) { [member_1, member_2] } before :each do allow(consumer_role_1).to receive(:ssa_pending?).and_return(false) allow(consumer_role_2).to receive(:ssa_pending?).and_return(false) allow(consumer_role_1).to receive(:dhs_pending?).and_return(false) allow(consumer_role_2).to receive(:dhs_pending?).and_return(false) allow(consumer_role_1).to receive(:verification_outstanding?).and_return(false) allow(consumer_role_2).to receive(:verification_outstanding?).and_return(true) end it "should recommend the enrolled_contingent state" do expect(subject.determine_next_state).to eq(:move_to_contingent!) end end end end end end end
jattenberg/parallax
src/main/java/com/dsi/parallax/ml/util/HashFunctionType.java
/******************************************************************************* * Copyright 2012 <NAME>. Not for re-use or redistribution. ******************************************************************************/ package com.dsi.parallax.ml.util; import java.security.MessageDigest; public enum HashFunctionType { SHA { @Override public int hash(String input, int bins) { byte[] bytes = sha.digest(input.getBytes()); int out = 17; for(byte b : bytes) out = 31*out+b; return Math.abs(out)%bins; } }, MD5 { @Override public int hash(String input, int bins) { byte[] bytes = md5.digest(input.getBytes()); int out = 17; for(byte b : bytes) out = 31*out+b; return Math.abs(out)%bins; } }, JENKINS { @Override public int hash(String token, int bins) { // alternate hash function. // slower then String.hashCode(), but possibly is a more uniform // hash // function byte[] input = token.getBytes(); return jenkinsHashOnBytes(bins, input); } }, JAVA { @Override public int hash(String input, int bins) { return Math.abs((input).hashCode()) % bins; } }; static MessageDigest md5, sha; static { try { md5 = MessageDigest.getInstance("MD5"); sha = MessageDigest.getInstance("SHA-256"); } catch (Exception e) { // TODO: handle exception } } public abstract int hash(String input, int bins); private static int jenkinsHashOnBytes(int bins, byte[] input) { long hash = 0; String key = new String(input); for (int i = 0; i < key.length(); i++) { hash += key.charAt(i); hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return (int) Math.abs(hash % bins); } }
j-h-m/Media-Journaling-Tool
plugins/DLIBFaceSelection/__init__.py
import cv2 import dlib # path to pretrained model utilized in face detection # assumes the model file is in the same directory as this code, please specify full path in case this condition is invalid on user's local machine import numpy PREDICTOR_PATH = "pretrained_model.dat" # pre-defined parameters used by the dlib library towards face detection SCALE_FACTOR = 1 FEATHER_AMOUNT = 11 FACE_POINTS = list(range(17, 68)) MOUTH_POINTS = list(range(48, 61)) RIGHT_BROW_POINTS = list(range(17, 22)) LEFT_BROW_POINTS = list(range(22, 27)) RIGHT_EYE_POINTS = list(range(36, 42)) LEFT_EYE_POINTS = list(range(42, 48)) NOSE_POINTS = list(range(27, 35)) JAW_POINTS = list(range(0, 17)) # Points used to line up the face patch in donor and recipient images ALIGN_POINTS = (LEFT_BROW_POINTS + RIGHT_EYE_POINTS + LEFT_EYE_POINTS + RIGHT_BROW_POINTS + NOSE_POINTS + MOUTH_POINTS) # Points from the donor image to overlay on the recipient image OVERLAY_POINTS = [ LEFT_EYE_POINTS + RIGHT_EYE_POINTS + LEFT_BROW_POINTS + RIGHT_BROW_POINTS, NOSE_POINTS + MOUTH_POINTS, ] # blur to use during color correction COLOR_CORRECT_BLUR_FRAC = 0.6 # instantiate objects from dlib library classes for face detection detector = dlib.get_frontal_face_detector() predictor = None class TooManyFaces(Exception): pass class NoFaces(Exception): pass def loadModel(path=None): global predictor if predictor is None: path = PREDICTOR_PATH if path is None else path predictor = dlib.shape_predictor(path) def get_landmarks(im): global predictor rects = detector(im, 1) if len(rects) > 1: print('Image seems to have more than one detecable faces present.') if len(rects) == 0: raise NoFaces return numpy.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()]) def annotate_landmarks(im, landmarks): im = im.copy() for idx, point in enumerate(landmarks): pos = (point[0, 0], point[0, 1]) cv2.putText(im, str(idx), pos, fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, fontScale=0.4, color=(0, 0, 255)) cv2.circle(im, pos, 3, color=(0, 255, 255)) return im def read_im_and_landmarks(fname): """ Read the computed facial landmarks """ im = cv2.imread(fname, cv2.IMREAD_COLOR) im = cv2.resize(im, (im.shape[1] * SCALE_FACTOR, im.shape[0] * SCALE_FACTOR)) s = get_landmarks(im) return im, s def draw_convex_hull(im, points, color): points = cv2.convexHull(points) cv2.fillConvexPoly(im, points, color=color) def get_face_mask(im, landmarks): im = numpy.zeros(im.shape[:2], dtype=numpy.float64) for group in OVERLAY_POINTS: draw_convex_hull(im, landmarks[group], color=1) im = numpy.array([im, im, im]).transpose((1, 2, 0)) im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0 im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) return im def transform(img, source, target, **kwargs): loadModel(kwargs['model'].strip()) im2, landmarks2 = read_im_and_landmarks(source) mask = get_face_mask(im2, landmarks2) im = cv2.imread(source) im = numpy.array(im) mask[mask > 0.5] = 255 fin = numpy.concatenate((im, mask[:,:,0:1]), axis=2) cv2.imwrite(target, fin) return {'subject':'face','location change':'no'}, None def operation(): return {'name': 'SelectRegion', 'category': 'Select', 'description': 'Select a face based on DLIB trained model', 'software': 'DLIB', 'version': '19.9', 'arguments': {'alpha': {'type': "yesno", "defaultvalue": "yes", 'description': "If yes, save the image with an alpha channel instead of the mask."}, 'model': {'type': 'text', 'description': 'The face selection model'}}, 'transitions': [ 'image.image' ] } def suffix(): return None
AxeyGabriel/dummy_load
spl/src/stm8s_flash_ProgramOptionByte.c
/** ******************************************************************************** * @file stm8s_flash_ProgramOptionByte.c * @author MCD Application Team * @version V2.2.0 * @date 30-September-2014 * @brief This file contains all the functions for the UART1 peripheral. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm8s_flash.h" #include "private/stm8s_flash_private.h" /** @addtogroup STM8S_StdPeriph_Driver * @{ */ /** @} * @addtogroup FLASH_Public_Functions * @{ */ /** * @brief Programs option byte * @param Address : option byte address to program * @param Data : Value to write * @retval None */ void FLASH_ProgramOptionByte(uint16_t Address, uint8_t Data) { /* Check parameter */ assert_param(IS_OPTION_BYTE_ADDRESS_OK(Address)); /* Enable write access to option bytes */ FLASH->CR2 |= FLASH_CR2_OPT; FLASH->NCR2 &= (uint8_t)(~FLASH_NCR2_NOPT); /* check if the option byte to program is ROP*/ if(Address == 0x4800) { /* Program option byte*/ *((NEAR uint8_t*)Address) = Data; } else { /* Program option byte and his complement */ *((NEAR uint8_t*)Address) = Data; *((NEAR uint8_t*)((uint16_t)(Address + 1))) = (uint8_t)(~Data); } FLASH_WaitForLastOperation(FLASH_MEMTYPE_PROG); /* Disable write access to option bytes */ FLASH->CR2 &= (uint8_t)(~FLASH_CR2_OPT); FLASH->NCR2 |= FLASH_NCR2_NOPT; } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
DarkHighness/HeCBench
bmf-hip/src/helper/rngpu.hpp
<filename>bmf-hip/src/helper/rngpu.hpp #ifndef RNGPU_HPP #define RNGPU_HPP #include <stdint.h> #if defined(__HIPCC__) #define INLINE_QUALIFIERS __host__ __device__ inline #else #include <math.h> #define INLINE_QUALIFIERS #endif ////////////////////////////////////////////////////////////////////////////// // Thomas Mueller hash for initialization of rngs // http://stackoverflow.com/questions/664014/ // what-integer-hash-function-are-good-that-accepts-an-integer-hash-key ////////////////////////////////////////////////////////////////////////////// #define hash32(x) (nvidia_hash(x)) INLINE_QUALIFIERS uint32_t mueller_hash(uint32_t x) { x = ((x >> 16) ^ x) * 0x45d9f3b; x = ((x >> 16) ^ x) * 0x45d9f3b; x = ((x >> 16) ^ x); return x; } INLINE_QUALIFIERS uint32_t nvidia_hash(uint32_t x) { x = (x + 0x7ed55d16) + (x << 12); x = (x ^ 0xc761c23c) ^ (x >> 19); x = (x + 0x165667b1) + (x << 5); x = (x + 0xd3a2646c) ^ (x << 9); x = (x + 0xfd7046c5) + (x << 3); x = (x ^ 0xb55a4f09) ^ (x >> 16); return x; } ////////////////////////////////////////////////////////////////////////////// // hash random number generator (period unknown) ////////////////////////////////////////////////////////////////////////////// struct hashrng_state32_t { uint32_t x; }; template <uint32_t num_iters=4> INLINE_QUALIFIERS hashrng_state32_t get_initial_hashrng_state32(uint32_t seed) { hashrng_state32_t state; state.x = !seed ? 4294967295 : seed; for (uint32_t iter = 0; iter < num_iters; iter++) state.x = hash32(state.x); return state; } ////////////////////////////////////////////////////////////////////////////// // linear congruential generator ////////////////////////////////////////////////////////////////////////////// struct lcg_state32_t{ uint32_t x; }; INLINE_QUALIFIERS uint32_t lcg32(lcg_state32_t &state) { state.x = 314527869*state.x+1234567; return state.x; } template <uint32_t num_iters=8> INLINE_QUALIFIERS lcg_state32_t get_initial_lcg_state32(uint32_t seed) { lcg_state32_t state; state.x = !seed ? 4294967295 : seed; for (uint32_t iter = 0; iter < num_iters; iter++) state.x = hash32(state.x); return state; } ////////////////////////////////////////////////////////////////////////////// // keep it simple stupid generator ////////////////////////////////////////////////////////////////////////////// struct kiss_state32_t{ uint32_t x; uint32_t y; uint32_t z; uint32_t w; }; INLINE_QUALIFIERS uint32_t kiss32(kiss_state32_t &state) { // lcg state.x = 314527869*state.x+1234567; // xorshift state.y ^= state.y << 5; state.y ^= state.y >> 7; state.y ^= state.y << 22; // carry and multiply uint64_t t = 4294584393ULL*state.z+state.w; state.w = t; state.w = t >> 32; // combine return state.x+state.y+state.z; } template <uint32_t num_iters=8> INLINE_QUALIFIERS kiss_state32_t get_initial_kiss_state32(const uint32_t seed) { kiss_state32_t state; state.w = !seed ? 4294967295 : seed; for (uint32_t iter = 0; iter < num_iters; iter++) { state.x = hash32(state.w); state.y = hash32(state.x); state.z = hash32(state.y); state.w = hash32(state.z); } return state; } ////////////////////////////////////////////////////////////////////////////// // fast keep it simple stupid generator ////////////////////////////////////////////////////////////////////////////// struct fast_kiss_state32_t{ uint32_t x; uint32_t y; uint32_t z; uint32_t w; uint32_t c; }; INLINE_QUALIFIERS uint32_t fast_kiss32(fast_kiss_state32_t &state) { state.y ^= state.y << 5; state.y ^= state.y >> 7; state.y ^= state.y << 22; int32_t t = state.z+state.w+state.c; state.z = state.w; state.c = t < 0; state.w = t & 2147483647; state.x += 1411392427; // combine return state.x+state.y+state.w; } template <uint32_t num_iters=8> INLINE_QUALIFIERS fast_kiss_state32_t get_initial_fast_kiss_state32(const uint32_t seed) { fast_kiss_state32_t state; state.w = !seed ? 4294967295 : seed; for (uint32_t iter = 0; iter < num_iters; iter++) { state.x = hash32(state.w); state.y = hash32(state.x); state.z = hash32(state.y); state.w = hash32(state.z); } state.c = 0; return state; } ////////////////////////////////////////////////////////////////////////////// // xorwow random number generator ////////////////////////////////////////////////////////////////////////////// struct xorwow_state32_t{ uint32_t x; uint32_t y; uint32_t z; uint32_t w; uint32_t v; uint32_t d; }; INLINE_QUALIFIERS uint32_t xorwow32(xorwow_state32_t &state) { uint32_t t = (state.x^(state.x>>2)); state.x = state.y; state.y = state.z; state.z = state.w; state.v = (state.v^(state.v<<4))^(t^(t<<1)); state.d = state.d+362437; return state.v+state.d; } template <uint32_t num_iters=8> INLINE_QUALIFIERS xorwow_state32_t get_initial_xorwow_state32(uint32_t seed) { xorwow_state32_t state; state.d= !seed ? 4294967295 : seed; for (uint32_t iter = 0; iter < num_iters; iter++) { state.x = hash32(state.d); state.y = hash32(state.x); state.z = hash32(state.y); state.w = hash32(state.z); state.v = hash32(state.w); state.d = hash32(state.v); } return state; } ////////////////////////////////////////////////////////////////////////////// // meta functions for uniform sampling in [0, 1) ////////////////////////////////////////////////////////////////////////////// template <class rng_t, class state_t> INLINE_QUALIFIERS float uniform_float(rng_t rng, state_t * state) { uint32_t a = rng(state) >> 9; float x; *((unsigned int *)&x) = a | 0x3F800000; return x-1.0f; } template <class rng_t, class state_t> INLINE_QUALIFIERS double uniform_double(rng_t rng, state_t * state) { uint32_t a = rng(state) >> 6; uint32_t b = rng(state) >> 5; double x = (a * 134217728.0 + b) / 9007199254740992.0; return x; } ////////////////////////////////////////////////////////////////////////////// // shuffle functions for arrays ////////////////////////////////////////////////////////////////////////////// template <class rng_t, class state_t, class value_t, class index_t> INLINE_QUALIFIERS void fisher_yates_shuffle(rng_t rng, state_t * state, value_t * array, index_t length) { for (index_t i = length-1; i >= 1; i--) { index_t r = (double) rng(state) * (i + 1) / 4294967296.0; value_t temp = array[i]; array[i] = array[r]; array[r] = temp; } } #endif
mebigfatguy/clytemnestra
src/com/mebigfatguy/clytemnestra/controllers/ColumnFamiliesController.java
<filename>src/com/mebigfatguy/clytemnestra/controllers/ColumnFamiliesController.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 com.mebigfatguy.clytemnestra.controllers; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.apache.cassandra.thrift.Cassandra; import org.apache.cassandra.thrift.CfDef; import org.apache.cassandra.thrift.KsDef; import com.mebigfatguy.clytemnestra.Context; import com.mebigfatguy.clytemnestra.actions.OpenColumnFamilyAction; import com.mebigfatguy.clytemnestra.model.ColumnFamiliesTableModel; public class ColumnFamiliesController implements Controller<CfDef>, ListSelectionListener { private KsDef keySpace; private final Context context; private final JTable table; private final ColumnFamiliesTableModel model; public ColumnFamiliesController(KsDef ks, Context ctxt, JTable cfTable, ColumnFamiliesTableModel cfModel) { keySpace = ks; context = ctxt; table = cfTable; model = cfModel; table.getSelectionModel().addListSelectionListener(this); table.addMouseListener(new OpenColumnFamilyMouseListener()); } @Override public void refresh(Cassandra.Client client) { try { keySpace = (client == null) ? null : client.describe_keyspace(keySpace.getName()); final List<CfDef> columnFamilies = (client == null) ? new ArrayList<CfDef>() : keySpace.getCf_defs(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { model.replaceContents(columnFamilies); } }); } catch (Exception e) { JOptionPane.showMessageDialog(table, e.getMessage()); } } @Override public List<CfDef> getSelectedItems() { int[] selRows = table.getSelectedRows(); List<CfDef> selectedColumnFamilies = new ArrayList<CfDef>(); for (int i = 0; i < selRows.length; i++) { selectedColumnFamilies.add(model.getColumnFamilyAt(selRows[i])); } return selectedColumnFamilies; } @Override public void clear() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { model.replaceContents(new ArrayList<CfDef>()); } }); } @Override public void valueChanged(ListSelectionEvent lse) { } public class OpenColumnFamilyMouseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent me) { if (me.getComponent().isEnabled() && me.getButton() == MouseEvent.BUTTON1 && me.getClickCount() == 2) { Point p = me.getPoint(); int row = table.rowAtPoint(p); CfDef columnFamily = model.getColumnFamilyAt(row); if (columnFamily != null) { OpenColumnFamilyAction action = new OpenColumnFamilyAction(context, ColumnFamiliesController.this); ActionEvent ae = new ActionEvent(table, 0, ""); action.actionPerformed(ae); } } } } }
wad/zerbat
js/app/places.js
<reponame>wad/zerbat define([ 'app/constants', 'app/gameContext', 'app/map', 'app/world', 'app/gear'], function (c, gx, Map, World, Gear) { var Places = {}; Places.PlaceDetailDescriptionOnly = function (description) { return { placeDetailDescription: description }; }; Places.PlaceDetailLoot = function (dateLootGenerated, description, items) { return { dateLootGenerated: dateLootGenerated, description: description, items: items }; }; Places.PlaceDetailStash = function (howWellHiddenTheStashIs, dateStashed, stashNumber, items) { return { howWellHiddenTheStashIs: howWellHiddenTheStashIs, dateStashed: dateStashed, stashNumber: stashNumber, items: items }; }; Places.PlaceDetailMine = function (description, isInUse, hasSmelter, hasMonsters, hoursRequiredToExplore, itemTypeThatCanBeFound) { return { placeDetailDescription: description, isInUse: isInUse, hasSmelter: hasSmelter, hasMonsters: hasMonsters, hoursRequiredToExplore: hoursRequiredToExplore, itemTypeThatCanBeFound: itemTypeThatCanBeFound }; }; // todo Places.PlaceDetailEncounter = function (description) { return { placeDetailDescription: description }; }; Places.Place = function (placeType, placeName, placeDescription, tabName, iconIndex, coordinates, visibility, placeDetail) { return { placeId: gx.getNewUniqueId(), placeType: placeType, placeName: placeName, placeDescription: placeDescription, tabName: tabName, iconIndex: iconIndex, coordinates: coordinates, visibility: visibility, placeDetail: placeDetail, isOnPlayerCharactersMap: false }; }; Places.Block = function (blockCoordinates) { return { position: blockCoordinates, hasBeenPopulated: false, places: [] }; }; Places.isStashStillHere = function (place) { // todo: consider how long the stash has been here, and how well it was hidden return true; }; Places.computeChanceOfDiscovery = function (placeVisibility, terrainType, distanceAwayInMiles, isSearching, isDistracted, weather, date, wisdom, intelligence) { if (placeVisibility == c.PLACE_VISIBILITY_KNOWN) { return 1; } if (placeVisibility == c.PLACE_VISIBILITY_NONE) { return 0; } var canOnlyBeSeenInImmediateArea = placeVisibility === c.PLACE_VISIBILITY_TINY || placeVisibility === c.PLACE_VISIBILITY_SMALL || placeVisibility === c.PLACE_VISIBILITY_MEDIUM; if ((distanceAwayInMiles > 0.001) && canOnlyBeSeenInImmediateArea) { return 0; } var chance = 0; switch (placeVisibility) { case c.PLACE_VISIBILITY_TINY: // The discoverable thing is assumed to be in the vicinity, not a mile away. chance = .07; break; case c.PLACE_VISIBILITY_SMALL: chance = .1; break; case c.PLACE_VISIBILITY_MEDIUM: chance = .2; break; case c.PLACE_VISIBILITY_LARGE: chance = (-0.4 * distanceAwayInMiles) + 0.8; break; case c.PLACE_VISIBILITY_HUGE: chance = (-0.1 * distanceAwayInMiles) + 1.1; break; } // let's make it a bit harder to discover stuff. chance *= .5; if (wisdom > .65 || intelligence > .65) { chance += .1; } if (wisdom < .4 || intelligence < .4) { chance *= .8; } switch (terrainType) { case c.TERRAIN_TYPE_OCEAN: case c.TERRAIN_TYPE_MTN_OVER_PLAINS: case c.TERRAIN_TYPE_PLAIN: case c.TERRAIN_TYPE_LAKE: case c.TERRAIN_TYPE_DESERT: case c.TERRAIN_TYPE_AGRICULTURAL: chance += .2; break; case c.TERRAIN_TYPE_UNKNOWN: case c.TERRAIN_TYPE_SHORE: case c.TERRAIN_TYPE_MTN_OVER_DESERT: case c.TERRAIN_TYPE_RIVER: case c.TERRAIN_TYPE_TOWN: // no change break; case c.TERRAIN_TYPE_PINE_FOREST: case c.TERRAIN_TYPE_MTN_OVER_PINE: case c.TERRAIN_TYPE_MTN_OVER_JUNGLE: case c.TERRAIN_TYPE_JUNGLE: case c.TERRAIN_TYPE_CLIFFS: case c.TERRAIN_TYPE_IMPASSABLE_CLIFFS: case c.TERRAIN_TYPE_SWAMP: case c.TERRAIN_TYPE_LAVAFLOW: case c.TERRAIN_TYPE_LAVA: chance -= .2; break; default: throw "Unexpected terrain type encountered: " + terrainType; } if (isSearching) { chance += .15; } if (isDistracted) { chance *= .2; } if (c.isFullNight(date)) { chance *= .2; } else if (c.isTwilight(date)) { chance *= .75; } if (weather === c.WEATHER_CLOUDY) { chance *= .9; } else if (weather === c.WEATHER_STORMY) { chance *= .3; } return chance < 0 ? 0 : chance > 1 ? 1 : chance; }; Places.createPlaceLoot = function(placeCoordinates) { return new Places.Place( c.PLACE_TYPE_LOOT, "an item", "This is something here you can pick up.", "Loot", c.ICON_INDEX_QUESTION_MARK, placeCoordinates, c.PLACE_VISIBILITY_SMALL, new Places.PlaceDetailLoot( c.cloneDate(gx.gs.currentDate), "This might be useful", Gear.generateRandomLoot() )); }; Places.mineTypeOptions = [ [40, Gear.GearSet.coal], [2, Gear.GearSet.roughTopaz], [2, Gear.GearSet.roughDiamond], [1, Gear.GearSet.roughSapphire], [1, Gear.GearSet.roughEmerald], [.7, Gear.GearSet.roughRuby], [15, Gear.GearSet.ironOre], [10, Gear.GearSet.copperOre], [5, Gear.GearSet.silverOre], [1, Gear.GearSet.goldOre], [.1, Gear.GearSet.mithrilOre] ]; Places.createPlaceMine = function(placeCoordinates) { var isInUse = c.checkRandom(.1, "is mine in use"); var hasMonsters = false; if (!isInUse && c.checkRandom(.4, "check empty mine for monsters")) { hasMonsters = true; } return new Places.Place( c.PLACE_TYPE_MINE, "a mine", "At some point, someone was extracting minerals from the ground here.", "Mine", c.ICON_INDEX_QUESTION_MARK, placeCoordinates, c.PLACE_VISIBILITY_LARGE, new Places.PlaceDetailMine( "The mine shaft leads downward into darkness, at a steep angle. Piles of crushed stone surround the entrance.", isInUse, c.checkRandom(.3, "mine has smelter"), hasMonsters, c.determineRandomNumberInRange(1, 10, "how long to explore mine"), c.chooseWeightedOption(c.getRandom("choose mine type"), Places.mineTypeOptions) )); }; Places._populateBlock = function (block) { var blockPos = [ block.position[X] * c.BLOCK_SIZE[X], block.position[Y] * c.BLOCK_SIZE[Y] ]; if (c.DEBUG) { c.db("Populating block at position " + blockPos[X] + "," + blockPos[Y]); } for (var y = 0; y < c.BLOCK_SIZE[Y]; y++) { for (var x = 0; x < c.BLOCK_SIZE[X]; x++) { var placeCoordinates = [blockPos[X] + x, blockPos[Y] + y]; var terrainType = Map.identifyTerrainType(placeCoordinates); var placeTypeOptions = World.getPlaceRandomOptions(terrainType); var placeType = c.chooseWeightedOption(c.getRandom("Determine a place type"), placeTypeOptions); var place = null; switch (placeType) { case c.PLACE_TYPE_NOTHING_OF_INTEREST: case c.PLACE_TYPE_STASH: case c.PLACE_TYPE_DESCRIPTION_ONLY: case c.PLACE_TYPE_CONVERSATION: break; case c.PLACE_TYPE_LOOT: place = Places.createPlaceLoot(placeCoordinates); break; case c.PLACE_TYPE_MINE: place = Places.createPlaceMine(placeCoordinates); break; case c.PLACE_TYPE_ENCOUNTER: case c.PLACE_TYPE_DAMSEL_IN_DISTRESS: case c.PLACE_TYPE_MERCHANT: case c.PLACE_TYPE_SKYSHIP: case c.PLACE_TYPE_TRAP: case c.PLACE_TYPE_TREEHOUSE: case c.PLACE_TYPE_COTTAGE: case c.PLACE_TYPE_FARM: case c.PLACE_TYPE_VILLAGE: case c.PLACE_TYPE_FORTRESS: case c.PLACE_TYPE_CASTLE: case c.PLACE_TYPE_SHIP: case c.PLACE_TYPE_TOWER: case c.PLACE_TYPE_PYRAMID: case c.PLACE_TYPE_FAIRY_RING: case c.PLACE_TYPE_STONE_RUINS: case c.PLACE_TYPE_WOODEN_RUINS: case c.PLACE_TYPE_QUICKSAND: case c.PLACE_TYPE_PIT: case c.PLACE_TYPE_CAVE: // todo: fill all these in break; default: throw "Unknown place type: " + placeType; } if (place !== null) { block.places.push(place); } } } c.db("Populated block with " + block.places.length + " places."); block.hasBeenPopulated = true; }; Places._lookupBlock = function (blocks, blockCoordinates) { var key = c.convertBlockCoordinatesToKey(blockCoordinates); var block = blocks[key]; if (block === undefined) { block = new Places.Block(blockCoordinates); blocks[key] = block; } return block; }; Places._lookupPlaceIndexByPlaceId = function (places, placeId) { for (var i = 0; i < places.length; i++) { if (places[i].placeId === placeId) { return i; } } return -1; }; Places.addPlace = function (blocks, place) { var mapCoordinates = place.coordinates; var blockCoordinates = c._computeBlockCoordinatesFromMapCoordinates(mapCoordinates); var block = Places._lookupBlock(blocks, blockCoordinates); block.places.push(place); }; Places._removeFromListOfPlaces = function (places, placeId) { var indexToRemove = Places._lookupPlaceIndexByPlaceId(places, placeId); if (indexToRemove === -1) { throw "Cannot remove place, it doesn't exist: " + placeId; } places.splice(indexToRemove, 1); }; Places.removePlace = function (blocks, place) { var blockCoordinates = c._computeBlockCoordinatesFromMapCoordinates(place.coordinates); var block = Places._lookupBlock(blocks, blockCoordinates); Places._removeFromListOfPlaces(block.places, place.placeId); Places._removeFromListOfPlaces(gx.gs.placesAtCurrentLocation, place.placeId); }; Places._areBlockCoordinatesValid = function (blockCoordinates) { var max = c._computeBlockCoordinatesFromMapCoordinates(c.MAP_DETAIL_SIZE_IN_PIXELS); return blockCoordinates[X] >= 0 && blockCoordinates[X] < max[X] && blockCoordinates[Y] >= 0 && blockCoordinates[Y] < max[Y]; }; Places._getPlacesFromBlock = function (blocks, blockCoordinates) { if (Places._areBlockCoordinatesValid(blockCoordinates)) { var block = Places._lookupBlock(blocks, blockCoordinates); if (!block.hasBeenPopulated) { Places._populateBlock(block); } return block.places; } else { return []; } }; Places.getNearbyPlaces = function (blocks, playerMapCoordinates) { var centerPos = c._computeBlockCoordinatesFromMapCoordinates(playerMapCoordinates); return [].concat( Places._getPlacesFromBlock(blocks, [centerPos[X] - 1, centerPos[Y] - 1]), Places._getPlacesFromBlock(blocks, [centerPos[X], centerPos[Y] - 1]), Places._getPlacesFromBlock(blocks, [centerPos[X] + 1, centerPos[Y] - 1]), Places._getPlacesFromBlock(blocks, [centerPos[X] - 1, centerPos[Y]]), Places._getPlacesFromBlock(blocks, [centerPos[X], centerPos[Y]]), Places._getPlacesFromBlock(blocks, [centerPos[X] + 1, centerPos[Y]]), Places._getPlacesFromBlock(blocks, [centerPos[X] - 1, centerPos[Y] + 1]), Places._getPlacesFromBlock(blocks, [centerPos[X], centerPos[Y] + 1]), Places._getPlacesFromBlock(blocks, [centerPos[X] + 1, centerPos[Y] + 1]) ); }; Places.getKnownPlacesAtThisLocation = function (blocks, playerMapCoordinates) { return Places._getPlacesFromBlock(blocks, c._computeBlockCoordinatesFromMapCoordinates(playerMapCoordinates)).filter(function (place) { return c.areLocationsEquivalent(playerMapCoordinates, place.coordinates) && place.isOnPlayerCharactersMap; }); }; Places.getNoticeMessage = function (currentPosition, place) { var message = "You notice " + place.placeName + " "; if (c.areLocationsEquivalent(gx.gs.playerLocation, place.coordinates)) { message += "here. (Click the area tab to check it out.)"; } else { var distanceAway = c.computeDistanceBetweenTwoPointsInMiles(currentPosition, place.coordinates); var directionName = c.DIRECTION_NAMES[c.determineDirectionByAngle(c.angleOfLine(currentPosition, place.coordinates))]; message += c.formatFloatSingleDecimal(distanceAway) + " miles to the " + directionName + ". " + place.placeDescription; } return message; }; return Places; });
Grosskopf/openoffice
main/sc/source/core/tool/formulaparserpool.cxx
/************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "formulaparserpool.hxx" #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/container/XContentEnumerationAccess.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/lang/XSingleComponentFactory.hpp> #include <com/sun/star/sheet/XFilterFormulaParser.hpp> #include <rtl/instance.hxx> #include <comphelper/processfactory.hxx> #include <sfx2/objsh.hxx> #include "document.hxx" using ::rtl::OUString; using ::rtl::OUStringHash; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sheet; using namespace ::com::sun::star::uno; // ============================================================================ namespace { class ScParserFactoryMap { public: explicit ScParserFactoryMap(); Reference< XFormulaParser > createFormulaParser( const Reference< XComponent >& rxComponent, const OUString& rNamespace ); private: typedef ::std::hash_map< OUString, Reference< XSingleComponentFactory >, OUStringHash > FactoryMap; Reference< XComponentContext > mxContext; /// Global component context. FactoryMap maFactories; /// All parser factories, mapped by formula namespace. }; ScParserFactoryMap::ScParserFactoryMap() : mxContext( ::comphelper::getProcessComponentContext() ) { if( mxContext.is() ) try { // enumerate all implementations of the FormulaParser service Reference< XContentEnumerationAccess > xFactoryEA( mxContext->getServiceManager(), UNO_QUERY_THROW ); Reference< XEnumeration > xEnum( xFactoryEA->createContentEnumeration( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sheet.FilterFormulaParser" ) ) ), UNO_SET_THROW ); while( xEnum->hasMoreElements() ) try // single try/catch for every element { // create an instance of the formula parser implementation Reference< XSingleComponentFactory > xCompFactory( xEnum->nextElement(), UNO_QUERY_THROW ); Reference< XFilterFormulaParser > xParser( xCompFactory->createInstanceWithContext( mxContext ), UNO_QUERY_THROW ); // store factory in the map OUString aNamespace = xParser->getSupportedNamespace(); if( aNamespace.getLength() > 0 ) maFactories[ aNamespace ] = xCompFactory; } catch( Exception& ) { } } catch( Exception& ) { } } Reference< XFormulaParser > ScParserFactoryMap::createFormulaParser( const Reference< XComponent >& rxComponent, const OUString& rNamespace ) { Reference< XFormulaParser > xParser; FactoryMap::const_iterator aIt = maFactories.find( rNamespace ); if( aIt != maFactories.end() ) try { Sequence< Any > aArgs( 1 ); aArgs[ 0 ] <<= rxComponent; xParser.set( aIt->second->createInstanceWithArgumentsAndContext( aArgs, mxContext ), UNO_QUERY_THROW ); } catch( Exception& ) { } return xParser; } struct ScParserFactorySingleton : public ::rtl::Static< ScParserFactoryMap, ScParserFactorySingleton > {}; } // namespace // ============================================================================ ScFormulaParserPool::ScFormulaParserPool( const ScDocument& rDoc ) : mrDoc( rDoc ) { } ScFormulaParserPool::~ScFormulaParserPool() { } bool ScFormulaParserPool::hasFormulaParser( const OUString& rNamespace ) { return getFormulaParser( rNamespace ).is(); } Reference< XFormulaParser > ScFormulaParserPool::getFormulaParser( const OUString& rNamespace ) { // try to find an existing parser entry ParserMap::iterator aIt = maParsers.find( rNamespace ); if( aIt != maParsers.end() ) return aIt->second; // always create a new entry in the map (even if the following initialization fails) Reference< XFormulaParser >& rxParser = maParsers[ rNamespace ]; // try to create a new parser object if( SfxObjectShell* pDocShell = mrDoc.GetDocumentShell() ) try { Reference< XComponent > xComponent( pDocShell->GetModel(), UNO_QUERY_THROW ); ScParserFactoryMap& rFactoryMap = ScParserFactorySingleton::get(); rxParser = rFactoryMap.createFormulaParser( xComponent, rNamespace ); } catch( Exception& ) { } return rxParser; } // ============================================================================
wardensky/wardensky-demo
java/mq_request_reply/src/main/java/com/wardensky/demo/mqkill/GlobalConfig.java
<gh_stars>0 package com.wardensky.demo.mqkill; public class GlobalConfig { public static String MQ_URL = "failover://tcp://192.168.163.50:61616?jms.prefetchPolicy.queuePrefetch=1"; public volatile static boolean IS_ALIVE = true; }
nazarov-pro/training
db/db-tunning/src/main/java/org/shahin/nazarov/db/tunning/util/Constants.java
package org.shahin.nazarov.db.tunning.util; public class Constants { public static final String MYBATIS_CONFIG_FILE = "mybatis-postgres-config.xml"; public static final String MYBATIS_CONFIG_MYSQL_FILE = "mybatis-mysql-config.xml"; }
devlato/spark-skeleton
src/main/java/com/moneytapp/restapi/infrastructure/base/Model.java
/** * Created by d.tokarev on 02/12/15. */ package com.moneytapp.restapi.infrastructure.base; public abstract class Model { public Model() { } }
cspath1/AndcultureCode.Cli
_modules/dotnet-build.js
// ----------------------------------------------------------------------------------------- // #region Imports // ----------------------------------------------------------------------------------------- const child_process = require("child_process"); const dotnetClean = require("./dotnet-clean"); const dotnetPath = require("./dotnet-path"); const dotnetRestore = require("./dotnet-restore"); const echo = require("./echo"); const shell = require("shelljs"); // #endregion Imports // ----------------------------------------------------------------------------------------- // #region Functions // ----------------------------------------------------------------------------------------- const dotnetBuild = { cmd() { return { args: ["build", dotnetPath.solutionPath(), "--no-restore"], cmd: "dotnet", toString() { return `${this.cmd} ${this.args.join(" ")}`; }, }; }, options() { return ["-b", "--build"]; }, description() { return `Builds the dotnet project (via ${this.cmd()})`; }, run(clean, restore) { // Verify that the solution path exists or exit early. dotnetPath.solutionPathOrExit(); if (clean) { dotnetClean.run(); } if (restore) { dotnetRestore.run(); } const { cmd, args } = this.cmd(); echo.message(`Building solution (via ${this.cmd()})...`); const { status } = child_process.spawnSync(cmd, args, { stdio: "inherit", shell: true }); if (status !== 0) { echo.error("Solution failed to build. See output for details."); shell.exit(status); } return status; }, }; // #endregion Functions // ----------------------------------------------------------------------------------------- // #region Exports // ----------------------------------------------------------------------------------------- module.exports = dotnetBuild; // #endregion Exports
dimitrov-dimitar/competitive-programming
CodeForces/easy problems/122_a_lucky_division.py
<filename>CodeForces/easy problems/122_a_lucky_division.py # https://codeforces.com/problemset/problem/122/A n = int(input()) def lucky_numbers(num): num = str(num) counter = 0 for ch in num: if ch == '4' or ch == '7': counter += 1 if len(num) == counter: return 'YES' k = 0 number = 0 bool_var = True answer_var = False if lucky_numbers(n): print(lucky_numbers(n)) else: while k < n: k += 1 if lucky_numbers(k): while number < n: number += 1 if k * number == n: print('YES') bool_var = False answer_var = True break number = 0 if answer_var: break else: continue if bool_var: print('NO')
Boxin-ChinaGD/BXERP
20190902_v1_1/src/nbr/src/test/java/com/bx/erp/test/commodity/CommoditySITTest.java
package com.bx.erp.test.commodity; import static org.testng.Assert.assertTrue; import java.util.List; import java.util.Map; import org.springframework.test.context.web.WebAppConfiguration; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.bx.erp.action.BaseAction; import com.bx.erp.action.BaseAction.EnumSession; import com.bx.erp.action.bo.BaseBO; import com.bx.erp.cache.CacheManager; import com.bx.erp.cache.config.ConfigCacheSizeCache.EnumConfigCacheSizeCache; import com.bx.erp.model.BaseModel; import com.bx.erp.model.CacheType.EnumCacheType; import com.bx.erp.model.ErrorInfo; import com.bx.erp.model.Staff; import com.bx.erp.model.ErrorInfo.EnumErrorCode; import com.bx.erp.model.commodity.Brand; import com.bx.erp.model.commodity.Category; import com.bx.erp.model.commodity.Commodity; import com.bx.erp.model.config.ConfigCacheSize; import com.bx.erp.model.purchasing.Provider; import com.bx.erp.test.BaseActionTest; import com.bx.erp.test.BaseBrandTest; import com.bx.erp.test.BaseCommodityTest; import com.bx.erp.test.Shared; import com.bx.erp.util.DataSourceContextHolder; @WebAppConfiguration public class CommoditySITTest extends BaseActionTest { private Staff staff; public static class DataInput { private static Provider providerInput = null; // 获取供应商数据 protected static final Provider getProvider() throws CloneNotSupportedException, InterruptedException { if (providerInput == null) { providerInput = new Provider(); providerInput.setName(Shared.getLongestProviderName("阿里")); providerInput.setDistrictID(5); providerInput.setAddress("山东"); providerInput.setContactName("king"); providerInput.setMobile(Shared.getValidStaffPhone()); } else { providerInput.setName("京东" + String.valueOf(System.currentTimeMillis()).substring(5)); providerInput.setMobile(Shared.getValidStaffPhone()); } return (Provider) providerInput.clone(); } } @BeforeClass public void setup() { super.setUp(); try { staff = (Staff) sessionBoss.getAttribute(EnumSession.SESSION_Staff.getName()); } catch (Exception e) { e.printStackTrace(); } } @AfterClass public void tearDown() { super.tearDown(); } @Test public void createAndDeleteCommodity() throws CloneNotSupportedException, InterruptedException { Shared.printTestMethodStartInfo(); // 创建一个新商品类别CategoryA Category categoryAData = BaseCategoryParentTest.DataInput.getCategory(); Map<String, Object> categoryParamsA = categoryAData.getCreateParam(BaseBO.INVALID_CASE_ID, categoryAData); DataSourceContextHolder.setDbName(Shared.DBName_Test); Category categoryA = (Category) categoryMapper.create(categoryParamsA); // categoryA.setIgnoreIDInComparision(true); Assert.assertNotNull(categoryA, "商品类别创建失败"); if (categoryA.compareTo(categoryAData) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } // Assert.assertTrue(categoryA != null && EnumErrorCode.values()[Integer.parseInt(categoryParamsA.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "商品类别对象创建成功"); System.out.println("创建的商品类别是:" + categoryA); System.out.println("------------------------------- 商品类别A创建成功----------------------------"); // 创建一个新商品品牌BrandA Brand brandAData = BaseBrandTest.DataInput.getBrand(); Map<String, Object> brandParam = brandAData.getCreateParam(BaseBO.INVALID_CASE_ID, brandAData); DataSourceContextHolder.setDbName(Shared.DBName_Test); Brand brandA = (Brand) brandMapper.create(brandParam); // brandA.setIgnoreIDInComparision(true); Assert.assertNotNull(brandA, "商品品牌创建失败"); // if (brandA.compareTo(brandAData) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } // Assert.assertTrue(brandA != null && EnumErrorCode.values()[Integer.parseInt(brandParam.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "商品品牌对象创建成功"); System.out.println("创建的商品品牌为" + brandA); System.out.println("-------------------------- 商品品牌A创建成功 ------------------------------"); // 创建一个新商品供应商ProviderA Provider providerAData = DataInput.getProvider(); Map<String, Object> providerParam = providerAData.getCreateParam(BaseBO.INVALID_CASE_ID, providerAData); DataSourceContextHolder.setDbName(Shared.DBName_Test); Provider providerA = (Provider) providerMapper.create(providerParam); // providerA.setIgnoreIDInComparision(true); Assert.assertNotNull(providerA, "供应商创建失败"); // if (providerA.compareTo(providerAData) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } // Assert.assertTrue(providerA != null && EnumErrorCode.values()[Integer.parseInt(brandParam.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "商品品牌对象创建成功"); System.out.println("创建的供应商是:" + providerA); System.out.println("------------------------- 供应商A创建成功 ------------------"); // 用以上信息创建一个新商品CommodityA Commodity commodityData = BaseCommodityTest.DataInput.getCommodity(); commodityData.setCategoryID(categoryA.getID()); commodityData.setBrandID(brandA.getID()); commodityData.setProviderIDs(String.valueOf(providerA.getID())); commodityData.setnOStart(commodityData.getNO());// 当nOStart不等于-1时,把nOStart赋值给NO的(NO=nOStart),如果nOStart等于-1,NO是为0的 commodityData.setPurchasingPriceStart(100D); // Map<String, Object> commodityParam = commodityData.getCreateParamEx(BaseBO.INVALID_CASE_ID, commodityData); DataSourceContextHolder.setDbName(Shared.DBName_Test); List<List<BaseModel>> bmList = commodityMapper.createSimpleEx(commodityParam); // Commodity commodity = (Commodity) bmList.get(5).get(0); commodity.setIgnoreIDInComparision(true); Assert.assertNotNull(commodity, "商品创建失败"); commodity.setLatestPricePurchase(commodityData.getLatestPricePurchase()); // 为了让compareTo()通过 if (commodity.compareTo(commodityData) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } // Assert.assertTrue(commodity != null && EnumErrorCode.values()[Integer.parseInt(commodityParam.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "商品创建成功"); System.out.println("创建的商品是:" + commodity); System.out.println("-------------------- 商品A创建成功 ------------------"); // 创建一个新商品类别CategoryB Category categoryData = BaseCategoryParentTest.DataInput.getCategory(); Map<String, Object> categoryParamsB = categoryData.getCreateParam(BaseBO.INVALID_CASE_ID, categoryData); DataSourceContextHolder.setDbName(Shared.DBName_Test); Category categoryB = (Category) categoryMapper.create(categoryParamsB); // categoryB.setIgnoreIDInComparision(true); Assert.assertNotNull(categoryB, "商品类别创建失败"); // if (categoryB.compareTo(categoryData) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } // Assert.assertTrue(categoryB != null && EnumErrorCode.values()[Integer.parseInt(categoryParamsB.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "商品类别B对象创建成功"); System.out.println("新创建的商品类别B的ID是:" + categoryB.getID()); System.out.println("---------------------- 商品类别B创建成功 ---------------------"); // 更改CommodityA的类别为CategoryB Commodity commodityBData = BaseCommodityTest.DataInput.getCommodity(); commodityBData.setCategoryID(categoryB.getID()); commodityBData.setBrandID(brandA.getID()); commodityBData.setProviderIDs(String.valueOf(providerA.getID())); commodityBData.setOperatorStaffID(STAFF_ID3); commodityBData.setID(commodity.getID()); commodityBData.setName("西瓜薯片" + System.currentTimeMillis() % 1000000); commodityBData.setnOStart(commodityData.getNO());// 当nOStart不等于-1时,把nOStart赋值给NO的(NO=nOStart),如果nOStart等于-1,NO是为0的 commodityBData.setPurchasingPriceStart(commodityData.getPurchasingPriceStart()); // Map<String, Object> updateParamsA = commodityBData.getUpdateParam(BaseBO.INVALID_CASE_ID, commodityBData); DataSourceContextHolder.setDbName(Shared.DBName_Test); Commodity updateCommodityA = (Commodity) commodityMapper.update(updateParamsA); // commodityBData.setIgnoreIDInComparision(true); Assert.assertNotNull(updateCommodityA, "商品更新失败"); // updateCommodityA.setLatestPricePurchase(commodityBData.getLatestPricePurchase()); // 为了让compareTo()通过 if (commodityBData.compareTo(updateCommodityA) != 0) { Assert.assertTrue(false, "更新的对象的字段与DB读出的不相等"); } // Assert.assertTrue(updateCommodityA != null && EnumErrorCode.values()[Integer.parseInt(updateParamsA.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "商品更新类别成功"); System.out.println("更新成功后的商品是:" + updateCommodityA); System.out.println("-------------------- 商品更新商品类别B成功 -----------------------"); // 创建一个新商品品牌BrandB Brand brandBData = BaseBrandTest.DataInput.getBrand(); Map<String, Object> brandParamB = brandBData.getCreateParam(BaseBO.INVALID_CASE_ID, brandBData); // DataSourceContextHolder.setDbName(Shared.DBName_Test); Brand brandB = (Brand) brandMapper.create(brandParamB); // brandB.setIgnoreIDInComparision(true); Assert.assertNotNull(brandB, "商品品牌B创建失败"); // if (brandB.compareTo(brandBData) != 0) { Assert.assertTrue(false, "创建的对象的字段与DB读出的不相等"); } // Assert.assertTrue(brandB != null && EnumErrorCode.values()[Integer.parseInt(brandParamB.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "商品品牌B创建成功"); System.out.println("新创建的商品品牌B的ID是:" + brandB.getID()); System.out.println("------------------ 商品品牌B创建成功 ------------------------"); // 更改CommodityA的品牌为BrandB Commodity commodityCData = BaseCommodityTest.DataInput.getCommodity(); commodityCData.setCategoryID(categoryB.getID()); commodityCData.setBrandID(brandB.getID()); commodityCData.setProviderIDs(String.valueOf(providerA.getID())); commodityCData.setOperatorStaffID(STAFF_ID3); commodityCData.setID(commodity.getID()); commodityCData.setnOStart(commodityData.getNO());// 当nOStart不等于-1时,把nOStart赋值给NO的(NO=nOStart),如果nOStart等于-1,NO是为0的 commodityCData.setPurchasingPriceStart(100D); // Map<String, Object> updateParamsB = commodityCData.getUpdateParam(BaseBO.INVALID_CASE_ID, commodityCData); DataSourceContextHolder.setDbName(Shared.DBName_Test); Commodity updateCommodityB = (Commodity) commodityMapper.update(updateParamsB); // commodityCData.setIgnoreIDInComparision(true); Assert.assertNotNull(updateCommodityB, "更新商品失败"); // updateCommodityB.setLatestPricePurchase(commodityBData.getLatestPricePurchase()); // 为了让compareTo()通过 if (commodityCData.compareTo(updateCommodityB) != 0) { Assert.assertTrue(false, "更新的对象的字段与DB读出的不相等"); } // Assert.assertTrue(updateCommodityB != null && EnumErrorCode.values()[Integer.parseInt(updateParamsB.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "商品品牌B创建成功"); System.out.println("更改品牌成功的商品:" + updateCommodityB); System.out.println("--------------- 更改商品品牌B成功 --------------------"); // 创建一个新供应商ProviderB Provider providerBData = DataInput.getProvider(); Map<String, Object> providerParamB = providerBData.getCreateParam(BaseBO.INVALID_CASE_ID, providerBData); DataSourceContextHolder.setDbName(Shared.DBName_Test); Provider providerB = (Provider) providerMapper.create(providerParamB); // providerBData.setIgnoreIDInComparision(true); Assert.assertNotNull(providerB, "创建新供应商B失败"); // if (providerBData.compareTo(providerB) != 0) { Assert.assertTrue(false, "创建供应商B失败"); } // Assert.assertTrue(providerB != null && EnumErrorCode.values()[Integer.parseInt(providerParamB.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "创建供应商B成功!"); System.out.println("新供应商B为:" + providerB); System.out.println("-------------------- 创建新供应商B成功 ---------------------"); // 更改CommodityA的供应商为ProviderB Commodity commodityDData = BaseCommodityTest.DataInput.getCommodity(); commodityDData.setCategoryID(categoryB.getID()); commodityDData.setBrandID(brandB.getID()); commodityDData.setProviderIDs(String.valueOf(providerB.getID())); commodityDData.setOperatorStaffID(STAFF_ID3); commodityDData.setID(commodity.getID()); commodityDData.setnOStart(commodityData.getNO());// 当nOStart不等于-1时,把nOStart赋值给NO的(NO=nOStart),如果nOStart等于-1,NO是为0的 commodityDData.setPurchasingPriceStart(100D); // Map<String, Object> updateParamsC = commodityDData.getUpdateParam(BaseBO.INVALID_CASE_ID, commodityDData); DataSourceContextHolder.setDbName(Shared.DBName_Test); Commodity updateCommodityC = (Commodity) commodityMapper.update(updateParamsC); // commodityDData.setIgnoreIDInComparision(true); Assert.assertNotNull(updateCommodityC, "更新商品失败"); // updateCommodityC.setLatestPricePurchase(commodityBData.getLatestPricePurchase()); // 为了让compareTo()通过 if (commodityDData.compareTo(updateCommodityC) != 0) { Assert.assertTrue(false, "商品更新供应商失败"); } // Assert.assertTrue(updateCommodityC != null && EnumErrorCode.values()[Integer.parseInt(updateParamsC.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "更改新供应商成功"); System.out.println("更改供应商成功的商品:" + updateCommodityC); System.out.println("--------------------- 更改商品供应商成功 --------------------"); // 删除CommodityA commodityParam.put("F_ID", commodity.getID()); Commodity cd = new Commodity(); cd.setID(commodity.getID()); // Map<String, Object> paramForDelete = cd.getDeleteParam(BaseBO.INVALID_CASE_ID, cd); DataSourceContextHolder.setDbName(Shared.DBName_Test); Commodity delete = (Commodity) commodityMapper.deleteSimple(paramForDelete); // Assert.assertTrue(delete == null && EnumErrorCode.values()[Integer.parseInt(commodityParam.get(BaseAction.SP_OUT_PARAM_iErrorCode).toString())] == EnumErrorCode.EC_NoError, "删除商品成功!"); System.out.println("商品删除成功:" + delete); System.out.println("------------------------ 删除商品成功 -----------------------"); // 运行本测试至少2次(不能修改任何代码!),看看能否成功创建商品。如不能,修改代码令其能 // ... } /** * 测试目的:测试缓存的对象个数限制是否起作用 */ @Test public void testCacheSize() throws Exception { Shared.printTestMethodStartInfo(); Shared.getStaffLoginSession(mvc, Shared.PhoneOfBoss); // 1)清空商品缓存。 CacheManager.getCache(Shared.DBName_Test, EnumCacheType.ECT_Commodity).deleteAll(); // 2)读取N个不同的商品对象,N大于配置中的个数Q。 System.out.println("-----------:" + CacheManager.getCache(Shared.DBName_Test, EnumCacheType.ECT_Commodity).readN(false, false).size()); ConfigCacheSize ccs = new ConfigCacheSize(); ccs.setID(EnumConfigCacheSizeCache.ECC_CommodityCacheSize.getIndex()); ccs.setName(EnumConfigCacheSizeCache.ECC_CommodityCacheSize.getName()); ccs.setValue("10"); CacheManager.getCache(Shared.DBName_Test, EnumCacheType.ECT_ConfigCacheSize).write1(ccs, Shared.DBName_Test, staff.getID()); System.out.println(CacheManager.getCache(Shared.DBName_Test, EnumCacheType.ECT_ConfigCacheSize).readN(false, false)); for (int i = 1; i <= 20; i++) { ErrorInfo ecOut = new ErrorInfo(); Commodity comm = (Commodity) CacheManager.getCache(Shared.DBName_Test, EnumCacheType.ECT_Commodity).read1(i, BaseBO.SYSTEM, ecOut, Shared.DBName_Test); if (ecOut.getErrorCode() != EnumErrorCode.EC_NoError) { assertTrue(false); } System.out.println(comm.getID()); } System.out.println("-----------:" + CacheManager.getCache(Shared.DBName_Test, EnumCacheType.ECT_Commodity).readN(false, false).size()); // 因为设置缓存上限为10,所以顺序插入20个商品的时候,前10个ID会被删除掉,则list里面ID从11开始,size为10. List<BaseModel> commList = CacheManager.getCache(Shared.DBName_Test, EnumCacheType.ECT_Commodity).readN(false, false); assertTrue(commList.size() == 10, "没有正确删除"); // 恢复缓存的值 ccs.setID(EnumConfigCacheSizeCache.ECC_CommodityCacheSize.getIndex()); ccs.setName(EnumConfigCacheSizeCache.ECC_CommodityCacheSize.getName()); ccs.setValue("100"); CacheManager.getCache(Shared.DBName_Test, EnumCacheType.ECT_ConfigCacheSize).write1(ccs, Shared.DBName_Test, staff.getID()); } }
m312z/Mercs
src/mission/powers/PowerEater.java
package mission.powers; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import mission.Board; import mission.SupportFactory; import mission.gameobject.AllyMech; import mission.gameobject.Component; import mission.gameobject.Mech; import mission.gameobject.Player; import mission.weapon.SelfDefenceLaser; import mission.weapon.Weapon.ShotType; import mission.weapon.bullet.Bullet; import mission.weapon.bullet.BulletMod; import phys.Point2D; public class PowerEater { List<ActivePower> activePowers; /* stuff for specific powers */ AllyMech clone; List<AllyMech> gadgets; List<AllyMech> support; List<AllyMech> drones; AllyMech port; AllyMech decoy; float explodeFireTimer; public PowerEater() { activePowers = new ArrayList<PowerEater.ActivePower>(); support = new ArrayList<AllyMech>(); gadgets = new ArrayList<AllyMech>(); drones = new ArrayList<AllyMech>(); } public void tick(float dt, Board board, Player player) { for(ActivePower ap: activePowers) { if(ap.remainingCooldown > dt) ap.remainingCooldown -= dt; else if(ap.remainingCooldown > 0) ap.remainingCooldown = 0; tickPower(dt, board, player, ap); if(ap.remainingActive > dt) { ap.remainingActive -= dt; } else if(ap.remainingActive > 0) { ap.remainingActive = 0; } if(ap.active && ap.remainingActive<=0) { removePower(ap,board,player); ap.active = false; } Iterator<AllyMech> mit = support.iterator(); while(mit.hasNext()) { if(mit.next().isDead()) mit.remove(); } mit = drones.iterator(); while(mit.hasNext()) { if(mit.next().isDead()) mit.remove(); } mit = gadgets.iterator(); while(mit.hasNext()) { if(mit.next().isDead()) mit.remove(); } if(decoy!=null && decoy.isDead()) { if(hasPower(Power.PORT_EXPLOSION)) { Bullet bullet = player.getComponents().get(0).getWeapon().getBullet(); for(int i=0;i<36;i++) { Bullet b = bullet.clone(); b.getPos().x = decoy.getPos().x; b.getPos().y = decoy.getPos().y; b.getDirection().x = (float) Math.cos(Math.toRadians(i*360.0/36.0)); b.getDirection().y = (float) Math.sin(Math.toRadians(i*360.0/36.0)); board.addBullet(b); } } decoy = null; } } } public void activatePower(Power p, Board board, Player player) { for(int i=0;i<activePowers.size();i++) { if(activePowers.get(i).type == p) { activatePower(i, board, player); } } } public void activatePower(int powerIndex, Board board, Player player) { if(powerIndex<0 || powerIndex >= activePowers.size()) return; ActivePower ap = activePowers.get(powerIndex); if(ap.remainingCooldown > 0) return; ap.remainingCooldown = ap.type.coolDown; ap.remainingActive = ap.type.duration; ap.active = true; switch(ap.type) { case SLOW: board.setTimeScale(0.2f); break; case CLUSTERPOWER: addBulletMod(player, BulletMod.CLUSTER,8); break; case GARGANTUA: addBulletMod(player, BulletMod.GARGANTUA,8); break; case SHIELD_CHARGING: addBulletMod(player, BulletMod.SHIELDCHARGE,8); break; case FIREPOWER: addBulletMod(player, BulletMod.FIRE,8); break; case HOMINGPOWER: addBulletMod(player, BulletMod.HOMING,1); break; case MEGAPOWER: addBulletMod(player, BulletMod.MEGA,6); break; case MINEPOWER: if(!player.getComponents().get(0).getWeapon().getBullet().getMods().containsKey(BulletMod.MINE)) addBulletMod(player, BulletMod.MINE,1); else removeBulletMod(player, BulletMod.MINE); break; case TELEPORT: if(port==null) { port = SupportFactory.makePort(board, player); if(hasPower(Power.SUPPORT_DRONEMASTER)) addAllBulletModsToSupport(player, port); support.add(port); board.addNonCompetingMech(port); } else { if(hasPower(Power.PORT_EXPLOSION)) { Bullet bullet = player.getComponents().get(0).getWeapon().getBullet(); for(int i=0;i<36;i++) { Bullet b = bullet.clone(); b.getPos().x = port.getPos().x; b.getPos().y = port.getPos().y; b.getDirection().x = (float) Math.cos(Math.toRadians(i*360.0/36.0)); b.getDirection().y = (float) Math.sin(Math.toRadians(i*360.0/36.0)); board.addBullet(b); } } player.getPos().x = port.getPos().x; player.getPos().y = port.getPos().y; port.destroy(board, false); port = null; } break; case SUPPORT_KILLSTAR: AllyMech k = SupportFactory.makeKillstar(board, player); if(hasPower(Power.SUPPORT_DRONEMASTER)) addAllBulletModsToSupport(player, k); support.add(k); board.addMech(k, 120); break; case SUPPORT_DRONE: if(drones.size()<4) { AllyMech d = SupportFactory.makeDrone(board, player); if(hasPower(Power.SUPPORT_DRONEMASTER)) addAllBulletModsToSupport(player, d); support.add(d); drones.add(d); board.addMech(d, 120); } else { ap.remainingCooldown = 0; } break; case SUPPORT_DECOY: if(decoy!=null && !decoy.isDead()) { if(hasPower(Power.PORT_EXPLOSION)) { Bullet bullet = player.getComponents().get(0).getWeapon().getBullet(); for(int i=0;i<36;i++) { Bullet b = bullet.clone(); b.getPos().x = decoy.getPos().x; b.getPos().y = decoy.getPos().y; b.getDirection().x = (float) Math.cos(Math.toRadians(i*360.0/36.0)); b.getDirection().y = (float) Math.sin(Math.toRadians(i*360.0/36.0)); board.addBullet(b); } } decoy.destroy(board, false); } decoy = SupportFactory.makeDecoy(board, player); if(hasPower(Power.SUPPORT_DRONEMASTER)) addAllBulletModsToSupport(player, decoy); support.add(decoy); board.addMech(decoy); break; case SPIRALPOWER: player.getComponents().get(0).getWeapon().setShotType(ShotType.SPIRAL); break; case RAPIDFIRE: player.getComponents().get(0).getWeapon().setFireDelay(player.getOriginalFireDelay()/2f); break; case CLONE: if(player.getComponents().get(0).getWeapon().getShotType()==ShotType.CLONERAY) { player.getComponents().get(0).getWeapon().setShotType(player.getOriginalShotType()); } else player.getComponents().get(0).getWeapon().setShotType(ShotType.CLONERAY); break; case CLONE_SELFDESTRUCT: if(clone!=null && !clone.isDead()) { clone.destroy(board, false); Point2D dir = new Point2D(); for(Bullet b: board.getEnemyBullets()) { dir.x = clone.getPos().x - b.getPos().x; dir.y = clone.getPos().y - b.getPos().y; if(Point2D.magnitude(dir) < Mech.MECH_RADIUS*10) b.setSpeed(0); } for(Component c: clone.getComponents()) { Bullet bullet = player.getComponents().get(0).getWeapon().getBullet(); for(int i=0;i<20;i++) { Bullet b = bullet.clone(); b.getPos().x = c.getPos().x + clone.getPos().x; b.getPos().y = c.getPos().y + clone.getPos().y; b.getDirection().x = (float) Math.cos(Math.toRadians(i*360.0/20.0)); b.getDirection().y = (float) Math.sin(Math.toRadians(i*360.0/20.0)); board.addBullet(b); } } } break; case IONBEAMS: if(player.getComponents().get(0).getWeapon().getShotType()==ShotType.IONBEAM) { player.getComponents().get(0).getWeapon().setShotType(player.getOriginalShotType()); } else player.getComponents().get(0).getWeapon().setShotType(ShotType.IONBEAM); break; case EXPLOSIVECHARGE: explodeFireTimer = 0; break; default: break; } } private void tickPower(float dt, Board board, Player player, ActivePower ap) { switch(ap.type) { case EXPLOSIVECHARGE: if(ap.active) { explodeFireTimer += dt; if(explodeFireTimer > 3) { explodeFireTimer = explodeFireTimer%3; Bullet bullet = player.getComponents().get(0).getWeapon().getBullet(); Bullet b = bullet.clone(); b.getPos().x = player.getPos().x; b.getPos().y = player.getPos().y; b.getDirection().x = (float) Math.cos(Math.toRadians(ap.remainingCooldown*8)); b.getDirection().y = (float) Math.sin(Math.toRadians(ap.remainingCooldown*8)); board.addBullet(b); } } break; case DEFENCELASER: if(ap.active) { Point2D pos = player.getPos(); SelfDefenceLaser.fire(dt, board, pos, player); SelfDefenceLaser.getHitObjects().clear(); } break; case DEFLECTORSHIELD: if(player.getShield()!=null && player.getShield().getCurrentCapacity()>0) { // defelct bullets Point2D p = new Point2D(); for(Bullet b: board.getEnemyBullets()) { p.x = (b.getPos().x-player.getPos().x); p.y = (b.getPos().y-player.getPos().y); if(Point2D.magnitude(p)<Mech.MECH_RADIUS*5) { Point2D.normalise(p); Point2D.normalise(b.getDirection()); b.getDirection().x *= 25; b.getDirection().y *= 25; p.x *= player.getShield().getCurrentCapacity()/player.getShield().getMaxCapacity(); p.y *= player.getShield().getCurrentCapacity()/player.getShield().getMaxCapacity(); b.getDirection().x = b.getDirection().x + p.x; b.getDirection().y = b.getDirection().y + p.y; } } } break; default: break; } } public void removePower(ActivePower ap, Board board, Player player) { switch(ap.type) { case SLOW: board.setTimeScale(1f); break; case CLUSTERPOWER: removeBulletMod(player, BulletMod.CLUSTER); break; case GARGANTUA: removeBulletMod(player, BulletMod.GARGANTUA); break; case SHIELD_CHARGING: removeBulletMod(player, BulletMod.SHIELDCHARGE); break; case FIREPOWER: removeBulletMod(player, BulletMod.FIRE); break; case HOMINGPOWER: removeBulletMod(player, BulletMod.HOMING); break; case MEGAPOWER: removeBulletMod(player, BulletMod.MEGA); break; case SPIRALPOWER: player.getComponents().get(0).getWeapon().setShotType(player.getOriginalShotType()); break; case RAPIDFIRE: player.getComponents().get(0).getWeapon().setFireDelay(player.getOriginalFireDelay()); break; default: break; } } private void addBulletMod(Player player, BulletMod mod, int amnt) { player.getComponents().get(0).getWeapon().getBullet().getMods().put(mod, amnt); // share bullet mods if(hasPower(Power.SUPPORT_DRONEMASTER)) { for(AllyMech m: support) { for(Component c: m.getComponents()) { if(c.getWeapon()!=null && c.getWeapon().getBullet()!=null) c.getWeapon().getBullet().getMods().put(mod, amnt); } } } } private void removeBulletMod(Player player, BulletMod mod) { player.getComponents().get(0).getWeapon().getBullet().getMods().remove(mod); // remove mods if(hasPower(Power.SUPPORT_DRONEMASTER)) { for(AllyMech m: support) { for(Component c: m.getComponents()) { if(c.getWeapon()!=null && c.getWeapon().getBullet()!=null) c.getWeapon().getBullet().getMods().remove(mod); } } } } public boolean hasPower(Power power) { for(ActivePower ap: getActivePowers()) if(ap.type==power) return true; return false; } public List<ActivePower> getActivePowers() { return activePowers; } public void addActivePower(Power power) { ActivePower ap = new ActivePower(); ap.type = power; ap.remainingActive = 0; ap.remainingCooldown = 0; activePowers.add(ap); } public void addAllBulletModsToSupport(Player player, Mech support) { // share bullet mods for(BulletMod mod: player.getBullet().getMods().keySet()) { for(Component c: support.getComponents()) { if(c.getWeapon()!=null && c.getWeapon().getBullet()!=null) c.getWeapon().getBullet().getMods().put(mod, player.getBullet().getMods().get(mod)); } } } public Mech getClone() { return clone; } public void setClone(AllyMech clone) { support.add(clone); this.clone = clone; } public List<AllyMech> getGadgets() { return gadgets; } public void addGadget(AllyMech g) { gadgets.add(g); support.add(g); } public class ActivePower { public Power type; public float remainingCooldown; public float remainingActive; public boolean active; } }
hjqcl316602/app-trade-admin
package/es/imager/transformer.js
<reponame>hjqcl316602/app-trade-admin /** * @name 图片格式转换 * @param { src } [ string ] * @param { type } ["base64", "blob"] * @return [ promise ] */ let transformer = function(src, type = "base64") { if (typeof src !== "string") throw new Error("The first argument must be string."); if (["base64", "blob"].findIndex(item => item === type) === -1) throw new Error("The third argument must be in ['base64', 'blob' ]."); return new Promise((resolve, reject) => { setTimeout(() => { let image = new Image(); image.src = src; image["crossOrigin"] = "Anonymous"; //image.setAttribute("crossOrigin",'Anonymous') // Tainted canvases may not be exported. 跨域问题 image.onload = () => { try { let canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; let ctx = canvas.getContext("2d"); ctx.drawImage(image, 0, 0, canvas.width, canvas.height); if (type === "base64") { let dataurl = canvas.toDataURL(type, 1); ctx.clearRect(0, 0, canvas.width, canvas.height); resolve(dataurl); } else { canvas.toBlob( function(blob) { resolve(blob); }, type, 1 ); ctx.clearRect(0, 0, canvas.width, canvas.height); } } catch (e) { reject(e); } }; image.onerror = e => { reject(e); }; }, 0); }); }; transformer.base64 = function(src) { return transformer(src, "base64"); }; transformer.blob = function(src) { return transformer(src, "blob"); }; export default transformer; // transformer("http://img5.imgtn.bdimg.com/it/u=1128579105,2742690848&fm=26&gp=0.jpg", "blob").then(res => console.log(res)); //image/jpeg // transformer.blob("http://img5.imgtn.bdimg.com/it/u=1128579105,2742690848&fm=26&gp=0.jpg").then(res => console.log(res)); //image/jpeg // transformer.base64("http://img5.imgtn.bdimg.com/it/u=1128579105,2742690848&fm=26&gp=0.jpg").then(res => console.log(res)); //image/jpeg
redhawkIT/typescript-eslint
packages/shared-fixtures/fixtures/javascript/forIn/for-in-with-bare-assigment.src.js
for (x = 0 in arr);
ArpNetworking/artemis
app/com/groupon/deployment/host/Rpm.java
/** * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.groupon.deployment.host; import akka.actor.AbstractActor; import com.arpnetworking.steno.LoggerFactory; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import com.groupon.deployment.HostDeploymentNotifications; import com.groupon.deployment.SshSessionFactory; import com.typesafe.config.Config; import models.Deployment; import models.Host; import models.PackageVersion; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.Session; import play.Logger; import utils.RpmVersionComparator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * RPM deployment actor. * * @author <NAME> (brandon dot arp at inscopemetrics dot com) */ public class Rpm extends AbstractActor { /** * Public constructor. * * @param host host to deploy to * @param deployment the deployment spec * @param sshFactory factory for ssh connections * @param config artemis configuration */ @AssistedInject public Rpm( @Assisted final Host host, @Assisted final Deployment deployment, final SshSessionFactory sshFactory, final Config config) { _host = host; _deployment = deployment; _sshFactory = sshFactory; LOGGER.info() .setMessage("Started rpm deployment actor for host") .addData("host", host.getName()) .log(); context().parent().tell(new HostDeploymentNotifications.DeploymentStarted(host), self()); self().tell("start", self()); } @Override public Receive createReceive() { return receiveBuilder() .matchEquals("start", msg -> deploy()) .build(); } private void deploy() { try (SSHClient sshClient = _sshFactory.create(_host.getName())) { final Map<String, PackageVersion> deploymentMap = _deployment.getManifestHistory().getManifest().asPackageMap(); // Yum install final Map<String, String> installedPackages = getInstalledPackages(sshClient, deploymentMap); final List<String> installTargets = Lists.newArrayList(); final List<String> updateTargets = Lists.newArrayList(); final List<String> downgradeTargets = Lists.newArrayList(); for (final Map.Entry<String, PackageVersion> entry : deploymentMap.entrySet()) { final String pkg = entry.getKey(); final String newVersion = entry.getValue().getVersion(); final String oldVersion = installedPackages.get(pkg); final String line; if (oldVersion != null) { final int comparison = RPM_VERSION_COMPARATOR.compare(oldVersion, newVersion); if (comparison < 0) { line = String.format("upgrade package %s from %s to %s", pkg, oldVersion, newVersion); updateTargets.add(pkg); } else if (comparison > 0) { line = String.format("downgrade package %s from %s to %s", pkg, oldVersion, newVersion); downgradeTargets.add(pkg); } else { line = String.format("package %s version not changing", pkg); } } else { line = String.format("installing package %s version %s", pkg, newVersion); installTargets.add(pkg); } context().parent().tell(new HostDeploymentNotifications.DeploymentLog(_host, line), self()); } if (installTargets.size() > 0 || downgradeTargets.size() > 0 || updateTargets.size() > 0) { executeRequired(sshClient, "sudo -n yum clean expire-cache", "yum"); } executeYum(sshClient, deploymentMap, "install", installTargets); executeYum(sshClient, deploymentMap, "downgrade", downgradeTargets); executeYum(sshClient, deploymentMap, "update", updateTargets); context().parent().tell(new HostDeploymentNotifications.DeploymentSucceeded(_host), self()); // CHECKSTYLE.OFF: IllegalCatch - we need to catch everything, we'll record it and die } catch (final IOException | RuntimeException e) { // CHECKSTYLE.ON: IllegalCatch context().parent().tell(new HostDeploymentNotifications.DeploymentFailed(_host, e), self()); } } private void executeYum( final SSHClient sshClient, final Map<String, PackageVersion> deploymentMap, final String operation, final List<String> targetList) throws IOException { if (targetList.size() > 0) { final String installString = targetList.stream() .map(pkg -> String.format("%s-%s", pkg, deploymentMap.get(pkg).getVersion())) .reduce("", (a, b) -> String.format("%s %s", a, b)); executeRequired(sshClient, String.format("sudo -n yum %s -y %s 2>&1", operation, installString), "yum"); } } private void executeRequired(final SSHClient sshClient, final String commandString, final String description) throws IOException { final Integer exitStatus; exitStatus = executeCommand(sshClient, commandString); if (exitStatus == null || exitStatus != 0) { throw new IllegalStateException(description + " exit code was " + exitStatus); } } private Integer executeCommand(final SSHClient sshClient, final String commandString) throws IOException { context().parent().tell(new HostDeploymentNotifications.DeploymentLog(_host, "Executing '" + commandString + "'"), self()); final Integer exitStatus; try (Session session = sshClient.startSession()) { session.allocateDefaultPTY(); try ( Session.Command command = session.exec(commandString); BufferedReader error = new BufferedReader(new InputStreamReader(command.getErrorStream(), Charsets.UTF_8)); BufferedReader reader = new BufferedReader(new InputStreamReader(command.getInputStream(), Charsets.UTF_8))) { String line = reader.readLine(); while (line != null) { LOGGER.info("***" + line); context().parent().tell(new HostDeploymentNotifications.DeploymentLog(_host, line), self()); line = reader.readLine(); } command.join(30, TimeUnit.SECONDS); session.join(30, TimeUnit.SECONDS); exitStatus = command.getExitStatus(); } } return exitStatus; } private Map<String, String> getInstalledPackages( final SSHClient sshClient, final Map<String, PackageVersion> deployVersions) throws IOException { final String commandString = "rpm -qa --queryformat \"%{NAME} %{VERSION} %{RELEASE}\\n\""; final Map<String, String> versions = Maps.newHashMap(); context().parent().tell(new HostDeploymentNotifications.DeploymentLog(_host, "Executing '" + commandString + "'"), self()); final Integer exitStatus; try (Session session = sshClient.startSession(); Session.Command command = session.exec(commandString); BufferedReader error = new BufferedReader(new InputStreamReader(command.getErrorStream(), Charsets.UTF_8)); BufferedReader reader = new BufferedReader(new InputStreamReader(command.getInputStream(), Charsets.UTF_8))) { String line = reader.readLine(); while (line != null) { final String[] split = line.split(" ", 3); if (split.length == 3) { final String name = split[0]; final String version = split[1] + "-" + split[2]; if (deployVersions.containsKey(name)) { versions.put(name, version); } } LOGGER.info("***" + line); context().parent().tell(new HostDeploymentNotifications.DeploymentLog(_host, line), self()); line = reader.readLine(); } command.join(30, TimeUnit.SECONDS); session.join(30, TimeUnit.SECONDS); exitStatus = command.getExitStatus(); if (exitStatus == null || exitStatus != 0) { throw new IllegalStateException("package lookup exit code was " + exitStatus); } } return versions; } private final Host _host; private final Deployment _deployment; private final SshSessionFactory _sshFactory; private static final RpmVersionComparator RPM_VERSION_COMPARATOR = new RpmVersionComparator(); private static final com.arpnetworking.steno.Logger LOGGER = LoggerFactory.getLogger(Rpm.class); }
zhouchengtang/ZCKitFramework
ZCKit/ZCKit/ZCCategory/UIKit/UIViewController/UIViewController+ZCSystemBackButtonHandler.h
<filename>ZCKit/ZCKit/ZCCategory/UIKit/UIViewController/UIViewController+ZCSystemBackButtonHandler.h // // UIViewController+ZCSystemBackButtonHandler.h // ZCKit // // Created by zhoucheng on 2016/10/19. // Copyright © 2016年 zhoucheng. All rights reserved. // #import <UIKit/UIKit.h> @protocol ZCBackButtonHandlerProtocol <NSObject> @optional // Override this method in UIViewController derived class to handle 'Back' button click -(BOOL)navigationShouldPopOnBackButton; @end @interface UIViewController (SystemBackButtonHandler)<ZCBackButtonHandlerProtocol> @end
coppelia517/orlov
tests/seir/ui/browndust/initial.py
<filename>tests/seir/ui/browndust/initial.py """ BrownDust Initial Class """ import logging # pylint: disable=E0401 from seir.element import elements from seir.element import Component logger = logging.getLogger(__name__) TEST_PATH = { 'eclipse': 'initial/eclipse', 'skip': 'initial/skip', 'close': 'initial/close', 'server': 'initial/sever', 'server_alert': 'initial/server/alert', 'server_taiwan': 'initial/server/taiwan', 'server_japan': 'initial/server/japan', 'server_asia': 'initial/server/asia', 'server_connect': 'initial/server/connect', 'name': 'initial/playername', 'name_keyboard': 'initial/playername/keyboard', 'name_delete': 'initial/playername/delete', 'name_check': 'initial/playername/check', 'name_title': 'initial/playername/title', 'name_cancel': 'initial/playername/cancel', 'name_ok': 'initial/playername/ok', 'member': 'initial/erin' } @elements(TEST_PATH) class Initial(Component): """ BrownDust Initial View. """ def displayed(self, max_wait=20): """ Displayed Initial UI Component. Arguments: max_wait(int): max wait time. Returns: result(bool): displayed Initial Components. """ return self.eclipse.displayed(max_wait=max_wait) def skip_prologue(self): """ Skip Prologue. Returns: result(bool): displayed User Name. """ assert self.eclipse.displayed(max_wait=120), 'Initial - Eclipse : Not Displayed.' assert self.skip.displayed(), 'Initial - Skip : Not Displayed.' while self.skip.displayed(max_wait=5): self.skip.click(check=False) self.sleep(0.5, strict=True) #if self.server_alert.displayed(max_wait=5): # self.server_alert.click(check=False) #if self.server.displayed(max_wait=5): # assert self.server_taiwan.displayed(), 'Initial - Server : Not Displayed.' # self.server_taiwan.click() # self.sleep(1, strict=True) # assert self.server_connect.displayed(), 'Initial - Server : Not Button Displayed.' # self.server_connect.click() return self.name.displayed() def set_player_name(self, player_name): """ Set Player Name. Arguments: player_name(str): set player name Returns: result(bool): Set Player Name. """ assert self.name.displayed(), 'Initial - Set Player Name : Not Displayed.' self.name.click() self.sleep(2, strict=True) self.name_keyboard.click() self.name.input_str(player_name) self.sleep(1, strict=True) self.name_delete.click(check=False) self.sleep(2, strict=True) self.name_check.click() assert self.name_title.displayed(), 'Initial - Set Player Name Title : Not Displayed.' self.name_ok.click(check=False) return True def get_member(self): """ Get Member. Returns: result(bool): Return Home Screen. """ assert self.member.displayed(), 'Initial - Set Member : Not Displayed.' assert self.skip.displayed(), 'Initial - Skip : Not Displayed.' while self.skip.displayed(max_wait=5): self.skip.click(check=False) self.sleep(0.5, strict=True) assert self.close.displayed(), 'Initial - Set Member : Not Close Displayed.' self.close.click() assert self.skip.displayed(), 'Initial - Skip : Not Displayed.' while self.skip.displayed(max_wait=5): self.skip.click(check=False) self.sleep(0.5, strict=True) return True
wanglei2659297/das
das-client/src/test/java/com/ppdai/das/client/DistributedTransactionTableTest.java
package com.ppdai.das.client; import static com.ppdai.das.client.SqlBuilder.selectAllFrom; import static com.ppdai.das.core.enums.DatabaseCategory.MySql; import static com.ppdai.das.core.enums.DatabaseCategory.SqlServer; import static org.junit.Assert.fail; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.ppdai.das.client.DbSetupUtil.DbSetuper; import com.ppdai.das.client.Person.PersonDefinition; @RunWith(Parameterized.class) public class DistributedTransactionTableTest { private static final int DB_MODE = 2; private static final int TABLE_MODE = 4; private final static String TABLE_NAME = "person"; private DataPreparer preparer; private DasClient dao; private DbSetuper setuper; private static PersonDefinition p = Person.PERSON; @Parameters public static Collection data() throws SQLException { return Arrays.asList(new Object[][]{ {new DasClientTest(MySql)}, {new DasClientTest(SqlServer)}, {DasClientTableTest.of(MySql)}, {DasClientTableTest.of(SqlServer)}, }); } public DistributedTransactionTableTest(DataPreparer preparer) throws SQLException { this.preparer = preparer; dao = DasClientFactory.getClient(preparer.getDbName()); } public Hints hints() { return new Hints(); } @Before public void setup() throws Exception { preparer.setup(); } @After public void tearDown() throws Exception { preparer.tearDown(); } @Test public void testBatchWrongLogicDb() throws Exception { PersonDefinition p = Person.PERSON; SqlBuilder builder = selectAllFrom(p).where().allOf(p.CountryID.eq(0), p.CityID.eq(0)).orderBy(p.PeopleID.asc()).into(Person.class); List<Person> plist = dao.query(builder); try { DasClientFactory.getClient(preparer.getDbName(MySql)).execute(() -> { DasClient c2 = DasClientFactory.getClient(preparer.getDbName(SqlServer)); c2.batchDelete(plist); }, new Hints().inShard(0)); fail(); } catch (SQLException e) { e.printStackTrace(); } } }
velmyshanovnyi/rockbrama
!arh/landing/65_landings_templates/27/js/custom.js
$(function() { $.clicks = 318; $.converse = 16; $.offright = 0; $( "#slider" ).slider({ value: $.clicks, min: 0, max: 5000, step: 10, slide: function( event, ui ) { $( "#slider a" ).text( ui.value ); $.clicks = ui.value; $('#how_much_clients span').html(($.clicks * $.converse/100).toFixed(0)); $('#cmnsd').html(($.clicks * $.converse/100*12).toFixed(0)); if ( ui.value <= 100 ) {$("#slider").slider('option', 'step', 10);} if ( ui.value <= 700 ) {$("#slider").slider('option', 'step', 20);} if ( ui.value >= 700 ) {$("#slider").slider('option', 'step', 50);} //$.offset = parseFloat($('#slider a').css('left')); $('#omg').css('width', parseFloat($(".ui-slider-handle.ui-state-default.ui-corner-all")[0].style.left)-2+'%'); }, change: function( event, ui ) { $('#omg').css('width', parseFloat($(".ui-slider-handle.ui-state-default.ui-corner-all")[0].style.left)-2+'%'); } }); $( "#slider-1" ).slider({ value: $.converse, min: 0, max: 30, step: 1, slide: function( event, ui ) { $.converse = ui.value $('#how_much_clients span').html(($.clicks * $.converse/100).toFixed(0)); $('#cmnsd').html(($.clicks * $.converse/100*12).toFixed(0)); $( "#slider-1 a" ).text( ui.value ); $.offset = parseFloat($('#slider-1 a').css('left')); //('#omg1').css('width', $.offset+'px'); $('#omg1').css('width', $('#omg1').css('width', parseFloat($(".ui-slider-handle.ui-state-default.ui-corner-all")[1].style.left)-2+'%')); }, change: function( event, ui ) { $('#omg1').css('width', $('#omg1').css('width', parseFloat($(".ui-slider-handle.ui-state-default.ui-corner-all")[1].style.left)-2+'%')); } }); $( "#slider a" ).text( $.clicks ); $( "#slider-1 a" ).text( $.converse ); google_maps(); // Load google maps onload page function google_maps() { var latlng = new google.maps.LatLng(55.736812,37.617574); var settings = { zoom: 16, center: latlng, mapTypeControl: true, mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}, navigationControl: false, navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL}, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"), settings); var myLatlng = new google.maps.LatLng(55.736812,37.617574); var myOptions = { zoom: 16, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var zhks = new google.maps.LatLng(55.736607,37.623652); var iconBase = 'img/'; var marker = new google.maps.Marker({position: zhks,map: map,icon: iconBase + 'marker.png'}); } $('.lmk').click(function(event) { event.preventDefault(); $('#nastr').html($(this).data('buy-id')); $('#dsd').attr('value', $(this).data('buy-id')); }); $("#menu .wrapper .in a").click(function(event){ event.preventDefault(); var dest=0; if($(this.hash).offset().top > $(document).height()-$(window).height()){ dest=$(document).height()-$(window).height()-56; }else{ dest=$(this.hash).offset().top-56; } $('html,body').animate({scrollTop:dest}, 500,'swing'); }); });
dipta007/Competitive-Programming
OTHERS/ICPC/ICPC 2014/mock/B.c
#include<stdio.h> int main() { int n,i,j,a[100],swap; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n;i++) { for(j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) { swap=a[j+1]; a[j+1]=a[j]; a[j]=swap; } } } for(i=0;i<n;i++) { printf("%d",a[i]); } }
untgames/funner
components/system/sources/platform/windows/application/win_platform_configuration.cpp
#include "../shared.h" #ifndef LOCALE_SNAME #define LOCALE_SNAME 0x0000005c // locale name (ie: en-us) #endif namespace { const char* CONFIG_PATH = "/anonymous/platform_config.xml"; /* Компонент сохранения параметров платформы в файле */ class PlatformConfigurationComponent { public: //загрузка компонента PlatformConfigurationComponent () : config_file ((size_t)0, common::FileMode_ReadWrite | common::FileMode_Create) { try { common::FileSystem::Rename (config_file.Path (), CONFIG_PATH); common::XmlWriter writer (CONFIG_PATH); writer.BeginNode ("Configuration"); writer.BeginNode ("Properties"); SaveProperty (writer, "OS", "windows"); SaveProperty (writer, "ExecutableSuffix", ".exe"); SaveProperty (writer, "SharedLibrarySuffix", ".dll"); SaveProperty (writer, "SharedLibraryPrefix", ""); wchar_t language_name_buffer [16]; memset (language_name_buffer, 0, sizeof (language_name_buffer)); GetLocaleInfoW (LOCALE_USER_DEFAULT, LOCALE_SNAME, language_name_buffer, sizeof (language_name_buffer)); if (xtl::xstrlen (language_name_buffer)) SaveProperty (writer, "Language", common::to_utf8_string (language_name_buffer).c_str ()); } catch (xtl::exception& e) { printf ("Exception caught '%s'\n", e.what ()); throw; } } private: void SaveProperty (common::XmlWriter& writer, const char* name, const char* value) { writer.BeginNode ("Property"); writer.WriteAttribute ("Name", name); writer.WriteAttribute ("Value", value); writer.EndNode (); } private: common::MemFile config_file; }; extern "C" { common::ComponentRegistrator<PlatformConfigurationComponent> PlatformConfiguration ("common.file_systems.platform_configuration"); } }
ChaojieDZhao/jb-brother
jb-basic/src/main/java/basic/io/nio/utils/ByteBufferUtils.java
/* * Copyright (c) * * 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 basic.io.nio.utils; import java.io.*; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; /** * ByteBuffer工具类 */ public class ByteBufferUtils { private ByteBufferUtils() { } /** * 序列化ByteBuffer * * @param serializable 可序列化的对象 * @return 字节缓冲区 * @throws IOException */ public static ByteBuffer writeObject(Serializable serializable) throws IOException { ByteArrayOutputStream bos = null; ObjectOutputStream oos = null; try { bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(new BufferedOutputStream(bos)); oos.writeObject(serializable); } finally { if (oos != null) { oos.close(); } } // System.out.println(printByteArray(bos.toByteArray())); return ByteBuffer.wrap(bos.toByteArray()); } /** * 反序列化ByteBuffer * * @param byteBuffer * @return 可序列化的对象 * @throws IOException */ public static Serializable readObject(ByteBuffer byteBuffer) throws IOException, ClassNotFoundException { ByteArrayInputStream bis = null; ObjectInputStream ois = null; Serializable object = null; try { byte[] bytes = readToBytes(byteBuffer); // System.out.println(printByteArray(bytes)); bis = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(new BufferedInputStream(bis)); object = (Serializable)ois.readObject(); } finally { if (ois != null) { ois.close(); } } return object; } /** * 转化byte数组 * * @param byteBuffer * @return */ public static byte[] readToBytes(ByteBuffer byteBuffer) { byteBuffer.flip(); // Retrieve bytes between the position and limit // (see Putting Bytes into a ByteBuffer) byte[] bytes = new byte[byteBuffer.remaining()]; // transfer bytes from this buffer into the given destination array byteBuffer.get(bytes, 0, bytes.length); byteBuffer.clear(); return bytes; } /** * 聚集为一个ByteBuffer * * @param bytes * @return */ public static ByteBuffer gather(List<ByteBuffer> bytes) { int length = 0; for (int i = 0; i < bytes.size(); i++) { bytes.get(i).flip(); length += bytes.get(i).remaining(); } ByteBuffer buffer = ByteBuffer.allocate(length); buffer.clear(); for (int i = 0, offset = 0; i < bytes.size(); i++) { while (bytes.get(i).hasRemaining()) { buffer.put(bytes.get(i)); } bytes.get(i).clear(); } return buffer; } private static String printByteArray(byte[] bytes) { StringBuilder stringBuilder = new StringBuilder(bytes.length); stringBuilder.append("length=").append(bytes.length).append("["); for (int i = 0; i < bytes.length; i++) { stringBuilder.append(bytes[i]); } stringBuilder.append("]"); return stringBuilder.toString(); } public static void main(String[] args) { ByteBuffer b1 = ByteBuffer.allocate(10); b1.put((byte)1); b1.put((byte)2); b1.put((byte)3); ByteBuffer b2 = ByteBuffer.allocate(10); b2.put((byte)1); b2.put((byte)2); b2.put((byte)3); ByteBuffer buffer = gather(Arrays.asList(b1, b2)); byte[] bb = readToBytes(buffer); System.out.println(printByteArray(bb)); } }