repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
lonely7345/bi-platform
fileserver/src/main/java/com/baidu/rigel/biplatform/ma/common/file/protocol/Request.java
/** * Copyright (c) 2014 Baidu, Inc. 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.baidu.rigel.biplatform.ma.common.file.protocol; import java.io.Serializable; import java.util.Map; /** * * 请求对象 * * @author david.wang * @version 1.0.0.1 */ public class Request implements Serializable { /** * serialized id */ private static final long serialVersionUID = 686714690446844985L; /** * 请求指令 */ private Command command; /** * 请求参数 */ private Map<String, Object> params; public Request() { } /** * 构造函数 * * @param command * @param params */ public Request(Command command, Map<String, Object> params) { super(); this.command = command; this.params = params; } /** * * @return 请求指令 */ public Command getCommand() { return this.command; } /** * * @return 请求参数 */ public Map<String, Object> getParams() { return this.params; } public void setCommand(Command command) { this.command = command; } public void setParams(Map<String, Object> params) { this.params = params; } @Override public String toString() { return "[command : " + this.command.name() + " , params : " + this.params + "]"; } }
zhangxing4418/ZXCrashProtection
ZXCrashProtection/Class/Notification/ZXNotificationDelegate.h
<filename>ZXCrashProtection/Class/Notification/ZXNotificationDelegate.h // // ZXNotificationDelegate.h // ZXCrashProtection // // Created by bug on 2018/10/30. // Copyright © 2018 CRM. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface ZXNotificationDelegate : NSObject @property (nonatomic, assign) BOOL needRemove; - (instancetype)initWithObserver:(id)observer; @end NS_ASSUME_NONNULL_END
Xchuanshuo/LiteNESEmulator
src/main/java/com/legend/utils/PropertiesUtils.java
package com.legend.utils; import java.io.*; import java.util.Properties; import java.util.Set; /** * @author Legend * @data by on 20-6-5. * @description 全局属性配置工具类 */ public class PropertiesUtils { private static Properties properties = new Properties(); static { try { File file = new File(Constants.GLOBAL_CONFIG_FILE); File parentDir = file.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } if (!file.exists()) { file.createNewFile(); } FileInputStream fis = new FileInputStream(Constants.GLOBAL_CONFIG_FILE); properties.load(fis); } catch (IOException e) { e.printStackTrace(); } } public static void put(String key, String value) { try (FileOutputStream fos = new FileOutputStream(Constants.GLOBAL_CONFIG_FILE)) { properties.setProperty(key, value); properties.store(fos, null); fos.flush(); } catch (IOException e) { e.printStackTrace(); } } public static String get(String key) { return properties.getProperty(key); } public static void remove(String key) { try (FileOutputStream fos = new FileOutputStream(Constants.GLOBAL_CONFIG_FILE)) { properties.remove(key); properties.store(fos, null); fos.flush(); } catch (IOException e) { e.printStackTrace(); } } public static Set<String> getKeys() { return properties.stringPropertyNames(); } }
ScalablyTyped/SlinkyTyped
f/firefox-webext-browser/src/main/scala/typingsSlinky/firefoxWebextBrowser/browser/extensionTypes.scala
<gh_stars>10-100 package typingsSlinky.firefoxWebextBrowser.browser import org.scalablytyped.runtime.StringDictionary import typingsSlinky.firefoxWebextBrowser.browser.manifest.ExtensionURL import typingsSlinky.std.Array import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /** * The `browser.extensionTypes` API contains type declarations for WebExtensions. * * Not allowed in: Content scripts, Devtools pages */ object extensionTypes { /** The origin of the CSS to inject, this affects the cascading order (priority) of the stylesheet. */ /* Rewritten from type alias, can be one of: - typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.user - typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.author */ trait CSSOrigin extends StObject object CSSOrigin { @scala.inline def author: typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.author = "author".asInstanceOf[typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.author] @scala.inline def user: typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.user = "user".asInstanceOf[typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.user] } type Date = String | Double | (/* import warning: transforms.QualifyReferences#resolveTypeRef many Couldn't qualify globalThis.Date */ js.Any) /* Rewritten from type alias, can be one of: - typingsSlinky.firefoxWebextBrowser.anon.File - typingsSlinky.firefoxWebextBrowser.anon.Code */ trait ExtensionFileOrCode extends StObject object ExtensionFileOrCode { @scala.inline def Code(code: String): typingsSlinky.firefoxWebextBrowser.anon.Code = { val __obj = js.Dynamic.literal(code = code.asInstanceOf[js.Any]) __obj.asInstanceOf[typingsSlinky.firefoxWebextBrowser.anon.Code] } @scala.inline def File(file: ExtensionURL): typingsSlinky.firefoxWebextBrowser.anon.File = { val __obj = js.Dynamic.literal(file = file.asInstanceOf[js.Any]) __obj.asInstanceOf[typingsSlinky.firefoxWebextBrowser.anon.File] } } /** Details about the format, quality, area and scale of the capture. */ @js.native trait ImageDetails extends StObject { /** The format of the resulting image. Default is `"jpeg"`. */ var format: js.UndefOr[ImageFormat] = js.native /** * When format is `"jpeg"`, controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. */ var quality: js.UndefOr[Double] = js.native /** * The area of the document to capture, in CSS pixels, relative to the page. If omitted, capture the visible viewport. */ var rect: js.UndefOr[ImageDetailsRect] = js.native /** The scale of the resulting image. Defaults to `devicePixelRatio`. */ var scale: js.UndefOr[Double] = js.native } object ImageDetails { @scala.inline def apply(): ImageDetails = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[ImageDetails] } @scala.inline implicit class ImageDetailsMutableBuilder[Self <: ImageDetails] (val x: Self) extends AnyVal { @scala.inline def setFormat(value: ImageFormat): Self = StObject.set(x, "format", value.asInstanceOf[js.Any]) @scala.inline def setFormatUndefined: Self = StObject.set(x, "format", js.undefined) @scala.inline def setQuality(value: Double): Self = StObject.set(x, "quality", value.asInstanceOf[js.Any]) @scala.inline def setQualityUndefined: Self = StObject.set(x, "quality", js.undefined) @scala.inline def setRect(value: ImageDetailsRect): Self = StObject.set(x, "rect", value.asInstanceOf[js.Any]) @scala.inline def setRectUndefined: Self = StObject.set(x, "rect", js.undefined) @scala.inline def setScale(value: Double): Self = StObject.set(x, "scale", value.asInstanceOf[js.Any]) @scala.inline def setScaleUndefined: Self = StObject.set(x, "scale", js.undefined) } } /** * The area of the document to capture, in CSS pixels, relative to the page. If omitted, capture the visible viewport. */ @js.native trait ImageDetailsRect extends StObject { var height: Double = js.native var width: Double = js.native var x: Double = js.native var y: Double = js.native } object ImageDetailsRect { @scala.inline def apply(height: Double, width: Double, x: Double, y: Double): ImageDetailsRect = { val __obj = js.Dynamic.literal(height = height.asInstanceOf[js.Any], width = width.asInstanceOf[js.Any], x = x.asInstanceOf[js.Any], y = y.asInstanceOf[js.Any]) __obj.asInstanceOf[ImageDetailsRect] } @scala.inline implicit class ImageDetailsRectMutableBuilder[Self <: ImageDetailsRect] (val x: Self) extends AnyVal { @scala.inline def setHeight(value: Double): Self = StObject.set(x, "height", value.asInstanceOf[js.Any]) @scala.inline def setWidth(value: Double): Self = StObject.set(x, "width", value.asInstanceOf[js.Any]) @scala.inline def setX(value: Double): Self = StObject.set(x, "x", value.asInstanceOf[js.Any]) @scala.inline def setY(value: Double): Self = StObject.set(x, "y", value.asInstanceOf[js.Any]) } } /* extensionTypes types */ /** The format of an image. */ /* Rewritten from type alias, can be one of: - typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.jpeg - typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.png */ trait ImageFormat extends StObject object ImageFormat { @scala.inline def jpeg: typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.jpeg = "jpeg".asInstanceOf[typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.jpeg] @scala.inline def png: typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.png = "png".asInstanceOf[typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.png] } /** * Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. */ @js.native trait InjectDetails extends StObject { /** * If allFrames is `true`, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's `false` and is only injected into the top frame. */ var allFrames: js.UndefOr[Boolean] = js.native /** * JavaScript or CSS code to inject. * * **Warning:** * Be careful using the `code` parameter. Incorrect use of it may open your extension to [cross site scripting](https://en.wikipedia.org/wiki/Cross-site_scripting) attacks. */ var code: js.UndefOr[String] = js.native /** The css origin of the stylesheet to inject. Defaults to "author". */ var cssOrigin: js.UndefOr[CSSOrigin] = js.native /** JavaScript or CSS file to inject. */ var file: js.UndefOr[String] = js.native /** The ID of the frame to inject the script into. This may not be used in combination with `allFrames`. */ var frameId: js.UndefOr[Double] = js.native /** * If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is `false`. */ var matchAboutBlank: js.UndefOr[Boolean] = js.native /** The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle". */ var runAt: js.UndefOr[RunAt] = js.native } object InjectDetails { @scala.inline def apply(): InjectDetails = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[InjectDetails] } @scala.inline implicit class InjectDetailsMutableBuilder[Self <: InjectDetails] (val x: Self) extends AnyVal { @scala.inline def setAllFrames(value: Boolean): Self = StObject.set(x, "allFrames", value.asInstanceOf[js.Any]) @scala.inline def setAllFramesUndefined: Self = StObject.set(x, "allFrames", js.undefined) @scala.inline def setCode(value: String): Self = StObject.set(x, "code", value.asInstanceOf[js.Any]) @scala.inline def setCodeUndefined: Self = StObject.set(x, "code", js.undefined) @scala.inline def setCssOrigin(value: CSSOrigin): Self = StObject.set(x, "cssOrigin", value.asInstanceOf[js.Any]) @scala.inline def setCssOriginUndefined: Self = StObject.set(x, "cssOrigin", js.undefined) @scala.inline def setFile(value: String): Self = StObject.set(x, "file", value.asInstanceOf[js.Any]) @scala.inline def setFileUndefined: Self = StObject.set(x, "file", js.undefined) @scala.inline def setFrameId(value: Double): Self = StObject.set(x, "frameId", value.asInstanceOf[js.Any]) @scala.inline def setFrameIdUndefined: Self = StObject.set(x, "frameId", js.undefined) @scala.inline def setMatchAboutBlank(value: Boolean): Self = StObject.set(x, "matchAboutBlank", value.asInstanceOf[js.Any]) @scala.inline def setMatchAboutBlankUndefined: Self = StObject.set(x, "matchAboutBlank", js.undefined) @scala.inline def setRunAt(value: RunAt): Self = StObject.set(x, "runAt", value.asInstanceOf[js.Any]) @scala.inline def setRunAtUndefined: Self = StObject.set(x, "runAt", js.undefined) } } @js.native trait PlainJSONArray extends Array[PlainJSONValue] with _PlainJSONValue @js.native trait PlainJSONObject extends /* key */ StringDictionary[PlainJSONValue] with _PlainJSONValue object PlainJSONObject { @scala.inline def apply(): PlainJSONObject = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[PlainJSONObject] } } /** A plain JSON value */ /* Rewritten from type alias, can be one of: - scala.Null - java.lang.String - scala.Double - scala.Boolean - typingsSlinky.firefoxWebextBrowser.browser.extensionTypes.PlainJSONArray - typingsSlinky.firefoxWebextBrowser.browser.extensionTypes.PlainJSONObject */ type PlainJSONValue = _PlainJSONValue | Null | String | Double | Boolean /** The soonest that the JavaScript or CSS will be injected into the tab. */ /* Rewritten from type alias, can be one of: - typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.document_start - typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.document_end - typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.document_idle */ trait RunAt extends StObject object RunAt { @scala.inline def document_end: typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.document_end = "document_end".asInstanceOf[typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.document_end] @scala.inline def document_idle: typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.document_idle = "document_idle".asInstanceOf[typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.document_idle] @scala.inline def document_start: typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.document_start = "document_start".asInstanceOf[typingsSlinky.firefoxWebextBrowser.firefoxWebextBrowserStrings.document_start] } trait _PlainJSONValue extends StObject }
colinw7/CGL
include/CGL_glx.h
#include <GL/glx.h> #include <CGL.h> #include <CXMachine.h>
stwe/Benno4j
src/main/java/de/sg/benno/ecs/core/Signature.java
/* * This file is part of the Benno4j project. * * Copyright (c) 2021, stwe <https://github.com/stwe/Benno4j> * * 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 de.sg.benno.ecs.core; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import static de.sg.benno.ogl.Log.LOGGER; /** * Represents a Signature. */ public class Signature { //------------------------------------------------- // Member //------------------------------------------------- /** * A set of components the entity must have. */ private final BitSet all = new BitSet(); /** * A set of components of which the entity must have at least one. */ private final BitSet one = new BitSet(); /** * A set of components the entity cannot have. */ private final BitSet exclude = new BitSet(); //------------------------------------------------- // Ctors. //------------------------------------------------- /** * Constructs a new {@link Signature} object. */ public Signature() { LOGGER.debug("Creates Signature object."); } //------------------------------------------------- // Matches //------------------------------------------------- /** * Checks whether the entity matches this signature. * * @param entity The {@link Entity} to check. * * @return boolean */ public boolean matches(Entity entity) { var ec = entity.getComponentsBitSet(); if (!containsAll(ec, all)) { return false; } if (!one.isEmpty()) { if (!one.intersects(ec)) { return false; } } if (!exclude.isEmpty()) { if (exclude.intersects(ec)) { return false; } } return true; } //------------------------------------------------- // Init //------------------------------------------------- @SafeVarargs public final void setAll(Class<? extends Component>... allTypes) { var types = new ArrayList<>(Arrays.asList(allTypes)); for (var type : types) { all.set(EcsSettings.getComponentIndex(type)); } } @SafeVarargs public final void setOne(Class<? extends Component>... oneTypes) { var types = new ArrayList<>(Arrays.asList(oneTypes)); for (var type : types) { one.set(EcsSettings.getComponentIndex(type)); } } @SafeVarargs public final void setExclude(Class<? extends Component>... excludeTypes) { var types = new ArrayList<>(Arrays.asList(excludeTypes)); for (var type : types) { exclude.set(EcsSettings.getComponentIndex(type)); } } //------------------------------------------------- // Helper //------------------------------------------------- /** * A containsAll method for {@link BitSet}. * * @param s1 A {@link BitSet}. * @param s2 A {@link BitSet}. * * @return boolean */ private static boolean containsAll(BitSet s1, BitSet s2) { BitSet intersection = (BitSet) s1.clone(); intersection.and(s2); return intersection.equals(s2); } /** * {@link BitSet} to {@link String}. * * @param bits A {@link BitSet}. * * @return String */ public static String getBitsString (BitSet bits) { var stringBuilder = new StringBuilder(); var numBits = bits.length(); for (var i = 0; i < numBits; i++) { stringBuilder.append(bits.get(i) ? "1" : "0"); } return stringBuilder.toString(); } }
Paul17041993/Railcraft
src/main/java/mods/railcraft/client/render/carts/CartModelManager.java
/*------------------------------------------------------------------------------ Copyright (c) CovertJaguar, 2011-2017 http://railcraft.info This code is the property of CovertJaguar and may only be used with explicit written permission unless otherwise specified on the license page at http://railcraft.info/wiki/info:license. -----------------------------------------------------------------------------*/ package mods.railcraft.client.render.carts; import mods.railcraft.client.render.models.programmatic.ModelSimpleCube; import mods.railcraft.client.render.models.programmatic.ModelTextured; import mods.railcraft.client.render.models.programmatic.carts.ModelGift; import mods.railcraft.client.render.models.programmatic.carts.ModelLowSidesMinecart; import mods.railcraft.client.render.models.programmatic.carts.ModelMaintance; import mods.railcraft.client.render.models.programmatic.carts.ModelMinecartRailcraft; import mods.railcraft.common.carts.*; import mods.railcraft.common.core.RailcraftConstants; import net.minecraft.client.model.ModelBase; import net.minecraft.entity.item.EntityMinecart; import java.util.HashMap; import java.util.Map; /** * @author CovertJaguar <http://www.railcraft.info> */ public final class CartModelManager { public static final ModelBase modelMinecart = new ModelMinecartRailcraft(); public static final ModelBase modelSnow = new ModelMinecartRailcraft(0.125f); public static final ModelTextured emptyModel = new ModelTextured("empty"); public static final Map<Class<?>, ModelBase> modelsCore = new HashMap<>(); public static final Map<Class<?>, ModelBase> modelsSnow = new HashMap<>(); public static final Map<Class<?>, ModelTextured> modelsContents = new HashMap<>(); static { //TODO move to cart containers? EntityEntry subclasses? That way we do not forget these code here ModelLowSidesMinecart lowSides = new ModelLowSidesMinecart(); ModelLowSidesMinecart lowSidesSnow = new ModelLowSidesMinecart(0.125f); modelsCore.put(EntityCartTank.class, lowSides); modelsSnow.put(EntityCartTank.class, lowSidesSnow); modelsCore.put(EntityCartCargo.class, lowSides); modelsSnow.put(EntityCartCargo.class, lowSidesSnow); modelsCore.put(EntityCartBed.class, lowSides); modelsSnow.put(EntityCartBed.class, lowSidesSnow); ModelTextured tank = new ModelSimpleCube(); tank.setTexture(RailcraftConstants.CART_TEXTURE_FOLDER + "cart_tank.png"); tank.doBackFaceCulling(false); modelsContents.put(EntityCartTank.class, tank); modelsContents.put(EntityCartGift.class, new ModelGift()); ModelTextured maint = new ModelMaintance(); maint.setTexture(RailcraftConstants.CART_TEXTURE_FOLDER + "cart_undercutter.png"); modelsContents.put(EntityCartUndercutter.class, maint); maint = new ModelMaintance(); maint.setTexture(RailcraftConstants.CART_TEXTURE_FOLDER + "cart_track_relayer.png"); modelsContents.put(EntityCartTrackRelayer.class, maint); maint = new ModelMaintance(); maint.setTexture(RailcraftConstants.CART_TEXTURE_FOLDER + "cart_track_layer.png"); modelsContents.put(EntityCartTrackLayer.class, maint); maint = new ModelMaintance(); maint.setTexture(RailcraftConstants.CART_TEXTURE_FOLDER + "cart_track_remover.png"); modelsContents.put(EntityCartTrackRemover.class, maint); } public static ModelBase getCoreModel(Class<?> eClass) { ModelBase render = modelsCore.get(eClass); if (render == null && eClass != EntityMinecart.class) { render = getCoreModel(eClass.getSuperclass()); modelsCore.put(eClass, render); } return render != null ? render : modelMinecart; } public static ModelBase getSnowModel(Class<?> eClass) { ModelBase render = modelsSnow.get(eClass); if (render == null && eClass != EntityMinecart.class) { render = getSnowModel(eClass.getSuperclass()); modelsSnow.put(eClass, render); } return render != null ? render : modelSnow; } public static ModelTextured getContentModel(Class<?> eClass) { ModelTextured render = modelsContents.get(eClass); if (render == null && eClass != EntityMinecart.class) { render = getContentModel(eClass.getSuperclass()); modelsContents.put(eClass, render); } return render != null ? render : emptyModel; } }
ORNL-BTRIC/OpenStudio
openstudiocore/src/model/CoilCoolingWater.cpp
<reponame>ORNL-BTRIC/OpenStudio /********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <model/CoilCoolingWater.hpp> #include <model/CoilCoolingWater_Impl.hpp> #include <model/ControllerWaterCoil.hpp> #include <model/ControllerWaterCoil_Impl.hpp> #include <model/Node.hpp> #include <model/Node_Impl.hpp> #include <model/Model.hpp> #include <model/ScheduleCompact.hpp> #include <model/ScheduleCompact_Impl.hpp> #include <model/AirLoopHVACUnitarySystem.hpp> #include <model/AirLoopHVACUnitarySystem_Impl.hpp> #include <model/ZoneHVACComponent.hpp> #include <model/ZoneHVACComponent_Impl.hpp> #include <model/ZoneHVACFourPipeFanCoil.hpp> #include <model/ZoneHVACFourPipeFanCoil_Impl.hpp> #include <utilities/idd/OS_Coil_Cooling_Water_FieldEnums.hxx> #include <utilities/core/Compare.hpp> #include <utilities/core/Assert.hpp> #include <boost/foreach.hpp> namespace openstudio { namespace model { namespace detail { CoilCoolingWater_Impl::CoilCoolingWater_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : WaterToAirComponent_Impl(idfObject, model, keepHandle) { OS_ASSERT(idfObject.iddObject().type() == CoilCoolingWater::iddObjectType()); } CoilCoolingWater_Impl::CoilCoolingWater_Impl( const openstudio::detail::WorkspaceObject_Impl& other,Model_Impl* model,bool keepHandle) : WaterToAirComponent_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == CoilCoolingWater::iddObjectType()); } CoilCoolingWater_Impl::CoilCoolingWater_Impl(const CoilCoolingWater_Impl& other, Model_Impl* model, bool keepHandle) : WaterToAirComponent_Impl(other,model,keepHandle) {} CoilCoolingWater_Impl::~CoilCoolingWater_Impl(){} IddObjectType CoilCoolingWater_Impl::iddObjectType() const { return CoilCoolingWater::iddObjectType(); } std::vector<ScheduleTypeKey> CoilCoolingWater_Impl::getScheduleTypeKeys(const Schedule& schedule) const { std::vector<ScheduleTypeKey> result; UnsignedVector fieldIndices = getSourceIndices(schedule.handle()); UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end()); if (std::find(b,e,OS_Coil_Cooling_WaterFields::AvailabilityScheduleName) != e) { result.push_back(ScheduleTypeKey("CoilCoolingWater","Availability")); } return result; } Schedule CoilCoolingWater_Impl::availabilitySchedule() const { OptionalSchedule value = getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_Coil_Cooling_WaterFields::AvailabilityScheduleName); if (!value){ // it is an error if we get here, however we don't want to crash // so we hook up to global always on schedule LOG(Error, "Required availability schedule not set, using 'Always On' schedule"); value = this->model().alwaysOnDiscreteSchedule(); OS_ASSERT(value); const_cast<CoilCoolingWater_Impl*>(this)->setAvailabilitySchedule(*value); value = getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_Coil_Cooling_WaterFields::AvailabilityScheduleName); } OS_ASSERT(value); return value.get(); } bool CoilCoolingWater_Impl::setAvailabilitySchedule(Schedule& schedule) { bool result = setSchedule(OS_Coil_Cooling_WaterFields::AvailabilityScheduleName, "CoilCoolingWater", "Availability", schedule); return result; } boost::optional<double> CoilCoolingWater_Impl::designWaterFlowRate() { return getDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignWaterFlowRate ); } void CoilCoolingWater_Impl::setDesignWaterFlowRate( double value ) { setDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignWaterFlowRate, value ); } bool CoilCoolingWater_Impl::isDesignWaterFlowRateAutosized() { bool result = false; boost::optional<std::string> value = getString(OS_Coil_Cooling_WaterFields::DesignWaterFlowRate, true); if (value) { result = openstudio::istringEqual(value.get(), "Autosize"); } return result; } void CoilCoolingWater_Impl::autosizeDesignWaterFlowRate() { setString(OS_Coil_Cooling_WaterFields::DesignWaterFlowRate, "Autosize"); } boost::optional<double> CoilCoolingWater_Impl::designAirFlowRate() { return getDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignAirFlowRate ); } void CoilCoolingWater_Impl::setDesignAirFlowRate( double value ) { setDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignAirFlowRate, value ); } bool CoilCoolingWater_Impl::isDesignAirFlowRateAutosized() { bool result = false; boost::optional<std::string> value = getString(OS_Coil_Cooling_WaterFields::DesignAirFlowRate, true); if (value) { result = openstudio::istringEqual(value.get(), "Autosize"); } return result; } void CoilCoolingWater_Impl::autosizeDesignAirFlowRate() { setString(OS_Coil_Cooling_WaterFields::DesignAirFlowRate, "Autosize"); } boost::optional<double> CoilCoolingWater_Impl::designInletWaterTemperature() { return getDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignInletWaterTemperature ); } void CoilCoolingWater_Impl::setDesignInletWaterTemperature( double value ) { setDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignInletWaterTemperature, value ); } bool CoilCoolingWater_Impl::isDesignInletWaterTemperatureAutosized() { bool result = false; boost::optional<std::string> value = getString(OS_Coil_Cooling_WaterFields::DesignInletWaterTemperature, true); if (value) { result = openstudio::istringEqual(value.get(), "Autosize"); } return result; } void CoilCoolingWater_Impl::autosizeDesignInletWaterTemperature() { setString(OS_Coil_Cooling_WaterFields::DesignInletWaterTemperature, "Autosize"); } boost::optional<double> CoilCoolingWater_Impl::designInletAirTemperature() { return getDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignInletAirTemperature ); } void CoilCoolingWater_Impl::setDesignInletAirTemperature( double value ) { setDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignInletAirTemperature, value ); } bool CoilCoolingWater_Impl::isDesignInletAirTemperatureAutosized() { bool result = false; boost::optional<std::string> value = getString(OS_Coil_Cooling_WaterFields::DesignInletAirTemperature, true); if (value) { result = openstudio::istringEqual(value.get(), "Autosize"); } return result; } void CoilCoolingWater_Impl::autosizeDesignInletAirTemperature() { setString(OS_Coil_Cooling_WaterFields::DesignInletAirTemperature, "Autosize"); } boost::optional<double> CoilCoolingWater_Impl::designOutletAirTemperature() { return getDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignOutletAirTemperature ); } void CoilCoolingWater_Impl::setDesignOutletAirTemperature( double value ) { setDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignOutletAirTemperature, value ); } bool CoilCoolingWater_Impl::isDesignOutletAirTemperatureAutosized() { bool result = false; boost::optional<std::string> value = getString(OS_Coil_Cooling_WaterFields::DesignOutletAirTemperature, true); if (value) { result = openstudio::istringEqual(value.get(), "Autosize"); } return result; } void CoilCoolingWater_Impl::autosizeDesignOutletAirTemperature() { setString(OS_Coil_Cooling_WaterFields::DesignOutletAirTemperature, "Autosize"); } boost::optional<double> CoilCoolingWater_Impl::designInletAirHumidityRatio() { return getDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignInletAirHumidityRatio ); } void CoilCoolingWater_Impl::setDesignInletAirHumidityRatio( double value ) { setDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignInletAirHumidityRatio, value ); } bool CoilCoolingWater_Impl::isDesignInletAirHumidityRatioAutosized() { bool result = false; boost::optional<std::string> value = getString(OS_Coil_Cooling_WaterFields::DesignInletAirHumidityRatio, true); if (value) { result = openstudio::istringEqual(value.get(), "Autosize"); } return result; } void CoilCoolingWater_Impl::autosizeDesignInletAirHumidityRatio() { setString(OS_Coil_Cooling_WaterFields::DesignInletAirHumidityRatio, "Autosize"); } boost::optional<double> CoilCoolingWater_Impl::designOutletAirHumidityRatio() { return getDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignOutletAirHumidityRatio ); } void CoilCoolingWater_Impl::setDesignOutletAirHumidityRatio( double value ) { setDouble( openstudio::OS_Coil_Cooling_WaterFields::DesignOutletAirHumidityRatio, value ); } bool CoilCoolingWater_Impl::isDesignOutletAirHumidityRatioAutosized() { bool result = false; boost::optional<std::string> value = getString(OS_Coil_Cooling_WaterFields::DesignOutletAirHumidityRatio, true); if (value) { result = openstudio::istringEqual(value.get(), "Autosize"); } return result; } void CoilCoolingWater_Impl::autosizeDesignOutletAirHumidityRatio() { setString(OS_Coil_Cooling_WaterFields::DesignOutletAirHumidityRatio, "Autosize"); } std::string CoilCoolingWater_Impl::typeOfAnalysis() { return getString( openstudio::OS_Coil_Cooling_WaterFields::TypeofAnalysis,true ).get(); } void CoilCoolingWater_Impl::setTypeOfAnalysis( std::string value ) { setString( openstudio::OS_Coil_Cooling_WaterFields::TypeofAnalysis, value ); } std::string CoilCoolingWater_Impl::heatExchangerConfiguration() { return getString( openstudio::OS_Coil_Cooling_WaterFields::HeatExchangerConfiguration,true ).get(); } void CoilCoolingWater_Impl::setHeatExchangerConfiguration( std::string value ) { setString( openstudio::OS_Coil_Cooling_WaterFields::HeatExchangerConfiguration, value ); } bool CoilCoolingWater_Impl::addToNode(Node & node) { bool success; success = WaterToAirComponent_Impl::addToNode( node ); if( success && (! containingHVACComponent()) && (! containingZoneHVACComponent()) ) { if( boost::optional<ModelObject> _waterInletModelObject = waterInletModelObject() ) { Model _model = model(); boost::optional<ControllerWaterCoil> oldController; oldController = controllerWaterCoil(); if( oldController ) { oldController->remove(); } ControllerWaterCoil controller(_model); boost::optional<Node> coilWaterInletNode = _waterInletModelObject->optionalCast<Node>(); OS_ASSERT(coilWaterInletNode); controller.setActuatorNode(coilWaterInletNode.get()); if( boost::optional<ModelObject> mo = airOutletModelObject() ) { if( boost::optional<Node> coilAirOutletNode = mo->optionalCast<Node>() ) { controller.setSensorNode(coilAirOutletNode.get()); } } controller.setAction("Reverse"); } } return success; } boost::optional<ControllerWaterCoil> CoilCoolingWater_Impl::controllerWaterCoil() { boost::optional<Node> coilWaterInletNode; if( boost::optional<ModelObject> mo = waterInletModelObject() ) { coilWaterInletNode = mo->optionalCast<Node>(); } if( coilWaterInletNode ) { std::vector<ControllerWaterCoil> controllers = this->model().getConcreteModelObjects<ControllerWaterCoil>(); for( std::vector<ControllerWaterCoil>::iterator it = controllers.begin(); it < controllers.end(); ++it ) { if( it->actuatorNode() == coilWaterInletNode ) { return *it; } } } return boost::none; } bool CoilCoolingWater_Impl::removeFromPlantLoop() { if( boost::optional<ControllerWaterCoil> controller = this->controllerWaterCoil() ) { controller->remove(); } return WaterToAirComponent_Impl::removeFromPlantLoop(); } std::vector<openstudio::IdfObject> CoilCoolingWater_Impl::remove() { if( isRemovable() ) { return WaterToAirComponent_Impl::remove(); } return std::vector<IdfObject>(); } ModelObject CoilCoolingWater_Impl::clone(Model model) const { CoilCoolingWater newCoil = WaterToAirComponent_Impl::clone( model ).optionalCast<CoilCoolingWater>().get(); return newCoil; } unsigned CoilCoolingWater_Impl::airInletPort() { return OS_Coil_Cooling_WaterFields::AirInletNodeName; } unsigned CoilCoolingWater_Impl::airOutletPort() { return OS_Coil_Cooling_WaterFields::AirOutletNodeName; } unsigned CoilCoolingWater_Impl::waterInletPort() { return OS_Coil_Cooling_WaterFields::WaterInletNodeName; } unsigned CoilCoolingWater_Impl::waterOutletPort() { return OS_Coil_Cooling_WaterFields::WaterOutletNodeName; } boost::optional<ModelObject> CoilCoolingWater_Impl::availabilityScheduleAsModelObject() const { OptionalModelObject result = availabilitySchedule(); return result; } bool CoilCoolingWater_Impl::setAvailabilityScheduleAsModelObject(const boost::optional<ModelObject>& modelObject) { if (modelObject) { OptionalSchedule intermediate = modelObject->optionalCast<Schedule>(); if (intermediate) { Schedule schedule(*intermediate); return setAvailabilitySchedule(schedule); } } return false; } boost::optional<HVACComponent> CoilCoolingWater_Impl::containingHVACComponent() const { // AirLoopHVACUnitarySystem std::vector<AirLoopHVACUnitarySystem> airLoopHVACUnitarySystems = this->model().getConcreteModelObjects<AirLoopHVACUnitarySystem>(); for( std::vector<AirLoopHVACUnitarySystem>::iterator it = airLoopHVACUnitarySystems.begin(); it < airLoopHVACUnitarySystems.end(); ++it ) { if( boost::optional<HVACComponent> coolingCoil = it->coolingCoil() ) { if( coolingCoil->handle() == this->handle() ) { return *it; } } } return boost::none; } boost::optional<ZoneHVACComponent> CoilCoolingWater_Impl::containingZoneHVACComponent() const { // ZoneHVACFourPipeFanCoil std::vector<ZoneHVACFourPipeFanCoil> zoneHVACFourPipeFanCoils; zoneHVACFourPipeFanCoils = this->model().getConcreteModelObjects<ZoneHVACFourPipeFanCoil>(); for( std::vector<ZoneHVACFourPipeFanCoil>::iterator it = zoneHVACFourPipeFanCoils.begin(); it < zoneHVACFourPipeFanCoils.end(); ++it ) { if( boost::optional<HVACComponent> coil = it->coolingCoil() ) { if( coil->handle() == this->handle() ) { return *it; } } } return boost::none; } } // detail CoilCoolingWater::CoilCoolingWater(const Model& model, Schedule & availableSchedule) : WaterToAirComponent(CoilCoolingWater::iddObjectType(),model) { OS_ASSERT(getImpl<detail::CoilCoolingWater_Impl>()); setAvailableSchedule( availableSchedule ); } CoilCoolingWater::CoilCoolingWater(boost::shared_ptr<detail::CoilCoolingWater_Impl> p) : WaterToAirComponent(p) {} Schedule CoilCoolingWater::availabilitySchedule() const { return getImpl<detail::CoilCoolingWater_Impl>()->availabilitySchedule(); } Schedule CoilCoolingWater::availableSchedule() const { return getImpl<detail::CoilCoolingWater_Impl>()->availabilitySchedule(); } bool CoilCoolingWater::setAvailabilitySchedule(Schedule& schedule ) { return getImpl<detail::CoilCoolingWater_Impl>()->setAvailabilitySchedule( schedule ); } bool CoilCoolingWater::setAvailableSchedule(Schedule& schedule ) { return getImpl<detail::CoilCoolingWater_Impl>()->setAvailabilitySchedule( schedule ); } boost::optional<double> CoilCoolingWater::designWaterFlowRate() { return getImpl<detail::CoilCoolingWater_Impl>()->designWaterFlowRate(); } void CoilCoolingWater::setDesignWaterFlowRate( double value ) { getImpl<detail::CoilCoolingWater_Impl>()->setDesignWaterFlowRate( value ); } bool CoilCoolingWater::isDesignWaterFlowRateAutosized() { return getImpl<detail::CoilCoolingWater_Impl>()->isDesignWaterFlowRateAutosized(); } void CoilCoolingWater::autosizeDesignWaterFlowRate() { getImpl<detail::CoilCoolingWater_Impl>()->autosizeDesignWaterFlowRate(); } boost::optional<double> CoilCoolingWater::designAirFlowRate() { return getImpl<detail::CoilCoolingWater_Impl>()->designAirFlowRate(); } void CoilCoolingWater::setDesignAirFlowRate( double value ) { getImpl<detail::CoilCoolingWater_Impl>()->setDesignAirFlowRate( value ); } bool CoilCoolingWater::isDesignAirFlowRateAutosized() { return getImpl<detail::CoilCoolingWater_Impl>()->isDesignAirFlowRateAutosized(); } void CoilCoolingWater::autosizeDesignAirFlowRate() { getImpl<detail::CoilCoolingWater_Impl>()->autosizeDesignAirFlowRate(); } boost::optional<double> CoilCoolingWater::designInletWaterTemperature() { return getImpl<detail::CoilCoolingWater_Impl>()->designInletWaterTemperature(); } void CoilCoolingWater::setDesignInletWaterTemperature( double value ) { getImpl<detail::CoilCoolingWater_Impl>()->setDesignInletWaterTemperature( value ); } bool CoilCoolingWater::isDesignInletWaterTemperatureAutosized() { return getImpl<detail::CoilCoolingWater_Impl>()->isDesignInletWaterTemperatureAutosized(); } void CoilCoolingWater::autosizeDesignInletWaterTemperature() { getImpl<detail::CoilCoolingWater_Impl>()->autosizeDesignInletWaterTemperature(); } boost::optional<double> CoilCoolingWater::designInletAirTemperature() { return getImpl<detail::CoilCoolingWater_Impl>()->designInletAirTemperature(); } void CoilCoolingWater::setDesignInletAirTemperature( double value ) { getImpl<detail::CoilCoolingWater_Impl>()->setDesignInletAirTemperature( value ); } bool CoilCoolingWater::isDesignInletAirTemperatureAutosized() { return getImpl<detail::CoilCoolingWater_Impl>()->isDesignInletAirTemperatureAutosized(); } void CoilCoolingWater::autosizeDesignInletAirTemperature() { getImpl<detail::CoilCoolingWater_Impl>()->autosizeDesignInletAirTemperature(); } boost::optional<double> CoilCoolingWater::designOutletAirTemperature() { return getImpl<detail::CoilCoolingWater_Impl>()->designOutletAirTemperature(); } void CoilCoolingWater::setDesignOutletAirTemperature( double value ) { getImpl<detail::CoilCoolingWater_Impl>()->setDesignOutletAirTemperature( value ); } bool CoilCoolingWater::isDesignOutletAirTemperatureAutosized() { return getImpl<detail::CoilCoolingWater_Impl>()->isDesignOutletAirTemperatureAutosized(); } void CoilCoolingWater::autosizeDesignOutletAirTemperature() { getImpl<detail::CoilCoolingWater_Impl>()->autosizeDesignOutletAirTemperature(); } boost::optional<double> CoilCoolingWater::designInletAirHumidityRatio() { return getImpl<detail::CoilCoolingWater_Impl>()->designInletAirHumidityRatio(); } void CoilCoolingWater::setDesignInletAirHumidityRatio( double value ) { getImpl<detail::CoilCoolingWater_Impl>()->setDesignInletAirHumidityRatio( value ); } bool CoilCoolingWater::isDesignInletAirHumidityRatioAutosized() { return getImpl<detail::CoilCoolingWater_Impl>()->isDesignInletAirHumidityRatioAutosized(); } void CoilCoolingWater::autosizeDesignInletAirHumidityRatio() { getImpl<detail::CoilCoolingWater_Impl>()->autosizeDesignInletAirHumidityRatio(); } boost::optional<double> CoilCoolingWater::designOutletAirHumidityRatio() { return getImpl<detail::CoilCoolingWater_Impl>()->designOutletAirHumidityRatio(); } void CoilCoolingWater::setDesignOutletAirHumidityRatio( double value ) { getImpl<detail::CoilCoolingWater_Impl>()->setDesignOutletAirHumidityRatio( value ); } bool CoilCoolingWater::isDesignOutletAirHumidityRatioAutosized() { return getImpl<detail::CoilCoolingWater_Impl>()->isDesignOutletAirHumidityRatioAutosized(); } void CoilCoolingWater::autosizeDesignOutletAirHumidityRatio() { getImpl<detail::CoilCoolingWater_Impl>()->autosizeDesignOutletAirHumidityRatio(); } std::string CoilCoolingWater::typeOfAnalysis() { return getImpl<detail::CoilCoolingWater_Impl>()->typeOfAnalysis(); } void CoilCoolingWater::setTypeOfAnalysis( std::string value ) { getImpl<detail::CoilCoolingWater_Impl>()->setTypeOfAnalysis( value ); } std::string CoilCoolingWater::heatExchangerConfiguration() { return getImpl<detail::CoilCoolingWater_Impl>()->heatExchangerConfiguration(); } void CoilCoolingWater::setHeatExchangerConfiguration( std::string value ) { getImpl<detail::CoilCoolingWater_Impl>()->setHeatExchangerConfiguration( value ); } IddObjectType CoilCoolingWater::iddObjectType() { IddObjectType result(IddObjectType::OS_Coil_Cooling_Water); return result; } boost::optional<ControllerWaterCoil> CoilCoolingWater::controllerWaterCoil() { return getImpl<detail::CoilCoolingWater_Impl>()->controllerWaterCoil(); } } // model } // openstudio
trngaje/mame-2003-plus-kaze
src/drivers/mrdo.c
<gh_stars>100-1000 /*************************************************************************** Mr Do! driver by <NAME> Video clock: XTAL = 19.6 MHz Horizontal video frequency: HSYNC = XTAL/4/312 = 15.7051282051 kHz Video frequency: VSYNC = HSYNC/262 = 59.94323742 Hz VBlank duration: 1/VSYNC * (70/262) = 4457 us ***************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" #include "cpu/z80/z80.h" #define MAIN_CLOCK 8200000 /* XTAL_8_2MHz */ #define VIDEO_CLOCK 19600000.0 /* XTAL_19_6_MHz */ extern unsigned char *mrdo_bgvideoram,*mrdo_fgvideoram; WRITE_HANDLER( mrdo_bgvideoram_w ); WRITE_HANDLER( mrdo_fgvideoram_w ); WRITE_HANDLER( mrdo_scrollx_w ); WRITE_HANDLER( mrdo_scrolly_w ); WRITE_HANDLER( mrdo_flipscreen_w ); PALETTE_INIT( mrdo ); VIDEO_START( mrdo ); VIDEO_UPDATE( mrdo ); /* this looks like some kind of protection. The game doesn't clear the screen */ /* if a read from this address doesn't return the value it expects. */ READ_HANDLER( mrdo_SECRE_r ) { unsigned char *RAM = memory_region(REGION_CPU1); return RAM[ activecpu_get_reg(Z80_HL) ]; } static MEMORY_READ_START( readmem ) { 0x0000, 0x7fff, MRA_ROM }, { 0x8000, 0x8fff, MRA_RAM }, /* video and color RAM */ { 0x9803, 0x9803, mrdo_SECRE_r }, { 0xa000, 0xa000, input_port_0_r }, /* IN0 */ { 0xa001, 0xa001, input_port_1_r }, /* IN1 */ { 0xa002, 0xa002, input_port_2_r }, /* DSW1 */ { 0xa003, 0xa003, input_port_3_r }, /* DSW2 */ { 0xe000, 0xefff, MRA_RAM }, MEMORY_END static MEMORY_WRITE_START( writemem ) { 0x0000, 0x7fff, MWA_ROM }, { 0x8000, 0x87ff, mrdo_bgvideoram_w, &mrdo_bgvideoram }, { 0x8800, 0x8fff, mrdo_fgvideoram_w, &mrdo_fgvideoram }, { 0x9000, 0x90ff, MWA_RAM, &spriteram, &spriteram_size }, { 0x9800, 0x9800, mrdo_flipscreen_w }, /* screen flip + playfield priority */ { 0x9801, 0x9801, SN76496_0_w }, { 0x9802, 0x9802, SN76496_1_w }, { 0xe000, 0xefff, MWA_RAM }, { 0xf000, 0xf7ff, mrdo_scrollx_w }, { 0xf800, 0xffff, mrdo_scrolly_w }, MEMORY_END INPUT_PORTS_START( mrdo ) PORT_START /* IN0 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_TILT ) PORT_START /* IN1 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_4WAY | IPF_COCKTAIL ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_4WAY | IPF_COCKTAIL ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_4WAY | IPF_COCKTAIL ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_4WAY | IPF_COCKTAIL ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_START /* DSW0 */ PORT_DIPNAME( 0x03, 0x03, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x03, "Easy" ) PORT_DIPSETTING( 0x02, "Medium" ) PORT_DIPSETTING( 0x01, "Hard" ) PORT_DIPSETTING( 0x00, "Hardest" ) PORT_BITX( 0x04, 0x04, IPT_DIPSWITCH_NAME | IPF_CHEAT, "Rack Test", KEYCODE_F1, IP_JOY_NONE ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, "Special" ) PORT_DIPSETTING( 0x08, "Easy" ) PORT_DIPSETTING( 0x00, "Hard" ) PORT_DIPNAME( 0x10, 0x10, "Extra" ) PORT_DIPSETTING( 0x10, "Easy" ) PORT_DIPSETTING( 0x00, "Hard" ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x00, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x20, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "2" ) PORT_DIPSETTING( 0xc0, "3" ) PORT_DIPSETTING( 0x80, "4" ) PORT_DIPSETTING( 0x40, "5" ) PORT_START /* DSW1 */ PORT_DIPNAME( 0x0f, 0x0f, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x06, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0a, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x07, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x0f, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x09, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0x0e, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0d, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0b, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) /* settings 0x01 thru 0x05 all give 1 Coin/1 Credit */ PORT_DIPNAME( 0xf0, 0xf0, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x60, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x80, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0xa0, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x70, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0xf0, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x90, DEF_STR( 2C_3C ) ) PORT_DIPSETTING( 0xe0, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0xd0, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0xc0, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0xb0, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) /* settings 0x10 thru 0x50 all give 1 Coin/1 Credit */ INPUT_PORTS_END static struct GfxLayout charlayout = { 8,8, /* 8*8 characters */ 512, /* 512 characters */ 2, /* 2 bits per pixel */ { 0, 512*8*8 }, /* the two bitplanes are separated */ { 7, 6, 5, 4, 3, 2, 1, 0 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 /* every char takes 8 consecutive bytes */ }; static struct GfxLayout spritelayout = { 16,16, /* 16*16 sprites */ 128, /* 128 sprites */ 2, /* 2 bits per pixel */ { 4, 0 }, /* the two bitplanes for 4 pixels are packed into one byte */ { 3, 2, 1, 0, 8+3, 8+2, 8+1, 8+0, 16+3, 16+2, 16+1, 16+0, 24+3, 24+2, 24+1, 24+0 }, { 0*16, 2*16, 4*16, 6*16, 8*16, 10*16, 12*16, 14*16, 16*16, 18*16, 20*16, 22*16, 24*16, 26*16, 28*16, 30*16 }, 64*8 /* every sprite takes 64 consecutive bytes */ }; static struct GfxDecodeInfo gfxdecodeinfo[] = { { REGION_GFX1, 0, &charlayout, 0, 64 }, /* colors 0-255 directly mapped */ { REGION_GFX2, 0, &charlayout, 0, 64 }, { REGION_GFX3, 0, &spritelayout, 4*64, 16 }, { -1 } /* end of array */ }; static struct SN76496interface sn76496_interface = { 2, /* 2 chips */ { MAIN_CLOCK/2, MAIN_CLOCK/2 }, /* 4.1 MHz */ { 50, 50 } }; static MACHINE_DRIVER_START( mrdo ) /* basic machine hardware */ MDRV_CPU_ADD(Z80,MAIN_CLOCK/2) /* 4.1 MHz */ MDRV_CPU_MEMORY(readmem,writemem) MDRV_CPU_VBLANK_INT(irq0_line_hold,1) MDRV_FRAMES_PER_SECOND((VIDEO_CLOCK/4)/312/262) MDRV_VBLANK_DURATION(4457) /* video hardware */ MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER) MDRV_SCREEN_SIZE(32*8, 32*8) MDRV_VISIBLE_AREA(1*8, 31*8-1, 4*8, 28*8-1) MDRV_GFXDECODE(gfxdecodeinfo) MDRV_PALETTE_LENGTH(256) MDRV_COLORTABLE_LENGTH(64*4+16*4) MDRV_PALETTE_INIT(mrdo) MDRV_VIDEO_START(mrdo) MDRV_VIDEO_UPDATE(mrdo) /* sound hardware */ MDRV_SOUND_ADD(SN76496, sn76496_interface) MACHINE_DRIVER_END /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( mrdo ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* 64k for code */ ROM_LOAD( "a4-01.bin", 0x0000, 0x2000, CRC(03dcfba2) SHA1(c15e3d0c4225e0ca120bcd28aca39632575f8e11) ) ROM_LOAD( "c4-02.bin", 0x2000, 0x2000, CRC(0ecdd39c) SHA1(c64b3363593911a676c647bf3dba8fe063fcb0de) ) ROM_LOAD( "e4-03.bin", 0x4000, 0x2000, CRC(358f5dc2) SHA1(9fed1f5d1d04935d1b77687c8b2f3bfce970dc08) ) ROM_LOAD( "f4-04.bin", 0x6000, 0x2000, CRC(f4190cfc) SHA1(24f5125d900f944294d4eda068b710c8f1c6d39f) ) ROM_REGION( 0x2000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "s8-09.bin", 0x0000, 0x1000, CRC(aa80c5b6) SHA1(76f9f90deb74598470e7ed565237da38dd07e4e9) ) ROM_LOAD( "u8-10.bin", 0x1000, 0x1000, CRC(d20ec85b) SHA1(9762bbe34d3fa209ea719807c723f57cb6bf4e01) ) ROM_REGION( 0x2000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "r8-08.bin", 0x0000, 0x1000, CRC(dbdc9ffa) SHA1(93f29fc106283eecbba3fd69cf3c4658aa38ab9f) ) ROM_LOAD( "n8-07.bin", 0x1000, 0x1000, CRC(4b9973db) SHA1(8766c51a345a5e63446e65614c6f665ab5fbe0d7) ) ROM_REGION( 0x2000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "h5-05.bin", 0x0000, 0x1000, CRC(e1218cc5) SHA1(d946613a1cf1c97f7533a4f8c2d0078d1b7daaa8) ) ROM_LOAD( "k5-06.bin", 0x1000, 0x1000, CRC(b1f68b04) SHA1(25709cd81c03df51f27cd730fecf86a1daa9e27e) ) ROM_REGION( 0x0080, REGION_PROMS, 0 ) ROM_LOAD( "u02--2.bin", 0x0000, 0x0020, CRC(238a65d7) SHA1(a5b20184a1989db23544296331462ec4d7be7516) ) /* palette (high bits) */ ROM_LOAD( "t02--3.bin", 0x0020, 0x0020, CRC(ae263dc0) SHA1(7072c100b9d692f5bb12b0c9e304425f534481e2) ) /* palette (low bits) */ ROM_LOAD( "f10--1.bin", 0x0040, 0x0020, CRC(16ee4ca2) SHA1(fcba4d103708b9711452009cd29c4f88d2f64cd3) ) /* sprite color lookup table */ ROM_LOAD( "j10--4.bin", 0x0060, 0x0020, CRC(ff7fe284) SHA1(3ac8e30011c1fcba0ee8f4dc932f82296c3ba143) ) /* timing (not used) */ ROM_END ROM_START( mrdot ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* 64k for code */ ROM_LOAD( "d1", 0x0000, 0x2000, CRC(3dcd9359) SHA1(bfe00450ee8822f437d87514f051ad1be6de9463) ) ROM_LOAD( "d2", 0x2000, 0x2000, CRC(710058d8) SHA1(168cc179f2266bbf9437445bef9ff7d3358a8e6b) ) ROM_LOAD( "d3", 0x4000, 0x2000, CRC(467d12d8) SHA1(7bb85e6a780de1c0c224229ee571cab39098f78d) ) ROM_LOAD( "d4", 0x6000, 0x2000, CRC(fce9afeb) SHA1(26236a42c1c620975d4480c4315d0c6f112429b6) ) ROM_REGION( 0x2000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "d9", 0x0000, 0x1000, CRC(de4cfe66) SHA1(c217dcc24305f3b4badfb778a1cf4e57c178d168) ) ROM_LOAD( "d10", 0x1000, 0x1000, CRC(a6c2f38b) SHA1(7c132771bf385c8ed28d8c8bdfc3dbf0b4aa75e8) ) ROM_REGION( 0x2000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "r8-08.bin", 0x0000, 0x1000, CRC(dbdc9ffa) SHA1(93f29fc106283eecbba3fd69cf3c4658aa38ab9f) ) ROM_LOAD( "n8-07.bin", 0x1000, 0x1000, CRC(4b9973db) SHA1(8766c51a345a5e63446e65614c6f665ab5fbe0d7) ) ROM_REGION( 0x2000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "h5-05.bin", 0x0000, 0x1000, CRC(e1218cc5) SHA1(d946613a1cf1c97f7533a4f8c2d0078d1b7daaa8) ) ROM_LOAD( "k5-06.bin", 0x1000, 0x1000, CRC(b1f68b04) SHA1(25709cd81c03df51f27cd730fecf86a1daa9e27e) ) ROM_REGION( 0x0080, REGION_PROMS, 0 ) ROM_LOAD( "u02--2.bin", 0x0000, 0x0020, CRC(238a65d7) SHA1(a5b20184a1989db23544296331462ec4d7be7516) ) /* palette (high bits) */ ROM_LOAD( "t02--3.bin", 0x0020, 0x0020, CRC(ae263dc0) SHA1(7072c100b9d692f5bb12b0c9e304425f534481e2) ) /* palette (low bits) */ ROM_LOAD( "f10--1.bin", 0x0040, 0x0020, CRC(16ee4ca2) SHA1(fcba4d103708b9711452009cd29c4f88d2f64cd3) ) /* sprite color lookup table */ ROM_LOAD( "j10--4.bin", 0x0060, 0x0020, CRC(ff7fe284) SHA1(3ac8e30011c1fcba0ee8f4dc932f82296c3ba143) ) /* timing (not used) */ ROM_END ROM_START( mrdofix ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* 64k for code */ ROM_LOAD( "d1", 0x0000, 0x2000, CRC(3dcd9359) SHA1(bfe00450ee8822f437d87514f051ad1be6de9463) ) ROM_LOAD( "d2", 0x2000, 0x2000, CRC(710058d8) SHA1(168cc179f2266bbf9437445bef9ff7d3358a8e6b) ) ROM_LOAD( "dofix.d3", 0x4000, 0x2000, CRC(3a7d039b) SHA1(ac87a3c9fa6433d1700e858914a995dce35113fa) ) ROM_LOAD( "dofix.d4", 0x6000, 0x2000, CRC(32db845f) SHA1(5c58532ae2cfab9bd81383824d970b20015c960e) ) ROM_REGION( 0x2000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "d9", 0x0000, 0x1000, CRC(de4cfe66) SHA1(c217dcc24305f3b4badfb778a1cf4e57c178d168) ) ROM_LOAD( "d10", 0x1000, 0x1000, CRC(a6c2f38b) SHA1(7c132771bf385c8ed28d8c8bdfc3dbf0b4aa75e8) ) ROM_REGION( 0x2000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "r8-08.bin", 0x0000, 0x1000, CRC(dbdc9ffa) SHA1(93f29fc106283eecbba3fd69cf3c4658aa38ab9f) ) ROM_LOAD( "n8-07.bin", 0x1000, 0x1000, CRC(4b9973db) SHA1(8766c51a345a5e63446e65614c6f665ab5fbe0d7) ) ROM_REGION( 0x2000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "h5-05.bin", 0x0000, 0x1000, CRC(e1218cc5) SHA1(d946613a1cf1c97f7533a4f8c2d0078d1b7daaa8) ) ROM_LOAD( "k5-06.bin", 0x1000, 0x1000, CRC(b1f68b04) SHA1(25709cd81c03df51f27cd730fecf86a1daa9e27e) ) ROM_REGION( 0x0080, REGION_PROMS, 0 ) ROM_LOAD( "u02--2.bin", 0x0000, 0x0020, CRC(238a65d7) SHA1(a5b20184a1989db23544296331462ec4d7be7516) ) /* palette (high bits) */ ROM_LOAD( "t02--3.bin", 0x0020, 0x0020, CRC(ae263dc0) SHA1(7072c100b9d692f5bb12b0c9e304425f534481e2) ) /* palette (low bits) */ ROM_LOAD( "f10--1.bin", 0x0040, 0x0020, CRC(16ee4ca2) SHA1(fcba4d103708b9711452009cd29c4f88d2f64cd3) ) /* sprite color lookup table */ ROM_LOAD( "j10--4.bin", 0x0060, 0x0020, CRC(ff7fe284) SHA1(3ac8e30011c1fcba0ee8f4dc932f82296c3ba143) ) /* timing (not used) */ ROM_END ROM_START( mrlo ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* 64k for code */ ROM_LOAD( "mrlo01.bin", 0x0000, 0x2000, CRC(6f455e7d) SHA1(82fbe05229f19fb849c90b41e3365be74f4f448f) ) ROM_LOAD( "d2", 0x2000, 0x2000, CRC(710058d8) SHA1(168cc179f2266bbf9437445bef9ff7d3358a8e6b) ) ROM_LOAD( "dofix.d3", 0x4000, 0x2000, CRC(3a7d039b) SHA1(ac87a3c9fa6433d1700e858914a995dce35113fa) ) ROM_LOAD( "mrlo04.bin", 0x6000, 0x2000, CRC(49c10274) SHA1(e94b638f9888ebdff114f80e2c5906bbc81d9c6b) ) ROM_REGION( 0x2000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "mrlo09.bin", 0x0000, 0x1000, CRC(fdb60d0d) SHA1(fe3502058a68247e5a55b930136f8d0cb80f894f) ) ROM_LOAD( "mrlo10.bin", 0x1000, 0x1000, CRC(0492c10e) SHA1(782e541539537ab3f3a590770ca48bdc0fabdc10) ) ROM_REGION( 0x2000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "r8-08.bin", 0x0000, 0x1000, CRC(dbdc9ffa) SHA1(93f29fc106283eecbba3fd69cf3c4658aa38ab9f) ) ROM_LOAD( "n8-07.bin", 0x1000, 0x1000, CRC(4b9973db) SHA1(8766c51a345a5e63446e65614c6f665ab5fbe0d7) ) ROM_REGION( 0x2000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "h5-05.bin", 0x0000, 0x1000, CRC(e1218cc5) SHA1(d946613a1cf1c97f7533a4f8c2d0078d1b7daaa8) ) ROM_LOAD( "k5-06.bin", 0x1000, 0x1000, CRC(b1f68b04) SHA1(25709cd81c03df51f27cd730fecf86a1daa9e27e) ) ROM_REGION( 0x0080, REGION_PROMS, 0 ) ROM_LOAD( "u02--2.bin", 0x0000, 0x0020, CRC(238a65d7) SHA1(a5b20184a1989db23544296331462ec4d7be7516) ) /* palette (high bits) */ ROM_LOAD( "t02--3.bin", 0x0020, 0x0020, CRC(ae263dc0) SHA1(7072c100b9d692f5bb12b0c9e304425f534481e2) ) /* palette (low bits) */ ROM_LOAD( "f10--1.bin", 0x0040, 0x0020, CRC(16ee4ca2) SHA1(fcba4d103708b9711452009cd29c4f88d2f64cd3) ) /* sprite color lookup table */ ROM_LOAD( "j10--4.bin", 0x0060, 0x0020, CRC(ff7fe284) SHA1(3ac8e30011c1fcba0ee8f4dc932f82296c3ba143) ) /* timing (not used) */ ROM_END ROM_START( mrdu ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* 64k for code */ ROM_LOAD( "d1", 0x0000, 0x2000, CRC(3dcd9359) SHA1(bfe00450ee8822f437d87514f051ad1be6de9463) ) ROM_LOAD( "d2", 0x2000, 0x2000, CRC(710058d8) SHA1(168cc179f2266bbf9437445bef9ff7d3358a8e6b) ) ROM_LOAD( "d3", 0x4000, 0x2000, CRC(467d12d8) SHA1(7bb85e6a780de1c0c224229ee571cab39098f78d) ) ROM_LOAD( "du4.bin", 0x6000, 0x2000, CRC(893bc218) SHA1(2b546989c4eef9f94594c50a48458c91e3f4983f) ) ROM_REGION( 0x2000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "du9.bin", 0x0000, 0x1000, CRC(4090dcdc) SHA1(7f481f2e966d6a98fd7d82404afefc1483658ffa) ) ROM_LOAD( "du10.bin", 0x1000, 0x1000, CRC(1e63ab69) SHA1(f0a4a12f818bc21c2bf0fe755c2e378b968b977b) ) ROM_REGION( 0x2000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "r8-08.bin", 0x0000, 0x1000, CRC(dbdc9ffa) SHA1(93f29fc106283eecbba3fd69cf3c4658aa38ab9f) ) ROM_LOAD( "n8-07.bin", 0x1000, 0x1000, CRC(4b9973db) SHA1(8766c51a345a5e63446e65614c6f665ab5fbe0d7) ) ROM_REGION( 0x2000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "h5-05.bin", 0x0000, 0x1000, CRC(e1218cc5) SHA1(d946613a1cf1c97f7533a4f8c2d0078d1b7daaa8) ) ROM_LOAD( "k5-06.bin", 0x1000, 0x1000, CRC(b1f68b04) SHA1(25709cd81c03df51f27cd730fecf86a1daa9e27e) ) ROM_REGION( 0x0080, REGION_PROMS, 0 ) ROM_LOAD( "u02--2.bin", 0x0000, 0x0020, CRC(238a65d7) SHA1(a5b20184a1989db23544296331462ec4d7be7516) ) /* palette (high bits) */ ROM_LOAD( "t02--3.bin", 0x0020, 0x0020, CRC(ae263dc0) SHA1(7072c100b9d692f5bb12b0c9e304425f534481e2) ) /* palette (low bits) */ ROM_LOAD( "f10--1.bin", 0x0040, 0x0020, CRC(16ee4ca2) SHA1(fcba4d103708b9711452009cd29c4f88d2f64cd3) ) /* sprite color lookup table */ ROM_LOAD( "j10--4.bin", 0x0060, 0x0020, CRC(ff7fe284) SHA1(3ac8e30011c1fcba0ee8f4dc932f82296c3ba143) ) /* timing (not used) */ ROM_END ROM_START( mrdoy ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* 64k for code */ ROM_LOAD( "dosnow.1", 0x0000, 0x2000, CRC(d3454e2c) SHA1(f8ecb9eec414badbcb65b7188d4a4d06739534cc) ) ROM_LOAD( "dosnow.2", 0x2000, 0x2000, CRC(5120a6b2) SHA1(1db6dc3a91ac024e763179f425ad46d9d0aff8f9) ) ROM_LOAD( "dosnow.3", 0x4000, 0x2000, CRC(96416dbe) SHA1(55f5262448b65899309f3e9e16c62b0c1e0b86c3) ) ROM_LOAD( "dosnow.4", 0x6000, 0x2000, CRC(c05051b6) SHA1(6f528370dc097bf1550f4fa4b5f740214bc18f0b) ) ROM_REGION( 0x2000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "dosnow.9", 0x0000, 0x1000, CRC(85d16217) SHA1(35cb4e4a9e55f42f7818aeaa3f72892d2ddc99aa) ) ROM_LOAD( "dosnow.10", 0x1000, 0x1000, CRC(61a7f54b) SHA1(19b0074f098955d61e5dfab060873ac96fdb30b4) ) ROM_REGION( 0x2000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "dosnow.8", 0x0000, 0x1000, CRC(2bd1239a) SHA1(43a36afbf7374578e9735956f54412823486b3ff) ) ROM_LOAD( "dosnow.7", 0x1000, 0x1000, CRC(ac8ffddf) SHA1(9911524de6b4e9056944b92a53ac93de110d52bd) ) ROM_REGION( 0x2000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "dosnow.5", 0x0000, 0x1000, CRC(7662d828) SHA1(559150326e3edc7ee062bfd962fe8d39f9423b45) ) ROM_LOAD( "dosnow.6", 0x1000, 0x1000, CRC(413f88d1) SHA1(830df0def7289536e2d08e0517cdb6edbc947400) ) ROM_REGION( 0x0080, REGION_PROMS, 0 ) ROM_LOAD( "u02--2.bin", 0x0000, 0x0020, CRC(238a65d7) SHA1(a5b20184a1989db23544296331462ec4d7be7516) ) /* palette (high bits) */ ROM_LOAD( "t02--3.bin", 0x0020, 0x0020, CRC(ae263dc0) SHA1(7072c100b9d692f5bb12b0c9e304425f534481e2) ) /* palette (low bits) */ ROM_LOAD( "f10--1.bin", 0x0040, 0x0020, CRC(16ee4ca2) SHA1(fcba4d103708b9711452009cd29c4f88d2f64cd3) ) /* sprite color lookup table */ ROM_LOAD( "j10--4.bin", 0x0060, 0x0020, CRC(ff7fe284) SHA1(3ac8e30011c1fcba0ee8f4dc932f82296c3ba143) ) /* timing (not used) */ ROM_END ROM_START( yankeedo ) ROM_REGION( 0x10000, REGION_CPU1, 0 ) /* 64k for code */ ROM_LOAD( "a4-01.bin", 0x0000, 0x2000, CRC(03dcfba2) SHA1(c15e3d0c4225e0ca120bcd28aca39632575f8e11) ) ROM_LOAD( "yd_d2.c4", 0x2000, 0x2000, CRC(7c9d7ce0) SHA1(37889575c7c83cb647008b038e4efdc87355bd3e) ) ROM_LOAD( "e4-03.bin", 0x4000, 0x2000, CRC(358f5dc2) SHA1(9fed1f5d1d04935d1b77687c8b2f3bfce970dc08) ) ROM_LOAD( "f4-04.bin", 0x6000, 0x2000, CRC(f4190cfc) SHA1(24f5125d900f944294d4eda068b710c8f1c6d39f) ) ROM_REGION( 0x2000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "s8-09.bin", 0x0000, 0x1000, CRC(aa80c5b6) SHA1(76f9f90deb74598470e7ed565237da38dd07e4e9) ) ROM_LOAD( "u8-10.bin", 0x1000, 0x1000, CRC(d20ec85b) SHA1(9762bbe34d3fa209ea719807c723f57cb6bf4e01) ) ROM_REGION( 0x2000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "r8-08.bin", 0x0000, 0x1000, CRC(dbdc9ffa) SHA1(93f29fc106283eecbba3fd69cf3c4658aa38ab9f) ) ROM_LOAD( "n8-07.bin", 0x1000, 0x1000, CRC(4b9973db) SHA1(8766c51a345a5e63446e65614c6f665ab5fbe0d7) ) ROM_REGION( 0x2000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "yd_d5.h5", 0x0000, 0x1000, CRC(f530b79b) SHA1(bffc4ddf8aa26933c8a15ed40bfa0b4cee85b408) ) ROM_LOAD( "yd_d6.k5", 0x1000, 0x1000, CRC(790579aa) SHA1(89d8a77d2046cf8cfc393e0f08d361d1886bfec1) ) ROM_REGION( 0x0080, REGION_PROMS, 0 ) ROM_LOAD( "u02--2.bin", 0x0000, 0x0020, CRC(238a65d7) SHA1(a5b20184a1989db23544296331462ec4d7be7516) ) /* palette (high bits) */ ROM_LOAD( "t02--3.bin", 0x0020, 0x0020, CRC(ae263dc0) SHA1(7072c100b9d692f5bb12b0c9e304425f534481e2) ) /* palette (low bits) */ ROM_LOAD( "f10--1.bin", 0x0040, 0x0020, CRC(16ee4ca2) SHA1(fcba4d103708b9711452009cd29c4f88d2f64cd3) ) /* sprite color lookup table */ ROM_LOAD( "j10--4.bin", 0x0060, 0x0020, CRC(ff7fe284) SHA1(3ac8e30011c1fcba0ee8f4dc932f82296c3ba143) ) /* timing (not used) */ ROM_END GAME( 1982, mrdo, 0, mrdo, mrdo, 0, ROT270, "Universal", "Mr. Do!" ) GAME( 1982, mrdoy, mrdo, mrdo, mrdo, 0, ROT270, "Universal", "Mr. Do! (prototype)" ) /* aka Yukidaruma */ GAME( 1982, mrdot, mrdo, mrdo, mrdo, 0, ROT270, "Universal (Taito license)", "Mr. Do! (Taito)" ) GAME( 1982, mrdofix, mrdo, mrdo, mrdo, 0, ROT270, "Universal (Taito license)", "Mr. Do! (bugfixed)" ) GAME( 1982, mrlo, mrdo, mrdo, mrdo, 0, ROT270, "bootleg", "Mr. Lo!" ) GAME( 1982, mrdu, mrdo, mrdo, mrdo, 0, ROT270, "bootleg", "<NAME>!" ) GAME( 1982, yankeedo, mrdo, mrdo, mrdo, 0, ROT270, "hack", "Yankee DO!" )
DirectStandards/timplus-server-core
src/main/java/org/jivesoftware/openfire/certificate/CertificateNotFoundException.java
package org.jivesoftware.openfire.certificate; public class CertificateNotFoundException extends CertificateException { private static final long serialVersionUID = 2921200431097540452L; public CertificateNotFoundException() { super(); } public CertificateNotFoundException(String msg) { super(msg); } public CertificateNotFoundException(Throwable nestedThrowable) { this.nestedThrowable = nestedThrowable; } public CertificateNotFoundException(String msg, Throwable nestedThrowable) { super(msg); this.nestedThrowable = nestedThrowable; } }
GalacticGlum/FrostyEngine
Engine/Source/Common/Private/Utilities/String.cpp
#include <Utilities/String.h> const std::hash<std::string> String::m_Hasher;
randolphwong/mcsema
boost/libs/typeof/test/odr_no_uns1.hpp
// Copyright (C) 2006 <NAME> // Copyright (C) 2006 <NAME> // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_TYPEOF_ODR_NO_UNS1_HPP_INCLUDED #define BOOST_TYPEOF_ODR_NO_UNS1_HPP_INCLUDED #define BOOST_TYPEOF_SUPPRESS_UNNAMED_NAMESPACE #include <boost/typeof/typeof.hpp> #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() struct odr_test_1 {}; BOOST_TYPEOF_REGISTER_TYPE(odr_test_1) #endif//BOOST_TYPEOF_ODR_NO_UNS1_HPP_INCLUDED
AlhonGelios/AO
org/openxmlformats/schemas/spreadsheetml/x2006/main/impl/WorksheetDocumentImpl.java
package org.openxmlformats.schemas.spreadsheetml.x2006.main.impl; import javax.xml.namespace.QName; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.impl.values.XmlComplexContentImpl; import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet; import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorksheetDocument; public class WorksheetDocumentImpl extends XmlComplexContentImpl implements WorksheetDocument { private static final QName WORKSHEET$0 = new QName("http://schemas.openxmlformats.org/spreadsheetml/2006/main", "worksheet"); public WorksheetDocumentImpl(SchemaType var1) { super(var1); } public CTWorksheet getWorksheet() { synchronized(this.monitor()) { this.check_orphaned(); CTWorksheet var2 = null; var2 = (CTWorksheet)this.get_store().find_element_user(WORKSHEET$0, 0); return var2 == null?null:var2; } } public void setWorksheet(CTWorksheet var1) { synchronized(this.monitor()) { this.check_orphaned(); CTWorksheet var3 = null; var3 = (CTWorksheet)this.get_store().find_element_user(WORKSHEET$0, 0); if(var3 == null) { var3 = (CTWorksheet)this.get_store().add_element_user(WORKSHEET$0); } var3.set(var1); } } public CTWorksheet addNewWorksheet() { synchronized(this.monitor()) { this.check_orphaned(); CTWorksheet var2 = null; var2 = (CTWorksheet)this.get_store().add_element_user(WORKSHEET$0); return var2; } } }
zabrewer/batfish
projects/batfish/src/main/java/org/batfish/representation/juniper/NatRuleMatchDstAddr.java
<filename>projects/batfish/src/main/java/org/batfish/representation/juniper/NatRuleMatchDstAddr.java<gh_stars>100-1000 package org.batfish.representation.juniper; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import org.batfish.datamodel.Prefix; /** A {@link NatRule} that matches on destination address */ @ParametersAreNonnullByDefault public final class NatRuleMatchDstAddr implements NatRuleMatch { private final Prefix _prefix; public NatRuleMatchDstAddr(Prefix prefix) { _prefix = prefix; } @Override public <T> T accept(NatRuleMatchVisitor<T> visitor) { return visitor.visitNatRuleMatchDstAddr(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof NatRuleMatchDstAddr)) { return false; } NatRuleMatchDstAddr that = (NatRuleMatchDstAddr) o; return Objects.equals(_prefix, that._prefix); } @Nonnull public Prefix getPrefix() { return _prefix; } @Override public int hashCode() { return Objects.hashCode(_prefix); } }
BoomApps-LLC/SteemApp
steemj-core/src/main/java/eu/bittrade/libs/steemj/apis/market/history/model/MarketTicker.java
<gh_stars>1-10 package eu.bittrade.libs.steemj.apis.market.history.model; import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonProperty; import eu.bittrade.libs.steemj.base.models.Asset; /** * This class represents a Steem "market_ticker" object of the * "market_history_plugin". * * @author <a href="http://steemit.com/@dez1337">dez1337</a> */ public class MarketTicker { private double latest; @JsonProperty("lowest_ask") private double lowestAsk; @JsonProperty("highest_bid") private double highestBid; @JsonProperty("percent_change") private double percentChange; @JsonProperty("steem_volume") private Asset steemVolume; @JsonProperty("sbd_volume") private Asset sbdVolume; /** * This object is only used to wrap the JSON response in a POJO, so * therefore this class should not be instantiated. */ protected MarketTicker() { } /** * @return the latest */ public double getLatest() { return latest; } /** * @return the lowestAsk */ public double getLowestAsk() { return lowestAsk; } /** * @return the highestBid */ public double getHighestBid() { return highestBid; } /** * @return the percentChange */ public double getPercentChange() { return percentChange; } /** * @return the steemVolume */ public Asset getSteemVolume() { return steemVolume; } /** * @return the sbdVolume */ public Asset getSbdVolume() { return sbdVolume; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
navikt/basta-frontend
frontend/js/containers/order/Results.js
<filename>frontend/js/containers/order/Results.js import React from 'react' import PropTypes from 'prop-types' function buildResultBody(data) { return ( <div> {data.map(result => { return ( <div className="resultLine" key={'resultline_' + result.id}> <div className="result">{createResultLine(result)}</div> </div> ) })} </div> ) } function vaultUrl(vaultPath) { const baseUrl = 'https://vault.adeo.no/ui/vault/secrets/' const replaced = vaultPath.replace(/^([\w-]+)\/data\/(.*)$/, '$1/show/$2') return baseUrl + replaced } function fasitUrl(resultName) { return `https://fasit.adeo.no/search?q=${resultName}` } function createResultLine(result) { if (result.details.vaultpath && result.details.vaultpath.length > 0) { return ( <React.Fragment> <div className="result-info"> <div>Name: </div> <div>{result.resultName}</div> </div> <div className="result-info"> <div>Vaultpath:</div> <div> <a href={vaultUrl(result.details.vaultpath)} target="new"> {`/${result.details.vaultpath}`.replace('//', '/')} </a> </div> </div> <div className="result-info"> <div></div> <div> To get access to this user in vault, please read the{' '} <a target="new" href="https://github.com/navikt/vault-iac/blob/master/doc/service-users.md" > vault-iac documentation </a> </div> </div> </React.Fragment> ) } return ( <React.Fragment> <div className="result-info"> <div>Name: </div> <div> <a href={fasitUrl(result.resultName)}>{result.resultName}</a> </div> </div> </React.Fragment> ) } const Results = props => { const { data, type } = props return ( <div className="results"> <div className="panel panel-default"> <div className="panel-heading"> <i className="fa fa-server" /> Results </div> <div className="panel-body">{buildResultBody(data, type)}</div> </div> </div> ) } Results.propTypes = { label: PropTypes.string, description: PropTypes.string, image: PropTypes.string, tags: PropTypes.array, url: PropTypes.string, access: PropTypes.array, enabled: PropTypes.bool } export default Results
Hansiyuan131/redis-example
springboot-redis-cache/src/main/java/com/cc/springbootrediscache/service/UserService.java
package com.cc.springbootrediscache.service; import com.cc.springbootrediscache.entity.User; import com.cc.springbootrediscache.mapper.UserMapper; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * Created by CarlosXiao on 2018/7/1. */ @Service public class UserService { @Resource private UserMapper userMapper; /** * 添加和更新都调用这个方法 * @param user * @return user_1 */ @CachePut(value = "usercache", key = "'user_' + #user.id.toString()", unless = "#result eq null") public User save(User user) { if (null != user.getId()) { userMapper.updateUser(user); } else { userMapper.addUser(user); } return user; } @Cacheable(value = "usercache", key = "'user_' + #id", unless = "#result eq null") public User findUser(Integer id) { return userMapper.getById(id); } @CacheEvict(value = "usercache", key = "'user_' + #id", condition = "#result eq true") public boolean delUser(Integer id) { return userMapper.deleteUserById(id) > 0; } }
ElderDelp/fiction
test/algorithms/physical_design/one_pass_synthesis.cpp
<filename>test/algorithms/physical_design/one_pass_synthesis.cpp // // Created by marcel on 24.09.21. // #if (MUGEN) #include "catch.hpp" #include "utils/blueprints/network_blueprints.hpp" #include "utils/equivalence_checking_utils.hpp" #include <fiction/algorithms/physical_design/apply_gate_library.hpp> #include <fiction/algorithms/physical_design/one_pass_synthesis.hpp> #include <fiction/io/print_layout.hpp> #include <fiction/technology/qca_one_library.hpp> #include <mockturtle/networks/aig.hpp> #include <mockturtle/networks/mig.hpp> #include <chrono> #include <iostream> #include <memory> #include <type_traits> #include <vector> using namespace fiction; template <typename Lyt> one_pass_synthesis_params<Lyt> configuration() noexcept { one_pass_synthesis_params<Lyt> ps{}; ps.enable_and = true; ps.enable_not = true; ps.enable_or = true; ps.enable_wires = true; return ps; } template <typename Lyt> one_pass_synthesis_params<Lyt>&& twoddwave(one_pass_synthesis_params<Lyt>&& ps) noexcept { ps.scheme = std::make_shared<clocking_scheme<coordinate<Lyt>>>(twoddwave_clocking<Lyt>()); return std::move(ps); } template <typename Lyt> one_pass_synthesis_params<Lyt>&& use(one_pass_synthesis_params<Lyt>&& ps) noexcept { ps.scheme = std::make_shared<clocking_scheme<coordinate<Lyt>>>(use_clocking<Lyt>()); return std::move(ps); } template <typename Lyt> one_pass_synthesis_params<Lyt>&& res(one_pass_synthesis_params<Lyt>&& ps) noexcept { ps.scheme = std::make_shared<clocking_scheme<coordinate<Lyt>>>(res_clocking<Lyt>()); ps.enable_maj = true; return std::move(ps); } template <typename Lyt> one_pass_synthesis_params<Lyt>&& crossings(one_pass_synthesis_params<Lyt>&& ps) noexcept { ps.crossings = true; return std::move(ps); } template <typename Lyt> one_pass_synthesis_params<Lyt>&& maj(one_pass_synthesis_params<Lyt>&& ps) noexcept { ps.enable_maj = true; return std::move(ps); } template <typename Lyt> one_pass_synthesis_params<Lyt>&& async(const std::size_t t, one_pass_synthesis_params<Lyt>&& ps) noexcept { ps.num_threads = t; return std::move(ps); } void check_stats(const one_pass_synthesis_stats& st) noexcept { CHECK(std::chrono::duration_cast<std::chrono::milliseconds>(st.time_total).count() > 0); CHECK(st.x_size > 0); CHECK(st.y_size > 0); CHECK(st.num_gates > 0); CHECK(st.num_wires > 0); } template <typename Lyt, typename Ntk> Lyt generate_layout(const Ntk& ntk, const one_pass_synthesis_params<Lyt>& ps) { one_pass_synthesis_stats stats{}; const auto layout = one_pass_synthesis<Lyt>(ntk, ps, &stats); REQUIRE(layout.has_value()); check_stats(stats); print_gate_level_layout(std::cout, *layout); return *layout; } template <typename Lyt> void apply_gate_library(const Lyt& lyt) { CHECK_NOTHROW(apply_gate_library<qca_cell_clk_lyt, qca_one_library>(lyt)); } template <typename Ntk, typename Lyt> void check(const Ntk& ntk, const one_pass_synthesis_params<Lyt>& ps) { const auto layout = generate_layout<Lyt>(ntk, ps); check_eq(ntk, layout); apply_gate_library(layout); } TEST_CASE("One-pass synthesis", "[one-pass]") { SECTION("2DDWave clocking") { check(blueprints::and_or_network<mockturtle::mig_network>(), twoddwave(crossings(configuration<cart_gate_clk_lyt>()))); } SECTION("USE clocking") { check(blueprints::and_or_network<mockturtle::mig_network>(), use(crossings(configuration<cart_gate_clk_lyt>()))); } SECTION("RES clocking") { check(blueprints::and_or_network<mockturtle::mig_network>(), res(crossings(configuration<cart_gate_clk_lyt>()))); } SECTION("Planar") { check(blueprints::unbalanced_and_inv_network<mockturtle::aig_network>(), twoddwave(configuration<cart_gate_clk_lyt>())); } SECTION("MAJ network") { check(blueprints::maj1_network<mockturtle::mig_network>(), res(maj(configuration<cart_gate_clk_lyt>()))); } SECTION("Constant input MAJ network") { check(blueprints::constant_gate_input_maj_network<mockturtle::mig_network>(), twoddwave(crossings(configuration<cart_gate_clk_lyt>()))); } SECTION("Multi-output network") { check(blueprints::multi_output_and_network<mockturtle::aig_network>(), twoddwave(crossings(configuration<cart_gate_clk_lyt>()))); } #if !defined(__APPLE__) SECTION("Async") { check(blueprints::unbalanced_and_inv_network<mockturtle::aig_network>(), res(crossings(async(2, configuration<cart_gate_clk_lyt>())))); } #endif } TEST_CASE("Timeout", "[one-pass]") { auto timeout_config = use(configuration<cart_gate_clk_lyt>()); timeout_config.timeout = 1u; // allow only one second to find a solution; this will fail (and is tested for) const auto half_adder = blueprints::full_adder_network<mockturtle::aig_network>(); const auto layout = one_pass_synthesis<cart_gate_clk_lyt>(half_adder, timeout_config); // since a full adder cannot be synthesized in just one second, layout should not have a value CHECK(!layout.has_value()); } TEST_CASE("Name conservation", "[one-pass]") { auto maj = blueprints::maj1_network<mockturtle::names_view<mockturtle::mig_network>>(); maj.set_network_name("maj"); const auto layout = one_pass_synthesis<cart_gate_clk_lyt>(maj, res(configuration<cart_gate_clk_lyt>())); REQUIRE(layout.has_value()); // network name CHECK(layout->get_layout_name() == "maj"); // PI names CHECK(layout->get_name(layout->pi_at(0)) == "a"); // first PI CHECK(layout->get_name(layout->pi_at(1)) == "b"); // second PI CHECK(layout->get_name(layout->pi_at(2)) == "c"); // third PI // PO names CHECK(layout->get_output_name(0) == "f"); } #endif // MUGEN
benetech/Winnow2.0
web/src/common/components/Spacer.js
import React from "react"; import clsx from "clsx"; import PropTypes from "prop-types"; import { makeStyles } from "@material-ui/styles"; const useStyles = makeStyles({ spacer: { flexGrow: ({ grow }) => grow, }, }); function Spacer(props) { const { grow = 1, className, ...other } = props; const classes = useStyles({ grow }); return <div className={clsx(classes.spacer, className)} {...other} />; } Spacer.propTypes = { grow: PropTypes.number, className: PropTypes.string, }; export default Spacer;
Maroju100/check-ins
server/src/main/java/com/objectcomputing/checkins/services/questions/QuestionController.java
package com.objectcomputing.checkins.services.questions; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.HttpStatus; import io.micronaut.http.MediaType; import io.micronaut.http.annotation.Error; import io.micronaut.http.annotation.*; import io.micronaut.http.hateoas.JsonError; import io.micronaut.http.hateoas.Link; import io.micronaut.scheduling.TaskExecutors; import io.micronaut.security.annotation.Secured; import io.micronaut.security.rules.SecurityRule; import io.netty.channel.EventLoopGroup; import io.reactivex.Single; import io.reactivex.exceptions.CompositeException; import io.reactivex.schedulers.Schedulers; import io.swagger.v3.oas.annotations.tags.Tag; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Named; import javax.validation.Valid; import java.net.URI; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; @Controller("/services/questions") @Secured(SecurityRule.IS_AUTHENTICATED) @Produces(MediaType.APPLICATION_JSON) @Tag(name="questions") public class QuestionController { @Inject private final QuestionServices questionService; private final EventLoopGroup eventLoopGroup; private final ExecutorService ioExecutorService; public QuestionController(QuestionServices questionService, EventLoopGroup eventLoopGroup, @Named(TaskExecutors.IO) ExecutorService ioExecutorService) { this.questionService = questionService; this.eventLoopGroup = eventLoopGroup; this.ioExecutorService = ioExecutorService; } @Error(exception = QuestionNotFoundException.class) public HttpResponse<?> handleNotFound(HttpRequest<?> request, QuestionNotFoundException e) { JsonError error = new JsonError(e.getMessage()).link(Link.SELF, Link.of(request.getUri())); return HttpResponse.notFound().body(error); } @Error(exception = QuestionDuplicateException.class) public HttpResponse<?> handleDupe(HttpRequest<?> request, QuestionDuplicateException e) { JsonError error = new JsonError(e.getMessage()).link(Link.SELF, Link.of(request.getUri())); return HttpResponse.status(HttpStatus.CONFLICT).body(error); } @Error(exception = QuestionBadArgException.class) public HttpResponse<?> handleBadArgs(HttpRequest<?> request, QuestionBadArgException e) { JsonError error = new JsonError(e.getMessage()).link(Link.SELF, Link.of(request.getUri())); return HttpResponse.badRequest().body(error); } @Error(exception = CompositeException.class) public HttpResponse<?> handleRxException(HttpRequest<?> request, CompositeException e) { for (Throwable t : e.getExceptions()) { if (t instanceof QuestionBadArgException) { return handleBadArgs(request, (QuestionBadArgException) t); } else if (t instanceof QuestionNotFoundException) { return handleNotFound(request, (QuestionNotFoundException) t); } else if (t instanceof QuestionDuplicateException) { return handleDupe(request, (QuestionDuplicateException) t); } } return HttpResponse.<JsonError>serverError(); } /** * Create and save a new question. * * @param question, {@link QuestionCreateDTO} * @return {@link HttpResponse<QuestionResponseDTO>} */ @Post(value = "/") public Single<HttpResponse<QuestionResponseDTO>> createAQuestion(@Body @Valid QuestionCreateDTO question, HttpRequest<QuestionCreateDTO> request) { return Single.fromCallable(() -> questionService.saveQuestion(toModel(question))) .observeOn(Schedulers.from(eventLoopGroup)) .map(newQuestion -> (HttpResponse<QuestionResponseDTO>) HttpResponse .created(fromModel(newQuestion)) .headers(headers -> headers.location( URI.create(String.format("%s/%s", request.getPath(), newQuestion.getId()))))) .subscribeOn(Schedulers.from(ioExecutorService)); } /** * Find and read a question given its id. * * @param id {@link UUID} of the question entry * @return {@link HttpResponse< QuestionResponseDTO >} */ @Get("/{id}") public Single<HttpResponse<QuestionResponseDTO>> getById(UUID id) { return Single.fromCallable(() -> { Question found = questionService.findById(id); if (found == null) { throw new QuestionNotFoundException("No question for UUID"); } return found; }) .observeOn(Schedulers.from(eventLoopGroup)) .map(question -> (HttpResponse<QuestionResponseDTO>)HttpResponse.ok(fromModel(question))) .subscribeOn(Schedulers.from(ioExecutorService)); } /** * Find questions with a particular string or read all questions. * * @param text, the text of the question * * @return {@link List HttpResponse< QuestionResponseDTO >} */ @Get("/{?text}") public Single<HttpResponse<Set<QuestionResponseDTO>>> findByText(@Nullable Optional<String> text) { return Single.fromCallable(() -> { if(text.isPresent()) { return questionService.findByText(text.get()); } else { return questionService.readAllQuestions(); } }) .observeOn(Schedulers.from(eventLoopGroup)) .map(questions -> { Set<QuestionResponseDTO> responseBody = questions.stream() .map(question -> fromModel(question)) .collect(Collectors.toSet()); return (HttpResponse<Set<QuestionResponseDTO>>)HttpResponse.ok(responseBody); }) .subscribeOn(Schedulers.from(ioExecutorService)); } /** * Update the text of a question. * @param question, {@link QuestionUpdateDTO} * @return {@link HttpResponse< QuestionResponseDTO >} */ @Put("/") public Single<HttpResponse<QuestionResponseDTO>> update(@Body @Valid QuestionUpdateDTO question, HttpRequest<QuestionCreateDTO> request) { if (question == null) { return Single.just(HttpResponse.ok()); } return Single.fromCallable(() -> questionService.update(toModel(question))) .observeOn(Schedulers.from(eventLoopGroup)) .map(updatedQuestion -> (HttpResponse<QuestionResponseDTO>) HttpResponse .created(fromModel(updatedQuestion)) .headers(headers -> headers.location( URI.create(String.format("%s/%s", request.getPath(), updatedQuestion.getId()))))) .subscribeOn(Schedulers.from(ioExecutorService)); } private QuestionResponseDTO fromModel(Question question) { QuestionResponseDTO qrdto = new QuestionResponseDTO(); qrdto.setQuestionId(question.getId()); qrdto.setText(question.getText()); return qrdto; } private Question toModel(QuestionUpdateDTO dto) { Question model = new Question(); model.setId(dto.getId()); model.setText(dto.getText()); return model; } private Question toModel(QuestionCreateDTO dto) { Question model = new Question(); model.setText(dto.getText()); return model; } }
muescha/homebrew-cask
Casks/bitmessage.rb
<reponame>muescha/homebrew-cask class Bitmessage < Cask url 'https://bitmessage.org/download/osx/Bitmessage.dmg' homepage 'https://bitmessage.org/' version 'latest' no_checksum link 'Bitmessage.app' end
dweng0/game
node_modules/@babylonjs/core/Lights/shadowLight.js
import { __decorate, __extends } from "tslib"; import { serialize, serializeAsVector3 } from "../Misc/decorators"; import { Matrix, Vector3 } from "../Maths/math.vector"; import { Light } from "./light"; import { Axis } from '../Maths/math.axis'; /** * Base implementation IShadowLight * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern. */ var ShadowLight = /** @class */ (function (_super) { __extends(ShadowLight, _super); function ShadowLight() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._needProjectionMatrixCompute = true; return _this; } ShadowLight.prototype._setPosition = function (value) { this._position = value; }; Object.defineProperty(ShadowLight.prototype, "position", { /** * Sets the position the shadow will be casted from. Also use as the light position for both * point and spot lights. */ get: function () { return this._position; }, /** * Sets the position the shadow will be casted from. Also use as the light position for both * point and spot lights. */ set: function (value) { this._setPosition(value); }, enumerable: false, configurable: true }); ShadowLight.prototype._setDirection = function (value) { this._direction = value; }; Object.defineProperty(ShadowLight.prototype, "direction", { /** * In 2d mode (needCube being false), gets the direction used to cast the shadow. * Also use as the light direction on spot and directional lights. */ get: function () { return this._direction; }, /** * In 2d mode (needCube being false), sets the direction used to cast the shadow. * Also use as the light direction on spot and directional lights. */ set: function (value) { this._setDirection(value); }, enumerable: false, configurable: true }); Object.defineProperty(ShadowLight.prototype, "shadowMinZ", { /** * Gets the shadow projection clipping minimum z value. */ get: function () { return this._shadowMinZ; }, /** * Sets the shadow projection clipping minimum z value. */ set: function (value) { this._shadowMinZ = value; this.forceProjectionMatrixCompute(); }, enumerable: false, configurable: true }); Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", { /** * Sets the shadow projection clipping maximum z value. */ get: function () { return this._shadowMaxZ; }, /** * Gets the shadow projection clipping maximum z value. */ set: function (value) { this._shadowMaxZ = value; this.forceProjectionMatrixCompute(); }, enumerable: false, configurable: true }); /** * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light * @returns true if the information has been computed, false if it does not need to (no parenting) */ ShadowLight.prototype.computeTransformedInformation = function () { if (this.parent && this.parent.getWorldMatrix) { if (!this.transformedPosition) { this.transformedPosition = Vector3.Zero(); } Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition); // In case the direction is present. if (this.direction) { if (!this.transformedDirection) { this.transformedDirection = Vector3.Zero(); } Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection); } return true; } return false; }; /** * Return the depth scale used for the shadow map. * @returns the depth scale. */ ShadowLight.prototype.getDepthScale = function () { return 50.0; }; /** * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed. * @param faceIndex The index of the face we are computed the direction to generate shadow * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true */ ShadowLight.prototype.getShadowDirection = function (faceIndex) { return this.transformedDirection ? this.transformedDirection : this.direction; }; /** * Returns the ShadowLight absolute position in the World. * @returns the position vector in world space */ ShadowLight.prototype.getAbsolutePosition = function () { return this.transformedPosition ? this.transformedPosition : this.position; }; /** * Sets the ShadowLight direction toward the passed target. * @param target The point to target in local space * @returns the updated ShadowLight direction */ ShadowLight.prototype.setDirectionToTarget = function (target) { this.direction = Vector3.Normalize(target.subtract(this.position)); return this.direction; }; /** * Returns the light rotation in euler definition. * @returns the x y z rotation in local space. */ ShadowLight.prototype.getRotation = function () { this.direction.normalize(); var xaxis = Vector3.Cross(this.direction, Axis.Y); var yaxis = Vector3.Cross(xaxis, this.direction); return Vector3.RotationFromAxis(xaxis, yaxis, this.direction); }; /** * Returns whether or not the shadow generation require a cube texture or a 2d texture. * @returns true if a cube texture needs to be use */ ShadowLight.prototype.needCube = function () { return false; }; /** * Detects if the projection matrix requires to be recomputed this frame. * @returns true if it requires to be recomputed otherwise, false. */ ShadowLight.prototype.needProjectionMatrixCompute = function () { return this._needProjectionMatrixCompute; }; /** * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. */ ShadowLight.prototype.forceProjectionMatrixCompute = function () { this._needProjectionMatrixCompute = true; }; /** @hidden */ ShadowLight.prototype._initCache = function () { _super.prototype._initCache.call(this); this._cache.position = Vector3.Zero(); }; /** @hidden */ ShadowLight.prototype._isSynchronized = function () { if (!this._cache.position.equals(this.position)) { return false; } return true; }; /** * Computes the world matrix of the node * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch * @returns the world matrix */ ShadowLight.prototype.computeWorldMatrix = function (force) { if (!force && this.isSynchronized()) { this._currentRenderId = this.getScene().getRenderId(); return this._worldMatrix; } this._updateCache(); this._cache.position.copyFrom(this.position); if (!this._worldMatrix) { this._worldMatrix = Matrix.Identity(); } Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix); if (this.parent && this.parent.getWorldMatrix) { this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix); this._markSyncedWithParent(); } // Cache the determinant this._worldMatrixDeterminantIsDirty = true; return this._worldMatrix; }; /** * Gets the minZ used for shadow according to both the scene and the light. * @param activeCamera The camera we are returning the min for * @returns the depth min z */ ShadowLight.prototype.getDepthMinZ = function (activeCamera) { return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; }; /** * Gets the maxZ used for shadow according to both the scene and the light. * @param activeCamera The camera we are returning the max for * @returns the depth max z */ ShadowLight.prototype.getDepthMaxZ = function (activeCamera) { return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; }; /** * Sets the shadow projection matrix in parameter to the generated projection matrix. * @param matrix The materix to updated with the projection information * @param viewMatrix The transform matrix of the light * @param renderList The list of mesh to render in the map * @returns The current light */ ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { if (this.customProjectionMatrixBuilder) { this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix); } else { this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList); } return this; }; __decorate([ serializeAsVector3() ], ShadowLight.prototype, "position", null); __decorate([ serializeAsVector3() ], ShadowLight.prototype, "direction", null); __decorate([ serialize() ], ShadowLight.prototype, "shadowMinZ", null); __decorate([ serialize() ], ShadowLight.prototype, "shadowMaxZ", null); return ShadowLight; }(Light)); export { ShadowLight }; //# sourceMappingURL=shadowLight.js.map
mgontar/ucu-advanced-programming
HW2/src/main/java/lab4/Cleaner.java
<filename>HW2/src/main/java/lab4/Cleaner.java<gh_stars>0 package lab4; public interface Cleaner { void clean(); }
tandonn/streams
src/main/scala/com/fndef/streams/core/ExecutionParams.scala
package com.fndef.streams.core abstract class ResponseCriteria case class WithResponse(responseEndpointId: String, timeout: Long = -1, incrementalResponse: Boolean = false) extends ResponseCriteria case object WithoutResponse extends ResponseCriteria case class ExecutionParams(responseCriteria: ResponseCriteria = WithoutResponse, maxRetry: Int = 0, highPriority: Boolean = false)
chasepang/shanjupay
shanjupay-merchant/shanjupay-merchant-service/src/main/java/com/shanjupay/merchant/mapper/StaffMapper.java
package com.shanjupay.merchant.mapper; import com.shanjupay.merchant.entity.Staff; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.springframework.stereotype.Repository; /** * <p> * Mapper 接口 * </p> * * @author author * @since 2021-04-28 */ @Repository public interface StaffMapper extends BaseMapper<Staff> { }
Damons-work/icodework_vue__back_end
src/main/java/cn/js/icode/basis/mapper/OrganizationMapper.java
<gh_stars>0 package cn.js.icode.basis.mapper; import team.bangbang.common.sql.IMybatisMapper; import org.apache.ibatis.annotations.Mapper; import cn.js.icode.basis.data.Organization; /** * 组织机构 - Mapper * 对应数据库表:basis_organization_base * * @author ICode Studio * @version 1.0 2018-09-23 */ @Mapper public interface OrganizationMapper extends IMybatisMapper<Organization> { /***************************************************************************************** * 如果有部分字段的查询需求,请不要使用getObject()、list(),应按以下步骤操作: * 1. 在下面自定义对应的方法; * 注意配置的方法不要使用IMapper已有方法:getObject()、list() * 2. 在相应的mapper.xml中配置SQL块。 *****************************************************************************************/ }
opendata-mvcr/csvw-validator
csvw-validator-lib/src/main/java/com/malyvoj3/csvwvalidator/parser/metadata/ParserFactory.java
package com.malyvoj3.csvwvalidator.parser.metadata; import com.malyvoj3.csvwvalidator.domain.metadata.ObjectDescription; import com.malyvoj3.csvwvalidator.parser.metadata.parsers.PropertyParser; /** * Factory which creates parsers for properties. * @param <T> */ public interface ParserFactory<T extends ObjectDescription> { /** * Create parser factory for property given by name. * @param propertyName Name of the property which should be parsed. * @return PropertyParser for given propertyName, or null if this property is not allowed by CSV on the Web. */ PropertyParser<T> createParser(String propertyName); }
wayshall/onetwo
core/modules/security/src/main/java/org/onetwo/ext/security/method/DefaultMethodSecurityConfigurer.java
package org.onetwo.ext.security.method; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.onetwo.common.utils.LangUtils; import org.onetwo.ext.security.ajax.AjaxAuthenticationHandler; import org.onetwo.ext.security.ajax.AjaxLogoutSuccessHandler; import org.onetwo.ext.security.ajax.AjaxSupportedAccessDeniedHandler; import org.onetwo.ext.security.ajax.AjaxSupportedAuthenticationEntryPoint; import org.onetwo.ext.security.matcher.MatcherUtils; import org.onetwo.ext.security.utils.IgnoreCsrfProtectionRequestUrlMatcher; import org.onetwo.ext.security.utils.SecurityConfig; import org.onetwo.ext.security.utils.SimpleThrowableAnalyzer; import org.springframework.beans.ConfigurablePropertyAccessor; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer; import org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer.UserDetailsBuilder; 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.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.config.annotation.web.configurers.DefaultLoginPageConfigurer; import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer; import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer; import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.access.ExceptionTranslationFilter; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import lombok.Getter; public class DefaultMethodSecurityConfigurer extends WebSecurityConfigurerAdapter { // private Logger logger = LoggerFactory.getLogger(this.getClass()); @Getter @Autowired private AjaxAuthenticationHandler ajaxAuthenticationHandler; @Getter @Autowired private AjaxSupportedAccessDeniedHandler ajaxSupportedAccessDeniedHandler; @Autowired(required=false) private AjaxSupportedAuthenticationEntryPoint authenticationEntryPoint; @Autowired(required=false) private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler; @Getter @Autowired private PasswordEncoder passwordEncoder; @Getter @Autowired(required=false) private UserDetailsService userDetailsService; @Getter @Autowired protected SecurityConfig securityConfig; //redis @Autowired(required=false) private SecurityContextRepository securityContextRepository; @Autowired(required=false) private LogoutSuccessHandler logoutSuccessHandler; @Override public void configure(WebSecurity web) throws Exception { // web.ignoring().antMatchers("/webjars/**", "/images/**", "/oauth/uncache_approvals", "/oauth/cache_approvals"); //= new DefaultSecurityFilterChain(ignoredRequest) see: WebSecurity#performBuild if(securityConfig.isIgnoringDefautStaticPaths()){ web.ignoring().antMatchers("/webjars/**", "/images/**", "/static/**"); } if(!LangUtils.isEmpty(securityConfig.getIgnoringUrls())){ web.ignoring().antMatchers(securityConfig.getIgnoringUrls()); } web.debug(securityConfig.isDebug()); } @SuppressWarnings("rawtypes") @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { if(userDetailsService!=null){ auth.userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder); }else{ InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemory = auth.inMemoryAuthentication(); // InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemory = auth.apply(new ExtInMemoryUserDetailsManagerConfigurer()); securityConfig.getMemoryUsers().forEach((user, config)->{ UserDetailsBuilder udb = inMemory.withUser(user).password(config.getPassword()); if(!LangUtils.isEmpty(config.getRoles())){ udb.roles(config.getRoles()); } if(!LangUtils.isEmpty(config.getAuthorities())){ udb.authorities(config.getAuthorities()); } }); inMemory.passwordEncoder(passwordEncoder); } /*DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider(); daoProvider.setUserDetailsService(userDetailsService); daoProvider.setPasswordEncoder(passwordEncoder); daoProvider.afterPropertiesSet(); auth.authenticationProvider(daoProvider);*/ } @Override protected void configure(HttpSecurity http) throws Exception { //if basic method interceptor, ignore all url interceptor configureAnyRequest(http); defaultConfigure(http); } protected void configureAnyRequest(HttpSecurity http) throws Exception { defaultAnyRequest(http, securityConfig.getAnyRequest()); } public static void defaultAnyRequest(HttpSecurity http, String anyRequest) throws Exception { //其它未标记管理的功能的默认权限 if(StringUtils.isBlank(anyRequest)){ http.authorizeRequests() .anyRequest() .authenticated()//需要登录 // .fullyAuthenticated()//需要登录,并且不是rememberme的方式登录 ; }else if(SecurityConfig.ANY_REQUEST_NONE.equals(anyRequest)){ //not config anyRequest }else{ http.authorizeRequests() .anyRequest() .access(anyRequest); } } protected void configureCsrf(HttpSecurity http) throws Exception{ CsrfConfigurer<HttpSecurity> csrf = http.csrf(); if(securityConfig.getCsrf().isDisable()){ csrf.disable(); http.headers().frameOptions().disable(); return ; } if(ArrayUtils.isNotEmpty(securityConfig.getCsrf().getIgnoringPaths())){ csrf.ignoringAntMatchers(securityConfig.getCsrf().getIgnoringPaths()); } if(ArrayUtils.isNotEmpty(securityConfig.getCsrf().getRequirePaths())){ csrf.requireCsrfProtectionMatcher(MatcherUtils.matchAntPaths(securityConfig.getCsrf().getRequirePaths())); }else{ csrf.requireCsrfProtectionMatcher(IgnoreCsrfProtectionRequestUrlMatcher.ignoreUrls("/login*")); } } @SuppressWarnings("unchecked") protected void defaultConfigure(HttpSecurity http) throws Exception { if(securityContextRepository!=null){ http.securityContext().securityContextRepository(securityContextRepository); } if(logoutSuccessHandler!=null){ http.logout().logoutSuccessHandler(logoutSuccessHandler); } /*http .formLogin() .loginPage(securityConfig.getLoginUrl()).permitAll() .loginProcessingUrl(securityConfig.getLoginProcessUrl()).permitAll() .usernameParameter("username") .passwordParameter("password") .failureUrl(securityConfig.getLoginUrl()+"?error=true") .failureHandler(ajaxAuthenticationHandler) .successHandler(ajaxAuthenticationHandler); */ FormLoginConfigurer<HttpSecurity> formConfig = http.formLogin(); if(StringUtils.isNotBlank(securityConfig.getDefaultLoginPage())){ //if set default page, cannot set authenticationEntryPoint, see DefaultLoginPageConfigurer#configure // securityConfig.setLoginUrl(DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL); http.getConfigurer(DefaultLoginPageConfigurer.class).withObjectPostProcessor(new ObjectPostProcessor<DefaultLoginPageGeneratingFilter>(){ @Override public <O extends DefaultLoginPageGeneratingFilter> O postProcess(O filter) { filter.setLoginPageUrl(securityConfig.getDefaultLoginPage()); filter.setLogoutSuccessUrl(securityConfig.getLogoutSuccessUrl()); filter.setFailureUrl(securityConfig.getFailureUrl()); return filter; } }); http.getConfigurer(ExceptionHandlingConfigurer.class).withObjectPostProcessor(new ObjectPostProcessor<ExceptionTranslationFilter>(){ @Override public <O extends ExceptionTranslationFilter> O postProcess(O filter) { ConfigurablePropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(filter); accessor.setPropertyValue("authenticationEntryPoint", authenticationEntryPoint); // throwableAnalyzer // ThrowableAnalyzer analyzer = (ThrowableAnalyzer)accessor.getPropertyValue("throwableAnalyzer"); if(securityConfig.isDebug()){ SimpleThrowableAnalyzer analyzer = new SimpleThrowableAnalyzer(); filter.setThrowableAnalyzer(analyzer); } return filter; } }); /*formConfig.loginPage(securityConfig.getLoginUrl()) .permitAll(); PropertyAccessorFactory.forDirectFieldAccess(formConfig) .setPropertyValue("customLoginPage", false);*/ }else{ formConfig.loginPage(securityConfig.getLoginUrl()) .permitAll(); http.exceptionHandling() .authenticationEntryPoint(authenticationEntryPoint); } formConfig.loginProcessingUrl(securityConfig.getLoginProcessUrl()).permitAll() .usernameParameter("username") .passwordParameter("password") .failureUrl(securityConfig.getFailureUrl()) .failureHandler(ajaxAuthenticationHandler) .successHandler(ajaxAuthenticationHandler); LogoutConfigurer<HttpSecurity> logoutConf = http.logout() .logoutRequestMatcher(new AntPathRequestMatcher(securityConfig.getLogoutUrl())) .logoutSuccessUrl(securityConfig.getLogoutSuccessUrl()).permitAll(); if (ajaxLogoutSuccessHandler!=null) { logoutConf.logoutSuccessHandler(ajaxLogoutSuccessHandler); } http.httpBasic() .disable() .headers() .frameOptions() .sameOrigin() .xssProtection() .xssProtectionEnabled(true) .and() .and() .exceptionHandling() // .accessDeniedPage("/access?error=true") .accessDeniedHandler(ajaxSupportedAccessDeniedHandler) // .authenticationEntryPoint(authenticationEntryPoint) ; if(securityConfig.getRememberMe().isEnabled()){ http .rememberMe() .tokenValiditySeconds(securityConfig.getRememberMe().getTokenValiditySeconds()) //must be config .key(securityConfig.getRememberMe().getKey()); } configureCsrf(http); } }
Bnei-Baruch/keycloak
server-spi-private/src/main/java/org/keycloak/authorization/store/PolicyStore.java
<gh_stars>1-10 /* * JBoss, Home of Professional Open Source. * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.authorization.store; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import org.keycloak.authorization.model.Policy; import org.keycloak.authorization.model.Resource; import org.keycloak.authorization.model.ResourceServer; import org.keycloak.authorization.model.Scope; import org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation; /** * A {@link PolicyStore} is responsible to manage the persistence of {@link Policy} instances. * * @author <a href="mailto:<EMAIL>"><NAME></a> */ public interface PolicyStore { /** * Creates a new {@link Policy} instance. The new instance is not necessarily persisted though, which may require * a call to the {#save} method to actually make it persistent. * * @param resourceServer the resource server to which this policy belongs * @param representation the policy representation * @return a new instance of {@link Policy} */ Policy create(ResourceServer resourceServer, AbstractPolicyRepresentation representation); /** * Deletes a policy from the underlying persistence mechanism. * * @param id the id of the policy to delete */ void delete(String id); /** * Returns a {@link Policy} with the given <code>id</code> * * @param resourceServer the resource server * @param id the identifier of the policy * @return a policy with the given identifier. */ Policy findById(ResourceServer resourceServer, String id); /** * Returns a {@link Policy} with the given <code>name</code> * * @param resourceServer the resource server * @param name the name of the policy * @return a policy with the given name. */ Policy findByName(ResourceServer resourceServer, String name); /** * Returns a list of {@link Policy} associated with a {@link ResourceServer} with the given <code>resourceServerId</code>. * * @param resourceServer the identifier of a resource server * @return a list of policies that belong to the given resource server */ List<Policy> findByResourceServer(ResourceServer resourceServer); /** * Returns a list of {@link Policy} associated with a {@link ResourceServer} with the given <code>resourceServerId</code>. * * @param resourceServer the identifier of a resource server * @param attributes a map holding the attributes that will be used as a filter; possible filter options are given by {@link Policy.FilterOption} * @param firstResult first result to return. Ignored if negative or {@code null}. * @param maxResults maximum number of results to return. Ignored if negative or {@code null}. * @return a list of policies that belong to the given resource server * * @throws IllegalArgumentException when there is an unknown attribute in the {@code attributes} map */ List<Policy> findByResourceServer(ResourceServer resourceServer, Map<Policy.FilterOption, String[]> attributes, Integer firstResult, Integer maxResults); /** * Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.Resource} with the given <code>resourceId</code>. * * @param resourceServer the resource server * @param resource the resource * @return a list of policies associated with the given resource */ default List<Policy> findByResource(ResourceServer resourceServer, Resource resource) { List<Policy> result = new LinkedList<>(); findByResource(resourceServer, resource, result::add); return result; } /** * Searches for all policies associated with the {@link org.keycloak.authorization.model.Resource} and passes the result to the {@code consumer} * * @param resourceServer the resourceServer * @param resource the resource * @param consumer consumer of policies resulted from the search */ void findByResource(ResourceServer resourceServer, Resource resource, Consumer<Policy> consumer); /** * Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.ResourceServer} with the given <code>type</code>. * * @param resourceServer the resource server id * @param resourceType the type of a resource * @return a list of policies associated with the given resource type */ default List<Policy> findByResourceType(ResourceServer resourceServer, String resourceType) { List<Policy> result = new LinkedList<>(); findByResourceType(resourceServer, resourceType, result::add); return result; } /** * Searches for policies associated with a {@link org.keycloak.authorization.model.ResourceServer} and passes the result to the consumer * * @param resourceServer the resourceServer * @param type the type of a resource * @param policyConsumer consumer of policies resulted from the search */ void findByResourceType(ResourceServer resourceServer, String type, Consumer<Policy> policyConsumer); /** * Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.Scope} within the given <code>scope</code>. * * @param resourceServer the resource server * @param scopes the scopes * @return a list of policies associated with the given scopes */ List<Policy> findByScopes(ResourceServer resourceServer, List<Scope> scopes); /** * Returns a list of {@link Policy} associated with a {@link org.keycloak.authorization.model.Scope} with the given <code>resource</code> and <code>scopes</code>. * * @param resourceServer the resource server * @param resource the resource. Ignored if {@code null}. * @param scopes the scopes * @return a list of policies associated with the given scopes */ default List<Policy> findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes) { List<Policy> result = new LinkedList<>(); findByScopes(resourceServer, resource, scopes, result::add); return result; } /** * Effectively the same method as {@link #findByScopes(ResourceServer, Resource, List)}, however in the end * the {@code consumer} is fed with the result. * */ void findByScopes(ResourceServer resourceServer, Resource resource, List<Scope> scopes, Consumer<Policy> consumer); /** * Returns a list of {@link Policy} with the given <code>type</code>. * * @param resourceServer the resource server id * @param type the type of the policy * @return a list of policies with the given type */ List<Policy> findByType(ResourceServer resourceServer, String type); /** * Returns a list of {@link Policy} that depends on another policy with the given <code>id</code>. * * @param resourceServer the resource server * @param id the id of the policy to query its dependents * @return a list of policies that depends on the a policy with the given identifier */ List<Policy> findDependentPolicies(ResourceServer resourceServer, String id); }
tikskit/imin
src/test/java/ru/tikskit/imin/model/TagTest.java
package ru.tikskit.imin.model; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Calendar; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; @DataJpaTest public class TagTest { @Autowired private TestEntityManager em; @Test @DisplayName("Должен создавать 3 тэга для события") public void shouldAddTag4Event() { Organizer organizer = em.persist(new Organizer()); OffsetDateTime dateTime = Calendar.getInstance().toInstant().atOffset(ZoneOffset.of("+07:00")); Event event = new Event(0, organizer, "My first event", dateTime, EventStatus.ARRANGED, new EventPlace("http://youtube.com"), null); event.setTags(Set.of(new Tag(0, "Занятие йогой"), new Tag(0, "Собрание курильщиков трубки"), new Tag(0, "BDSM-вечеринка"))); long eventId = em.persist(event).getId(); em.flush(); em.clear(); Event event1 = em.find(Event.class, eventId); assertThat(event1.getTags()).isNotNull().size().isEqualTo(3); } }
enavarro51/retworkx
tests/test_custom_return_types.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import pickle import unittest import retworkx class TestBFSSuccessorsComparisons(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() node_a = self.dag.add_node("a") self.dag.add_child(node_a, "b", "Edgy") def test__eq__match(self): self.assertTrue(retworkx.bfs_successors(self.dag, 0) == [("a", ["b"])]) def test__eq__not_match(self): self.assertFalse(retworkx.bfs_successors(self.dag, 0) == [("b", ["c"])]) def test_eq_not_match_inner(self): self.assertFalse(retworkx.bfs_successors(self.dag, 0) == [("a", ["c"])]) def test__eq__different_length(self): self.assertFalse(retworkx.bfs_successors(self.dag, 0) == [("a", ["b"]), ("b", ["c"])]) def test__eq__invalid_type(self): with self.assertRaises(TypeError): retworkx.bfs_successors(self.dag, 0) == ["a"] def test__ne__match(self): self.assertFalse(retworkx.bfs_successors(self.dag, 0) != [("a", ["b"])]) def test__ne__not_match(self): self.assertTrue(retworkx.bfs_successors(self.dag, 0) != [("b", ["c"])]) def test_ne_not_match_inner(self): self.assertTrue(retworkx.bfs_successors(self.dag, 0) != [("a", ["c"])]) def test__ne__different_length(self): self.assertTrue(retworkx.bfs_successors(self.dag, 0) != [("a", ["b"]), ("b", ["c"])]) def test__ne__invalid_type(self): with self.assertRaises(TypeError): retworkx.bfs_successors(self.dag, 0) != ["a"] def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): retworkx.bfs_successors(self.dag, 0) > [("b", ["c"])] def test_deepcopy(self): bfs = retworkx.bfs_successors(self.dag, 0) bfs_copy = copy.deepcopy(bfs) self.assertEqual(bfs, bfs_copy) def test_pickle(self): bfs = retworkx.bfs_successors(self.dag, 0) bfs_pickle = pickle.dumps(bfs) bfs_copy = pickle.loads(bfs_pickle) self.assertEqual(bfs, bfs_copy) def test_str(self): res = retworkx.bfs_successors(self.dag, 0) self.assertEqual("BFSSuccessors[(a, [b])]", str(res)) def test_hash(self): res = retworkx.bfs_successors(self.dag, 0) hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_hash_invalid_type(self): self.dag.add_child(0, [1, 2, 3], "edgy") res = retworkx.bfs_successors(self.dag, 0) with self.assertRaises(TypeError): hash(res) class TestNodeIndicesComparisons(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() node_a = self.dag.add_node("a") self.dag.add_child(node_a, "b", "Edgy") def test__eq__match(self): self.assertTrue(self.dag.node_indexes() == [0, 1]) def test__eq__not_match(self): self.assertFalse(self.dag.node_indexes() == [1, 2]) def test__eq__different_length(self): self.assertFalse(self.dag.node_indexes() == [0, 1, 2, 3]) def test__eq__invalid_type(self): with self.assertRaises(TypeError): self.dag.node_indexes() == ["a", None] def test__ne__match(self): self.assertFalse(self.dag.node_indexes() != [0, 1]) def test__ne__not_match(self): self.assertTrue(self.dag.node_indexes() != [1, 2]) def test__ne__different_length(self): self.assertTrue(self.dag.node_indexes() != [0, 1, 2, 3]) def test__ne__invalid_type(self): with self.assertRaises(TypeError): self.dag.node_indexes() != ["a", None] def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): self.dag.node_indexes() > [2, 1] def test_deepcopy(self): nodes = self.dag.node_indexes() nodes_copy = copy.deepcopy(nodes) self.assertEqual(nodes, nodes_copy) def test_pickle(self): nodes = self.dag.node_indexes() nodes_pickle = pickle.dumps(nodes) nodes_copy = pickle.loads(nodes_pickle) self.assertEqual(nodes, nodes_copy) def test_str(self): res = self.dag.node_indexes() self.assertEqual("NodeIndices[0, 1]", str(res)) def test_hash(self): res = self.dag.node_indexes() hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) class TestNodesCountMapping(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() node_a = self.dag.add_node("a") self.dag.add_child(node_a, "b", "Edgy") def test__eq__match(self): self.assertTrue(retworkx.num_shortest_paths_unweighted(self.dag, 0) == {1: 1}) def test__eq__not_match_keys(self): self.assertFalse(retworkx.num_shortest_paths_unweighted(self.dag, 0) == {2: 1}) def test__eq__not_match_values(self): self.assertFalse(retworkx.num_shortest_paths_unweighted(self.dag, 0) == {1: 2}) def test__eq__different_length(self): self.assertFalse(retworkx.num_shortest_paths_unweighted(self.dag, 0) == {1: 1, 2: 2}) def test_eq__same_type(self): self.assertEqual( retworkx.num_shortest_paths_unweighted(self.dag, 0), retworkx.num_shortest_paths_unweighted(self.dag, 0), ) def test__eq__invalid_type(self): self.assertFalse(retworkx.num_shortest_paths_unweighted(self.dag, 0) == ["a", None]) def test__eq__invalid_inner_type(self): self.assertFalse(retworkx.num_shortest_paths_unweighted(self.dag, 0) == {0: "a"}) def test__ne__match(self): self.assertFalse(retworkx.num_shortest_paths_unweighted(self.dag, 0) != {1: 1}) def test__ne__not_match(self): self.assertTrue(retworkx.num_shortest_paths_unweighted(self.dag, 0) != {2: 1}) def test__ne__not_match_values(self): self.assertTrue(retworkx.num_shortest_paths_unweighted(self.dag, 0) != {1: 2}) def test__ne__different_length(self): self.assertTrue(retworkx.num_shortest_paths_unweighted(self.dag, 0) != {1: 1, 2: 2}) def test__ne__invalid_type(self): self.assertTrue(retworkx.num_shortest_paths_unweighted(self.dag, 0) != ["a", None]) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): retworkx.num_shortest_paths_unweighted(self.dag, 0) > {1: 1} def test_deepcopy(self): paths = retworkx.num_shortest_paths_unweighted(self.dag, 0) paths_copy = copy.deepcopy(paths) self.assertEqual(paths, paths_copy) def test_pickle(self): paths = retworkx.num_shortest_paths_unweighted(self.dag, 0) paths_pickle = pickle.dumps(paths) paths_copy = pickle.loads(paths_pickle) self.assertEqual(paths, paths_copy) def test_str(self): res = retworkx.num_shortest_paths_unweighted(self.dag, 0) self.assertEqual("NodesCountMapping{1: 1}", str(res)) def test_hash(self): res = retworkx.num_shortest_paths_unweighted(self.dag, 0) hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_index_error(self): res = retworkx.num_shortest_paths_unweighted(self.dag, 0) with self.assertRaises(IndexError): res[42] def test_keys(self): keys = retworkx.num_shortest_paths_unweighted(self.dag, 0).keys() self.assertEqual([1], list(keys)) def test_values(self): values = retworkx.num_shortest_paths_unweighted(self.dag, 0).values() self.assertEqual([1], list(values)) def test_items(self): items = retworkx.num_shortest_paths_unweighted(self.dag, 0).items() self.assertEqual([(1, 1)], list(items)) def test_iter(self): mapping_iter = iter(retworkx.num_shortest_paths_unweighted(self.dag, 0)) output = list(mapping_iter) self.assertEqual(output, [1]) def test_contains(self): res = retworkx.num_shortest_paths_unweighted(self.dag, 0) self.assertIn(1, res) def test_not_contains(self): res = retworkx.num_shortest_paths_unweighted(self.dag, 0) self.assertNotIn(0, res) class TestEdgeIndicesComparisons(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDiGraph() node_a = self.dag.add_node("a") node_b = self.dag.add_child(node_a, "b", "Edgy") self.dag.add_child(node_b, "c", "Super Edgy") def test__eq__match(self): self.assertTrue(self.dag.edge_indices() == [0, 1]) def test__eq__not_match(self): self.assertFalse(self.dag.edge_indices() == [1, 2]) def test__eq__different_length(self): self.assertFalse(self.dag.edge_indices() == [0, 1, 2, 3]) def test__eq__invalid_type(self): with self.assertRaises(TypeError): self.dag.edge_indices() == ["a", None] def test__ne__match(self): self.assertFalse(self.dag.edge_indices() != [0, 1]) def test__ne__not_match(self): self.assertTrue(self.dag.edge_indices() != [1, 2]) def test__ne__different_length(self): self.assertTrue(self.dag.edge_indices() != [0, 1, 2, 3]) def test__ne__invalid_type(self): with self.assertRaises(TypeError): self.dag.edge_indices() != ["a", None] def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): self.dag.edge_indices() > [2, 1] def test_deepcopy(self): edges = self.dag.edge_indices() edges_copy = copy.deepcopy(edges) self.assertEqual(edges, edges_copy) def test_pickle(self): edges = self.dag.edge_indices() edges_pickle = pickle.dumps(edges) edges_copy = pickle.loads(edges_pickle) self.assertEqual(edges, edges_copy) def test_str(self): res = self.dag.edge_indices() self.assertEqual("EdgeIndices[0, 1]", str(res)) def test_hash(self): res = self.dag.edge_indices() hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) class TestEdgeListComparisons(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() node_a = self.dag.add_node("a") self.dag.add_child(node_a, "b", "Edgy") def test__eq__match(self): self.assertTrue(self.dag.edge_list() == [(0, 1)]) def test__eq__not_match(self): self.assertFalse(self.dag.edge_list() == [(1, 2)]) def test__eq__different_length(self): self.assertFalse(self.dag.edge_list() == [(0, 1), (2, 3)]) def test__eq__invalid_type(self): self.assertFalse(self.dag.edge_list() == ["a", None]) def test__ne__match(self): self.assertFalse(self.dag.edge_list() != [(0, 1)]) def test__ne__not_match(self): self.assertTrue(self.dag.edge_list() != [(1, 2)]) def test__ne__different_length(self): self.assertTrue(self.dag.edge_list() != [(0, 1), (2, 3)]) def test__ne__invalid_type(self): self.assertTrue(self.dag.edge_list() != ["a", None]) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): self.dag.edge_list() > [(2, 1)] def test_deepcopy(self): edges = self.dag.edge_list() edges_copy = copy.deepcopy(edges) self.assertEqual(edges, edges_copy) def test_pickle(self): edges = self.dag.edge_list() edges_pickle = pickle.dumps(edges) edges_copy = pickle.loads(edges_pickle) self.assertEqual(edges, edges_copy) def test_str(self): res = self.dag.edge_list() self.assertEqual("EdgeList[(0, 1)]", str(res)) def test_hash(self): res = self.dag.edge_list() hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) class TestWeightedEdgeListComparisons(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() node_a = self.dag.add_node("a") self.dag.add_child(node_a, "b", "Edgy") def test__eq__match(self): self.assertTrue(self.dag.weighted_edge_list() == [(0, 1, "Edgy")]) def test__eq__not_match(self): self.assertFalse(self.dag.weighted_edge_list() == [(1, 2, None)]) def test__eq__different_length(self): self.assertFalse(self.dag.weighted_edge_list() == [(0, 1, "Edgy"), (2, 3, "Not Edgy")]) def test__eq__invalid_type(self): self.assertFalse(self.dag.weighted_edge_list() == ["a", None]) def test__ne__match(self): self.assertFalse(self.dag.weighted_edge_list() != [(0, 1, "Edgy")]) def test__ne__not_match(self): self.assertTrue(self.dag.weighted_edge_list() != [(1, 2, "Not Edgy")]) def test__ne__different_length(self): self.assertTrue(self.dag.node_indexes() != [0, 1, 2, 3]) def test__ne__invalid_type(self): self.assertTrue(self.dag.weighted_edge_list() != ["a", None]) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): self.dag.weighted_edge_list() > [(2, 1, "Not Edgy")] def test_deepcopy(self): edges = self.dag.weighted_edge_list() edges_copy = copy.deepcopy(edges) self.assertEqual(edges, edges_copy) def test_pickle(self): edges = self.dag.weighted_edge_list() edges_pickle = pickle.dumps(edges) edges_copy = pickle.loads(edges_pickle) self.assertEqual(edges, edges_copy) def test_str(self): res = self.dag.weighted_edge_list() self.assertEqual("WeightedEdgeList[(0, 1, Edgy)]", str(res)) def test_hash(self): res = self.dag.weighted_edge_list() hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_hash_invalid_type(self): self.dag.add_child(0, "c", ["edgy", "not_edgy"]) res = self.dag.weighted_edge_list() with self.assertRaises(TypeError): hash(res) class TestPathMapping(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() node_a = self.dag.add_node("a") self.dag.add_child(node_a, "b", "Edgy") def test__eq__match(self): self.assertTrue(retworkx.dijkstra_shortest_paths(self.dag, 0) == {1: [0, 1]}) def test__eq__not_match_keys(self): self.assertFalse(retworkx.dijkstra_shortest_paths(self.dag, 0) == {2: [0, 1]}) def test__eq__not_match_values(self): self.assertFalse(retworkx.dijkstra_shortest_paths(self.dag, 0) == {1: [0, 2]}) def test__eq__different_length(self): self.assertFalse(retworkx.dijkstra_shortest_paths(self.dag, 0) == {1: [0, 1], 2: [0, 2]}) def test_eq__same_type(self): self.assertEqual( retworkx.dijkstra_shortest_paths(self.dag, 0), retworkx.dijkstra_shortest_paths(self.dag, 0), ) def test__eq__invalid_type(self): self.assertFalse(retworkx.dijkstra_shortest_paths(self.dag, 0) == ["a", None]) def test__eq__invalid_inner_type(self): self.assertFalse(retworkx.dijkstra_shortest_paths(self.dag, 0) == {0: {"a": None}}) def test__ne__match(self): self.assertFalse(retworkx.dijkstra_shortest_paths(self.dag, 0) != {1: [0, 1]}) def test__ne__not_match(self): self.assertTrue(retworkx.dijkstra_shortest_paths(self.dag, 0) != {2: [0, 1]}) def test__ne__not_match_values(self): self.assertTrue(retworkx.dijkstra_shortest_paths(self.dag, 0) != {1: [0, 2]}) def test__ne__different_length(self): self.assertTrue(retworkx.dijkstra_shortest_paths(self.dag, 0) != {1: [0, 1], 2: [0, 2]}) def test__ne__invalid_type(self): self.assertTrue(retworkx.dijkstra_shortest_paths(self.dag, 0) != ["a", None]) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): retworkx.dijkstra_shortest_paths(self.dag, 0) > {1: [0, 2]} def test_deepcopy(self): paths = retworkx.dijkstra_shortest_paths(self.dag, 0) paths_copy = copy.deepcopy(paths) self.assertEqual(paths, paths_copy) def test_pickle(self): paths = retworkx.dijkstra_shortest_paths(self.dag, 0) paths_pickle = pickle.dumps(paths) paths_copy = pickle.loads(paths_pickle) self.assertEqual(paths, paths_copy) def test_str(self): res = retworkx.dijkstra_shortest_paths(self.dag, 0) self.assertEqual("PathMapping{1: [0, 1]}", str(res)) def test_hash(self): res = retworkx.dijkstra_shortest_paths(self.dag, 0) hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_index_error(self): res = retworkx.dijkstra_shortest_paths(self.dag, 0) with self.assertRaises(IndexError): res[42] def test_keys(self): keys = retworkx.dijkstra_shortest_paths(self.dag, 0).keys() self.assertEqual([1], list(keys)) def test_values(self): values = retworkx.dijkstra_shortest_paths(self.dag, 0).values() self.assertEqual([[0, 1]], list(values)) def test_items(self): items = retworkx.dijkstra_shortest_paths(self.dag, 0).items() self.assertEqual([(1, [0, 1])], list(items)) def test_iter(self): mapping_iter = iter(retworkx.dijkstra_shortest_paths(self.dag, 0)) output = list(mapping_iter) self.assertEqual(output, [1]) def test_contains(self): res = retworkx.dijkstra_shortest_paths(self.dag, 0) self.assertIn(1, res) def test_not_contains(self): res = retworkx.dijkstra_shortest_paths(self.dag, 0) self.assertNotIn(0, res) class TestPathLengthMapping(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() node_a = self.dag.add_node("a") self.dag.add_child(node_a, "b", "Edgy") self.fn = lambda _: 1.0 def test__eq__match(self): self.assertTrue(retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) == {1: 1.0}) def test__eq__not_match_keys(self): self.assertFalse(retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) == {2: 1.0}) def test__eq__not_match_values(self): self.assertFalse(retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) == {1: 2.0}) def test__eq__different_length(self): self.assertFalse( retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) == {1: 1.0, 2: 2.0} ) def test_eq__same_type(self): self.assertEqual( retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn), retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn), ) def test__eq__invalid_type(self): self.assertFalse( retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) == ["a", None] ) def test__eq__invalid_inner_type(self): self.assertFalse(retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) == {0: "a"}) def test__ne__match(self): self.assertFalse(retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) != {1: 1.0}) def test__ne__not_match(self): self.assertTrue(retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) != {2: 1.0}) def test__ne__not_match_values(self): self.assertTrue(retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) != {1: 2.0}) def test__ne__different_length(self): self.assertTrue( retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) != {1: 1.0, 2: 2.0} ) def test__ne__invalid_type(self): self.assertTrue( retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) != ["a", None] ) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) > {1: 1.0} def test_deepcopy(self): paths = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) paths_copy = copy.deepcopy(paths) self.assertEqual(paths, paths_copy) def test_pickle(self): paths = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) paths_pickle = pickle.dumps(paths) paths_copy = pickle.loads(paths_pickle) self.assertEqual(paths, paths_copy) def test_str(self): res = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, lambda _: 3.14) self.assertEqual("PathLengthMapping{1: 3.14}", str(res)) def test_hash(self): res = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_index_error(self): res = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) with self.assertRaises(IndexError): res[42] def test_keys(self): keys = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn).keys() self.assertEqual([1], list(keys)) def test_values(self): values = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn).values() self.assertEqual([1.0], list(values)) def test_items(self): items = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn).items() self.assertEqual([(1, 1.0)], list(items)) def test_iter(self): mapping_iter = iter(retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn)) output = list(mapping_iter) self.assertEqual(output, [1]) def test_contains(self): res = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) self.assertIn(1, res) def test_not_contains(self): res = retworkx.dijkstra_shortest_path_lengths(self.dag, 0, self.fn) self.assertNotIn(0, res) class TestPos2DMapping(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDiGraph() self.dag.add_node("a") def test__eq__match(self): res = retworkx.random_layout(self.dag, seed=10244242) self.assertTrue(res == {0: (0.4883489113112722, 0.6545867364101975)}) def test__eq__not_match_keys(self): self.assertFalse(retworkx.random_layout(self.dag, seed=10244242) == {2: 1.0}) def test__eq__not_match_values(self): self.assertFalse(retworkx.random_layout(self.dag, seed=10244242) == {1: 2.0}) def test__eq__different_length(self): res = retworkx.random_layout(self.dag, seed=10244242) self.assertFalse(res == {1: 1.0, 2: 2.0}) def test_eq__same_type(self): self.assertEqual( retworkx.random_layout(self.dag, seed=10244242), retworkx.random_layout(self.dag, seed=10244242), ) def test__eq__invalid_type(self): self.assertFalse(retworkx.random_layout(self.dag, seed=10244242) == {"a": None}) def test__ne__match(self): res = retworkx.random_layout(self.dag, seed=10244242) self.assertFalse(res != {0: (0.4883489113112722, 0.6545867364101975)}) def test__ne__not_match(self): self.assertTrue(retworkx.random_layout(self.dag, seed=10244242) != {2: 1.0}) def test__ne__not_match_values(self): self.assertTrue(retworkx.random_layout(self.dag, seed=10244242) != {1: 2.0}) def test__ne__different_length(self): res = retworkx.random_layout(self.dag, seed=10244242) self.assertTrue(res != {1: 1.0, 2: 2.0}) def test__ne__invalid_type(self): self.assertTrue(retworkx.random_layout(self.dag, seed=10244242) != ["a", None]) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): retworkx.random_layout(self.dag, seed=10244242) > {1: 1.0} def test_deepcopy(self): positions = retworkx.random_layout(self.dag) positions_copy = copy.deepcopy(positions) self.assertEqual(positions_copy, positions) def test_pickle(self): pos = retworkx.random_layout(self.dag) pos_pickle = pickle.dumps(pos) pos_copy = pickle.loads(pos_pickle) self.assertEqual(pos, pos_copy) def test_str(self): res = retworkx.random_layout(self.dag, seed=10244242) self.assertEqual( "Pos2DMapping{0: [0.4883489113112722, 0.6545867364101975]}", str(res), ) def test_hash(self): res = retworkx.random_layout(self.dag, seed=10244242) hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_index_error(self): res = retworkx.random_layout(self.dag, seed=10244242) with self.assertRaises(IndexError): res[42] def test_keys(self): keys = retworkx.random_layout(self.dag, seed=10244242).keys() self.assertEqual([0], list(keys)) def test_values(self): values = retworkx.random_layout(self.dag, seed=10244242).values() expected = [[0.4883489113112722, 0.6545867364101975]] self.assertEqual(expected, list(values)) def test_items(self): items = retworkx.random_layout(self.dag, seed=10244242).items() self.assertEqual([(0, [0.4883489113112722, 0.6545867364101975])], list(items)) def test_iter(self): mapping_iter = iter(retworkx.random_layout(self.dag, seed=10244242)) output = list(mapping_iter) self.assertEqual(output, [0]) def test_contains(self): res = retworkx.random_layout(self.dag, seed=10244242) self.assertIn(0, res) def test_not_contains(self): res = retworkx.random_layout(self.dag, seed=10244242) self.assertNotIn(1, res) class TestEdgeIndices(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDiGraph() self.dag.add_node("a") self.dag.add_child(0, "b", "edge") def test__eq__match(self): res = self.dag.edge_index_map() self.assertTrue(res == {0: (0, 1, "edge")}) def test__eq__not_match_keys(self): res = self.dag.edge_index_map() self.assertFalse(res == {2: (0, 1, "edge")}) def test__eq__not_match_values(self): res = self.dag.edge_index_map() self.assertFalse(res == {0: (1, 2, "edge")}) self.assertFalse(res == {0: (0, 1, "not edge")}) def test__eq__different_length(self): res = self.dag.edge_index_map() self.assertFalse(res == {1: (0, 1, "edge"), 0: (0, 1, "double edge")}) def test_eq__same_type(self): self.assertEqual(self.dag.edge_index_map(), self.dag.edge_index_map()) def test__eq__invalid_type(self): res = self.dag.edge_index_map() self.assertFalse(res == {"a": ("a", "b", "c")}) def test__ne__match(self): res = self.dag.edge_index_map() self.assertFalse(res != {0: (0, 1, "edge")}) def test__ne__not_match(self): res = self.dag.edge_index_map() self.assertTrue(res, {2: (0, 1, "edge")}) def test__ne__not_match_values(self): res = self.dag.edge_index_map() self.assertTrue(res, {0: (0, 2, "edge")}) def test__ne__different_length(self): res = self.dag.edge_index_map() self.assertTrue(res != {1: (0, 1, "double edge"), 0: (0, 1, "edge")}) def test__ne__invalid_type(self): res = self.dag.edge_index_map() self.assertTrue(res != {"a": ("a", "b", "c")}) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): self.dag.edge_index_map() > {0: (0, 1, "edge")} def test_deepcopy(self): edge_map = self.dag.edge_index_map() edge_map_copy = copy.deepcopy(edge_map) self.assertEqual(edge_map_copy, edge_map) def test_pickle(self): edge_map = self.dag.edge_index_map() edge_map_pickle = pickle.dumps(edge_map) edge_map_copy = pickle.loads(edge_map_pickle) self.assertEqual(edge_map, edge_map_copy) def test_str(self): res = self.dag.edge_index_map() self.assertEqual( "EdgeIndexMap{0: (0, 1, edge)}", str(res), ) def test_hash(self): res = self.dag.edge_index_map() hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_index_error(self): res = self.dag.edge_index_map() with self.assertRaises(IndexError): res[42] def test_keys(self): keys = self.dag.edge_index_map().keys() self.assertEqual([0], list(keys)) def test_values(self): values = self.dag.edge_index_map().values() expected = [(0, 1, "edge")] self.assertEqual(expected, list(values)) def test_items(self): items = self.dag.edge_index_map().items() self.assertEqual([(0, (0, 1, "edge"))], list(items)) def test_iter(self): mapping_iter = iter(self.dag.edge_index_map()) output = list(mapping_iter) self.assertEqual(output, [0]) def test_contains(self): res = self.dag.edge_index_map() self.assertIn(0, res) def test_not_contains(self): res = self.dag.edge_index_map() self.assertNotIn(1, res) class TestAllPairsPathMapping(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() node_a = self.dag.add_node("a") self.dag.add_child(node_a, "b", "Edgy") self.fn = lambda _: 1.0 def test__eq__match(self): self.assertTrue( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) == {0: {1: [0, 1]}, 1: {}} ) def test__eq__not_match_keys(self): self.assertFalse( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) == {2: {2: [0, 1]}, 1: {}} ) def test__eq__not_match_values(self): self.assertFalse( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) == {0: {1: [0, 2]}, 1: {}} ) def test__eq__different_length(self): self.assertFalse( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) == {1: [0, 1], 2: [0, 2]} ) def test_eq__same_type(self): self.assertEqual( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn), retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn), ) def test__eq__invalid_type(self): self.assertFalse(retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) == {"a": []}) def test__eq__invalid_inner_type(self): self.assertFalse( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) == {0: {1: None}} ) def test__ne__match(self): self.assertFalse( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) != {0: {1: [0, 1]}, 1: {}} ) def test__ne__not_match(self): self.assertTrue( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) != {2: [0, 1]} ) def test__ne__not_match_values(self): self.assertTrue( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) != {1: [0, 2]} ) def test__ne__different_length(self): self.assertTrue( retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) != {1: [0, 1], 2: [0, 2]} ) def test__ne__invalid_type(self): self.assertTrue(retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) != {"a": {}}) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) > {1: [0, 2]} def test_deepcopy(self): paths = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) paths_copy = copy.deepcopy(paths) self.assertEqual(paths, paths_copy) def test_pickle(self): paths = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) paths_pickle = pickle.dumps(paths) paths_copy = pickle.loads(paths_pickle) self.assertEqual(paths, paths_copy) def test_str(self): res = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) # Since run in parallel the order is not deterministic expected_valid = [ "AllPairsPathMapping{1: PathMapping{}, 0: PathMapping{1: [0, 1]}}", "AllPairsPathMapping{0: PathMapping{1: [0, 1]}, 1: PathMapping{}}", ] self.assertIn(str(res), expected_valid) def test_hash(self): res = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_index_error(self): res = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) with self.assertRaises(IndexError): res[42] def test_keys(self): keys = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn).keys() self.assertEqual([0, 1], list(sorted(keys))) def test_values(self): values = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn).values() # Since run in parallel the order is not deterministic expected_valid = [[{1: [0, 1]}, {}], [{}, {1: [0, 1]}]] self.assertIn(list(values), expected_valid) def test_items(self): items = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn).items() # Since run in parallel the order is not deterministic expected_valid = [ [(0, {1: [0, 1]}), (1, {})], [(1, {}), (0, {1: [0, 1]})], ] self.assertIn(list(items), expected_valid) def test_iter(self): mapping_iter = iter(retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn)) output = list(sorted(mapping_iter)) self.assertEqual(output, [0, 1]) def test_contains(self): res = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) self.assertIn(1, res) def test_not_contains(self): res = retworkx.all_pairs_dijkstra_shortest_paths(self.dag, self.fn) self.assertNotIn(2, res) class TestAllPairsPathLengthMapping(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() node_a = self.dag.add_node("a") self.dag.add_child(node_a, "b", "Edgy") self.fn = lambda _: 1.0 def test__eq__match(self): self.assertTrue( retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) == {0: {1: 1.0}, 1: {}} ) def test__eq__not_match_keys(self): self.assertFalse( retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) == {1: {2: 1.0}} ) def test__eq__not_match_values(self): self.assertFalse( retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) == {0: {2: 2.0}} ) def test__eq__different_length(self): self.assertFalse( retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) == {0: {1: 1.0, 2: 2.0}} ) def test_eq__same_type(self): self.assertEqual( retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn), retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn), ) def test__eq__invalid_type(self): self.assertFalse(retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) == {"a": 2}) def test__eq__invalid_inner_type(self): self.assertFalse(retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) == {0: "a"}) def test__ne__match(self): self.assertFalse( retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) != {0: {1: 1.0}, 1: {}} ) def test__ne__not_match(self): self.assertTrue( retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) != {0: {2: 1.0}} ) def test__ne__not_match_values(self): self.assertTrue( retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) != {0: {1: 2.0}} ) def test__ne__different_length(self): self.assertTrue( retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) != {0: {1: 1.0}, 2: {1: 2.0}} ) def test__ne__invalid_type(self): self.assertTrue(retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) != {1: []}) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) > {1: 1.0} def test_deepcopy(self): paths = retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) paths_copy = copy.deepcopy(paths) self.assertEqual(paths, paths_copy) def test_pickle(self): paths = retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) paths_pickle = pickle.dumps(paths) paths_copy = pickle.loads(paths_pickle) self.assertEqual(paths, paths_copy) def test_str(self): res = retworkx.all_pairs_dijkstra_path_lengths(self.dag, lambda _: 3.14) # Since all_pairs_dijkstra_path_lengths() is parallel the order of the # output is non-determinisitic valid_values = [ "AllPairsPathLengthMapping{1: PathLengthMapping{}, " "0: PathLengthMapping{1: 3.14}}", "AllPairsPathLengthMapping{" "0: PathLengthMapping{1: 3.14}, " "1: PathLengthMapping{}}", ] self.assertIn(str(res), valid_values) def test_hash(self): res = retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_index_error(self): res = retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) with self.assertRaises(IndexError): res[42] def test_keys(self): keys = retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn).keys() self.assertEqual([0, 1], list(sorted((keys)))) def test_values(self): values = retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn).values() # Since run in parallel the order is not deterministic valid_expected = [[{}, {1: 1.0}], [{1: 1.0}, {}]] self.assertIn(list(values), valid_expected) def test_items(self): items = retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn).items() # Since run in parallel the order is not deterministic valid_expected = [[(0, {1: 1.0}), (1, {})], [(1, {}), (0, {1: 1.0})]] self.assertIn(list(items), valid_expected) def test_iter(self): mapping_iter = iter(retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn)) output = list(sorted(mapping_iter)) self.assertEqual(output, [0, 1]) def test_contains(self): res = retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) self.assertIn(0, res) def test_not_contains(self): res = retworkx.all_pairs_dijkstra_path_lengths(self.dag, self.fn) self.assertNotIn(2, res) class TestNodeMap(unittest.TestCase): def setUp(self): self.dag = retworkx.PyDAG() self.dag.add_node("a") self.in_dag = retworkx.generators.directed_path_graph(1) def test__eq__match(self): self.assertTrue( self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) == {0: 1} ) def test__eq__not_match_keys(self): self.assertFalse( self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) == {2: 1} ) def test__eq__not_match_values(self): self.assertFalse( self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) == {0: 2} ) def test__eq__different_length(self): self.assertFalse( self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) == {0: 1, 1: 2} ) def test_eq__same_type(self): res = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) self.assertEqual(res, res) def test__ne__match(self): self.assertFalse( self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) != {0: 1} ) def test__ne__not_match(self): self.assertTrue( self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) != {2: 2} ) def test__ne__not_match_values(self): self.assertTrue( self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) != {0: 2} ) def test__ne__different_length(self): self.assertTrue( self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) != {0: 1, 1: 2} ) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) > {1: 2} def test__len__(self): in_dag = retworkx.generators.directed_grid_graph(5, 5) node_map = self.dag.substitute_node_with_subgraph(0, in_dag, lambda *args: None) self.assertEqual(25, len(node_map)) def test_deepcopy(self): node_map = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) node_map_copy = copy.deepcopy(node_map) self.assertEqual(node_map, node_map_copy) def test_pickle(self): node_map = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) node_map_pickle = pickle.dumps(node_map) node_map_copy = pickle.loads(node_map_pickle) self.assertEqual(node_map, node_map_copy) def test_str(self): res = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) self.assertEqual("NodeMap{0: 1}", str(res)) def test_hash(self): res = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) hash_res = hash(res) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(res)) def test_index_error(self): res = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) with self.assertRaises(IndexError): res[42] def test_keys(self): keys = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None).keys() self.assertEqual([0], list(keys)) def test_values(self): values = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None).values() self.assertEqual([1], list(values)) def test_items(self): items = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None).items() self.assertEqual([(0, 1)], list(items)) def test_iter(self): mapping_iter = iter( self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) ) output = list(mapping_iter) self.assertEqual(output, [0]) def test_contains(self): res = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) self.assertIn(0, res) def test_not_contains(self): res = self.dag.substitute_node_with_subgraph(0, self.in_dag, lambda *args: None) self.assertNotIn(2, res) def test_iter_stable_for_same_obj(self): graph = retworkx.PyDiGraph() graph.add_node(0) in_graph = retworkx.generators.directed_path_graph(5) res = self.dag.substitute_node_with_subgraph(0, in_graph, lambda *args: None) first_iter = list(iter(res)) second_iter = list(iter(res)) third_iter = list(iter(res)) self.assertEqual(first_iter, second_iter) self.assertEqual(first_iter, third_iter) class TestChainsComparisons(unittest.TestCase): def setUp(self): self.graph = retworkx.generators.cycle_graph(3) self.chains = retworkx.chain_decomposition(self.graph) def test__eq__match(self): self.assertTrue(self.chains == [[(0, 2), (2, 1), (1, 0)]]) def test__eq__not_match(self): self.assertFalse(self.chains == [[(0, 2), (2, 1), (2, 0)]]) def test__eq__different_length(self): self.assertFalse(self.chains == [[(0, 2)]]) def test__eq__invalid_type(self): with self.assertRaises(TypeError): self.chains == [0] def test__ne__match(self): self.assertFalse(self.chains != [[(0, 2), (2, 1), (1, 0)]]) def test__ne__not_match(self): self.assertTrue(self.chains != [[(0, 2), (2, 1), (2, 0)]]) def test__ne__different_length(self): self.assertTrue(self.chains != [[(0, 2)]]) def test__ne__invalid_type(self): with self.assertRaises(TypeError): self.chains != [0] def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): self.chains > [[(0, 2)]] def test_deepcopy(self): chains_copy = copy.deepcopy(self.chains) self.assertEqual(self.chains, chains_copy) def test_pickle(self): chains_pickle = pickle.dumps(self.chains) chains_copy = pickle.loads(chains_pickle) self.assertEqual(self.chains, chains_copy) def test_str(self): self.assertEqual("Chains[EdgeList[(0, 2), (2, 1), (1, 0)]]", str(self.chains)) def test_hash(self): hash_res = hash(self.chains) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(self.chains)) class TestProductNodeMap(unittest.TestCase): def setUp(self): self.first = retworkx.PyGraph() self.first.add_node("a0") self.first.add_node("a1") self.second = retworkx.PyGraph() self.second.add_node("b") _, self.node_map = retworkx.graph_cartesian_product(self.first, self.second) def test__eq__match(self): self.assertTrue(self.node_map == {(0, 0): 0, (1, 0): 1}) def test__eq__not_match_keys(self): self.assertFalse(self.node_map == {(0, 0): 0, (2, 0): 1}) def test__eq__not_match_values(self): self.assertFalse(self.node_map == {(0, 0): 0, (1, 0): 2}) def test__eq__different_length(self): self.assertFalse(self.node_map == {(0, 0): 0}) def test_eq__same_type(self): _, res = retworkx.graph_cartesian_product(self.first, self.second) self.assertEqual(self.node_map, res) def test__ne__match(self): self.assertFalse(self.node_map != {(0, 0): 0, (1, 0): 1}) def test__ne__not_match(self): self.assertTrue(self.node_map != {(0, 0): 0, (2, 0): 1}) def test__ne__not_match_values(self): self.assertTrue(self.node_map != {(0, 0): 0, (1, 0): 2}) def test__ne__different_length(self): self.assertTrue(self.node_map != {(0, 0): 0}) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): self.node_map > {1: 2} def test__len__(self): self.assertEqual(2, len(self.node_map)) def test_deepcopy(self): node_map_copy = copy.deepcopy(self.node_map) self.assertEqual(self.node_map, node_map_copy) def test_pickle(self): node_map_pickle = pickle.dumps(self.node_map) node_map_copy = pickle.loads(node_map_pickle) self.assertEqual(self.node_map, node_map_copy) def test_str(self): valid_str_output = [ "ProductNodeMap{(0, 0): 0, (1, 0): 1}", "ProductNodeMap{(1, 0): 1, (0, 0): 0}", ] self.assertTrue(str(self.node_map) in valid_str_output) def test_hash(self): hash_res = hash(self.node_map) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(self.node_map)) def test_index_error(self): with self.assertRaises(IndexError): self.node_map[(1, 1)] def test_keys(self): keys = self.node_map.keys() self.assertEqual(set([(0, 0), (1, 0)]), set(keys)) def test_values(self): values = self.node_map.values() self.assertEqual(set([0, 1]), set(values)) def test_items(self): items = self.node_map.items() self.assertEqual(set([((0, 0), 0), ((1, 0), 1)]), set(items)) def test_iter(self): mapping_iter = iter(self.node_map) output = set(mapping_iter) self.assertEqual(output, set([(0, 0), (1, 0)])) def test_contains(self): self.assertIn((0, 0), self.node_map) def test_not_contains(self): self.assertNotIn((1, 1), self.node_map) class TestBiconnectedComponentsMap(unittest.TestCase): def setUp(self): self.graph = retworkx.generators.path_graph(3) self.bicon_map = retworkx.biconnected_components(self.graph) def test__eq__match(self): self.assertTrue(self.bicon_map == {(0, 1): 1, (1, 2): 0}) def test__eq__not_match_keys(self): self.assertFalse(self.bicon_map == {(0, 0): 1, (2, 0): 0}) def test__eq__not_match_values(self): self.assertFalse(self.bicon_map == {(0, 1): 2, (1, 2): 0}) def test__eq__different_length(self): self.assertFalse(self.bicon_map == {(0, 1): 1}) def test_eq__same_type(self): res = retworkx.biconnected_components(self.graph) self.assertEqual(self.bicon_map, res) def test__ne__match(self): self.assertFalse(self.bicon_map != {(0, 1): 1, (1, 2): 0}) def test__ne__not_match(self): self.assertTrue(self.bicon_map != {(0, 2): 1, (1, 2): 0}) def test__ne__not_match_values(self): self.assertTrue(self.bicon_map != {(0, 1): 0, (1, 2): 0}) def test__ne__different_length(self): self.assertTrue(self.bicon_map != {(0, 1): 1}) def test__gt__not_implemented(self): with self.assertRaises(NotImplementedError): self.bicon_map > {1: 2} def test__len__(self): self.assertEqual(2, len(self.bicon_map)) def test_deepcopy(self): bicon_map_copy = copy.deepcopy(self.bicon_map) self.assertEqual(self.bicon_map, bicon_map_copy) def test_pickle(self): bicon_map_pickle = pickle.dumps(self.bicon_map) bicon_map_copy = pickle.loads(bicon_map_pickle) self.assertEqual(self.bicon_map, bicon_map_copy) def test_str(self): valid_str_output = [ "BiconnectedComponents{(0, 1): 1, (1, 2): 0}", "BiconnectedComponents{(1, 2): 0, (0, 1): 1}", ] self.assertTrue(str(self.bicon_map) in valid_str_output) def test_hash(self): hash_res = hash(self.bicon_map) self.assertIsInstance(hash_res, int) # Assert hash is stable self.assertEqual(hash_res, hash(self.bicon_map)) def test_index_error(self): with self.assertRaises(IndexError): self.bicon_map[(1, 1)] def test_keys(self): keys = self.bicon_map.keys() self.assertEqual(set([(0, 1), (1, 2)]), set(keys)) def test_values(self): values = self.bicon_map.values() self.assertEqual(set([0, 1]), set(values)) def test_items(self): items = self.bicon_map.items() self.assertEqual(set([((0, 1), 1), ((1, 2), 0)]), set(items)) def test_iter(self): mapping_iter = iter(self.bicon_map) output = set(mapping_iter) self.assertEqual(output, set([(0, 1), (1, 2)])) def test_contains(self): self.assertIn((0, 1), self.bicon_map) def test_not_contains(self): self.assertNotIn((0, 2), self.bicon_map)
ericAndrade/IAL-002
src/aula1/CelsiusToFarenheit.java
package aula1; import java.util.Scanner; public class CelsiusToFarenheit { public static void main(String[] args) { int celcius = 0; double farenheit = 0.0; Scanner scan = new Scanner(System.in); System.out.print("\nDigite em graus:>"); celcius = scan.nextInt(); farenheit = celcius * (9/5.0) + 32; System.out.println(celcius +"ºC são equivalentes a "+ farenheit +"ºF"); scan.close(); } }
jroeder/ninja-superbowl
src/main/java/entity/BowlModJoined.java
<reponame>jroeder/ninja-superbowl /** * Copyright (C) 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 entity; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.validation.constraints.NotNull; /** * Insert class description here... * * @author mbsusr01 * * ninja-superbowl 27.04.2017 mbsusr01 */ @Entity public class BowlModJoined implements Serializable { /** * Unique serial version identifier. */ private static final long serialVersionUID = -7808484025117225025L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "BOWLMODJOINED_ID", nullable = false) private Long bowlModJoinedId; @NotNull @Column(name = "BOWLMODJOINED_VERSION", nullable = false) private Integer bowlModJoinedVersion; /** * the technical identifier of a {@code BowlMod} */ @Column(name = "BOWLMODJOINED_BOWLMOD_ID", nullable = true) private Long bowlModJoinedBowlModId; /** * the version of a {@code BowlMod} */ @Column(name = "BOWLMODJOINED_BOWLMOD_VERSION", nullable = true) private Integer bowlModJoinedBowlModVersion; /** * the {@code Bowl} instance */ @Column(name = "BOWLMODJOINED_BOWL_ID", nullable = true) private Bowl bowlModJoinedBowl; /** * the {@code BowlModStep} instance */ @Column(name = "BOWLMODJOINED_BOWLMODSTEP_ID", nullable = true) private BowlModStep bowlModJoinedBowlModStep; /** * the date */ @Column(name = "BOWLMODJOINED_DATE", nullable = true) private Date bowlModJoinedDate; /** * the diameter */ @Column(name = "BOWLMODJOINED_DIAMETER", nullable = true) private BigDecimal bowlModJoinedDiameter; /** * the height */ @Column(name = "BOWLMODJOINED_HEIGHT", nullable = true) private BigDecimal bowlModJoinedHeight; /** * the minimum wallthickness */ @Column(name = "BOWLMODJOINED_WALLTHICKNESS_MIN", nullable = true) private BigDecimal bowlModJoinedWallthicknessMin; /** * the maximum wallthickness */ @Column(name = "BOWLMODJOINED_WALLTHICKNESS_MAX", nullable = true) private BigDecimal bowlModJoinedWallthicknessMax; /** * the granulation */ @Column(name = "BOWLMODJOINED_GRANULATION", nullable = true) private Integer bowlModJoinedGranulation; /** * the tap */ @Column(name = "BOWLMODJOINED_TAP", nullable = true) private Integer bowlModJoinedTap; /** * the recess */ @Column(name = "BOWLMODJOINED_RECESS", nullable = true) private Integer bowlModJoinedRecess; /** * the version */ @Column(name = "BOWLMODJOINED_SURFACE", nullable = true) private String bowlModJoinedSurface; /** * the comment */ @Column(name = "BOWLMODJOINED_COMMENT", nullable = true) private String bowlModJoinedComment; /** * the technical identifier */ @Column(name = "BOWLMODJOINED_ITEM_ID", nullable = true) private Long bowlModJoinedItemId; /** * the version */ @Column(name = "BOWLMODJOINED_ITEM_VERSION", nullable = true) private Integer bowlModJoinedItemVersion; /** * the {@code BowlMod} instance */ @Column(name = "BOWLMODJOINED_ITEM_BOWLMOD_ID", nullable = true) private BowlMod bowlModJoinedItemBowlMod; /** * the text */ @Column(name = "BOWLMODJOINED_ITEM_TEXT", nullable = true) private String bowlModJoinedItemText; /** * the date */ @Column(name = "BOWLMODJOINED_ITEM_DATE", nullable = true) private Date bowlModJoinedItemDate; /** * the diameter */ @Column(name = "BOWLMODJOINED_ITEM_WEIGHT", nullable = true) private BigDecimal bowlModJoinedItemWeight; /** * the height */ @NotNull @Column(name = "BOWLMODJOINED_ITEM_MOISTURE", nullable = true) private BigDecimal bowlModJoinedItemMoisture; /** * Constructor. */ public BowlModJoined() { super(); } /** * Constructor. * * @param bowlModJoinedId * the identifier * @param bowlModJoinedVersion * the version * @param bowlModJoinedBowlModId * the BowlMod identifier * @param bowlModJoinedBowlModVersion * the BowlMod version * @param bowlModJoinedBowl * the Bowl reference * @param bowlModJoinedBowlModStep * the BowlModStep reference * @param bowlModJoinedDate * the date * @param bowlModJoinedDiameter * the diameter * @param bowlModJoinedHeight * the height * @param bowlModJoinedWallthicknessMin * the wall thickness min * @param bowlModJoinedWallthicknessMax * the wall thickness max * @param bowlModJoinedGranulation * the granulation * @param bowlModJoinedTap * the tap * @param bowlModJoinedRecess * the recess * @param bowlModJoinedSurface * the surface * @param bowlModJoinedComment * the comment * @param bowlModJoinedItemId * the BowlModItem identifier * @param bowlModJoinedItemVersion * the BowlModItem version * @param bowlModJoinedItemBowlMod * the BowlMod reference * @param bowlModJoinedItemText * the BowlModItem text * @param bowlModJoinedItemDate * the BowlModItem date * @param bowlModJoinedItemWeight * the BowlModItem weight * @param bowlModJoinedItemMoisture * the BowlModItem moisture */ public BowlModJoined(Long bowlModJoinedId, Integer bowlModJoinedVersion, Long bowlModJoinedBowlModId, Integer bowlModJoinedBowlModVersion, Bowl bowlModJoinedBowl, BowlModStep bowlModJoinedBowlModStep, Date bowlModJoinedDate, BigDecimal bowlModJoinedDiameter, BigDecimal bowlModJoinedHeight, BigDecimal bowlModJoinedWallthicknessMin, BigDecimal bowlModJoinedWallthicknessMax, Integer bowlModJoinedGranulation, Integer bowlModJoinedTap, Integer bowlModJoinedRecess, String bowlModJoinedSurface, String bowlModJoinedComment, Long bowlModJoinedItemId, Integer bowlModJoinedItemVersion, BowlMod bowlModJoinedItemBowlMod, String bowlModJoinedItemText, Date bowlModJoinedItemDate, BigDecimal bowlModJoinedItemWeight, BigDecimal bowlModJoinedItemMoisture) { super(); this.bowlModJoinedId = bowlModJoinedId; this.bowlModJoinedVersion = bowlModJoinedVersion; this.bowlModJoinedBowlModId = bowlModJoinedBowlModId; this.bowlModJoinedBowlModVersion = bowlModJoinedBowlModVersion; this.bowlModJoinedBowl = bowlModJoinedBowl; this.bowlModJoinedBowlModStep = bowlModJoinedBowlModStep; this.bowlModJoinedDate = bowlModJoinedDate; this.bowlModJoinedDiameter = bowlModJoinedDiameter; this.bowlModJoinedHeight = bowlModJoinedHeight; this.bowlModJoinedWallthicknessMin = bowlModJoinedWallthicknessMin; this.bowlModJoinedWallthicknessMax = bowlModJoinedWallthicknessMax; this.bowlModJoinedGranulation = bowlModJoinedGranulation; this.bowlModJoinedTap = bowlModJoinedTap; this.bowlModJoinedRecess = bowlModJoinedRecess; this.bowlModJoinedSurface = bowlModJoinedSurface; this.bowlModJoinedComment = bowlModJoinedComment; this.bowlModJoinedItemId = bowlModJoinedItemId; this.bowlModJoinedItemVersion = bowlModJoinedItemVersion; this.bowlModJoinedItemBowlMod = bowlModJoinedItemBowlMod; this.bowlModJoinedItemText = bowlModJoinedItemText; this.bowlModJoinedItemDate = bowlModJoinedItemDate; this.bowlModJoinedItemWeight = bowlModJoinedItemWeight; this.bowlModJoinedItemMoisture = bowlModJoinedItemMoisture; } /** * @return the bowlModJoinedId */ public Long getBowlModJoinedId() { return bowlModJoinedId; } /** * @param bowlModJoinedId * the bowlModJoinedId to set */ public void setBowlModJoinedId(Long bowlModJoinedId) { this.bowlModJoinedId = bowlModJoinedId; } /** * @return the bowlModJoinedVersion */ public Integer getBowlModJoinedVersion() { return bowlModJoinedVersion; } /** * @param bowlModJoinedVersion * the bowlModJoinedVersion to set */ public void setBowlModJoinedVersion(Integer bowlModJoinedVersion) { this.bowlModJoinedVersion = bowlModJoinedVersion; } /** * @return the bowlModJoinedBowlModId */ public Long getBowlModJoinedBowlModId() { return bowlModJoinedBowlModId; } /** * @param bowlModJoinedBowlModId * the bowlModJoinedBowlModId to set */ public void setBowlModJoinedBowlModId(Long bowlModJoinedBowlModId) { this.bowlModJoinedBowlModId = bowlModJoinedBowlModId; } /** * @return the bowlModJoinedBowlModVersion */ public Integer getBowlModJoinedBowlModVersion() { return bowlModJoinedBowlModVersion; } /** * @param bowlModJoinedBowlModVersion * the bowlModJoinedBowlModVersion to set */ public void setBowlModJoinedBowlModVersion(Integer bowlModJoinedBowlModVersion) { this.bowlModJoinedBowlModVersion = bowlModJoinedBowlModVersion; } /** * @return the bowlModJoinedBowl */ public Bowl getBowlModJoinedBowl() { return bowlModJoinedBowl; } /** * @param bowlModJoinedBowl * the bowlModJoinedBowl to set */ public void setBowlModJoinedBowl(Bowl bowlModJoinedBowl) { this.bowlModJoinedBowl = bowlModJoinedBowl; } /** * @return the bowlModJoinedBowlModStep */ public BowlModStep getBowlModJoinedBowlModStep() { return bowlModJoinedBowlModStep; } /** * @param bowlModJoinedBowlModStep * the bowlModJoinedBowlModStep to set */ public void setBowlModJoinedBowlModStep(BowlModStep bowlModJoinedBowlModStep) { this.bowlModJoinedBowlModStep = bowlModJoinedBowlModStep; } /** * @return the bowlModJoinedDate */ public Date getBowlModJoinedDate() { return bowlModJoinedDate; } /** * @param bowlModJoinedDate * the bowlModJoinedDate to set */ public void setBowlModJoinedDate(Date bowlModJoinedDate) { this.bowlModJoinedDate = bowlModJoinedDate; } /** * @return the bowlModJoinedDiameter */ public BigDecimal getBowlModJoinedDiameter() { return bowlModJoinedDiameter; } /** * @param bowlModJoinedDiameter * the bowlModJoinedDiameter to set */ public void setBowlModJoinedDiameter(BigDecimal bowlModJoinedDiameter) { this.bowlModJoinedDiameter = bowlModJoinedDiameter; } /** * @return the bowlModJoinedHeight */ public BigDecimal getBowlModJoinedHeight() { return bowlModJoinedHeight; } /** * @param bowlModJoinedHeight * the bowlModJoinedHeight to set */ public void setBowlModJoinedHeight(BigDecimal bowlModJoinedHeight) { this.bowlModJoinedHeight = bowlModJoinedHeight; } /** * @return the bowlModJoinedWallthicknessMin */ public BigDecimal getBowlModJoinedWallthicknessMin() { return bowlModJoinedWallthicknessMin; } /** * @param bowlModJoinedWallthicknessMin * the bowlModJoinedWallthicknessMin to set */ public void setBowlModJoinedWallthicknessMin(BigDecimal bowlModJoinedWallthicknessMin) { this.bowlModJoinedWallthicknessMin = bowlModJoinedWallthicknessMin; } /** * @return the bowlModJoinedWallthicknessMax */ public BigDecimal getBowlModJoinedWallthicknessMax() { return bowlModJoinedWallthicknessMax; } /** * @param bowlModJoinedWallthicknessMax * the bowlModJoinedWallthicknessMax to set */ public void setBowlModJoinedWallthicknessMax(BigDecimal bowlModJoinedWallthicknessMax) { this.bowlModJoinedWallthicknessMax = bowlModJoinedWallthicknessMax; } /** * @return the bowlModJoinedGranulation */ public Integer getBowlModJoinedGranulation() { return bowlModJoinedGranulation; } /** * @param bowlModJoinedGranulation * the bowlModJoinedGranulation to set */ public void setBowlModJoinedGranulation(Integer bowlModJoinedGranulation) { this.bowlModJoinedGranulation = bowlModJoinedGranulation; } /** * @return the bowlModJoinedTap */ public Integer getBowlModJoinedTap() { return bowlModJoinedTap; } /** * @param bowlModJoinedTap * the bowlModJoinedTap to set */ public void setBowlModJoinedTap(Integer bowlModJoinedTap) { this.bowlModJoinedTap = bowlModJoinedTap; } /** * @return the bowlModJoinedRecess */ public Integer getBowlModJoinedRecess() { return bowlModJoinedRecess; } /** * @param bowlModJoinedRecess * the bowlModJoinedRecess to set */ public void setBowlModJoinedRecess(Integer bowlModJoinedRecess) { this.bowlModJoinedRecess = bowlModJoinedRecess; } /** * @return the bowlModJoinedSurface */ public String getBowlModJoinedSurface() { return bowlModJoinedSurface; } /** * @param bowlModJoinedSurface * the bowlModJoinedSurface to set */ public void setBowlModJoinedSurface(String bowlModJoinedSurface) { this.bowlModJoinedSurface = bowlModJoinedSurface; } /** * @return the bowlModJoinedComment */ public String getBowlModJoinedComment() { return bowlModJoinedComment; } /** * @param bowlModJoinedComment * the bowlModJoinedComment to set */ public void setBowlModJoinedComment(String bowlModJoinedComment) { this.bowlModJoinedComment = bowlModJoinedComment; } /** * @return the bowlModJoinedItemId */ public Long getBowlModJoinedItemId() { return bowlModJoinedItemId; } /** * @param bowlModJoinedItemId * the bowlModJoinedItemId to set */ public void setBowlModJoinedItemId(Long bowlModJoinedItemId) { this.bowlModJoinedItemId = bowlModJoinedItemId; } /** * @return the bowlModJoinedItemVersion */ public Integer getBowlModJoinedItemVersion() { return bowlModJoinedItemVersion; } /** * @param bowlModJoinedItemVersion * the bowlModJoinedItemVersion to set */ public void setBowlModJoinedItemVersion(Integer bowlModJoinedItemVersion) { this.bowlModJoinedItemVersion = bowlModJoinedItemVersion; } /** * @return the bowlModJoinedItemBowlMod */ public BowlMod getBowlModJoinedItemBowlMod() { return bowlModJoinedItemBowlMod; } /** * @param bowlModJoinedItemBowlMod * the bowlModJoinedItemBowlMod to set */ public void setBowlModJoinedItemBowlMod(BowlMod bowlModJoinedItemBowlMod) { this.bowlModJoinedItemBowlMod = bowlModJoinedItemBowlMod; } /** * @return the bowlModJoinedItemText */ public String getBowlModJoinedItemText() { return bowlModJoinedItemText; } /** * @param bowlModJoinedItemText * the bowlModJoinedItemText to set */ public void setBowlModJoinedItemText(String bowlModJoinedItemText) { this.bowlModJoinedItemText = bowlModJoinedItemText; } /** * @return the bowlModJoinedItemDate */ public Date getBowlModJoinedItemDate() { return bowlModJoinedItemDate; } /** * @param bowlModJoinedItemDate * the bowlModJoinedItemDate to set */ public void setBowlModJoinedItemDate(Date bowlModJoinedItemDate) { this.bowlModJoinedItemDate = bowlModJoinedItemDate; } /** * @return the bowlModJoinedItemWeight */ public BigDecimal getBowlModJoinedItemWeight() { return bowlModJoinedItemWeight; } /** * @param bowlModJoinedItemWeight * the bowlModJoinedItemWeight to set */ public void setBowlModJoinedItemWeight(BigDecimal bowlModJoinedItemWeight) { this.bowlModJoinedItemWeight = bowlModJoinedItemWeight; } /** * @return the bowlModJoinedItemMoisture */ public BigDecimal getBowlModJoinedItemMoisture() { return bowlModJoinedItemMoisture; } /** * @param bowlModJoinedItemMoisture * the bowlModJoinedItemMoisture to set */ public void setBowlModJoinedItemMoisture(BigDecimal bowlModJoinedItemMoisture) { this.bowlModJoinedItemMoisture = bowlModJoinedItemMoisture; } }
VivXwan/LeetCodeSolutions
Java/KthDistinctStringinanArray.java
<filename>Java/KthDistinctStringinanArray.java<gh_stars>100-1000 /* Source: https://leetcode.com/problems/kth-distinct-string-in-an-array/ Time: O(n), where n is the size of the given string array(arr) Space: O(n), we need a hashmap for storing the boolean values of each string in the given string array(arr) */ class Solution { public String kthDistinct(String[] arr, int k) { Map<String, Boolean> map = new HashMap<>(); for(String str : arr) { map.put(str, map.containsKey(str) ? false : true); } for(String str : arr) { if(map.get(str)) { if(--k == 0) { return str; } } } return ""; } }
milin/importanize
tests/test_utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import io import pytest # type: ignore from importanize.utils import ( OpenBytesIO, OpenStringIO, StdPath, add_prefix_to_text, force_bytes, force_text, generate_diff, is_piped, is_site_package, is_std_lib, largest_prefix, list_set, remove_largest_whitespace_prefix, takeafter, ) def test_is_std_lib() -> None: assert not is_std_lib("") assert not is_std_lib("foo") assert not is_std_lib("pytest") stdlib_modules = ( "argparse", "codecs", "collections", "copy", "csv", "datetime", "decimal", "fileinput", "fnmatch", "functools", "glob", "gzip", "hashlib", "hmac", "importlib", "io", "itertools", "json", "logging", "math", "numbers", "operator", "optparse", "os", "pickle", "pprint", "random", "re", "shelve", "shutil", "socket", "sqlite3", "ssl", "stat", "string", "struct", "subprocess", "sys", "typing", "sysconfig", "tempfile", "time", "timeit", "trace", "traceback", "unittest", "uuid", "xml", "zlib", ) for module in stdlib_modules: assert is_std_lib(module) def test_is_site_package() -> None: assert not is_site_package("") assert not is_site_package("foo") stdlib_modules = ("argparse", "codecs") for module in stdlib_modules: assert not is_site_package(module) # these packages come from requirements-dev.txt site_packages_modules = ("pytest", "tox") for module in site_packages_modules: assert is_site_package(module) def test_force_text() -> None: assert force_text(b"foo") == "foo" assert force_text("foo") == "foo" def test_force_bytes() -> None: assert force_bytes("foo") == b"foo" assert force_bytes(b"foo") == b"foo" def test_takeafter() -> None: assert list(takeafter(lambda i: i.strip(), [" ", "\t", "foo", " ", "bar"])) == [ "foo", " ", "bar", ] def test_list_set() -> None: assert list_set(["hello", "world", "hello", "mars"]) == ["hello", "world", "mars"] def test_largest_prefix() -> None: assert largest_prefix([" hello", " world"]) == " " def test_remove_largest_prefix_from_text() -> None: assert remove_largest_whitespace_prefix(" hello\n world\n") == ( "hello\nworld\n", " ", ) assert remove_largest_whitespace_prefix("hello\nworld\n") == ("hello\nworld\n", "") def test_add_prefix_to_text() -> None: assert add_prefix_to_text("hello\nworld\n", " ") == " hello\n world\n" assert add_prefix_to_text("hello\nworld\n", "") == "hello\nworld\n" def test_generate_diff() -> None: assert generate_diff( "hello\nworld", "hello\nmars", "test.py", color=False ) == "\n".join( [ # preserve multiline "--- original/test.py", "+++ importanized/test.py", "@@ -1,2 +1,2 @@", " hello", "-world", "+mars", ] ) def test_is_piped() -> None: assert is_piped(io.StringIO()) def test_open_bytes_io() -> None: fid = OpenBytesIO(b"hello") assert fid.read() == b"hello" assert fid.read() == b"hello" fid.close() assert fid.read() == b"hello" def test_open_string_io() -> None: fid = OpenStringIO("hello") assert fid.read() == "hello" assert fid.read() == "hello" fid.close() assert fid.read() == "hello" class TestStdPath: def test_stdin(self) -> None: p = StdPath("-").with_streams( stdin=io.BytesIO(b" hello\n world\n"), stdout=io.BytesIO() ) assert p.is_file() assert p.read_text() == "hello\nworld\n" p.write_text("hello\nmars\n") p.stdout.seek(0) assert p.stdout.read() == b" hello\n mars\n" def test_file(self) -> None: p = StdPath("test").with_streams( filein=OpenBytesIO(b"hello world"), fileout=OpenBytesIO() ) assert p.read_text() == "hello world" p.write_text("hello mars") assert p.fileout.read() == b"hello mars" def test_pep263(self) -> None: p = StdPath("-").with_streams( stdin=io.BytesIO("# -*- coding: ascii -*-\nпривет".encode("utf-8")), stdout=io.BytesIO(), ) assert p.is_file() with pytest.raises(UnicodeDecodeError): assert p.read_text()
sirrahd/teachermaps
app/controllers/resources_controller.rb
<reponame>sirrahd/teachermaps<filename>app/controllers/resources_controller.rb class ResourcesController < ApplicationController include SessionsHelper # before_filter :require_session def index require_session @user = User.find_by_account_name params[:user_id] unless @user Rails.logger.info 'Could not locate user' return redirect_to page404_url end @progress = @user.show_progress @is_admin = (signed_in? and @user.is_admin?(@current_user)) @resources = @user.resources.paginate(page: params[:page]).order('id DESC') @num_of_pages = @user.total_resources_count / 20 + 2 @filter_course_types = ResourceType.where( id: @user.resources.collect { |resource| resource.resource_type.id } ) @filter_course_grades = CourseGrade.where( id: @user.resources.collect { |resource| resource.course_grades.collect(&:id) } ) @filter_course_subjects = CourseSubject.where( id: @user.resources.collect { |resource| resource.course_subjects.collect(&:id) } ) end def show require_session Rails.logger.info(params) @resource = Resource.find_by_id_and_user_id params[:id], @current_user.id unless @resource return redirect_to resources_url, flash: { error: t('resources.does_not_exist') } end resource_link = @resource.open_link() # Gracefully handle nil links if !resource_link redirect_to @current_user, :flash => { :error => t('resources.resource_link_error', :title => @resource.title) } else redirect_to resource_link end end def edit require_session @resource = Resource.find_by_id_and_user_id params[:id], @current_user.id return render nothing: true, status: 404 unless @resource render partial: "resources/edit" end def update require_session Rails.logger.info(params) @resource = Resource.find_by_id_and_user_id params[:id], @current_user.id return render nothing: true, status: 404 unless @resource @resource.title = params[:resource][:title] if @resource.class.name == LinkResource::TYPE @resource.link = params[:resource][:link] end # Convert grade/subject primary keys to objects if params[:resource].has_key?('course_subjects') @resource.course_subjects = params[:resource][:course_subjects].present? ? CourseSubject.find_all_by_id(params[:resource][:course_subjects]) : [] else @resource.course_subjects = [] end if params[:resource].has_key?('course_grades') @resource.course_grades = params[:resource][:course_grades].present? ? CourseGrade.find_all_by_id(params[:resource][:course_grades]) : [] else @resource.course_grades = [] end respond_to do |format| if @resource.save #@resources = Resource.where user_id: @current_user.id # @current_user.update_attributes resources: Resource.where( user_id: @current_user.id ) # @current_user = User.find @current_user.id @resources = @current_user.resources format.html { render partial: 'resources/table_resources' } else format.html { render partial: 'shared/error_messages', :locals => { :object => @resource }, :status => 500 } end end end def destroy require_session @resource = Resource.find_by_id_and_user_id params[:id], @current_user.id unless @resource Rails.logger.info("404 Error, Resource not found #{@resource.errors.inspect}") return redirect_to resources_url, :flash => { :error => t('resources.does_not_exist') } end # Cache for flash notification deleted_title = @resource.title # Google Resource if @current_user.has_google_account? and @resource.class.name == GoogleResource::TYPE google_account = @current_user.google_account Rails.logger.info("Valid Google Session") result = google_account.delete_file(@resource.file_id) Rails.logger.info("Successful Deletion?: #{result.inspect}") else Rails.logger.info("User does not have a synced Google Account or File is not a GoogleResource") end # DropBox Resources if @current_user.has_drop_box_account? and @resource.class.name == DropBoxResource::TYPE drop_box_account = @current_user.drop_box_account result = drop_box_account.delete_file(@resource.path) Rails.logger.info("Successful Deletion?: #{result}") Rails.logger.info("Valid DropBox Session") else Rails.logger.info("User does not have a synced DropBox Account or File is not a DropBox Resource") end # Removing resource @resource.destroy respond_to do |format| if @resource.destroyed? format.html { redirect_to user_path(@current_user, anchor: 'resources'), :flash => { :success => t('resources.deleted_file', :title => deleted_title) } } else Rails.logger.info("Resource deletion failure!!! #{@resource.errors.inspect}") format.html { render json: @resource.errors, status: :unprocessable_entity } end end end def filter require_session Rails.logger.info(params) filter = {} #@resources = Resource.where user_id: @current_user.id @resources = @current_user.resources if params.has_key?('q') and !params[:q].empty? @resources &= Resource.where( Resource.arel_table[:title].matches("%#{params[:q].strip}%") ) end if params.has_key?('resource_types') @resources &= Resource.find(:all, conditions: {user_id: @current_user.id, resource_type_id: params[:resource_types]}) end if params.has_key?('course_grades') @resources &= Resource.find(:all, joins: :course_grades, conditions: {user_id: @current_user.id, course_grades: {id: params[:course_grades]}}) end if params.has_key?('course_subjects') @resources &= Resource.find(:all, joins: :course_subjects, conditions: { user_id: @current_user.id, course_subjects: { id:params[:course_subjects]}}) end # sleep(1.0) render partial: 'resources/table_resources' end def create_link_form render partial: 'create_link' end def create_link require_session Rails.logger.info(params) @resource = LinkResource.new @resource.user = @current_user @resource.title = params[:resource][:title] @resource.link = params[:resource][:link] @resource.resource_type = ResourceType.find_by_name('Web') # Convert primary keys to objects if params[:resource].has_key?('course_subjects') @resource.course_subjects = params[:resource][:course_subjects].present? ? CourseSubject.find_all_by_id(params[:resource][:course_subjects]) : [] end if params[:resource].has_key?('course_grades') @resource.course_grades = params[:resource][:course_grades].present? ? CourseGrade.find_all_by_id(params[:resource][:course_grades]) : [] end @type = LinkResource::TYPE respond_to do |format| if @resource.save #@resources = Resource.where user_id: @current_user.id @resources = @current_user.resources format.html { render partial: 'resources/table_resources' } else format.js { render partial: 'shared/error_messages', :locals => { :object => @resource }, :status => 500 } end end end def sync require_session sync_count = 0 # These two can be refactored into two simpler if statements # Google Files if @current_user.has_google_account? google_account = @current_user.google_account Rails.logger.info("Valid Google Session") #google_account.load_session() sync_count += google_account.sync_files() else Rails.logger.info("User does not have a synced Google Account") end # DropBox Files if @current_user.has_drop_box_account? drop_box_account = @current_user.drop_box_account Rails.logger.info("Valid DropBox Session") #drop_box_account.request_session() sync_count += drop_box_account.sync_files() else Rails.logger.info("User does not have a synced DropBox Account") end # After all syncing is done, re-query the resources to render #@resources = Resource.where user_id: @current_user.id @resources = @current_user.resources respond_to do |format| format.html { redirect_to show_resources_path(@current_user) } end end def page require_session @resources = @current_user.resources.paginate(page: params[:page]) render partial: 'resources/table_resources' end private # Requires user session def require_session unless current_user redirect_to signin_path end end end
Sunfocus/Utradia-Catlog-
app/src/main/java/com/utradia/catalogueappv2/model/ShipMethodsResponse.java
<filename>app/src/main/java/com/utradia/catalogueappv2/model/ShipMethodsResponse.java package com.utradia.catalogueappv2.model; import java.util.List; public class ShipMethodsResponse { /** * success : 1 * success_message : All Prices. * shipping_price : [{"id":"49","shipment_location_id":"4","start_weight":"1","end_weight":"100","price":"50","created":"2018-07-17 12:45:20","status":"1","delivery_method":"Standard Delivery: 3-5 days"},{"id":"55","shipment_location_id":"7","start_weight":"1","end_weight":"100","price":"20","created":"2018-07-18 07:19:20","status":"1","delivery_method":"Express Delivery: 1-2 days"}] * error_type : */ private int success; private String success_message; public String getError_message() { return error_message; } public void setError_message(String error_message) { this.error_message = error_message; } private String error_message; private String error_type; private List<ShippingPriceBean> shipping_price; public int getSuccess() { return success; } public void setSuccess(int success) { this.success = success; } public String getSuccess_message() { return success_message; } public void setSuccess_message(String success_message) { this.success_message = success_message; } public String getError_type() { return error_type; } public void setError_type(String error_type) { this.error_type = error_type; } public List<ShippingPriceBean> getShipping_price() { return shipping_price; } public void setShipping_price(List<ShippingPriceBean> shipping_price) { this.shipping_price = shipping_price; } public static class ShippingPriceBean { /** * id : 49 * shipment_location_id : 4 * start_weight : 1 * end_weight : 100 * price : 50 * created : 2018-07-17 12:45:20 * status : 1 * delivery_method : Standard Delivery: 3-5 days */ private String id; private String shipment_location_id; private String start_weight; private String end_weight; private String price; private String created; private String status; private String delivery_method; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getShipment_location_id() { return shipment_location_id; } public void setShipment_location_id(String shipment_location_id) { this.shipment_location_id = shipment_location_id; } public String getStart_weight() { return start_weight; } public void setStart_weight(String start_weight) { this.start_weight = start_weight; } public String getEnd_weight() { return end_weight; } public void setEnd_weight(String end_weight) { this.end_weight = end_weight; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDelivery_method() { return delivery_method; } public void setDelivery_method(String delivery_method) { this.delivery_method = delivery_method; } } }
Collatty/TDT4140
tdt4140-gr1812/app.ui/src/main/java/tdt4140/gr1812/app/ui/controllers/LoggedInController.java
<reponame>Collatty/TDT4140<gh_stars>0 package tdt4140.gr1812.app.ui.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.SubScene; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.StackedBarChart; import javafx.scene.chart.XYChart; import javafx.scene.control.Hyperlink; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.ImageView; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import tdt4140.gr1812.app.core.dataClasses.Sport; import tdt4140.gr1812.app.core.dataClasses.Workout; import tdt4140.gr1812.app.core.models.loggedIn.LoggedInModel; import tdt4140.gr1812.app.ui.FxApp; public class LoggedInController { private FxApp app; private String currentUser; private String selectedAthlete; private boolean coach; private List<Workout> workouts = new ArrayList<Workout>(); private ObservableList<Workout> observableWorkouts = FXCollections.observableArrayList(); private boolean atLoggedInView = false; @FXML Text name, tilbakeknapptekst; @FXML ImageView blank, tilbakeknapp; @FXML Hyperlink registrerOkt, tilbake; @FXML TableView workoutsTable; @FXML TableColumn goal, extraField, duration, date, maxpulse, sport; @FXML SubScene chartScene; public void registrerOkt() { // Registrer ookt hyperlink pressed this.atLoggedInView = false; this.app.goToWorkoutRegistration(); } public void update() { this.atLoggedInView = true; name.setText(LoggedInModel.getName(this.currentUser)); this.selectedAthlete = this.currentUser; if (this.coach) { //check if the logged in user is a coach this.selectedAthlete = this.app.getSelectedAthlete(); //hide the "Registrer okt"-button this.blank.setVisible(true); this.registrerOkt.setVisible(false); //make the "tilbakeknapp" visible this.tilbakeknapp.setVisible(true); this.tilbakeknapptekst.setVisible(true); this.tilbake.setVisible(true); } this.setWorkoutsInTable(); //update workouts-table this.setChart(); //update chart } // fields needed to create the chart final CategoryAxis xdays = new CategoryAxis(); final NumberAxis ytime = new NumberAxis(); StackedBarChart<String, Number> chart = new StackedBarChart<String, Number>(xdays, ytime); final XYChart.Series<String, Number> series1 = new XYChart.Series<String, Number>(); final XYChart.Series<String, Number> series2 = new XYChart.Series<String, Number>(); final XYChart.Series<String, Number> series3 = new XYChart.Series<String, Number>(); final XYChart.Series<String, Number> series4 = new XYChart.Series<String, Number>(); final XYChart.Series<String, Number> series5 = new XYChart.Series<String, Number>(); final static String mandag = "Mandag"; final static String tirsdag = "Tirsdag"; final static String onsdag = "Onsdag"; final static String torsdag = "Torsdag"; final static String fredag = "Fredag"; final static String lordag = "Lordag"; final static String sondag = "Sondag"; @SuppressWarnings({ "unchecked", "deprecation" }) public void setChart() { //set values to the chart (displays the workout's for the current week) // change the layout this.xdays.setLabel("Dager"); this.ytime.setLabel("Tid"); this.xdays.setTickLabelFont(Font.font(14)); this.ytime.setTickLabelFont(Font.font(14)); this.chart.setBackground(new Background(new BackgroundFill(Color.valueOf("#FFF2E5"), new CornerRadii(1), new Insets(5)))); xdays.setCategories(FXCollections.<String>observableArrayList( Arrays.asList( this.mandag, this.tirsdag, this.onsdag, this.torsdag, this.fredag, this.lordag, this.sondag))); List<String> weekdays = Arrays.asList(this.mandag, this.tirsdag, this.onsdag, this.torsdag, this.fredag, this.lordag, this.sondag); // for testing without backend /*HashMap<String, List<Integer>> testHashMap = new HashMap(); for (int i = 0; i< 7; i++) { List<Integer> testList = new ArrayList(); for (int j= 0; j<5; j++) { testList.add(7); } testHashMap.put(getDate(i), testList); }*/ // get duration in pulsezones from backend HashMap<String, List<Integer>> durationInPulsezonesHashMap = LoggedInModel.getPulseZones(this.selectedAthlete, this.coach); List<List<Integer>> durationInPulsezones = new ArrayList(); // create list with the dates for this week int todayInt = Calendar.getInstance().getTime().getDay(); List<String> dates = new ArrayList(); for (int i = 1; i < 8; i++) { if (i > todayInt) { dates.add(""); } else { dates.add(getDate(todayInt-i)); } } System.out.println(dates); int a = 0; for (String d : dates) { // go through the last 7 dates for (String date: durationInPulsezonesHashMap.keySet()) { // go through the dates in the HashMap from backend if (d.equals(date)) { // check if the dates are the same durationInPulsezones.add(durationInPulsezonesHashMap.get(date)); // add the duration in pulsezones-list to the list } } if (durationInPulsezones.size() == a ) { // if nothing has been added to that date - add a list of zeroes (no workout that day) durationInPulsezones.add(Arrays.asList(0,0,0,0,0)); } a++; } // create the series for the chart for (int i = 0; i<7; i++) { series1.setName("Pulssone " + 1); series1.getData().add(new XYChart.Data<String, Number>(weekdays.get(i), durationInPulsezones.get(i).get(0))); } for (int i = 0; i<7; i++) { series2.setName("Pulssone " + 2); series2.getData().add(new XYChart.Data<String, Number>(weekdays.get(i), durationInPulsezones.get(i).get(1))); } for (int i = 0; i<7; i++) { series3.setName("Pulssone " + 3); series3.getData().add(new XYChart.Data<String, Number>(weekdays.get(i), durationInPulsezones.get(i).get(2))); } for (int i = 0; i<7; i++) { series4.setName("Pulssone " + 4); series4.getData().add(new XYChart.Data<String, Number>(weekdays.get(i), durationInPulsezones.get(i).get(3))); } for (int i = 0; i<7; i++) { series5.setName("Pulssone " + 5); series5.getData().add(new XYChart.Data<String, Number>(weekdays.get(i), durationInPulsezones.get(i).get(4))); } chart.getData().addAll(series5, series4, series3, series2, series1); chartScene.setRoot(chart); } public String getDay(int dayNumber) { if (dayNumber == 0) { return this.sondag; } else if (dayNumber == 1) { return this.mandag; } else if (dayNumber == 2) { return this.tirsdag; } else if (dayNumber == 3) { return this.onsdag; } else if (dayNumber == 4) { return this.torsdag; } else if (dayNumber == 5) { return this.fredag; } else { return this.lordag; } } public String getDate(int i) { final Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -i); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); return dateFormat.format(cal.getTime()); } @SuppressWarnings("unchecked") public void setWorkoutsInTable() { //get workouts from backend this.observableWorkouts.addAll(LoggedInModel.getWorkoutsForAthlete(this.selectedAthlete, this.coach)); //set values in the workouts-table this.workoutsTable.setItems(observableWorkouts); this.goal.setCellValueFactory(new PropertyValueFactory<Workout, String>("goal")); this.date.setCellValueFactory(new PropertyValueFactory<Workout, String>("dateString")); this.duration.setCellValueFactory(new PropertyValueFactory<Workout,Integer >("duration")); this.maxpulse.setCellValueFactory(new PropertyValueFactory<Workout, Integer>("maxpulse")); this.sport.setCellValueFactory(new PropertyValueFactory<Workout, Sport>("sport")); this.extraField.setCellValueFactory(new PropertyValueFactory<Workout, String>("extraField")); } public void loggUt() { app.setCurrentUser(null); this.atLoggedInView = false; app.goToLogin(); } public void tilbake() { this.atLoggedInView = false; app.goToCoachView(); } public void slettBruker() { if (LoggedInModel.deleteUser(this.currentUser)) { this.atLoggedInView = false; app.goToLogin(); } } //set-methods: public void setApplication(FxApp app) { this.app = app; } public void setCoach(boolean coach) { this.coach = coach; } public void setCurrentUser(String user) { this.currentUser = user; } //get-methods: public FxApp getApplication() { return this.app; } public String getCurrentUser() { return this.currentUser; } public boolean getCoach() { return this.coach; } public boolean getAtLoggedInView() { return this.atLoggedInView; } public ObservableList<Workout> getObservableWorkouts() { return this.observableWorkouts; } }
thomas-bottesch/fcl
utils/types.h
<filename>utils/types.h #ifndef TYPES_H #define TYPES_H #include "pstdint.h" #include <float.h> typedef uint32_t KEY_TYPE; typedef uint64_t POINTER_TYPE; typedef double VALUE_TYPE; #define KEY_TYPE_MAX UINT32_MAX #define VALUE_TYPE_MAX DBL_MAX #define KEY_TYPE_PRINTF_MODIFIER PRINTF_INT32_MODIFIER #define POINTER_TYPE_PRINTF_MODIFIER PRINTF_INT64_MODIFIER #endif /* TYPES_H */
jumpinchat/jumpinchat-web
srv/api/user/controllers/user.resetPassword.js
<reponame>jumpinchat/jumpinchat-web<gh_stars>1-10 const Joi = require('joi'); const bcrypt = require('bcrypt'); const log = require('../../../utils/logger.util')({ name: 'user.resetPasswordVerify' }); const VerifyModel = require('../../verify/verify.model'); const userUtils = require('../user.utils'); const getUser = (userId, cb) => { userUtils.getUserById(userId, (err, user) => { if (err) { log.error('error getting user', err); return cb({ status: 401, message: 'Unauthorized' }); } if (!user) { log.error('user missing'); return cb({ status: 401, message: 'Unauthorized' }); } return cb(null, user); }); }; const generatePassHash = (password, cb) => bcrypt.genSalt(10, (err, salt) => { if (err) { log.fatal(err); return cb({ status: 403, message: 'Forbidden' }); } return bcrypt.hash(password, salt, (err, hash) => { if (err) { log.fatal(err); return cb({ status: 403, message: 'Forbidden' }); } return cb(null, hash); }); }); module.exports = function resetPassword(req, res) { const schema = Joi.object().keys({ password: Joi.string().min(6).required(), userId: Joi.string().required(), }); Joi.validate(req.body, schema, (err, validated) => { if (err) { log.warn('invalid email verification token'); res.status(400).send({ error: 'ERR_NO_DATA', message: 'required parameters are missing' }); return; } getUser(validated.userId, (err, user) => { if (err) { return res.status(err.status).send(err.message); } generatePassHash(validated.password, (err, hash) => { if (err) { return res.status(err.status).send(err.message); } user.auth.passhash = hash; user.save((err) => { if (err) { log.fatal({ err }, 'Failed to save user'); return res.status(403).send('Forbidden'); } res.status(200).send(); }); }); }); }); };
partyfly/php-flame
src/flame/time/ticker.cpp
#include "deps.h" #include "../flame.h" #include "../coroutine.h" #include "ticker.h" namespace flame { namespace time { php::value ticker::__construct(php::parameters& params) { if(!params[0].is_long()) { throw php::exception("tick interval of type integer is required"); } prop("interval", 8) = static_cast<int>(params[0]); if(params.length() > 1) { prop("repeat", 6) = params[1].is_true(); }else{ prop("repeat", 6) = php::BOOL_YES; } tm_ = (uv_timer_t*)malloc(sizeof(uv_timer_t)); uv_timer_init(flame::loop, tm_); tm_->data = this; return nullptr; } php::value ticker::__destruct(php::parameters& params) { uv_timer_stop(tm_); uv_close((uv_handle_t*)tm_, flame::free_handle_cb); return nullptr; } void ticker::tick_cb(uv_timer_t* handle) { ticker* self = static_cast<ticker*>(handle->data); coroutine::start(self->cb_, self); if(!self->prop("repeat").is_true()) { // 非重复定时器立即清理引用 self->ref_ = nullptr; } } php::value ticker::start(php::parameters& params) { cb_ = params[0]; int iv = prop("interval", 8); if(prop("repeat", 6).is_true()) { uv_timer_start(tm_, tick_cb, iv, iv); }else{ uv_timer_start(tm_, tick_cb, iv, 0); } // 异步引用 ref_ = this; return nullptr; } php::value ticker::stop(php::parameters& params) { uv_timer_stop(tm_); ref_ = nullptr; return nullptr; } php::value after(php::parameters& params) { php::object tick = php::object::create<ticker>(); tick.call("__construct", params[0], php::BOOL_NO); php::callable cb = params[1]; tick.call("start", cb); return std::move(tick); } php::value tick(php::parameters& params) { php::object tick = php::object::create<ticker>(); tick.call("__construct", params[0], php::BOOL_YES); php::callable cb = params[1]; tick.call("start", cb); return std::move(tick); } } }
Sercomm-Demeter-group/lcmdemeter
openfire.plugin.demeter_core/src/java/com/sercomm/openfire/plugin/BatchManager.java
package com.sercomm.openfire.plugin; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.TimerTask; import java.util.UUID; import com.sercomm.common.util.ManagerBase; import com.sercomm.commons.util.DateTime; import com.sercomm.commons.util.XStringUtil; import com.sercomm.openfire.plugin.data.frontend.Batch; import com.sercomm.openfire.plugin.data.frontend.BatchData; import com.sercomm.openfire.plugin.define.BatchCommand; import com.sercomm.openfire.plugin.define.BatchState; import com.sercomm.openfire.plugin.exception.DemeterException; import com.sercomm.openfire.plugin.task.BatchTask; import com.sercomm.openfire.plugin.util.DbConnectionUtil; import org.jivesoftware.database.DbConnectionManager; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.cluster.ClusterManager; import org.jivesoftware.openfire.cluster.ClusterNodeInfo; import org.jivesoftware.util.TaskEngine; import org.jivesoftware.util.cache.CacheFactory; // import org.slf4j.Logger; // import org.slf4j.LoggerFactory; public class BatchManager extends ManagerBase { // private static final Logger log = LoggerFactory.getLogger(DeviceManager.class); private static final String TABLE_S_BATCH = "sBatch"; private static final String SQL_QUERY_BATCH = String.format( "SELECT * FROM `%s` WHERE `id`=?", TABLE_S_BATCH); private static final String SQL_UPDATE_BATCH = String.format( "INSERT INTO `%s`(`id`,`appId`,`versionId`,`command`,`state`,`nodeId`,`creationTime`,`updatedTime`,`totalCount`,`data`) " + "VALUES(?,?,?,?,?,?,?,?,?,?) " + "ON DUPLICATE KEY UPDATE `state`=?,`nodeId`=?,`updatedTime`=?,`doneCount`=?,`failedCount`=?,`data`=?", TABLE_S_BATCH); private BatchManager() { } private static class BatchManagerContainer { private final static BatchManager instance = new BatchManager(); } public static BatchManager getInstance() { return BatchManagerContainer.instance; } @Override protected void onInitialize() { } @Override protected void onUninitialize() { } public Batch getBatch( String batchId) throws DemeterException, Throwable { Batch batch = null; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DbConnectionManager.getConnection(); stmt = conn.prepareStatement(SQL_QUERY_BATCH); int idx = 0; stmt.setString(++idx, batchId); rs = stmt.executeQuery(); if(!rs.next()) { throw new DemeterException("BATCH CANNOT BE FOUND: " + batchId); } batch = Batch.from(rs); } finally { DbConnectionManager.closeConnection(rs, stmt, conn); } return batch; } public Batch updateBatch( String batchId, String applicationId, String versionId, BatchCommand batchCommand, BatchState batchState, List<String> totalDevices, List<String> doneDevices, List<String> failedDevices) throws DemeterException, Throwable { Batch batch = null; DateTime now = DateTime.now(); if(XStringUtil.isBlank(batchId)) { batchId = UUID.randomUUID().toString(); batch = new Batch(); batch.setId(batchId); batch.setApplicationId(applicationId); batch.setVersionId(versionId); batch.setCommand(batchCommand.intValue()); batch.setNodeId(XMPPServer.getInstance().getNodeID().toString()); batch.setCreationTime(now.getTimeInMillis()); batch.setUpdatedTime(now.getTimeInMillis()); } else { batch = this.getBatch(batchId); batch.setNodeId(XMPPServer.getInstance().getNodeID().toString()); batch.setUpdatedTime(now.getTimeInMillis()); } if(null == batchState) { batchState = BatchState.PENDING; } batch.setState(batchState.toString()); // check if the application ID is still valid AppManager.getInstance().getApp(batch.getApplicationId()); // check if the version ID is still valid AppManager.getInstance().getAppVersion(batch.getVersionId()); batch.setTotalCount(totalDevices.size()); batch.setDoneCount(doneDevices.size()); batch.setFailedCount(failedDevices.size()); BatchData batchData = new BatchData( totalDevices, doneDevices, failedDevices); batch.setData(batchData.toByteArray()); boolean abortTransaction = true; Connection conn = null; PreparedStatement stmt = null; try { conn = DbConnectionManager.getConnection(); DbConnectionUtil.openTransaction(conn); stmt = conn.prepareStatement(SQL_UPDATE_BATCH); int idx = 0; // `id`,`appId`,`versionId`,`command`,`state`,`nodeId`,`creationTime`,`updatedTime`,`totalCount`,`data` // `state`=?,`nodeId`=?,`updatedTime`=?,`doneCount`=?,`failedCount`=?,`data`=? stmt.setString(++idx, batch.getId()); stmt.setString(++idx, batch.getApplicationId()); stmt.setString(++idx, batch.getVersionId()); stmt.setInt(++idx, batch.getCommand()); stmt.setString(++idx, batch.getState()); stmt.setString(++idx, batch.getNodeId()); stmt.setLong(++idx, batch.getCreationTime()); stmt.setLong(++idx, batch.getUpdatedTime()); stmt.setInt(++idx, batch.getTotalCount()); stmt.setBytes(++idx, batchData.toByteArray()); stmt.setString(++idx, batch.getState()); stmt.setString(++idx, batch.getNodeId()); stmt.setLong(++idx, batch.getUpdatedTime()); stmt.setInt(++idx, batch.getDoneCount()); stmt.setInt(++idx, batch.getFailedCount()); stmt.setBytes(++idx, batch.getData()); stmt.executeUpdate(); // create cluster task if necessary if(batchState == BatchState.PENDING) { // get cluster nodes information List<ClusterNodeInfo> nodes = new ArrayList<>(ClusterManager.getNodesInfo()); if(nodes.isEmpty()) { throw new DemeterException("NO CLUSTER NODE AVAILABLE"); } // random a cluster node to execute the batch task Collections.shuffle(nodes); final ClusterNodeInfo node = nodes.get(0); final String passValue = batchId; TaskEngine.getInstance().schedule(new TimerTask(){ @Override public void run() { CacheFactory.doClusterTask( new BatchTask(passValue), node.getNodeID().toByteArray()); } }, 3 * 1000L); } abortTransaction = false; } finally { DbConnectionManager.closeStatement(stmt); DbConnectionUtil.closeTransaction(conn, abortTransaction); DbConnectionManager.closeConnection(conn); } return batch; } }
Axxiss/finagle
finagle-core/src/main/scala/com/twitter/finagle/loadbalancer/NoNodesOpenException.scala
package com.twitter.finagle.loadbalancer import com.twitter.finagle.{FailureFlags, SourcedException} import com.twitter.logging.{HasLogLevel, Level} /** * While this exception is safe to retry, the assumption used here is * that the underlying situation will not change soon enough to make * a retry worthwhile as retrying is most likely to eat up the entire * budget. */ class NoNodesOpenException private[loadbalancer] (private[finagle] val flags: Long) extends RuntimeException with FailureFlags[NoNodesOpenException] with HasLogLevel with SourcedException { protected def copyWithFlags(newFlags: Long): NoNodesOpenException = new NoNodesOpenException(newFlags) def logLevel: Level = Level.DEBUG }
YJBeetle/QtAndroidAPI
android-31/android/telecom/RemoteConnection_VideoProvider_Callback.cpp
#include "./RemoteConnection_VideoProvider.hpp" #include "./VideoProfile.hpp" #include "./VideoProfile_CameraCapabilities.hpp" #include "./RemoteConnection_VideoProvider_Callback.hpp" namespace android::telecom { // Fields // QJniObject forward RemoteConnection_VideoProvider_Callback::RemoteConnection_VideoProvider_Callback(QJniObject obj) : JObject(obj) {} // Constructors RemoteConnection_VideoProvider_Callback::RemoteConnection_VideoProvider_Callback() : JObject( "android.telecom.RemoteConnection$VideoProvider$Callback", "()V" ) {} // Methods void RemoteConnection_VideoProvider_Callback::onCallDataUsageChanged(android::telecom::RemoteConnection_VideoProvider arg0, jlong arg1) const { callMethod<void>( "onCallDataUsageChanged", "(Landroid/telecom/RemoteConnection$VideoProvider;J)V", arg0.object(), arg1 ); } void RemoteConnection_VideoProvider_Callback::onCallSessionEvent(android::telecom::RemoteConnection_VideoProvider arg0, jint arg1) const { callMethod<void>( "onCallSessionEvent", "(Landroid/telecom/RemoteConnection$VideoProvider;I)V", arg0.object(), arg1 ); } void RemoteConnection_VideoProvider_Callback::onCameraCapabilitiesChanged(android::telecom::RemoteConnection_VideoProvider arg0, android::telecom::VideoProfile_CameraCapabilities arg1) const { callMethod<void>( "onCameraCapabilitiesChanged", "(Landroid/telecom/RemoteConnection$VideoProvider;Landroid/telecom/VideoProfile$CameraCapabilities;)V", arg0.object(), arg1.object() ); } void RemoteConnection_VideoProvider_Callback::onPeerDimensionsChanged(android::telecom::RemoteConnection_VideoProvider arg0, jint arg1, jint arg2) const { callMethod<void>( "onPeerDimensionsChanged", "(Landroid/telecom/RemoteConnection$VideoProvider;II)V", arg0.object(), arg1, arg2 ); } void RemoteConnection_VideoProvider_Callback::onSessionModifyRequestReceived(android::telecom::RemoteConnection_VideoProvider arg0, android::telecom::VideoProfile arg1) const { callMethod<void>( "onSessionModifyRequestReceived", "(Landroid/telecom/RemoteConnection$VideoProvider;Landroid/telecom/VideoProfile;)V", arg0.object(), arg1.object() ); } void RemoteConnection_VideoProvider_Callback::onSessionModifyResponseReceived(android::telecom::RemoteConnection_VideoProvider arg0, jint arg1, android::telecom::VideoProfile arg2, android::telecom::VideoProfile arg3) const { callMethod<void>( "onSessionModifyResponseReceived", "(Landroid/telecom/RemoteConnection$VideoProvider;ILandroid/telecom/VideoProfile;Landroid/telecom/VideoProfile;)V", arg0.object(), arg1, arg2.object(), arg3.object() ); } void RemoteConnection_VideoProvider_Callback::onVideoQualityChanged(android::telecom::RemoteConnection_VideoProvider arg0, jint arg1) const { callMethod<void>( "onVideoQualityChanged", "(Landroid/telecom/RemoteConnection$VideoProvider;I)V", arg0.object(), arg1 ); } } // namespace android::telecom
frontyard/cordova-plugin-toast
src/sectv-orsay/tvchannelProxy.js
/* * Copyright 2015 Samsung Electronics Co., Ltd. * * 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. */ 'use strict'; var sefObject = require('cordova/plugin/SEF'); var sef = sefObject.get('Window'); var windowType = 0; var channelChangeCallback = []; var setChannel = { up: 3, down: 4 }; var tuneModeList = { ALL: 0, DIGITAL: 1, ANALOG: 2, FAVORITE: 3 }; function fireChannelChangeEvent (channelInfo) { for (var i = 0; i < channelChangeCallback.length; i++) { channelChangeCallback[i](channelInfo); } } module.exports = { tune: function (success, fail, args) { var result = sef.Execute('SetChannel', args[0].major, args[0].minor); if (result != -1) { var channelInfo = webapis.tv.channel.getCurrentChannel(windowType); setTimeout(function () { success.onsuccess(channelInfo); fireChannelChangeEvent(channelInfo); }, 0); } else { setTimeout(function () { success.onnosignal(); }, 0); } }, tuneUp: function (success, fail, args) { var result = sef.Execute('SetChannel_Seek', setChannel.up, tuneModeList[args[0]]); if (result != -1) { var channelInfo = webapis.tv.channel.getCurrentChannel(windowType); setTimeout(function () { success.onsuccess(channelInfo); fireChannelChangeEvent(channelInfo); }, 0); } else { setTimeout(function () { fail(new Error('Fail to tune up.')); }, 0); } }, tuneDown: function (success, fail, args) { var result = sef.Execute('SetChannel_Seek', setChannel.down, tuneModeList[args[0]]); if (result != -1) { setTimeout(function () { var channelInfo = webapis.tv.channel.getCurrentChannel(windowType); success.onsuccess(channelInfo); fireChannelChangeEvent(channelInfo); }, 0); } else { setTimeout(function () { fail(new Error('Fail to tune up.')); }, 0); } }, findChannel: function (success, fail, args) { webapis.tv.channel.findChannel(args[0], args[1], success, fail); }, getChannelList: function (success, fail, args) { webapis.tv.channel.getChannelList(success, fail, tuneModeList[args[0]], args[1], args[2]); }, getCurrentChannel: function (success, fail, args) { var channelInfo = webapis.tv.channel.getCurrentChannel(windowType); setTimeout(function () { success(channelInfo); }, 0); }, getProgramList: function (success, fail, args) { var startTime = Math.round(args[1].getTime()/1000); //convert to epoch time var duration = args[2] * 3600; //convert hour to second webapis.tv.channel.getProgramList(args[0], startTime, success, fail, duration); }, getCurrentProgram: function (success, fail, args) { var programInfo = webapis.tv.channel.getCurrentProgram(windowType); setTimeout(function () { success(programInfo); }, 0); }, addChannelChangeListener: function (success, fail, args) { channelChangeCallback.push(success); }, removeChannelChangeListener: function (success, fail, args) { if(success) { for (var i = 0; i < channelChangeCallback.length; i++) { if (success === channelChangeCallback[i]) { channelChangeCallback.splice(i, 1); } } } else { channelChangeCallback = []; } } }; require('cordova/exec/proxy').add('toast.tvchannel', module.exports);
MasterMochi/MochiKernel
src/kernel/Taskmng/TaskmngProc.c
<reponame>MasterMochi/MochiKernel<gh_stars>0 /******************************************************************************/ /* */ /* src/kernel/Taskmng/TaskmngProc.c */ /* 2021/06/13 */ /* Copyright (C) 2018-2021 Mochi. */ /* */ /******************************************************************************/ /******************************************************************************/ /* インクルード */ /******************************************************************************/ /* 標準ヘッダ */ #include <limits.h> #include <stdarg.h> #include <stdint.h> /* ライブラリヘッダ */ #include <MLib/MLibUtil.h> /* 共通ヘッダ */ #include <kernel/config.h> #include <kernel/proc.h> #include <kernel/types.h> /* 外部モジュールヘッダ */ #include <Cmn.h> #include <Debug.h> #include <IntMng.h> #include <Memmng.h> #include <Taskmng.h> /* 内部モジュールヘッダ */ #include "TaskmngElf.h" #include "TaskmngSched.h" #include "TaskmngTask.h" #include "TaskmngThread.h" /******************************************************************************/ /* 定義 */ /******************************************************************************/ /** デバッグトレースログ出力マクロ */ #ifdef DEBUG_LOG_ENABLE #define DEBUG_LOG( ... ) \ DebugLogOutput( CMN_MODULE_TASKMNG_PROC, \ __LINE__, \ __VA_ARGS__ ) #else #define DEBUG_LOG( ... ) #endif /** プロセス管理情報動的配列チャンクサイズ */ #define PROCTBL_CHUNK_SIZE ( 8 ) /******************************************************************************/ /* ローカル関数宣言 */ /******************************************************************************/ /* プロセス管理情報割当 */ static ProcInfo_t *AllocProcInfo( uint8_t type ); /* プロセス管理情報解放 */ static void FreeProcInfo( ProcInfo_t *pProcInfo ); /* 割込みハンドラ */ static void HdlInt( uint32_t intNo, IntMngContext_t context ); /* ブレイクポイント設定 */ static void SetBreakPoint( MkProcParam_t *pParam ); /* ユーザスタック情報設定 */ static CmnRet_t SetUserStack( ProcInfo_t *pProcInfo ); /* ユーザスタック情報削除 */ static void UnsetUserStack( ProcInfo_t *pProcInfo ); /******************************************************************************/ /* 静的グローバル変数定義 */ /******************************************************************************/ /* プロセス管理情報動的配列 */ static MLibDynamicArray_t gProcTbl; /******************************************************************************/ /* グローバル関数定義 */ /******************************************************************************/ /******************************************************************************/ /** * @brief プロセス追加 * @details 実行ファイルから新しいプロセスを追加する。 * * @param[in] type プロセスタイプ * - MK_PROCESS_TYPE_DRIVER ドライバプロセス * - MK_PROCESS_TYPE_SERVER サーバプロセス * - MK_PROCESS_TYPE_USER ユーザプロセス * @param[in] *pAddr 実行ファイルアドレス * @param[in] size 実行ファイルサイズ * * @return 追加時に割り当てたプロセスIDを返す。 * @retval MK_PID_NULL 失敗 * @retval MK_PID_MIN タスクID最小値 * @retval MK_PID_MAX タスクID最大値 */ /******************************************************************************/ MkPid_t TaskmngProcAdd( uint8_t type, void *pAddr, size_t size ) { void *pEndPoint; /* エンドポイント */ CmnRet_t ret; /* 関数戻り値 */ MkTid_t tid; /* スレッドID */ ProcInfo_t *pProcInfo; /* プロセス管理情報 */ /* 初期化 */ pEndPoint = NULL; ret = CMN_FAILURE; tid = MK_TID_NULL; pProcInfo = NULL; /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() start.", __func__ ); DEBUG_LOG( " type=%u, pAddr=%010p, size=%d", type, pAddr, size ); /* プロセス管理情報割当 */ pProcInfo = AllocProcInfo( type ); /* 割当結果判定 */ if ( pProcInfo == NULL ) { /* 失敗 */ /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() end. ret=NULL", __func__ ); return MK_PID_NULL; } /* ページディレクトリ割当 */ pProcInfo->dirId = MemmngPageAllocDir( pProcInfo->pid ); /* 割当結果判定 */ if ( pProcInfo->dirId == MEMMNG_PAGE_DIR_ID_NULL ) { /* 失敗 */ /* プロセス管理情報解放 */ FreeProcInfo( pProcInfo ); /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() end. ret=NULL", __func__ ); return MK_PID_NULL; } /* ページディレクトリベースレジスタ値取得 */ pProcInfo->pdbr = MemmngPageGetPdbr( pProcInfo->dirId ); /* 仮想メモリ領域管理開始 */ ret = MemmngVirtStart( pProcInfo->pid ); /* 管理開始結果判定 */ if ( ret == CMN_FAILURE ) { /* 失敗 */ /* プロセス管理情報解放 */ FreeProcInfo( pProcInfo ); /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() end. ret=NULL", __func__ ); return MK_PID_NULL; } /* ELFファイル読込 */ ret = ElfLoad( pAddr, size, pProcInfo->dirId, &( pProcInfo->pEntryPoint ), &pEndPoint ); /* 読込結果判定 */ if ( ret != CMN_SUCCESS ) { /* 失敗 */ /* プロセス管理情報解放 */ FreeProcInfo( pProcInfo ); /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() end. ret=NULL", __func__ ); return MK_PID_NULL; } /* ブレイクポイント設定 */ pProcInfo->userHeap.pEndPoint = pEndPoint; pProcInfo->userHeap.pBreakPoint = ( void * ) MLIB_UTIL_ALIGN( ( uint32_t ) pEndPoint - 1, IA32_PAGING_PAGE_SIZE ); /* ユーザスタック設定 */ ret = SetUserStack( pProcInfo ); /* 設定結果判定 */ if ( ret != CMN_SUCCESS ) { /* 失敗 */ /* プロセス管理情報解放 */ FreeProcInfo( pProcInfo ); /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() end. ret=NULL", __func__ ); return MK_PID_NULL; } /* スレッド追加 */ tid = ThreadAddMain( pProcInfo ); /* 追加結果判定 */ if ( tid == MK_TID_NULL ) { /* 失敗 */ /* プロセス管理情報解放 */ FreeProcInfo( pProcInfo ); /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() end. ret=NULL", __func__ ); return MK_PID_NULL; } /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() end. ret=%d", __func__, pProcInfo->pid ); return pProcInfo->pid; } /******************************************************************************/ /* モジュール内グローバル関数定義 */ /******************************************************************************/ /******************************************************************************/ /** * @brief プロセス管理情報取得 * @details 引数pidのプロセス管理情報を取得する。 * * @param[in] pid プロセスID * * @return プロセス管理情報を返す。 * @retval NULL 失敗 * @retval NULL以外 成功(プロセス管理情報) */ /******************************************************************************/ ProcInfo_t *ProcGetInfo( MkPid_t pid ) { MLibErr_t errMLib; /* MLIBライブラリエラー値 */ MLibRet_t retMLib; /* MLIBライブラリ戻り値 */ ProcInfo_t *pProcInfo; /* プロセス管理情報 */ /* 初期化 */ errMLib = MLIB_ERR_NONE; retMLib = MLIB_RET_FAILURE; pProcInfo = NULL; /* プロセス管理情報取得 */ retMLib = MLibDynamicArrayGet( &gProcTbl, ( uint_t ) pid, ( void ** ) &pProcInfo, &errMLib ); /* 取得結果判定 */ if ( retMLib != MLIB_RET_SUCCESS ) { /* 失敗 */ return NULL; } return pProcInfo; } /******************************************************************************/ /** * @brief プロセス管理初期化 * @details プロセス管理情報テーブルの初期化、アイドルプロセス用のプロセス * 管理情報の設定、および、プロセス管理提供のカーネルコール用割込 * みハンドラを設定する。 */ /******************************************************************************/ void ProcInit( void ) { ProcInfo_t *pProcInfo; /* アイドルプロセス管理情報 */ ProcHeapInfo_t *pUserHeap; /* ユーザヒープ情報 */ /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() start.", __func__ ); /* 初期化 */ pProcInfo = NULL; pUserHeap = NULL; /* プロセス管理情報動的配列初期化 */ MLibDynamicArrayInit( &gProcTbl, PROCTBL_CHUNK_SIZE, sizeof ( ProcInfo_t ), UINT_MAX, NULL ); /* アイドルプロセス管理情報割当 */ pProcInfo = AllocProcInfo( TASKMNG_PROC_TYPE_KERNEL ); /* アイドルプロセス管理情報設定 */ pProcInfo->pEntryPoint = NULL; pProcInfo->dirId = MEMMNG_PAGE_DIR_ID_IDLE; pProcInfo->pdbr = MemmngPageGetPdbr( MEMMNG_PAGE_DIR_ID_IDLE ); /* ユーザヒープ情報設定 */ pUserHeap = &( pProcInfo->userHeap ); pUserHeap->pEndPoint = NULL; pUserHeap->pBreakPoint = NULL; /* アイドルプロセス用スレッド情報設定 */ ThreadAddMainIdle( pProcInfo ); /* 割込みハンドラ設定 */ IntMngHdlSet( MK_PROC_INTNO, /* 割込み番号 */ HdlInt, /* 割込みハンドラ */ IA32_DESCRIPTOR_DPL_3 ); /* 特権レベル */ /* デバッグトレースログ出力 */ DEBUG_LOG( "%s() end.", __func__ ); return; } /******************************************************************************/ /* ローカル関数定義 */ /******************************************************************************/ /******************************************************************************/ /** * @brief プロセス管理情報割当 * @details プロセス管理情報を割り当てて、初期化する。 * * @param[in] type プロセスタイプ * - MK_PROCESS_TYPE_DRIVER ドライバプロセス * - MK_PROCESS_TYPE_SERVER サーバプロセス * - MK_PROCESS_TYPE_USER ユーザプロセス * * @return プロセス管理情報を返す。 * @retval NULL 失敗 * @retval NULL以外 成功(プロセス管理情報) */ /******************************************************************************/ static ProcInfo_t *AllocProcInfo( uint8_t type ) { MkPid_t pid; /* プロセスID */ MLibErr_t errMLib; /* MLibライブラリエラー値 */ MLibRet_t retMLib; /* MLibライブラリ戻り値 */ ProcInfo_t *pProcInfo; /* プロセス管理情報 */ /* 初期化 */ pid = MK_PID_NULL; errMLib = MLIB_ERR_NONE; retMLib = MLIB_RET_FAILURE; pProcInfo = NULL; /* プロセス管理情報割当 */ retMLib = MLibDynamicArrayAlloc( &gProcTbl, ( uint_t * ) &pid, ( void ** ) &pProcInfo, &errMLib ); /* 割当結果判定 */ if ( retMLib != MLIB_RET_SUCCESS ) { /* 失敗 */ return NULL; } /* プロセス管理情報初期化 */ MLibUtilSetMemory8( pProcInfo, 0, sizeof ( ProcInfo_t ) ); pProcInfo->pid = pid; pProcInfo->type = type; return pProcInfo; } /******************************************************************************/ /** * @brief プロセス管理情報解放 * @details プロセス管理情報を解放する。 * * @param[in] *pProcInfo プロセス管理情報 */ /******************************************************************************/ static void FreeProcInfo( ProcInfo_t *pProcInfo ) { MLibErr_t errMLib; /* MLibライブラリエラー値 */ /* 初期化 */ errMLib = MLIB_ERR_NONE; /* ユーザスタック削除 */ UnsetUserStack( pProcInfo ); /* [TODO] ELFロード領域解放 */ /* ページディレクトリ割当済判定 */ if ( pProcInfo->dirId != MEMMNG_PAGE_DIR_ID_NULL ) { /* 割当済 */ /* ページディレクトリ解放 */ MemmngPageFreeDir( pProcInfo->dirId ); } /* プロセス管理情報解放 */ MLibDynamicArrayFree( &gProcTbl, ( uint_t ) pProcInfo->pid, &errMLib ); return; } /******************************************************************************/ /** * @brief 割込みハンドラ * @details 機能IDから該当する機能を呼び出す。 * * @param[in] intNo 割込み番号 * @param[in] context 割込み発生時コンテキスト */ /******************************************************************************/ static void HdlInt( uint32_t intNo, IntMngContext_t context ) { MkProcParam_t *pParam; /* パラメータ */ /* 初期化 */ pParam = ( MkProcParam_t * ) context.genReg.esi; /* パラメータチェック */ if ( pParam == NULL ) { /* 不正 */ return; } /* 機能ID判定 */ switch ( pParam->funcId ) { case MK_PROC_FUNCID_SET_BREAKPOINT: /* ブレイクポイント設定 */ SetBreakPoint( pParam ); break; default: /* 不正 */ /* アウトプットパラメータ設定 */ pParam->ret = MK_RET_FAILURE; pParam->err = MK_ERR_PARAM; } return; } /******************************************************************************/ /** * @brief ブレイクポイント設定 * @details ブレイクポイントを設定する。必要があれば、仮想メモリの割り当て * または解放を行う。 * * @param[in] *pParam パラメータ */ /******************************************************************************/ static void SetBreakPoint( MkProcParam_t *pParam ) { void *pPhyAddr; /* 物理アドレス */ void *pVirtAddr; /* ページ先頭アドレス */ int32_t remain; /* 残増減量 */ int32_t quantity; /* 増減量(ページサイズ以下) */ uint32_t breakPoint; /* ブレイクポイント */ uint32_t oldPageNum; /* 旧ページ数 */ uint32_t newPageNum; /* 新ページ数 */ CmnRet_t ret; /* 呼出し関数戻り値 */ ProcInfo_t *pProcInfo; /* プロセス管理情報 */ /* 初期化 */ pPhyAddr = NULL; pVirtAddr = NULL; remain = pParam->quantity; quantity = 0; oldPageNum = 0; newPageNum = 0; ret = CMN_SUCCESS; pProcInfo = SchedGetProcInfo(); breakPoint = ( uint32_t ) pProcInfo->userHeap.pBreakPoint; while ( remain != 0 ) { /* 残増減量比較 */ if ( ( ( - IA32_PAGING_PAGE_SIZE ) <= remain ) && ( remain <= IA32_PAGING_PAGE_SIZE ) ) { /* ページサイズ以内の増減量 */ quantity = remain; remain = 0; } else if ( remain < ( - IA32_PAGING_PAGE_SIZE ) ) { /* ページサイズを超えた減量 */ quantity = ( - IA32_PAGING_PAGE_SIZE ); remain += IA32_PAGING_PAGE_SIZE; } else { /* ページサイズを超えた増量 */ quantity = IA32_PAGING_PAGE_SIZE; remain -= IA32_PAGING_PAGE_SIZE; } /* ブレイクポイント増減前後のページ数計算 */ oldPageNum = ( breakPoint - 1 ) / IA32_PAGING_PAGE_SIZE; newPageNum = ( breakPoint - 1 + quantity ) / IA32_PAGING_PAGE_SIZE; /* 新旧ページ数比較 */ if ( oldPageNum < newPageNum ) { /* ページ数増加 */ /* 物理メモリ領域割当 */ pPhyAddr = MemmngPhysAlloc( IA32_PAGING_PAGE_SIZE ); /* 割当結果判定 */ if ( pPhyAddr == NULL ) { /* 失敗 */ DEBUG_LOG( "%s(): MemmngPhysAlloc() error.", __func__ ); /* 戻り値設定 */ pParam->ret = MK_RET_FAILURE; pParam->err = MK_ERR_NO_MEMORY; pParam->pBreakPoint = ( void * ) breakPoint; return; } /* 0初期化 */ MemmngCtrlSet( pPhyAddr, 0, IA32_PAGING_PAGE_SIZE ); /* ページ先頭アドレス計算 */ pVirtAddr = ( void * ) ( MLIB_UTIL_ALIGN( breakPoint - 1, IA32_PAGING_PAGE_SIZE ) ); /* ページングマッピング設定 */ ret = MemmngPageSet( pProcInfo->dirId, pVirtAddr, pPhyAddr, IA32_PAGING_PAGE_SIZE, IA32_PAGING_G_NO, IA32_PAGING_US_USER, IA32_PAGING_RW_RW ); /* 設定結果判定 */ if ( ret != CMN_SUCCESS ) { /* 失敗 */ DEBUG_LOG( "%s(): MemmngPageSet() error(%d).", __func__, ret ); /* 戻り値設定 */ pParam->ret = MK_RET_FAILURE; pParam->err = MK_ERR_NO_MEMORY; pParam->pBreakPoint = ( void * ) breakPoint; return; } } else if ( oldPageNum > newPageNum ) { /* ページ数減少 */ /* ページ先頭アドレス計算 */ pVirtAddr = ( void * ) ( MLIB_UTIL_ALIGN( breakPoint - 1 + quantity, IA32_PAGING_PAGE_SIZE ) ); /* ページングマッピング解除 */ MemmngPageUnset( pProcInfo->dirId, pVirtAddr, IA32_PAGING_PAGE_SIZE ); } /* ブレイクポイント更新 */ breakPoint += quantity; } /* ブレイクポイント設定 */ pProcInfo->userHeap.pBreakPoint = ( void * ) breakPoint; /* 戻り値設定 */ pParam->ret = MK_RET_SUCCESS; pParam->err = MK_ERR_NONE; pParam->pBreakPoint = ( void * ) breakPoint; return; } /******************************************************************************/ /** * @brief ユーザスタック設定 * @details ユーザスタック領域を割り当てて、プロセス管理情報に設定する。 * * @param[in] *pProcInfo プロセス管理情報 * * @return 処理結果を返す。 * @retval CMN_SUCCESS 成功 * @retval CMN_FIALURE 失敗 */ /******************************************************************************/ static CmnRet_t SetUserStack( ProcInfo_t *pProcInfo ) { void *pPhysAddr; /* 物理メモリ領域 */ CmnRet_t ret; /* 戻り値 */ ProcStackInfo_t *pStackInfo; /* スタック情報 */ /* 初期化 */ pPhysAddr = NULL; ret = CMN_FAILURE; pStackInfo = &( pProcInfo->userStack ); /* 物理メモリ領域割当 */ pPhysAddr = MemmngPhysAlloc( MK_CONFIG_SIZE_USER_STACK ); /* 割当結果判定 */ if ( pPhysAddr == NULL ) { /* 失敗 */ return CMN_FAILURE; } /* ページマッピング設定 */ ret = MemmngPageSet( pProcInfo->dirId, /* ページディレクトリID */ ( void * ) MK_CONFIG_ADDR_USER_STACK, /* 仮想アドレス */ pPhysAddr, /* 物理アドレス */ MK_CONFIG_SIZE_USER_STACK, /* マッピングサイズ */ IA32_PAGING_G_NO, /* グローバルフラグ */ IA32_PAGING_US_USER, /* ユーザ/スーパバイザ */ IA32_PAGING_RW_RW /* 読込/書込許可 */ ); /* 設定結果判定 */ if ( ret != CMN_SUCCESS ) { /* 失敗 */ /* 物理メモリ領域解放 */ MemmngPhysFree( pPhysAddr ); return CMN_FAILURE; } /* ユーザスタック情報設定 */ pStackInfo->pPhysAddr = pPhysAddr; pStackInfo->pTopAddr = ( void * ) MK_CONFIG_ADDR_USER_STACK; pStackInfo->pBottomAddr = ( void * ) ( MK_CONFIG_ADDR_USER_STACK + MK_CONFIG_SIZE_USER_STACK - sizeof ( uint32_t ) ); pStackInfo->size = MK_CONFIG_SIZE_USER_STACK; return CMN_SUCCESS; } /******************************************************************************/ /** * @brief ユーザスタック削除 * @details ユーザスタック領域のマッピング解除と物理メモリ領域の解放を行う。 * * @param[in] *pProcInfo プロセス管理情報 */ /******************************************************************************/ static void UnsetUserStack( ProcInfo_t *pProcInfo ) { /* スタック設定済判定 */ if ( pProcInfo->userStack.pPhysAddr != NULL ) { /* スタック設定済 */ /* メモリマッピング解除 */ MemmngPageUnset( pProcInfo->dirId, /* ページディレクトリID */ pProcInfo->userStack.pTopAddr, /* 仮想アドレス */ pProcInfo->userStack.size /* マッピングサイズ */ ); /* 物理メモリ領域解放 */ MemmngHeapFree( pProcInfo->userStack.pPhysAddr ); /* スタック管理情報初期化 */ pProcInfo->userStack.pPhysAddr = NULL; pProcInfo->userStack.pTopAddr = NULL; pProcInfo->userStack.pBottomAddr = NULL; pProcInfo->userStack.size = 0; } return; } /******************************************************************************/
bananasmoothii/ScriptCommands
src/main/java/fr/bananasmoothii/scriptcommands/core/execution/ScriptThread.java
/* * Copyright 2020 ScriptCommands * * 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 fr.bananasmoothii.scriptcommands.core.execution; import org.antlr.v4.runtime.ParserRuleContext; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.naming.InvalidNameException; import java.util.*; import java.util.concurrent.*; public class ScriptThread implements Future<ScriptValue<?>> { private final @NotNull Context context; private final @NotNull ParserRuleContext ctxToExecute; private final @NotNull String threadName; private final @Nullable String group; private ScriptsExecutor scriptsExecutor; private @Nullable Thread thread; private @Nullable Future<Void> futureFromExecutorService; private boolean isCancelled; public static final ThreadGroup DEFAULT_SCRIPTCOMMANDS_THREAD_GROUP = new ThreadGroup("ScriptCommand-Threads"); private static final List<ScriptThread> threads = new ArrayList<>(); private static final Map<String, ExecutorService> threadGroupExecutors = new HashMap<>(); /** * New instance specifying a group * @param ctxToExecute the ANTLR4 context that will be executed * @param context the parent context, will be cloned * @param group the thread group name * @throws ScriptException if the group does not exist. * @see #initialiseThreadGroup(String, ExecutorService) */ public ScriptThread(@NotNull ParserRuleContext ctxToExecute, @NotNull Context context, @NotNull String group) { if (! threadGroupExecutors.containsKey(Objects.requireNonNull(group, "group was null in ScriptThread instantiation"))) throw new ScriptException(ExceptionType.THREAD_GROUP_ERROR, context, "Thread group \"" + group + "\" was not initialised."); this.ctxToExecute = Objects.requireNonNull(ctxToExecute, "ctxToExecute was null in ScriptThread instantiation"); // if it wouldn't be cloned, it would force the user to make separate variables if two thread are doing the same thing... this.context = Objects.requireNonNull(context, "context was null in ScriptThread instantiation").clone(); threadName = getNextThreadName(); this.group = group; threads.add(this); } /** * New instance without a thread group, and with {@link #getNextThreadName()} as name (same as {@link #ScriptThread(String, ParserRuleContext, Context)} * with {@code null} as first argument) * @param ctxToExecute the ANTLR4 context that will be executed * @param context the parent context, will be cloned * @throws ScriptException if the name is not available */ public ScriptThread(@NotNull ParserRuleContext ctxToExecute, @NotNull Context context) { this(null, ctxToExecute, context); } /** * New instance without a thread group, but with a name. if the name is null, it will be {@link #getNextThreadName()} * @param threadName the real name that will be passed to the {@link Thread#Thread(ThreadGroup, Runnable, String)} constructor * @param ctxToExecute the ANTLR4 context that will be executed * @param context the parent context, will be cloned * @throws ScriptException if the name is not available */ public ScriptThread(@Nullable String threadName, @NotNull ParserRuleContext ctxToExecute, @NotNull Context context) { if (threadName == null) this.threadName = getNextThreadName(); else if (isAvailableName(threadName)) this.threadName = threadName; else throw new ScriptException(ExceptionType.UNAVAILABLE_THREAD_NAME, context, "Thread name \"" + threadName + "\" is already used."); this.ctxToExecute = Objects.requireNonNull(ctxToExecute, "ctxToExecute was null in ScriptThread instantiation"); // if it wouldn't be cloned, it would force the user to make separate variables if two thread are doing the same thing... this.context = Objects.requireNonNull(context, "context was null in ScriptThread instantiation").clone(); group = null; threads.add(this); } public static boolean isAvailableName(String threadName) { if (threadName == null) throw new NullPointerException("threadName is null"); return threads.stream().noneMatch(sc -> sc.threadName.equals(threadName)); } public ScriptsExecutor getScriptsExecutor() { return scriptsExecutor; } public @NotNull String getThreadName() { return threadName; } @Contract(pure = true) public static @Nullable ScriptThread getFromName(String threadName) { for (ScriptThread thread : threads) { if (thread.threadName.equals(threadName)) return thread; } return null; } @Contract(pure = true) public static @NotNull String getNextThreadName() { return "SC-Thread-" + (threads.size() + 1); } public void start() { if (isCancelled) return; if (group != null) { //noinspection unchecked futureFromExecutorService = (Future<Void>) threadGroupExecutors.get(group).submit(() -> { scriptsExecutor = new ScriptsExecutor(context); scriptsExecutor.visit(ctxToExecute); }); } else { thread = new Thread(DEFAULT_SCRIPTCOMMANDS_THREAD_GROUP, () -> { scriptsExecutor = new ScriptsExecutor(context); scriptsExecutor.visit(ctxToExecute); }, threadName); thread.start(); } } @Override public boolean cancel(boolean mayInterruptIfRunning) { isCancelled = true; if (mayInterruptIfRunning) { if (futureFromExecutorService != null) return futureFromExecutorService.cancel(true); if (thread != null) thread.interrupt(); // if the two above are false it means the thread wasn't run return true; } else { scriptsExecutor.forceReturn(); } return false; } @Override public boolean isCancelled() { return isCancelled; } @Override public boolean isDone() { return isCancelled || scriptsExecutor.hasReturned(); } @Override public @NotNull ScriptValue<?> get() throws InterruptedException, ExecutionException { if (isCancelled) return ScriptValue.NONE; scriptsExecutor.onReturn(ignored -> ScriptThread.this.notifyAll()); while (! scriptsExecutor.hasReturned()) { wait(); } return scriptsExecutor.getReturned(); } @Override public ScriptValue<?> get(long timeout, @NotNull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { long callDateNano = System.nanoTime(); if (isCancelled) return ScriptValue.NONE; long timeoutNano = unit.toNanos(timeout); long maxDateNano = callDateNano + timeoutNano; scriptsExecutor.onReturn(ignored -> ScriptThread.this.notifyAll()); while (! scriptsExecutor.hasReturned()) { if (System.nanoTime() >= maxDateNano) throw new TimeoutException(); long waitTimeNano = maxDateNano - timeoutNano; long waitTimeMilli = TimeUnit.NANOSECONDS.toMillis(waitTimeNano); wait(waitTimeMilli, (int) (TimeUnit.MILLISECONDS.toNanos(waitTimeNano) - waitTimeMilli)); } return scriptsExecutor.getReturned(); } /** * What is called a "thread group" is in fact an {@link Executor}. You can create a new thread group here, or * modify an existing thread group with {@link #getThreadGroup(String)}. It is advised to set {@link #DEFAULT_SCRIPTCOMMANDS_THREAD_GROUP} * as thread group for new threads in your executor. * @throws InvalidNameException if the name provided already exists */ public static void initialiseThreadGroup(String name, ExecutorService executor) throws InvalidNameException { if (threadGroupExecutors.containsKey(name)) throw new InvalidNameException("That thread group already exists"); threadGroupExecutors.put(name, executor); } /** * @see #initialiseThreadGroup(String, ExecutorService) */ public static @Nullable ExecutorService getThreadGroup(String name) { return threadGroupExecutors.get(name); } }
DragonSSS/curated-list-of-top-75-leetcode-questions
leetcode/src/main/java/leetcode/interval/MeetingRooms.java
package leetcode.interval; import java.util.Arrays; public class MeetingRooms { public boolean canAttendMeetings(int[][] intervals) { if (intervals == null || intervals.length <= 1) return true; Arrays.sort(intervals, (i1, i2) -> i1[0] - i2[0]); for (int i = 0; i < intervals.length - 1; i++) { if (intervals[i][1] > intervals[i + 1][0] || intervals[i][0] == intervals[i + 1][0]) { return false; } } return true; } public boolean canAttendMeetings_2r(int[][] intervals) { if (intervals.length <= 1) return true; Arrays.sort(intervals, (a, b) -> a[0] - b [0]); int preEnd = intervals[0][1]; for(int i = 1; i < intervals.length; i++) { int curStart = intervals[i][0]; if (preEnd > curStart) { return false; } preEnd = intervals[i][1]; } return true; } public boolean canAttendMeetings_3r(int[][] intervals) { if (intervals.length == 0) return true; Arrays.sort(intervals, (a, b) -> a[0] - b[0]); int preEnd = intervals[0][1]; for(int i = 1; i < intervals.length; i++) { if (preEnd > intervals[i][0]) return false; else preEnd = intervals[i][1]; } return true; } }
ThreeEyedCrow/baseCP
app/src/main/java/cn/midnight/ticketsystem/group/LoadingHelp.java
<gh_stars>0 package cn.midnight.ticketsystem.group; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.pnikosis.materialishprogress.ProgressWheel; import com.standards.library.app.AppContext; import com.standards.library.listview.loading.OnFailClickListener; import cn.midnight.ticketsystem.R; public class LoadingHelp { private View loadingView; private RelativeLayout rlLoading; private ProgressWheel mProgressWheel; private TextView tvMsg; private RelativeLayout rlFailed; private ImageView ivLoadImg; private TextView tvLoadMsg; // private TextView btnLoadRefresh; private TextView tvLoadHint; private OnFailClickListener onFailClickListener; public LoadingHelp(Context context) { } public void initView(Context context) { loadingView = LayoutInflater.from(context).inflate(R.layout.tcc_loading_page, null); rlLoading = (RelativeLayout) loadingView.findViewById(R.id.rlLoading); mProgressWheel = (ProgressWheel) loadingView.findViewById(R.id.progress); tvMsg = (TextView) loadingView.findViewById(R.id.tv_msg); rlFailed = (RelativeLayout) loadingView.findViewById(R.id.rlFailed); ivLoadImg = (ImageView) loadingView.findViewById(R.id.ivLoadImg); tvLoadMsg = (TextView) loadingView.findViewById(R.id.tvLoadMsg); tvLoadHint = (TextView) loadingView.findViewById(R.id.tvLoadHint); // btnLoadRefresh = (TextView) loadingView.findViewById(R.id.btnLoadRefresh); rlLoading.setVisibility(View.GONE); rlFailed.setVisibility(View.GONE); } public void showLoading() { rlFailed.setVisibility(View.GONE); rlLoading.setVisibility(View.VISIBLE); tvMsg.setText(AppContext.getString(R.string.load_loading)); } public void showErrorPage(int failCode, LoadResource loadResource) { rlLoading.setVisibility(View.GONE); rlFailed.setVisibility(View.VISIBLE); ivLoadImg.setImageResource(loadResource.getImage()); tvLoadMsg.setText(loadResource.getErrorText()); tvLoadHint.setText(loadResource.getErrorHint()); tvLoadHint.setOnClickListener(v -> { if (onFailClickListener != null) { onFailClickListener.onFailClick(failCode); } }); } public View getRootView() { return loadingView; } public void setOnFailClickListener(OnFailClickListener onFailClickListener) { this.onFailClickListener = onFailClickListener; } }
DebraYona/twin
src/views/Landing/LandingHeader.js
<reponame>DebraYona/twin<gh_stars>0 import React, { Component } from 'react'; import { Link, Redirect, Route, Switch } from 'react-router-dom'; import PropTypes from 'prop-types'; // import { AppNavbarBrand } from '@coreui/react'; import logo from '../../assets/img/brand/twinexchange.png' import sygnet from '../../assets/img/brand/twinexchange.png' import * as Constants from '../../constants/constants'; const propTypes = { children: PropTypes.node, }; const defaultProps = {}; class DefaultHeader extends Component { render() { // eslint-disable-next-line const { children, ...attributes } = this.props; /* <nav className="navbar navbar-dark fixed-top" style={{ 'backgroundColor': '#05073B', 'height': '75px' }}> <button className="navbar-toggler" type="button" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="navbar-collapse" id="navbarTogglerDemo01"> <a className="navbar-brand" href="#">Hidden brand</a> <img src={logo} style={{ width: 95, height: 'auto', alt: 'REDI Logo'}} align='left' /> <ul className="navbar-nav mr-auto mt-2 mt-lg-0"> <li className="nav-item active"> <a className="nav-link" href="#">Inicio <span className="sr-only">(current)</span></a> </li> <li className="nav-item"> <a className="nav-link" href="#">Contacto</a> </li> <li className="nav-item"> <a className="nav-link" href="#">Acerca de REDI</a> </li> <li className="nav-item"> <a className="nav-link" href="#">Clientes</a> </li> <li className="nav-item"> <a className="nav-link" href="#">Residuos</a> </li> </ul> </div> </nav> */ return ( <React.Fragment> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light fixed-top" style={{ 'backgroundColor': '#05073B', 'height': '75px' }}> <Link to={Constants.DASH}> <img src={logo} style={{ width: 95, height: 'auto', alt: Constants.TITLEAPP}} align='left' /> </Link> <ul class="navbar-nav mr-auto mt-2 mt-lg-0" style={{ 'align': 'right' }}> <li class="nav-item active"> <a class="nav-link" href="#">Inicio <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <Link to=""> <p style={{ 'color': '#FFF', 'font-size': '16px', 'marginRight': '20px', 'fontWeight': 'bold' }}>Acerca de Constants.TITLEAPP</p> </Link> </li> <li class="nav-item"> <Link to={Constants.REGISTER}> <p style={{ 'color': '#FFF', 'font-size': '16px', 'marginRight': '20px', 'fontWeight': 'bold' }}>Regístrate</p> </Link> </li> <li class="nav-item"> <Link to={Constants.LOGIN}> <p style={{ 'color': '#FFF', 'font-size': '16px', 'marginRight': '20px', 'fontWeight': 'bold' }}>Iniciar Sesión</p> </Link> </li> </ul> </nav> </div> </React.Fragment> ); } } DefaultHeader.propTypes = propTypes; DefaultHeader.defaultProps = defaultProps; export default DefaultHeader;
selvaraj-kuppusamy/Programming_Languages
Java/java-misc/Program_34.java
class Program_34 { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } }
koeltv/Projet_LO02
src/com/model/card/Deck.java
<filename>src/com/model/card/Deck.java package com.model.card; import com.model.card.effect.*; import java.io.Serializable; import java.util.Collections; import java.util.LinkedList; /** * The type Deck. * * Gives all the methods related to the deck. */ public class Deck implements Serializable { /** * The Cards. * * @see com.model.card.RumourCard */ private final LinkedList<RumourCard> cards = new LinkedList<>(); /** * Instantiates a new Deck. * * @see com.model.card.CardName * @see com.model.card.RumourCard * @see com.model.card.effect.EffectList * @see com.model.card.effect.DiscardFromHandEffect * @see com.model.card.effect.TakeRevealedCardEffect * @see com.model.card.effect.TakeFromAccuserHandEffect * @see com.model.card.effect.ChooseNextEffect * @see com.model.card.effect.AccuserDiscardRandomEffect * @see com.model.card.effect.NextMustAccuseOtherEffect * @see com.model.card.effect.TakeNextTurnEffect * @see com.model.card.effect.RevealAnotherIdentityEffect * @see com.model.card.effect.SecretlyReadIdentityEffect * @see com.model.card.effect.TakeRandomCardFromNextEffect * @see com.model.card.effect.RevealOrDiscardEffect * @see com.model.card.effect.RevealOwnIdentityEffect * @see com.model.card.effect.DiscardedToHandEffect * @see com.model.card.effect.TakeRevealedFromOtherEffect */ public Deck() { for (CardName cardName : CardName.values()) { //Witch? effects EffectList witchEffects = switch (cardName) { case THE_INQUISITION -> new EffectList(new DiscardFromHandEffect()); case POINTED_HAT -> new EffectList(new TakeRevealedCardEffect()); case HOOKED_NOSE -> new EffectList(new TakeFromAccuserHandEffect()); case DUCKING_STOOL -> new EffectList(new ChooseNextEffect()); case CAULDRON -> new EffectList(new AccuserDiscardRandomEffect()); case EVIL_EYE -> new EffectList(new ChooseNextEffect(), new NextMustAccuseOtherEffect()); default -> new EffectList(new TakeNextTurnEffect()); }; //Hunt! Effects EffectList huntEffect = switch (cardName) { case ANGRY_MOB -> new EffectList(new RevealAnotherIdentityEffect()); case THE_INQUISITION -> new EffectList(new ChooseNextEffect(), new SecretlyReadIdentityEffect()); case POINTED_HAT -> new EffectList(new TakeRevealedCardEffect(), new ChooseNextEffect()); case HOOKED_NOSE -> new EffectList(new ChooseNextEffect(), new TakeRandomCardFromNextEffect()); case DUCKING_STOOL -> new EffectList(new RevealOrDiscardEffect()); case CAULDRON, TOAD -> new EffectList(new RevealOwnIdentityEffect()); case EVIL_EYE -> new EffectList(new ChooseNextEffect(), new NextMustAccuseOtherEffect()); case BLACK_CAT -> new EffectList(new DiscardedToHandEffect()); case PET_NEWT -> new EffectList(new TakeRevealedFromOtherEffect(), new ChooseNextEffect()); default -> new EffectList(new ChooseNextEffect()); }; cards.add(new RumourCard(cardName, witchEffects, huntEffect)); } shuffle(); } /** * Shuffle the cards. */ public void shuffle() { Collections.shuffle(cards); } /** * Remove top card rumour card. * * @return the rumour card * @see com.model.card.RumourCard */ public RumourCard removeTopCard() { return cards.poll(); } /** * Return card to deck. * * @param playingCard the playing card * @see com.model.card.RumourCard */ public void returnCardToDeck(RumourCard playingCard) { cards.addLast(playingCard); } }
javs1287/5Steps_ListReport_Extension
exercises/ex_4/sources/ProjectSample/ZPOEXT.NOTIF.XX/node_modules/fontoxpath/test/specs/parsing/functions/functions.qnames.tests.js
import jsonMlMapper from 'test-helpers/jsonMlMapper'; import * as slimdom from 'slimdom'; import { evaluateXPathToBoolean } from 'fontoxpath'; import evaluateXPathToAsyncSingleton from 'test-helpers/evaluateXPathToAsyncSingleton'; let documentNode; beforeEach(() => { documentNode = new slimdom.Document(); }); describe('functions over qnames', () => { describe('local-name-from-QName()', () => { it('Returns the local part of a qname with no prefix', () => chai.assert.isTrue(evaluateXPathToBoolean('local-name-from-QName(QName((), "someElement")) = "someElement"', documentNode))); it('Returns the local part of a qname with no prefix', () => chai.assert.isTrue(evaluateXPathToBoolean('local-name-from-QName(QName((), "someElement")) = "someElement"', documentNode))); it('Returns the local part of a qname resulting from an attribute', () => { documentNode.appendChild(documentNode.createElementNS('http://example.com/ns', 'someElement')).setAttributeNS('http://example.com/ns', 'ns:someAttribute', 'someValue'); chai.assert.isTrue(evaluateXPathToBoolean('local-name-from-QName(node-name(//@*)) eq "someAttribute"', documentNode)); }); it('allows async parameters', async () => { documentNode.appendChild(documentNode.createElementNS('http://example.com/ns', 'someElement')).setAttributeNS('http://example.com/ns', 'ns:someAttribute', 'someValue'); chai.assert.isTrue(await evaluateXPathToAsyncSingleton('local-name-from-QName(node-name(//@*) => fontoxpath:sleep(1)) eq "someAttribute"', documentNode)); }); }); describe('prefix-from-QName()', () => { it('returns the empty sequence if inputted the empty sequence', () => chai.assert.isTrue(evaluateXPathToBoolean('prefix-from-QName(()) => count() = 0', documentNode))); it('Returns the prefix of a qname with no prefix', () => chai.assert.isTrue(evaluateXPathToBoolean('prefix-from-QName(QName((), "someElement")) => empty()', documentNode))); it('Returns the prefix of a qname with a prefix', () => chai.assert.isTrue(evaluateXPathToBoolean('prefix-from-QName(QName("http://example.com/ns", "ns:someElement")) = "ns"', documentNode))); it('Returns the prefix of a qname resulting from an attribute', () => { documentNode.appendChild(documentNode.createElementNS('http://example.com/ns', 'someElement')).setAttributeNS('http://example.com/ns', 'ns:someAttribute', 'someValue'); chai.assert.isTrue(evaluateXPathToBoolean('prefix-from-QName(node-name(//@*)) = "ns"', documentNode)); }); it('allows async parameters', async () => { documentNode.appendChild(documentNode.createElementNS('http://example.com/ns', 'someElement')).setAttributeNS('http://example.com/ns', 'ns:someAttribute', 'someValue'); chai.assert.isTrue(await evaluateXPathToAsyncSingleton('prefix-from-QName(node-name(//@*) => fontoxpath:sleep(1)) eq "ns"', documentNode)); }); }); describe('namespace-uri-from-QName()', () => { it('Returns the namespace-uri of a qname with no prefix', () => chai.assert.isTrue(evaluateXPathToBoolean('namespace-uri-from-QName(QName((), "someElement")) = ""', documentNode))); it('Returns the namespace-uri of a qname with a prefix', () => chai.assert.isTrue(evaluateXPathToBoolean('namespace-uri-from-QName(QName("http://example.com/ns", "ns:someElement")) = "http://example.com/ns"', documentNode))); it('Returns the namespace uri of a qname resulting from an attribute', () => { documentNode.appendChild(documentNode.createElementNS('http://example.com/ns', 'ns:someElement')).setAttributeNS('http://example.com/ns', 'ns:someAttribute', 'someValue'); chai.assert.isTrue(evaluateXPathToBoolean('namespace-uri-from-QName(node-name((//@*)[1])) = "http://example.com/ns"', documentNode)); }); it('allows async parameters', async () => { documentNode.appendChild(documentNode.createElementNS('http://example.com/ns', 'someElement')).setAttributeNS('http://example.com/ns', 'ns:someAttribute', 'someValue'); chai.assert.isTrue(await evaluateXPathToAsyncSingleton('namespace-uri-from-QName(node-name(//@*) => fontoxpath:sleep(1)) eq "http://example.com/ns"', documentNode)); }); }); });
sigurasg/ghidra
Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/data/WideCharDataType.java
/* ### * IP: GHIDRA * * 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 ghidra.program.model.data; import ghidra.docking.settings.Settings; import ghidra.docking.settings.SettingsDefinition; import ghidra.program.model.mem.MemBuffer; import ghidra.program.model.mem.MemoryAccessException; import ghidra.program.model.scalar.Scalar; import ghidra.util.StringUtilities; public class WideCharDataType extends BuiltIn implements ArrayStringable, DataTypeWithCharset { final static SettingsDefinition[] DEFAULT_WIDE_CHAR_SETTINGS = new SettingsDefinition[] { EndianSettingsDefinition.DEF, RenderUnicodeSettingsDefinition.RENDER }; /** A statically defined WideCharDataType instance. */ public final static WideCharDataType dataType = new WideCharDataType(); public WideCharDataType() { this(null); } public WideCharDataType(DataTypeManager dtm) { super(null, "wchar_t", dtm); } @Override public int getLength() { return getDataOrganization().getWideCharSize(); } @Override public boolean hasLanguageDependantLength() { return true; } @Override public String getDescription() { return "Wide-Character (compiler-specific size)"; } @Override protected SettingsDefinition[] getBuiltInSettingsDefinitions() { return DEFAULT_WIDE_CHAR_SETTINGS; } @Override public DataType clone(DataTypeManager dtm) { if (dtm == getDataTypeManager()) { return this; } return new WideCharDataType(dtm); } @Override public String getMnemonic(Settings settings) { return "wchar_t"; } @Override public String getRepresentation(MemBuffer buf, Settings settings, int length) { return new StringDataInstance(this, settings, buf, getLength()).getCharRepresentation(); } @Override public Object getValue(MemBuffer buf, Settings settings, int length) { length = getLength(); try { switch (getLength()) { case 2: return Character.valueOf((char) buf.getShort(0)); case 4: return new Scalar(32, buf.getInt(0), true); } } catch (MemoryAccessException e) { // ignore } return null; } @Override public boolean isEncodable() { return true; } @Override public byte[] encodeValue(Object value, MemBuffer buf, Settings settings, int length) throws DataTypeEncodeException { return encodeCharacterValue(value, buf, settings); } @Override public byte[] encodeRepresentation(String repr, MemBuffer buf, Settings settings, int length) throws DataTypeEncodeException { return encodeCharacterRepresentation(repr, buf, settings); } @Override public Class<?> getValueClass(Settings settings) { switch (getLength()) { case 2: return Character.class; case 4: return Scalar.class; default: return null; } } @Override public String getDefaultLabelPrefix(MemBuffer buf, Settings settings, int length, DataTypeDisplayOptions options) { if (length != 2 && length != 4) { return "WCHAR_??"; } StringBuilder strBuf = new StringBuilder(); strBuf.append("WCHAR_"); try { int val = (int) buf.getVarLengthUnsignedInt(0, length); if (StringUtilities.isAsciiChar(val)) { strBuf.append((char) val); } else { strBuf.append(Integer.toHexString(val)); strBuf.append('h'); } } catch (MemoryAccessException e) { strBuf.append("??"); } return strBuf.toString(); } @Override public String getDefaultLabelPrefix() { return "WCHAR"; } @Override public String getCTypeDeclaration(DataOrganization dataOrganization) { return getCTypeDeclaration(getName(), dataOrganization.getWideCharSize(), true, dataOrganization, false); } @Override public boolean hasStringValue(Settings settings) { return true; } @Override public String getArrayDefaultLabelPrefix(MemBuffer buf, Settings settings, int len, DataTypeDisplayOptions options) { return new StringDataInstance(this, settings, buf, len, true).getLabel( AbstractStringDataType.DEFAULT_UNICODE_ABBREV_PREFIX + "_", AbstractStringDataType.DEFAULT_UNICODE_LABEL_PREFIX, AbstractStringDataType.DEFAULT_UNICODE_LABEL, options); } @Override public String getArrayDefaultOffcutLabelPrefix(MemBuffer buf, Settings settings, int len, DataTypeDisplayOptions options, int offcutOffset) { return new StringDataInstance(this, settings, buf, len, true).getOffcutLabelString( AbstractStringDataType.DEFAULT_UNICODE_ABBREV_PREFIX + "_", AbstractStringDataType.DEFAULT_UNICODE_LABEL_PREFIX, AbstractStringDataType.DEFAULT_UNICODE_LABEL, options, offcutOffset); } @Override public String getCharsetName(Settings settings) { switch (getLength()) { case 2: return CharsetInfo.UTF16; case 4: return CharsetInfo.UTF32; default: return StringDataInstance.DEFAULT_CHARSET_NAME; } } }
ktrzeciaknubisa/jxcore-binary-packaging
deps/mozjs/incs/nss/nss/lib/libpkix/pkix/top/pkix_validate.c
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * pkix_validate.c * * Top level validateChain function * */ #include "pkix_validate.h" #include "pkix_pl_common.h" /* --Private-Functions-------------------------------------------- */ /* * FUNCTION: pkix_AddToVerifyLog * DESCRIPTION: * * This function returns immediately if the address for the VerifyNode tree * pointed to by "pVerifyTree" is NULL. Otherwise it creates a new VerifyNode * from the Cert pointed to by "cert" and the Error pointed to by "error", * and inserts it at the depth in the VerifyNode tree determined by "depth". A * depth of zero means that this function creates the root node of a new tree. * * Note: this function does not include the means of choosing among branches * of a tree. It is intended for non-branching trees, that is, where each * parent node has only a single child node. * * PARAMETERS: * "cert" * The address of the Cert to be included in the new VerifyNode. Must be * non-NULL. * "depth" * The UInt32 value of the depth. * "error" * The address of the Error to be included in the new VerifyNode. * "pVerifyTree" * The address of the VerifyNode tree into which the created VerifyNode * is to be inserted. The node is not created if VerifyTree is NULL. * "plContext" * Platform-specific context pointer. * THREAD SAFETY: * Thread Safe (see Thread Safety Definitions in Programmer's Guide) * RETURNS: * Returns NULL if the function succeeds. * Returns a Validate Error if the function fails in a non-fatal way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ static PKIX_Error * pkix_AddToVerifyLog( PKIX_PL_Cert *cert, PKIX_UInt32 depth, PKIX_Error *error, PKIX_VerifyNode **pVerifyTree, void *plContext) { PKIX_VerifyNode *verifyNode = NULL; PKIX_ENTER(VALIDATE, "pkix_AddToVerifyLog"); PKIX_NULLCHECK_ONE(cert); if (pVerifyTree) { /* nothing to do if no address given for log */ PKIX_CHECK(pkix_VerifyNode_Create (cert, depth, error, &verifyNode, plContext), PKIX_VERIFYNODECREATEFAILED); if (depth == 0) { /* We just created the root node */ *pVerifyTree = verifyNode; } else { PKIX_CHECK(pkix_VerifyNode_AddToChain (*pVerifyTree, verifyNode, plContext), PKIX_VERIFYNODEADDTOCHAINFAILED); } } cleanup: PKIX_RETURN(VALIDATE); } /* * FUNCTION: pkix_CheckCert * DESCRIPTION: * * Checks whether the Cert pointed to by "cert" successfully validates * using the List of CertChainCheckers pointed to by "checkers". If the * certificate does not validate, an Error pointer is returned. * * This function should be called initially with the UInt32 pointed to by * "pCheckerIndex" containing zero, and the pointer at "pNBIOContext" * containing NULL. If a checker does non-blocking I/O, this function will * return with the index of that checker stored at "pCheckerIndex" and a * platform-dependent non-blocking I/O context stored at "pNBIOContext". * A subsequent call to this function with those values intact will allow the * checking to resume where it left off. This should be repeated until the * function returns with NULL stored at "pNBIOContext". * * PARAMETERS: * "cert" * Address of Cert to validate. Must be non-NULL. * "checkers" * List of CertChainCheckers which must each validate the certificate. * Must be non-NULL. * "checkedExtOIDs" * List of PKIX_PL_OID that has been processed. If called from building * chain, it is the list of critical extension OIDs that has been * processed prior to validation. May be NULL. * "pCheckerIndex" * Address at which is stored the the index, within the List "checkers", * of a checker whose processing was interrupted by non-blocking I/O. * Must be non-NULL. * "pNBIOContext" * Address at which is stored platform-specific non-blocking I/O context. * Must be non-NULL. * "plContext" * Platform-specific context pointer. * THREAD SAFETY: * Thread Safe (see Thread Safety Definitions in Programmer's Guide) * RETURNS: * Returns NULL if the function succeeds. * Returns a Validate Error if the function fails in a non-fatal way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ static PKIX_Error * pkix_CheckCert( PKIX_PL_Cert *cert, PKIX_List *checkers, PKIX_List *checkedExtOIDsList, PKIX_UInt32 *pCheckerIndex, void **pNBIOContext, void *plContext) { PKIX_CertChainChecker_CheckCallback checkerCheck = NULL; PKIX_CertChainChecker *checker = NULL; PKIX_List *unresCritExtOIDs = NULL; PKIX_UInt32 numCheckers; PKIX_UInt32 numUnresCritExtOIDs = 0; PKIX_UInt32 checkerIndex = 0; void *nbioContext = NULL; PKIX_ENTER(VALIDATE, "pkix_CheckCert"); PKIX_NULLCHECK_FOUR(cert, checkers, pCheckerIndex, pNBIOContext); nbioContext = *pNBIOContext; *pNBIOContext = NULL; /* prepare for case of error exit */ PKIX_CHECK(PKIX_PL_Cert_GetCriticalExtensionOIDs (cert, &unresCritExtOIDs, plContext), PKIX_CERTGETCRITICALEXTENSIONOIDSFAILED); PKIX_CHECK(PKIX_List_GetLength(checkers, &numCheckers, plContext), PKIX_LISTGETLENGTHFAILED); for (checkerIndex = *pCheckerIndex; checkerIndex < numCheckers; checkerIndex++) { PKIX_CHECK(PKIX_List_GetItem (checkers, checkerIndex, (PKIX_PL_Object **)&checker, plContext), PKIX_LISTGETITEMFAILED); PKIX_CHECK(PKIX_CertChainChecker_GetCheckCallback (checker, &checkerCheck, plContext), PKIX_CERTCHAINCHECKERGETCHECKCALLBACKFAILED); PKIX_CHECK(checkerCheck(checker, cert, unresCritExtOIDs, &nbioContext, plContext), PKIX_CERTCHAINCHECKERCHECKFAILED); if (nbioContext != NULL) { *pCheckerIndex = checkerIndex; *pNBIOContext = nbioContext; goto cleanup; } PKIX_DECREF(checker); } if (unresCritExtOIDs){ #ifdef PKIX_VALIDATEDEBUG { PKIX_PL_String *oidString = NULL; PKIX_UInt32 length; char *oidAscii = NULL; PKIX_TOSTRING(unresCritExtOIDs, &oidString, plContext, PKIX_LISTTOSTRINGFAILED); PKIX_CHECK(PKIX_PL_String_GetEncoded (oidString, PKIX_ESCASCII, (void **) &oidAscii, &length, plContext), PKIX_STRINGGETENCODEDFAILED); PKIX_VALIDATE_DEBUG_ARG ("unrecognized critical extension OIDs:" " %s\n", oidAscii); PKIX_DECREF(oidString); PKIX_PL_Free(oidAscii, plContext); } #endif if (checkedExtOIDsList != NULL) { /* Take out OID's that had been processed, if any */ PKIX_CHECK(pkix_List_RemoveItems (unresCritExtOIDs, checkedExtOIDsList, plContext), PKIX_LISTREMOVEITEMSFAILED); } PKIX_CHECK(PKIX_List_GetLength (unresCritExtOIDs, &numUnresCritExtOIDs, plContext), PKIX_LISTGETLENGTHFAILED); if (numUnresCritExtOIDs != 0){ PKIX_ERROR(PKIX_UNRECOGNIZEDCRITICALEXTENSION); } } cleanup: PKIX_DECREF(checker); PKIX_DECREF(unresCritExtOIDs); PKIX_RETURN(VALIDATE); } /* * FUNCTION: pkix_InitializeCheckers * DESCRIPTION: * * Creates several checkers and initializes them with values derived from the * TrustAnchor pointed to by "anchor", the ProcessingParams pointed to by * "procParams", and the number of Certs in the Chain, represented by * "numCerts". The List of checkers is stored at "pCheckers". * * PARAMETERS: * "anchor" * Address of TrustAnchor used to initialize the SignatureChecker and * NameChainingChecker. Must be non-NULL. * "procParams" * Address of ProcessingParams used to initialize the ExpirationChecker * and TargetCertChecker. Must be non-NULL. * "numCerts" * Number of certificates in the CertChain. * "pCheckers" * Address where object pointer will be stored. Must be non-NULL. * "plContext" * Platform-specific context pointer. * THREAD SAFETY: * Thread Safe (see Thread Safety Definitions in Programmer's Guide) * RETURNS: * Returns NULL if the function succeeds. * Returns a Validate Error if the function fails in a non-fatal way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ static PKIX_Error * pkix_InitializeCheckers( PKIX_TrustAnchor *anchor, PKIX_ProcessingParams *procParams, PKIX_UInt32 numCerts, PKIX_List **pCheckers, void *plContext) { PKIX_CertChainChecker *targetCertChecker = NULL; PKIX_CertChainChecker *expirationChecker = NULL; PKIX_CertChainChecker *nameChainingChecker = NULL; PKIX_CertChainChecker *nameConstraintsChecker = NULL; PKIX_CertChainChecker *basicConstraintsChecker = NULL; PKIX_CertChainChecker *policyChecker = NULL; PKIX_CertChainChecker *sigChecker = NULL; PKIX_CertChainChecker *defaultCrlChecker = NULL; PKIX_CertChainChecker *userChecker = NULL; PKIX_PL_X500Name *trustedCAName = NULL; PKIX_PL_PublicKey *trustedPubKey = NULL; PKIX_List *checkers = NULL; PKIX_PL_Date *testDate = NULL; PKIX_CertSelector *certSelector = NULL; PKIX_PL_Cert *trustedCert = NULL; PKIX_PL_CertNameConstraints *trustedNC = NULL; PKIX_List *initialPolicies = NULL; PKIX_Boolean policyQualifiersRejected = PKIX_FALSE; PKIX_Boolean initialPolicyMappingInhibit = PKIX_FALSE; PKIX_Boolean initialAnyPolicyInhibit = PKIX_FALSE; PKIX_Boolean initialExplicitPolicy = PKIX_FALSE; PKIX_List *userCheckersList = NULL; PKIX_List *certStores = NULL; PKIX_UInt32 numCertCheckers = 0; PKIX_UInt32 i; PKIX_ENTER(VALIDATE, "pkix_InitializeCheckers"); PKIX_NULLCHECK_THREE(anchor, procParams, pCheckers); PKIX_CHECK(PKIX_List_Create(&checkers, plContext), PKIX_LISTCREATEFAILED); /* * The TrustAnchor may have been created using CreateWithCert * (in which case GetCAPublicKey and GetCAName will return NULL) * or may have been created using CreateWithNameKeyPair (in which * case GetTrustedCert will return NULL. So we call GetTrustedCert * and populate trustedPubKey and trustedCAName accordingly. */ PKIX_CHECK(PKIX_TrustAnchor_GetTrustedCert (anchor, &trustedCert, plContext), PKIX_TRUSTANCHORGETTRUSTEDCERTFAILED); if (trustedCert){ PKIX_CHECK(PKIX_PL_Cert_GetSubjectPublicKey (trustedCert, &trustedPubKey, plContext), PKIX_CERTGETSUBJECTPUBLICKEYFAILED); PKIX_CHECK(PKIX_PL_Cert_GetSubject (trustedCert, &trustedCAName, plContext), PKIX_CERTGETSUBJECTFAILED); } else { PKIX_CHECK(PKIX_TrustAnchor_GetCAPublicKey (anchor, &trustedPubKey, plContext), PKIX_TRUSTANCHORGETCAPUBLICKEYFAILED); PKIX_CHECK(PKIX_TrustAnchor_GetCAName (anchor, &trustedCAName, plContext), PKIX_TRUSTANCHORGETCANAMEFAILED); } PKIX_NULLCHECK_TWO(trustedPubKey, trustedCAName); PKIX_CHECK(PKIX_TrustAnchor_GetNameConstraints (anchor, &trustedNC, plContext), PKIX_TRUSTANCHORGETNAMECONSTRAINTSFAILED); PKIX_CHECK(PKIX_ProcessingParams_GetTargetCertConstraints (procParams, &certSelector, plContext), PKIX_PROCESSINGPARAMSGETTARGETCERTCONSTRAINTSFAILED); PKIX_CHECK(PKIX_ProcessingParams_GetDate (procParams, &testDate, plContext), PKIX_PROCESSINGPARAMSGETDATEFAILED); PKIX_CHECK(PKIX_ProcessingParams_GetInitialPolicies (procParams, &initialPolicies, plContext), PKIX_PROCESSINGPARAMSGETINITIALPOLICIESFAILED); PKIX_CHECK(PKIX_ProcessingParams_GetPolicyQualifiersRejected (procParams, &policyQualifiersRejected, plContext), PKIX_PROCESSINGPARAMSGETPOLICYQUALIFIERSREJECTEDFAILED); PKIX_CHECK(PKIX_ProcessingParams_IsPolicyMappingInhibited (procParams, &initialPolicyMappingInhibit, plContext), PKIX_PROCESSINGPARAMSISPOLICYMAPPINGINHIBITEDFAILED); PKIX_CHECK(PKIX_ProcessingParams_IsAnyPolicyInhibited (procParams, &initialAnyPolicyInhibit, plContext), PKIX_PROCESSINGPARAMSISANYPOLICYINHIBITEDFAILED); PKIX_CHECK(PKIX_ProcessingParams_IsExplicitPolicyRequired (procParams, &initialExplicitPolicy, plContext), PKIX_PROCESSINGPARAMSISEXPLICITPOLICYREQUIREDFAILED); PKIX_CHECK(PKIX_ProcessingParams_GetCertStores (procParams, &certStores, plContext), PKIX_PROCESSINGPARAMSGETCERTSTORESFAILED); PKIX_CHECK(PKIX_ProcessingParams_GetCertChainCheckers (procParams, &userCheckersList, plContext), PKIX_PROCESSINGPARAMSGETCERTCHAINCHECKERSFAILED); /* now, initialize all the checkers */ PKIX_CHECK(pkix_TargetCertChecker_Initialize (certSelector, numCerts, &targetCertChecker, plContext), PKIX_TARGETCERTCHECKERINITIALIZEFAILED); PKIX_CHECK(pkix_ExpirationChecker_Initialize (testDate, &expirationChecker, plContext), PKIX_EXPIRATIONCHECKERINITIALIZEFAILED); PKIX_CHECK(pkix_NameChainingChecker_Initialize (trustedCAName, &nameChainingChecker, plContext), PKIX_NAMECHAININGCHECKERINITIALIZEFAILED); PKIX_CHECK(pkix_NameConstraintsChecker_Initialize (trustedNC, numCerts, &nameConstraintsChecker, plContext), PKIX_NAMECONSTRAINTSCHECKERINITIALIZEFAILED); PKIX_CHECK(pkix_BasicConstraintsChecker_Initialize (numCerts, &basicConstraintsChecker, plContext), PKIX_BASICCONSTRAINTSCHECKERINITIALIZEFAILED); PKIX_CHECK(pkix_PolicyChecker_Initialize (initialPolicies, policyQualifiersRejected, initialPolicyMappingInhibit, initialExplicitPolicy, initialAnyPolicyInhibit, numCerts, &policyChecker, plContext), PKIX_POLICYCHECKERINITIALIZEFAILED); PKIX_CHECK(pkix_SignatureChecker_Initialize (trustedPubKey, numCerts, &sigChecker, plContext), PKIX_SIGNATURECHECKERINITIALIZEFAILED); if (userCheckersList != NULL) { PKIX_CHECK(PKIX_List_GetLength (userCheckersList, &numCertCheckers, plContext), PKIX_LISTGETLENGTHFAILED); for (i = 0; i < numCertCheckers; i++) { PKIX_CHECK(PKIX_List_GetItem (userCheckersList, i, (PKIX_PL_Object **) &userChecker, plContext), PKIX_LISTGETITEMFAILED); PKIX_CHECK(PKIX_List_AppendItem (checkers, (PKIX_PL_Object *)userChecker, plContext), PKIX_LISTAPPENDITEMFAILED); PKIX_DECREF(userChecker); } } PKIX_CHECK(PKIX_List_AppendItem (checkers, (PKIX_PL_Object *)targetCertChecker, plContext), PKIX_LISTAPPENDITEMFAILED); PKIX_CHECK(PKIX_List_AppendItem (checkers, (PKIX_PL_Object *)expirationChecker, plContext), PKIX_LISTAPPENDITEMFAILED); PKIX_CHECK(PKIX_List_AppendItem (checkers, (PKIX_PL_Object *)nameChainingChecker, plContext), PKIX_LISTAPPENDITEMFAILED); PKIX_CHECK(PKIX_List_AppendItem (checkers, (PKIX_PL_Object *)nameConstraintsChecker, plContext), PKIX_LISTAPPENDITEMFAILED); PKIX_CHECK(PKIX_List_AppendItem (checkers, (PKIX_PL_Object *)basicConstraintsChecker, plContext), PKIX_LISTAPPENDITEMFAILED); PKIX_CHECK(PKIX_List_AppendItem (checkers, (PKIX_PL_Object *)policyChecker, plContext), PKIX_LISTAPPENDITEMFAILED); PKIX_CHECK(PKIX_List_AppendItem (checkers, (PKIX_PL_Object *)sigChecker, plContext), PKIX_LISTAPPENDITEMFAILED); *pCheckers = checkers; cleanup: if (PKIX_ERROR_RECEIVED){ PKIX_DECREF(checkers); } PKIX_DECREF(certSelector); PKIX_DECREF(testDate); PKIX_DECREF(initialPolicies); PKIX_DECREF(targetCertChecker); PKIX_DECREF(expirationChecker); PKIX_DECREF(nameChainingChecker); PKIX_DECREF(nameConstraintsChecker); PKIX_DECREF(basicConstraintsChecker); PKIX_DECREF(policyChecker); PKIX_DECREF(sigChecker); PKIX_DECREF(trustedCAName); PKIX_DECREF(trustedPubKey); PKIX_DECREF(trustedNC); PKIX_DECREF(trustedCert); PKIX_DECREF(defaultCrlChecker); PKIX_DECREF(userCheckersList); PKIX_DECREF(certStores); PKIX_DECREF(userChecker); PKIX_RETURN(VALIDATE); } /* * FUNCTION: pkix_RetrieveOutputs * DESCRIPTION: * * This function queries the respective states of the List of checkers in * "checkers" to to obtain the final public key from the SignatureChecker * and the policy tree from the PolicyChecker, storing those values at * "pFinalSubjPubKey" and "pPolicyTree", respectively. * * PARAMETERS: * "checkers" * Address of List of checkers to be queried. Must be non-NULL. * "pFinalSubjPubKey" * Address where final public key will be stored. Must be non-NULL. * "pPolicyTree" * Address where policy tree will be stored. Must be non-NULL. * "plContext" * Platform-specific context pointer. * THREAD SAFETY: * Thread Safe (see Thread Safety Definitions in Programmer's Guide) * RETURNS: * Returns NULL if the function succeeds. * Returns a Validate Error if the function fails in a non-fatal way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ static PKIX_Error * pkix_RetrieveOutputs( PKIX_List *checkers, PKIX_PL_PublicKey **pFinalSubjPubKey, PKIX_PolicyNode **pPolicyTree, void *plContext) { PKIX_PL_PublicKey *finalSubjPubKey = NULL; PKIX_PolicyNode *validPolicyTree = NULL; PKIX_CertChainChecker *checker = NULL; PKIX_PL_Object *state = NULL; PKIX_UInt32 numCheckers = 0; PKIX_UInt32 type; PKIX_Int32 j; PKIX_ENTER(VALIDATE, "pkix_RetrieveOutputs"); PKIX_NULLCHECK_TWO(checkers, pPolicyTree); /* * To optimize the search, we guess that the sigChecker is * last in the tree and is preceded by the policyChecker. We * search toward the front of the chain. Remember that List * items are indexed 0..(numItems - 1). */ PKIX_CHECK(PKIX_List_GetLength(checkers, &numCheckers, plContext), PKIX_LISTGETLENGTHFAILED); for (j = numCheckers - 1; j >= 0; j--){ PKIX_CHECK(PKIX_List_GetItem (checkers, j, (PKIX_PL_Object **)&checker, plContext), PKIX_LISTGETITEMFAILED); PKIX_CHECK(PKIX_CertChainChecker_GetCertChainCheckerState (checker, &state, plContext), PKIX_CERTCHAINCHECKERGETCERTCHAINCHECKERSTATEFAILED); /* user defined checker may have no state */ if (state != NULL) { PKIX_CHECK(PKIX_PL_Object_GetType(state, &type, plContext), PKIX_OBJECTGETTYPEFAILED); if (type == PKIX_SIGNATURECHECKERSTATE_TYPE){ /* final pubKey will include any inherited DSA params */ finalSubjPubKey = ((pkix_SignatureCheckerState *)state)-> prevPublicKey; PKIX_INCREF(finalSubjPubKey); *pFinalSubjPubKey = finalSubjPubKey; } if (type == PKIX_CERTPOLICYCHECKERSTATE_TYPE) { validPolicyTree = ((PKIX_PolicyCheckerState *)state)->validPolicyTree; break; } } PKIX_DECREF(checker); PKIX_DECREF(state); } PKIX_INCREF(validPolicyTree); *pPolicyTree = validPolicyTree; cleanup: PKIX_DECREF(checker); PKIX_DECREF(state); PKIX_RETURN(VALIDATE); } /* * FUNCTION: pkix_CheckChain * DESCRIPTION: * * Checks whether the List of Certs pointed to by "certs", containing * "numCerts" entries, successfully validates using each CertChainChecker in * the List pointed to by "checkers" and has not been revoked, according to any * of the Revocation Checkers in the List pointed to by "revChecker". Checkers * are expected to remove from "removeCheckedExtOIDs" and extensions that they * process. Indices to the certChain and the checkerChain are obtained and * returned in "pCertCheckedIndex" and "pCheckerIndex", respectively. These * should be set to zero prior to the initial call, but may be changed (and * must be supplied on subsequent calls) if processing is suspended for non- * blocking I/O. Each time a Cert passes from being validated by one of the * CertChainCheckers to being checked by a Revocation Checker, the Boolean * stored at "pRevChecking" is changed from FALSE to TRUE. If the Cert is * rejected by a Revocation Checker, its reason code is returned at * "pReasonCode. If the List of Certs successfully validates, the public key i * the final certificate is obtained and stored at "pFinalSubjPubKey" and the * validPolicyTree, which could be NULL, is stored at pPolicyTree. If the List * of Certs fails to validate, an Error pointer is returned. * * If "pVerifyTree" is non-NULL, a chain of VerifyNodes is created which * tracks the results of the validation. That is, either each node in the * chain has a NULL Error component, or the last node contains an Error * which indicates why the validation failed. * * The number of Certs in the List, represented by "numCerts", is used to * determine which Cert is the final Cert. * * PARAMETERS: * "certs" * Address of List of Certs to validate. Must be non-NULL. * "numCerts" * Number of certificates in the List of certificates. * "checkers" * List of CertChainCheckers which must each validate the List of * certificates. Must be non-NULL. * "revChecker" * List of RevocationCheckers which must each not reject the List of * certificates. May be empty, but must be non-NULL. * "removeCheckedExtOIDs" * List of PKIX_PL_OID that has been processed. If called from building * chain, it is the list of critical extension OIDs that has been * processed prior to validation. Extension OIDs that may be processed by * user defined checker processes are also in the list. May be NULL. * "procParams" * Address of ProcessingParams used to initialize various checkers. Must * be non-NULL. * "pCertCheckedIndex" * Address where Int32 index to the Cert chain is obtained and * returned. Must be non-NULL. * "pCheckerIndex" * Address where Int32 index to the CheckerChain is obtained and * returned. Must be non-NULL. * "pRevChecking" * Address where Boolean is obtained and returned, indicating, if FALSE, * that CertChainCheckers are being called; or, if TRUE, that RevChecker * are being called. Must be non-NULL. * "pReasonCode" * Address where UInt32 results of revocation checking are stored. Must be * non-NULL. * "pNBIOContext" * Address where platform-dependent context is stored if checking is * suspended for non-blocking I/O. Must be non-NULL. * "pFinalSubjPubKey" * Address where the final public key will be stored. Must be non-NULL. * "pPolicyTree" * Address where the final validPolicyTree is stored. Must be non-NULL. * "pVerifyTree" * Address where a VerifyTree is stored, if non-NULL. * "plContext" * Platform-specific context pointer. * THREAD SAFETY: * Thread Safe (see Thread Safety Definitions in Programmer's Guide) * RETURNS: * Returns NULL if the function succeeds. * Returns a Validate Error if the function fails in a non-fatal way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ PKIX_Error * pkix_CheckChain( PKIX_List *certs, PKIX_UInt32 numCerts, PKIX_TrustAnchor *anchor, PKIX_List *checkers, PKIX_RevocationChecker *revChecker, PKIX_List *removeCheckedExtOIDs, PKIX_ProcessingParams *procParams, PKIX_UInt32 *pCertCheckedIndex, PKIX_UInt32 *pCheckerIndex, PKIX_Boolean *pRevChecking, PKIX_UInt32 *pReasonCode, void **pNBIOContext, PKIX_PL_PublicKey **pFinalSubjPubKey, PKIX_PolicyNode **pPolicyTree, PKIX_VerifyNode **pVerifyTree, void *plContext) { PKIX_UInt32 j = 0; PKIX_Boolean revChecking = PKIX_FALSE; PKIX_Error *checkCertError = NULL; void *nbioContext = NULL; PKIX_PL_Cert *cert = NULL; PKIX_PL_Cert *issuer = NULL; PKIX_PL_NssContext *nssContext = NULL; CERTCertList *certList = NULL; const CERTChainVerifyCallback *chainVerifyCallback = NULL; CERTCertificate *nssCert = NULL; PKIX_ENTER(VALIDATE, "pkix_CheckChain"); PKIX_NULLCHECK_FOUR(certs, checkers, revChecker, pCertCheckedIndex); PKIX_NULLCHECK_FOUR(pCheckerIndex, pRevChecking, pReasonCode, anchor); PKIX_NULLCHECK_THREE(pNBIOContext, pFinalSubjPubKey, pPolicyTree); nbioContext = *pNBIOContext; *pNBIOContext = NULL; revChecking = *pRevChecking; nssContext = (PKIX_PL_NssContext *)plContext; chainVerifyCallback = &nssContext->chainVerifyCallback; if (chainVerifyCallback->isChainValid != NULL) { PRBool chainOK = PR_FALSE; /*assume failure*/ SECStatus rv; certList = CERT_NewCertList(); if (certList == NULL) { PKIX_ERROR_ALLOC_ERROR(); } /* Add the trust anchor to the list */ PKIX_CHECK(PKIX_TrustAnchor_GetTrustedCert (anchor, &cert, plContext), PKIX_TRUSTANCHORGETTRUSTEDCERTFAILED); PKIX_CHECK( PKIX_PL_Cert_GetCERTCertificate(cert, &nssCert, plContext), PKIX_CERTGETCERTCERTIFICATEFAILED); rv = CERT_AddCertToListHead(certList, nssCert); if (rv != SECSuccess) { PKIX_ERROR_ALLOC_ERROR(); } /* the certList takes ownership of nssCert on success */ nssCert = NULL; PKIX_DECREF(cert); /* Add the rest of the chain to the list */ for (j = *pCertCheckedIndex; j < numCerts; j++) { PKIX_CHECK(PKIX_List_GetItem( certs, j, (PKIX_PL_Object **)&cert, plContext), PKIX_LISTGETITEMFAILED); PKIX_CHECK( PKIX_PL_Cert_GetCERTCertificate(cert, &nssCert, plContext), PKIX_CERTGETCERTCERTIFICATEFAILED); rv = CERT_AddCertToListHead(certList, nssCert); if (rv != SECSuccess) { PKIX_ERROR_ALLOC_ERROR(); } /* the certList takes ownership of nssCert on success */ nssCert = NULL; PKIX_DECREF(cert); } rv = (*chainVerifyCallback->isChainValid) (chainVerifyCallback->isChainValidArg, certList, &chainOK); if (rv != SECSuccess) { PKIX_ERROR_FATAL(PKIX_CHAINVERIFYCALLBACKFAILED); } if (!chainOK) { PKIX_ERROR(PKIX_CHAINVERIFYCALLBACKFAILED); } } PKIX_CHECK(PKIX_TrustAnchor_GetTrustedCert (anchor, &cert, plContext), PKIX_TRUSTANCHORGETTRUSTEDCERTFAILED); for (j = *pCertCheckedIndex; j < numCerts; j++) { PORT_Assert(cert); PKIX_DECREF(issuer); issuer = cert; cert = NULL; PKIX_CHECK(PKIX_List_GetItem( certs, j, (PKIX_PL_Object **)&cert, plContext), PKIX_LISTGETITEMFAILED); /* check if cert pointer is valid */ PORT_Assert(cert); if (cert == NULL) { continue; } if (revChecking == PKIX_FALSE) { PKIX_CHECK(pkix_CheckCert (cert, checkers, removeCheckedExtOIDs, pCheckerIndex, &nbioContext, plContext), PKIX_CHECKCERTFAILED); if (nbioContext != NULL) { *pCertCheckedIndex = j; *pRevChecking = revChecking; *pNBIOContext = nbioContext; goto cleanup; } revChecking = PKIX_TRUE; *pCheckerIndex = 0; } if (revChecking == PKIX_TRUE) { PKIX_RevocationStatus revStatus; pkixErrorResult = PKIX_RevocationChecker_Check( cert, issuer, revChecker, procParams, PKIX_TRUE, (j == numCerts - 1) ? PKIX_TRUE : PKIX_FALSE, &revStatus, pReasonCode, &nbioContext, plContext); if (nbioContext != NULL) { *pCertCheckedIndex = j; *pRevChecking = revChecking; *pNBIOContext = nbioContext; goto cleanup; } if (revStatus == PKIX_RevStatus_Revoked || pkixErrorResult) { if (!pkixErrorResult) { /* if pkixErrorResult is returned then * use it as it has a detailed revocation * error code. Otherwise create a new error */ PKIX_ERROR_CREATE(VALIDATE, PKIX_CERTIFICATEREVOKED, pkixErrorResult); } goto cleanup; } revChecking = PKIX_FALSE; *pCheckerIndex = 0; } PKIX_CHECK(pkix_AddToVerifyLog (cert, j, NULL, pVerifyTree, plContext), PKIX_ADDTOVERIFYLOGFAILED); } PKIX_CHECK(pkix_RetrieveOutputs (checkers, pFinalSubjPubKey, pPolicyTree, plContext), PKIX_RETRIEVEOUTPUTSFAILED); *pNBIOContext = NULL; cleanup: if (PKIX_ERROR_RECEIVED && cert) { checkCertError = pkixErrorResult; PKIX_CHECK_FATAL( pkix_AddToVerifyLog(cert, j, checkCertError, pVerifyTree, plContext), PKIX_ADDTOVERIFYLOGFAILED); pkixErrorResult = checkCertError; pkixErrorCode = pkixErrorResult->errCode; checkCertError = NULL; } fatal: if (nssCert) { CERT_DestroyCertificate(nssCert); } if (certList) { CERT_DestroyCertList(certList); } PKIX_DECREF(checkCertError); PKIX_DECREF(cert); PKIX_DECREF(issuer); PKIX_RETURN(VALIDATE); } /* * FUNCTION: pkix_ExtractParameters * DESCRIPTION: * * Extracts several parameters from the ValidateParams object pointed to by * "valParams" and stores the CertChain at "pChain", the List of Certs at * "pCerts", the number of Certs in the chain at "pNumCerts", the * ProcessingParams object at "pProcParams", the List of TrustAnchors at * "pAnchors", and the number of TrustAnchors at "pNumAnchors". * * PARAMETERS: * "valParams" * Address of ValidateParams from which the parameters are extracted. * Must be non-NULL. * "pCerts" * Address where object pointer for List of Certs will be stored. * Must be non-NULL. * "pNumCerts" * Address where number of Certs will be stored. Must be non-NULL. * "pProcParams" * Address where object pointer for ProcessingParams will be stored. * Must be non-NULL. * "pAnchors" * Address where object pointer for List of Anchors will be stored. * Must be non-NULL. * "pNumAnchors" * Address where number of Anchors will be stored. Must be non-NULL. * "plContext" * Platform-specific context pointer. * THREAD SAFETY: * Thread Safe (see Thread Safety Definitions in Programmer's Guide) * RETURNS: * Returns NULL if the function succeeds. * Returns a Validate Error if the function fails in a non-fatal way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ static PKIX_Error * pkix_ExtractParameters( PKIX_ValidateParams *valParams, PKIX_List **pCerts, PKIX_UInt32 *pNumCerts, PKIX_ProcessingParams **pProcParams, PKIX_List **pAnchors, PKIX_UInt32 *pNumAnchors, void *plContext) { PKIX_ENTER(VALIDATE, "pkix_ExtractParameters"); PKIX_NULLCHECK_THREE(valParams, pCerts, pNumCerts); PKIX_NULLCHECK_THREE(pProcParams, pAnchors, pNumAnchors); /* extract relevant parameters from chain */ PKIX_CHECK(PKIX_ValidateParams_GetCertChain (valParams, pCerts, plContext), PKIX_VALIDATEPARAMSGETCERTCHAINFAILED); PKIX_CHECK(PKIX_List_GetLength(*pCerts, pNumCerts, plContext), PKIX_LISTGETLENGTHFAILED); /* extract relevant parameters from procParams */ PKIX_CHECK(PKIX_ValidateParams_GetProcessingParams (valParams, pProcParams, plContext), PKIX_VALIDATEPARAMSGETPROCESSINGPARAMSFAILED); PKIX_CHECK(PKIX_ProcessingParams_GetTrustAnchors (*pProcParams, pAnchors, plContext), PKIX_PROCESSINGPARAMSGETTRUSTANCHORSFAILED); PKIX_CHECK(PKIX_List_GetLength(*pAnchors, pNumAnchors, plContext), PKIX_LISTGETLENGTHFAILED); cleanup: PKIX_RETURN(VALIDATE); } /* --Public-Functions--------------------------------------------- */ /* * FUNCTION: PKIX_ValidateChain (see comments in pkix.h) */ PKIX_Error * PKIX_ValidateChain( PKIX_ValidateParams *valParams, PKIX_ValidateResult **pResult, PKIX_VerifyNode **pVerifyTree, void *plContext) { PKIX_Error *chainFailed = NULL; PKIX_ProcessingParams *procParams = NULL; PKIX_CertChainChecker *userChecker = NULL; PKIX_RevocationChecker *revChecker = NULL; PKIX_List *certs = NULL; PKIX_List *checkers = NULL; PKIX_List *anchors = NULL; PKIX_List *userCheckers = NULL; PKIX_List *userCheckerExtOIDs = NULL; PKIX_List *validateCheckedCritExtOIDsList = NULL; PKIX_TrustAnchor *anchor = NULL; PKIX_ValidateResult *valResult = NULL; PKIX_PL_PublicKey *finalPubKey = NULL; PKIX_PolicyNode *validPolicyTree = NULL; PKIX_Boolean supportForwarding = PKIX_FALSE; PKIX_Boolean revChecking = PKIX_FALSE; PKIX_UInt32 i, numCerts, numAnchors; PKIX_UInt32 numUserCheckers = 0; PKIX_UInt32 certCheckedIndex = 0; PKIX_UInt32 checkerIndex = 0; PKIX_UInt32 reasonCode = 0; void *nbioContext = NULL; PKIX_ENTER(VALIDATE, "PKIX_ValidateChain"); PKIX_NULLCHECK_TWO(valParams, pResult); /* extract various parameters from valParams */ PKIX_CHECK(pkix_ExtractParameters (valParams, &certs, &numCerts, &procParams, &anchors, &numAnchors, plContext), PKIX_EXTRACTPARAMETERSFAILED); /* * setup an extension OID list that user had defined for his checker * processing. User checker is not responsible for taking out OIDs * from unresolved critical extension list as the libpkix checker * is doing. Here we add those user checkers' OIDs to the removal * list to be taken out by CheckChain */ PKIX_CHECK(PKIX_ProcessingParams_GetCertChainCheckers (procParams, &userCheckers, plContext), PKIX_PROCESSINGPARAMSGETCERTCHAINCHECKERSFAILED); if (userCheckers != NULL) { PKIX_CHECK(PKIX_List_Create (&validateCheckedCritExtOIDsList, plContext), PKIX_LISTCREATEFAILED); PKIX_CHECK(PKIX_List_GetLength (userCheckers, &numUserCheckers, plContext), PKIX_LISTGETLENGTHFAILED); for (i = 0; i < numUserCheckers; i++) { PKIX_CHECK(PKIX_List_GetItem (userCheckers, i, (PKIX_PL_Object **) &userChecker, plContext), PKIX_LISTGETITEMFAILED); PKIX_CHECK (PKIX_CertChainChecker_IsForwardCheckingSupported (userChecker, &supportForwarding, plContext), PKIX_CERTCHAINCHECKERISFORWARDCHECKINGSUPPORTEDFAILED); if (supportForwarding == PKIX_FALSE) { PKIX_CHECK (PKIX_CertChainChecker_GetSupportedExtensions (userChecker, &userCheckerExtOIDs, plContext), PKIX_CERTCHAINCHECKERGETSUPPORTEDEXTENSIONSFAILED); if (userCheckerExtOIDs != NULL) { PKIX_CHECK(pkix_List_AppendList (validateCheckedCritExtOIDsList, userCheckerExtOIDs, plContext), PKIX_LISTAPPENDLISTFAILED); } } PKIX_DECREF(userCheckerExtOIDs); PKIX_DECREF(userChecker); } } PKIX_CHECK(PKIX_ProcessingParams_GetRevocationChecker (procParams, &revChecker, plContext), PKIX_PROCESSINGPARAMSGETREVOCATIONCHECKERFAILED); /* try to validate the chain with each anchor */ for (i = 0; i < numAnchors; i++){ /* get trust anchor */ PKIX_CHECK(PKIX_List_GetItem (anchors, i, (PKIX_PL_Object **)&anchor, plContext), PKIX_LISTGETITEMFAILED); /* initialize checkers using information from trust anchor */ PKIX_CHECK(pkix_InitializeCheckers (anchor, procParams, numCerts, &checkers, plContext), PKIX_INITIALIZECHECKERSFAILED); /* * Validate the chain using this trust anchor and these * checkers. (WARNING: checkers that use non-blocking I/O * are not currently supported.) */ certCheckedIndex = 0; checkerIndex = 0; revChecking = PKIX_FALSE; chainFailed = pkix_CheckChain (certs, numCerts, anchor, checkers, revChecker, validateCheckedCritExtOIDsList, procParams, &certCheckedIndex, &checkerIndex, &revChecking, &reasonCode, &nbioContext, &finalPubKey, &validPolicyTree, pVerifyTree, plContext); if (chainFailed) { /* cert chain failed to validate */ PKIX_DECREF(chainFailed); PKIX_DECREF(anchor); PKIX_DECREF(checkers); PKIX_DECREF(validPolicyTree); /* if last anchor, we fail; else, we try next anchor */ if (i == (numAnchors - 1)) { /* last anchor */ PKIX_ERROR(PKIX_VALIDATECHAINFAILED); } } else { /* XXX Remove this assertion after 2014-12-31. * See bug 946984. */ PORT_Assert(reasonCode == 0); /* cert chain successfully validated! */ PKIX_CHECK(pkix_ValidateResult_Create (finalPubKey, anchor, validPolicyTree, &valResult, plContext), PKIX_VALIDATERESULTCREATEFAILED); *pResult = valResult; /* no need to try any more anchors in the loop */ goto cleanup; } } cleanup: PKIX_DECREF(finalPubKey); PKIX_DECREF(certs); PKIX_DECREF(anchors); PKIX_DECREF(anchor); PKIX_DECREF(checkers); PKIX_DECREF(revChecker); PKIX_DECREF(validPolicyTree); PKIX_DECREF(chainFailed); PKIX_DECREF(procParams); PKIX_DECREF(userCheckers); PKIX_DECREF(validateCheckedCritExtOIDsList); PKIX_RETURN(VALIDATE); } /* * FUNCTION: pkix_Validate_BuildUserOIDs * DESCRIPTION: * * This function creates a List of the OIDs that are processed by the user * checkers in the List pointed to by "userCheckers", storing the resulting * List at "pUserCritOIDs". If the List of userCheckers is NULL, the output * List will be NULL. Otherwise the output List will be non-NULL, but may be * empty. * * PARAMETERS: * "userCheckers" * The address of the List of userCheckers. * "pUserCritOIDs" * The address at which the List is stored. Must be non-NULL. * "plContext" * Platform-specific context pointer. * THREAD SAFETY: * Thread Safe (see Thread Safety Definitions in Programmer's Guide) * RETURNS: * Returns NULL if the function succeeds. * Returns a VALIDATE Error if the function fails in a non-fatal way. * Returns a Fatal Error if the function fails in an unrecoverable way. */ static PKIX_Error * pkix_Validate_BuildUserOIDs( PKIX_List *userCheckers, PKIX_List **pUserCritOIDs, void *plContext) { PKIX_UInt32 numUserCheckers = 0; PKIX_UInt32 i = 0; PKIX_List *userCritOIDs = NULL; PKIX_List *userCheckerExtOIDs = NULL; PKIX_Boolean supportForwarding = PKIX_FALSE; PKIX_CertChainChecker *userChecker = NULL; PKIX_ENTER(VALIDATE, "pkix_Validate_BuildUserOIDs"); PKIX_NULLCHECK_ONE(pUserCritOIDs); if (userCheckers != NULL) { PKIX_CHECK(PKIX_List_Create(&userCritOIDs, plContext), PKIX_LISTCREATEFAILED); PKIX_CHECK(PKIX_List_GetLength (userCheckers, &numUserCheckers, plContext), PKIX_LISTGETLENGTHFAILED); for (i = 0; i < numUserCheckers; i++) { PKIX_CHECK(PKIX_List_GetItem (userCheckers, i, (PKIX_PL_Object **) &userChecker, plContext), PKIX_LISTGETITEMFAILED); PKIX_CHECK(PKIX_CertChainChecker_IsForwardCheckingSupported (userChecker, &supportForwarding, plContext), PKIX_CERTCHAINCHECKERISFORWARDCHECKINGSUPPORTEDFAILED); if (supportForwarding == PKIX_FALSE) { PKIX_CHECK(PKIX_CertChainChecker_GetSupportedExtensions (userChecker, &userCheckerExtOIDs, plContext), PKIX_CERTCHAINCHECKERGETSUPPORTEDEXTENSIONSFAILED); if (userCheckerExtOIDs != NULL) { PKIX_CHECK(pkix_List_AppendList (userCritOIDs, userCheckerExtOIDs, plContext), PKIX_LISTAPPENDLISTFAILED); } } PKIX_DECREF(userCheckerExtOIDs); PKIX_DECREF(userChecker); } } *pUserCritOIDs = userCritOIDs; cleanup: if (PKIX_ERROR_RECEIVED){ PKIX_DECREF(userCritOIDs); } PKIX_DECREF(userCheckerExtOIDs); PKIX_DECREF(userChecker); PKIX_RETURN(VALIDATE); } /* * FUNCTION: PKIX_ValidateChain_nb (see comments in pkix.h) */ PKIX_Error * PKIX_ValidateChain_NB( PKIX_ValidateParams *valParams, PKIX_UInt32 *pCertIndex, PKIX_UInt32 *pAnchorIndex, PKIX_UInt32 *pCheckerIndex, PKIX_Boolean *pRevChecking, PKIX_List **pCheckers, void **pNBIOContext, PKIX_ValidateResult **pResult, PKIX_VerifyNode **pVerifyTree, void *plContext) { PKIX_UInt32 numCerts = 0; PKIX_UInt32 numAnchors = 0; PKIX_UInt32 i = 0; PKIX_UInt32 certIndex = 0; PKIX_UInt32 anchorIndex = 0; PKIX_UInt32 checkerIndex = 0; PKIX_UInt32 reasonCode = 0; PKIX_Boolean revChecking = PKIX_FALSE; PKIX_List *certs = NULL; PKIX_List *anchors = NULL; PKIX_List *checkers = NULL; PKIX_List *userCheckers = NULL; PKIX_List *validateCheckedCritExtOIDsList = NULL; PKIX_TrustAnchor *anchor = NULL; PKIX_ValidateResult *valResult = NULL; PKIX_PL_PublicKey *finalPubKey = NULL; PKIX_PolicyNode *validPolicyTree = NULL; PKIX_ProcessingParams *procParams = NULL; PKIX_RevocationChecker *revChecker = NULL; PKIX_Error *chainFailed = NULL; void *nbioContext = NULL; PKIX_ENTER(VALIDATE, "PKIX_ValidateChain_NB"); PKIX_NULLCHECK_FOUR (valParams, pCertIndex, pAnchorIndex, pCheckerIndex); PKIX_NULLCHECK_FOUR(pRevChecking, pCheckers, pNBIOContext, pResult); nbioContext = *pNBIOContext; *pNBIOContext = NULL; /* extract various parameters from valParams */ PKIX_CHECK(pkix_ExtractParameters (valParams, &certs, &numCerts, &procParams, &anchors, &numAnchors, plContext), PKIX_EXTRACTPARAMETERSFAILED); /* * Create a List of the OIDs that will be processed by the user * checkers. User checkers are not responsible for removing OIDs from * the List of unresolved critical extensions, as libpkix checkers are. * So we add those user checkers' OIDs to the removal list to be taken * out by CheckChain. */ PKIX_CHECK(PKIX_ProcessingParams_GetCertChainCheckers (procParams, &userCheckers, plContext), PKIX_PROCESSINGPARAMSGETCERTCHAINCHECKERSFAILED); PKIX_CHECK(pkix_Validate_BuildUserOIDs (userCheckers, &validateCheckedCritExtOIDsList, plContext), PKIX_VALIDATEBUILDUSEROIDSFAILED); PKIX_CHECK(PKIX_ProcessingParams_GetRevocationChecker (procParams, &revChecker, plContext), PKIX_PROCESSINGPARAMSGETREVOCATIONCHECKERFAILED); /* Are we resuming after a WOULDBLOCK return, or starting anew ? */ if (nbioContext != NULL) { /* Resuming */ certIndex = *pCertIndex; anchorIndex = *pAnchorIndex; checkerIndex = *pCheckerIndex; revChecking = *pRevChecking; checkers = *pCheckers; *pCheckers = NULL; } /* try to validate the chain with each anchor */ for (i = anchorIndex; i < numAnchors; i++) { /* get trust anchor */ PKIX_CHECK(PKIX_List_GetItem (anchors, i, (PKIX_PL_Object **)&anchor, plContext), PKIX_LISTGETITEMFAILED); /* initialize checkers using information from trust anchor */ if (nbioContext == NULL) { PKIX_CHECK(pkix_InitializeCheckers (anchor, procParams, numCerts, &checkers, plContext), PKIX_INITIALIZECHECKERSFAILED); } /* * Validate the chain using this trust anchor and these * checkers. */ chainFailed = pkix_CheckChain (certs, numCerts, anchor, checkers, revChecker, validateCheckedCritExtOIDsList, procParams, &certIndex, &checkerIndex, &revChecking, &reasonCode, &nbioContext, &finalPubKey, &validPolicyTree, pVerifyTree, plContext); if (nbioContext != NULL) { *pCertIndex = certIndex; *pAnchorIndex = anchorIndex; *pCheckerIndex = checkerIndex; *pRevChecking = revChecking; PKIX_INCREF(checkers); *pCheckers = checkers; *pNBIOContext = nbioContext; goto cleanup; } if (chainFailed) { /* cert chain failed to validate */ PKIX_DECREF(chainFailed); PKIX_DECREF(anchor); PKIX_DECREF(checkers); PKIX_DECREF(validPolicyTree); /* if last anchor, we fail; else, we try next anchor */ if (i == (numAnchors - 1)) { /* last anchor */ PKIX_ERROR(PKIX_VALIDATECHAINFAILED); } } else { /* XXX Remove this assertion after 2014-12-31. * See bug 946984. */ PORT_Assert(reasonCode == 0); /* cert chain successfully validated! */ PKIX_CHECK(pkix_ValidateResult_Create (finalPubKey, anchor, validPolicyTree, &valResult, plContext), PKIX_VALIDATERESULTCREATEFAILED); *pResult = valResult; /* no need to try any more anchors in the loop */ goto cleanup; } } cleanup: PKIX_DECREF(finalPubKey); PKIX_DECREF(certs); PKIX_DECREF(anchors); PKIX_DECREF(anchor); PKIX_DECREF(checkers); PKIX_DECREF(revChecker); PKIX_DECREF(validPolicyTree); PKIX_DECREF(chainFailed); PKIX_DECREF(procParams); PKIX_DECREF(userCheckers); PKIX_DECREF(validateCheckedCritExtOIDsList); PKIX_RETURN(VALIDATE); }
RuralHunter/htmlunit
src/main/java/com/gargoylesoftware/htmlunit/util/geometry/Line2D.java
<gh_stars>0 /* * Copyright (c) 2002-2021 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gargoylesoftware.htmlunit.util.geometry; /** * Simple 2D shape line. * * @author <NAME> */ public class Line2D implements Shape2D { private final double startX_; private final double startY_; private final double endX_; private final double endY_; private final boolean isVertical_; private final double slope_; private final double yIntercept_; /** * Ctor. * @param start the start point * @param end the end point */ public Line2D(final Point2D start, final Point2D end) { this(start.getX(), start.getY(), end.getX(), end.getY()); } /** * Ctor. * @param x1 the x value of the start point * @param y1 the y value of the start point * @param x2 the x value of the end point * @param y2 the y value of the end point */ public Line2D(final double x1, final double y1, final double x2, final double y2) { startX_ = x1; startY_ = y1; endX_ = x2; endY_ = y2; isVertical_ = Math.abs(startX_ - endX_) < epsilon; if (isVertical_) { slope_ = Double.NaN; yIntercept_ = Double.NaN; } else { // y = slope * x + b slope_ = (endY_ - startY_) / (endX_ - startX_); yIntercept_ = startY_ - slope_ * startX_; } } /** * @param line the line to intersect this with * @return the intersection point of the two lines or null if they are parallel */ public Point2D intersect(final Line2D line) { if (isVertical_ && line.isVertical_) { return null; } if (isVertical_ && !line.isVertical_) { final double intersectY = line.slope_ * startX_ + line.yIntercept_; return new Point2D(startX_, intersectY); } if (!isVertical_ && line.isVertical_) { final double intersectY = slope_ * line.startX_ + yIntercept_; return new Point2D(line.startX_, intersectY); } // parallel? if (Math.abs(slope_ - line.slope_) < epsilon) { return null; } // x = (n2-n1)/(m1-m2) final double intersectX = (line.yIntercept_ - yIntercept_) / (slope_ - line.slope_); // y = m2*x+n2 final double intersectY = slope_ * intersectX + yIntercept_; return new Point2D(intersectX, intersectY); } /** * {@inheritDoc} */ @Override public boolean contains(final double x, final double y) { if (isVertical_) { if (Math.abs(startX_ - x) > epsilon) { return false; } } else { final double testY = slope_ * x + yIntercept_; if (Math.abs(y - testY) > epsilon) { return false; } if (x < startX_ && x < endX_ || (x > startX_ && x > endX_)) { return false; } } if (y < startY_ && y < endY_ || (y > startY_ && y > endY_)) { return false; } return true; } /** * {@inheritDoc} */ @Override public boolean isEmpty() { return Math.abs(startX_ - endX_) < epsilon && Math.abs(startY_ - endY_) < epsilon; } @Override public String toString() { return "Line2D [ (" + startX_ + ", " + startY_ + "), (" + endX_ + ", " + endY_ + "), " + (isVertical_ ? "isVertical" : "y = " + slope_ + "*x + " + yIntercept_ + "]"); } }
elgeish/auc-plethora
Plethora Core/src/org/netbeans/modules/plethora/peers/BoxWrapper.java
/* * The original code is Plethora. The initial developer of the original * code is the Plethora Group at The American University in Cairo. * * http://www.cs.aucegypt.edu/ * * BoxWrapper.java * Created on November 15, 2006 */ package org.netbeans.modules.plethora.peers; import edu.aucegypt.plethora.widgets.Appearance; import javax.xml.xpath.XPathExpressionException; import org.jdesktop.lg3d.utils.shape.Box; import org.netbeans.modules.plethora.inspector.Lg3dComponentInspector; import org.netbeans.modules.plethora.model.Lg3dDataDocument; import org.netbeans.modules.plethora.model.Parameter; import org.netbeans.modules.plethora.model.SimpleParameter; /** * Wrapper for a Box. * It provides setters for the properties that don't have setters. * It also provides getters for the properties whose getters take an out parameter. * It also provides setters that wraps the super's setters and save * the property in the Lg3dDataDocument if it's changed and removes it from the * Lg3dDataDocument if it's restored to its default value * * @see BoxPeer * @see Lg3dDataDocument * * @author <NAME> * @version 1.00 */ public class BoxWrapper extends Box implements ShapeWrapper { private static final int DEFAULT_DIM = 1; private Lg3dDataDocument lg3dDataDocument; private BoxPeer boxPeer; private Appearance appearance; public BoxWrapper() { this(DEFAULT_DIM, DEFAULT_DIM, DEFAULT_DIM, DEFAULT_APPEARANCE); } public BoxWrapper(float xdim, float ydim, float zdim, Appearance ap) { super(xdim, ydim, zdim, ap); lg3dDataDocument = Lg3dComponentInspector.getInstance().getLg3dDataDocument(); appearance = ap; } public ShapePeer getShapePeer() { return boxPeer; } public void setShapePeer(ShapePeer shapePeer) { boxPeer = (BoxPeer) shapePeer; } public void setProperty(String property, Class type, Object value) { try { if (lg3dDataDocument != null) { lg3dDataDocument.setProperty(getName(), property, type.getName(), String.valueOf(value)); } } catch (Exception ex) { ex.printStackTrace(); } } public void setProperty(String property, Class type, Parameter... parameters) { try { if (lg3dDataDocument != null) { lg3dDataDocument.setProperty(getName(), property, type.getName(), parameters); } } catch (Exception ex) { ex.printStackTrace(); } } public void resetProperty(String property) { try { if (lg3dDataDocument != null) { lg3dDataDocument.removeProperty(getName(), property); } } catch (Exception ex) { ex.printStackTrace(); } } public Lg3dDataDocument getLg3dDataDocument() { return lg3dDataDocument; } public void setParameters(float xdim, float ydim, float zdim, Appearance ap) { try { lg3dDataDocument.setParameters(getName(), new SimpleParameter(float.class.getName(), xdim + "f"), new SimpleParameter(float.class.getName(), ydim + "f"), new SimpleParameter(float.class.getName(), zdim + "f"), ShapePeer.createAppearanceParameter(ap)); } catch (XPathExpressionException ex) { ex.printStackTrace(); } } public void setXdimension(float xdim) { setParameters(xdim, getYdimension(), getZdimension(), getAppearance0()); ShapePeer.reconstruct(boxPeer, xdim, getYdimension(), getZdimension(), getAppearance0()); } public void setYdimension(float ydim) { setParameters(getXdimension(), ydim, getZdimension(), getAppearance0()); ShapePeer.reconstruct(boxPeer, getXdimension(), ydim, getZdimension(), getAppearance0()); } public void setZdimension(float zdim) { setParameters(getXdimension(), getYdimension(), zdim, getAppearance0()); ShapePeer.reconstruct(boxPeer, getXdimension(), getYdimension(), zdim, getAppearance0()); } public void setAppearance0(Appearance ap) { setParameters(getXdimension(), getYdimension(), getZdimension(), ap); ShapePeer.reconstruct(boxPeer, getXdimension(), getYdimension(), getZdimension(), ap); } public Appearance getAppearance0() { return appearance; } }
enfoTek/tomato.linksys.e2000.nvram-mod
release/src/linux/linux/include/asm-ia64/sn/sn2/mmzone_sn2.h
<filename>release/src/linux/linux/include/asm-ia64/sn/sn2/mmzone_sn2.h<gh_stars>10-100 #ifndef _ASM_IA64_SN_MMZONE_SN2_H #define _ASM_IA64_SN_MMZONE_SN2_H /* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (c) 2000-2002 Silicon Graphics, Inc. All rights reserved. */ #include <linux/config.h> /* * SGI SN2 Arch defined values * * An SN2 physical address is broken down as follows: * * +-----------------------------------------+ * | | | | node offset | * | unused | node | AS |-------------------| * | | | | cn | clump offset | * +-----------------------------------------+ * 6 4 4 3 3 3 3 3 3 0 * 3 9 8 8 7 6 5 4 3 0 * * bits 63-49 Unused - must be zero * bits 48-38 Node number. Note that some configurations do NOT * have a node zero. * bits 37-36 Address space ID. Cached memory has a value of 3 (!!!). * Chipset & IO addresses have other values. * (Yikes!! The hardware folks hate us...) * bits 35-0 Node offset. * * The node offset can be further broken down as: * bits 35-34 Clump (bank) number. * bits 33-0 Clump (bank) offset. * * A node consists of up to 4 clumps (banks) of memory. A clump may be empty, or may be * populated with a single contiguous block of memory starting at clump * offset 0. The size of the block is (2**n) * 64MB, where 0<n<9. * * Important notes: * - IO space addresses are embedded with the range of valid memory addresses. * - All cached memory addresses have bits 36 & 37 set to 1's. * - There is no physical address 0. * * NOTE: This file exports symbols prefixed with "PLAT_". Symbols prefixed with * "SN_" are intended for internal use only and should not be used in * any platform independent code. * * This file is also responsible for exporting the following definitions: * cnodeid_t Define a compact node id. */ typedef signed short cnodeid_t; #define SN2_BANKS_PER_NODE 4 #define SN2_NODE_SIZE (64UL*1024*1024*1024) /* 64GB per node */ #define SN2_BANK_SIZE (SN2_NODE_SIZE/SN2_BANKS_PER_NODE) #define SN2_NODE_SHIFT 38 #define SN2_NODE_MASK 0x7ffUL #define SN2_NODE_OFFSET_MASK (SN2_NODE_SIZE-1) #define SN2_NODE_NUMBER(addr) (((unsigned long)(addr) >> SN2_NODE_SHIFT) & SN2_NODE_MASK) #define SN2_NODE_CLUMP_NUMBER(kaddr) (((unsigned long)(kaddr) >>34) & 3) #define SN2_NODE_OFFSET(addr) (((unsigned long)(addr)) & SN2_NODE_OFFSET_MASK) #define SN2_KADDR(nasid, offset) (((unsigned long)(nasid)<<SN2_NODE_SHIFT) | (offset) | SN2_PAGE_OFFSET) #define SN2_PAGE_OFFSET 0xe000003000000000UL /* Cacheable memory space */ #define PLAT_MAX_NODE_NUMBER 2048 /* Maximum node number + 1 */ #define PLAT_MAX_COMPACT_NODES 128 /* Maximum number of nodes in SSI system */ #define PLAT_MAX_PHYS_MEMORY (1UL << 49) /* * On the SN platforms, a clump is the same as a memory bank. */ #define PLAT_CLUMPS_PER_NODE SN2_BANKS_PER_NODE #define PLAT_CLUMP_OFFSET(addr) ((unsigned long)(addr) & 0x3ffffffffUL) #define PLAT_CLUMPSIZE (SN2_NODE_SIZE/PLAT_CLUMPS_PER_NODE) #define PLAT_MAXCLUMPS (PLAT_CLUMPS_PER_NODE * PLAT_MAX_COMPACT_NODES) /* * PLAT_VALID_MEM_KADDR returns a boolean to indicate if a kaddr is potentially a * valid cacheable identity mapped RAM memory address. * Note that the RAM may or may not actually be present!! */ #define SN2_VALID_KERN_ADDR_MASK 0xffff003000000000UL #define SN2_VALID_KERN_ADDR_VALUE 0xe000003000000000UL #define PLAT_VALID_MEM_KADDR(kaddr) (((unsigned long)(kaddr) & SN2_VALID_KERN_ADDR_MASK) == SN2_VALID_KERN_ADDR_VALUE) /* * Memory is conceptually divided into chunks. A chunk is either * completely present, or else the kernel assumes it is completely * absent. Each node consists of a number of possibly contiguous chunks. */ #define SN2_CHUNKSHIFT 25 /* 32 MB */ #define PLAT_CHUNKSIZE (1UL << SN2_CHUNKSHIFT) #define PLAT_CHUNKNUM(addr) ({unsigned long _p=(unsigned long)(addr); \ (((_p&SN2_NODE_MASK)>>2) | \ (_p&SN2_NODE_OFFSET_MASK)) >>SN2_CHUNKSHIFT;}) /* * Given a kaddr, find the nid (compact nodeid) */ #ifdef CONFIG_IA64_SGI_SN_DEBUG #define DISCONBUG(kaddr) panic("DISCONTIG BUG: line %d, %s. kaddr 0x%lx", \ __LINE__, __FILE__, (long)(kaddr)) #define KVADDR_TO_NID(kaddr) ({long _ktn=(long)(kaddr); \ kern_addr_valid(_ktn) ? \ local_node_data->physical_node_map[SN2_NODE_NUMBER(_ktn)] : \ (DISCONBUG(_ktn), 0UL);}) #else #define KVADDR_TO_NID(kaddr) (local_node_data->physical_node_map[SN2_NODE_NUMBER(kaddr)]) #endif /* * Given a kaddr, find the index into the clump_mem_map_base array of the page struct entry * for the first page of the clump. */ #define PLAT_CLUMP_MEM_MAP_INDEX(kaddr) ({long _kmmi=(long)(kaddr); \ KVADDR_TO_NID(_kmmi) * PLAT_CLUMPS_PER_NODE + \ SN2_NODE_CLUMP_NUMBER(_kmmi);}) /* * Calculate a "goal" value to be passed to __alloc_bootmem_node for allocating structures on * nodes so that they dont alias to the same line in the cache as the previous allocated structure. * This macro takes an address of the end of previous allocation, rounds it to a page boundary & * changes the node number. */ #define PLAT_BOOTMEM_ALLOC_GOAL(cnode,kaddr) __pa(SN2_KADDR(PLAT_PXM_TO_PHYS_NODE_NUMBER(nid_to_pxm_map[cnode]), \ (SN2_NODE_OFFSET(kaddr) + PAGE_SIZE - 1) >> PAGE_SHIFT << PAGE_SHIFT)) /* * Convert a proximity domain number (from the ACPI tables) into a physical node number. * Note: on SN2, the promity domain number is the same as bits [8:1] of the NASID. The following * algorithm relies on: * - bit 0 of the NASID for cpu nodes is always 0 * - bits [10:9] of all NASIDs in a partition are always the same * - hard_smp_processor_id return the SAPIC of the current cpu & * bits 0..11 contain the NASID. * * All of this complexity is because MS architectually limited proximity domain numbers to * 8 bits. */ #define PLAT_PXM_TO_PHYS_NODE_NUMBER(pxm) (((pxm)<<1) | (hard_smp_processor_id() & 0x300)) #endif /* _ASM_IA64_SN_MMZONE_SN2_H */
dpla/primary-source-sets
app/controllers/authors_controller.rb
## # Handles HTTP requests for Authors # # @see Author class AuthorsController < ApplicationController before_action :authenticate_admin! def index @authors = Author.all end def show @author = Author.find(params[:id]) end def new @author = Author.new @author.source_set_ids = [params[:source_set_id]] @author.guide_ids = [params[:guide_id]] end def edit @author = Author.find(params[:id]) end def create @author = Author.new(author_params) if @author.save redirect_to @author else render 'new' end end def update @author = Author.find(params[:id]) if @author.update(author_params) redirect_to @author else render 'edit' end end def destroy @author = Author.find(params[:id]) @author.destroy redirect_to authors_path end private def author_params params.require(:author).permit(:name, :affiliation, source_set_ids: [], guide_ids: []) end end
BelousAI/JavaRush
1.JavaSyntax/src/Test/Shildt_G/Threads/TestThreadSynch_3_Wait_Flag.java
package Test.Shildt_G.Threads; /** * Created by Антон on 17.03.2017. */ public class TestThreadSynch_3_Wait_Flag { static class NewThread implements Runnable { String name; Thread t; boolean suspendFlag; NewThread(String nameThread) { name = nameThread; t = new Thread(this, name); System.out.println("Новый поток: " + t); t.start(); } public void run() { try { for (int i = 15; i > 0; i--) { System.out.println(name + " : " + i); Thread.sleep(200); synchronized (this) { while (suspendFlag) { wait(); } } } } catch (InterruptedException e) { System.out.println(name + " прерван"); } System.out.println(name + " завершен"); } synchronized void mysuspend() { suspendFlag = true; } synchronized void myresume() { suspendFlag = false; notify(); } } static class SuspendResume { public static void main(String[] args) { NewThread ob1 = new NewThread("Первый"); NewThread ob2 = new NewThread("Второй"); try { Thread.sleep(1000); ob1.mysuspend(); System.out.println("Приостановка Первого потока"); Thread.sleep(1000); ob1.myresume(); System.out.println("Возобновление Первого потока"); ob2.mysuspend(); System.out.println("Приостановка Второго потока"); Thread.sleep(1000); ob2.myresume(); System.out.println("Возобновление Второго потока"); } catch (InterruptedException e) { System.out.println("Главный поток прерван"); } // Ожидать завершения потоков исполнения try { System.out.println("Ожидание завершения потоков."); ob1.t.join(); ob2.t.join(); } catch (InterruptedException e) { System.out.println("Главный поток прерван"); } System.out.println("Главный поток завершен."); } } }
dcurrie/picrin
contrib/10.roundtrip/emyg_pow5.h
<gh_stars>100-1000 /* emyg_pow5.h */ /* This isn't really a header file, but we keep it in a separate file ** to support alternate implementations, and because it's big. ** It has be a .h (rather than a .c) file to avoid fooling premake4 ** into building into the image twice. */ #ifndef MAX_POW5_IN_TABLE #define MAX_POW5_IN_TABLE 345u /* These are powers of 5 with 32-bit digits in little endian format */ /* generated using (pow5c 345) from testgen.scm */ static const uint32_t pow5[] = { 1u, 5u, 25u, 125u, 625u, 3125u, 15625u, 78125u, 390625u, 1953125u, 9765625u, 48828125u, 244140625u, 1220703125u, 1808548329u, 1u, 452807053u, 7u, 2264035265u, 35u, 2730241733u, 177u, 766306777u, 888u, 3831533885u, 4440u, 1977800241u, 22204u, 1299066613u, 111022u, 2200365769u, 555111u, 2411894253u, 2775557u, 3469536673u, 13877787u, 167814181u, 69388939u, 839070905u, 346944695u, 4195354525u, 1734723475u, 3796903441u, 83682787u, 2u, 1804648021u, 418413939u, 10u, 433305513u, 2092069697u, 50u, 2166527565u, 1870413893u, 252u, 2242703233u, 762134875u, 1262u, 2623581573u, 3810674377u, 6310u, 233005977u, 1873502704u, 31554u, 1165029885u, 777578928u, 157772u, 1530182129u, 3887894641u, 788860u, 3355943349u, 2259604022u, 3944304u, 3894814857u, 2708085521u, 19721522u, 2294205101u, 655525721u, 98607613u, 2881090913u, 3277628607u, 493038065u, 1520552677u, 3503241150u, 2465190328u, 3307796089u, 336336567u, 3736017052u, 2u, 3654078557u, 1681682838u, 1500216076u, 14u, 1090523601u, 4113446898u, 3206113085u, 71u, 1157650709u, 3387365307u, 3145663541u, 358u, 1493286249u, 4051924648u, 2843415820u, 1793u, 3171463949u, 3079754057u, 1332177216u, 8968u, 2972417857u, 2513868400u, 2365918787u, 44841u, 1977187397u, 3979407411u, 3239659345u, 224207u, 1296002393u, 2717167873u, 3313394841u, 1121038u, 2185044669u, 700937478u, 3682072320u, 5605193u, 2335288753u, 3504687392u, 1230492416u, 28025969u, 3086509173u, 343567778u, 1857494788u, 140129846u, 2547643977u, 1717838893u, 697539348u, 700649232u, 4148285293u, 4294227171u, 3487696741u, 3503246160u, 3561557281u, 4291266675u, 258614525u, 336361620u, 4u, 627917221u, 4276464195u, 1293072629u, 1681808100u, 20u, 3139586105u, 4202451791u, 2170395853u, 4114073205u, 101u, 2813028637u, 3832389774u, 2262044677u, 3390496843u, 509u, 1180241297u, 1982079689u, 2720288797u, 4067582329u, 2548u, 1606239189u, 1320463854u, 716542099u, 3158042464u, 12744u, 3736228649u, 2307351975u, 3582710496u, 2905310432u, 63723u, 1501274061u, 2946825287u, 733683298u, 1641650276u, 318618u, 3211403009u, 1849224548u, 3668416493u, 3913284084u, 1593091u, 3172113157u, 656188151u, 1162213283u, 2386551240u, 7965459u, 2975663897u, 3280940758u, 1516099119u, 3342821609u, 39827297u, 1993417597u, 3519801905u, 3285528302u, 3829206158u, 199136488u, 1377153393u, 419140343u, 3542739626u, 1966161609u, 995682444u, 2590799669u, 2095701716u, 533828946u, 1240873457u, 683444926u, 1u, 69096457u, 1888573991u, 2669144732u, 1909399989u, 3417224631u, 5u, 345482285u, 852935363u, 460821774u, 957065356u, 4201221269u, 28u, 1727411425u, 4264676815u, 2304108870u, 490359484u, 3826237162u, 144u, 47122533u, 4143514893u, 2930609762u, 2451797422u, 1951316626u, 724u, 235612665u, 3537705281u, 1768146926u, 3669052521u, 1166648540u, 3622u, 1178063325u, 508657221u, 250800042u, 1165393423u, 1538275408u, 18111u, 1595349329u, 2543286106u, 1254000210u, 1531999819u, 3396409745u, 90556u, 3681779349u, 4126495939u, 1975033756u, 3365031800u, 4097146838u, 452783u, 1229027561u, 3452610515u, 1285234192u, 3940257114u, 3305865009u, 2263919u, 1850170509u, 83183392u, 2131203668u, 2521416387u, 3644423161u, 11319598u, 660917953u, 415916962u, 2066083748u, 4017147345u, 1042246623u, 56597994u, 3304589765u, 2079584810u, 1740484148u, 2905867543u, 916265823u, 282989971u, 3638046937u, 1807989461u, 112486150u, 1644435829u, 286361822u, 1414949856u, 1010365501u, 450012717u, 562430752u, 3927211849u, 1431809111u, 2779781984u, 1u, 756860209u, 2250063586u, 2812153760u, 2456190061u, 2864078263u, 1014008033u, 8u, 3784301045u, 2660383338u, 1175866914u, 3691015716u, 1435489429u, 775072872u, 41u, 1741636041u, 417014806u, 1584367277u, 1275209397u, 2882479853u, 3875364361u, 205u, 118245613u, 2085074032u, 3626869089u, 2081079690u, 1527497378u, 2196952624u, 1029u, 591228065u, 1835435568u, 954476263u, 1815463862u, 3342519596u, 2394828529u, 5147u, 2956140325u, 587243248u, 477414021u, 487384719u, 3827696094u, 3384208056u, 25737u, 1895799737u, 2936216243u, 2387070105u, 2436923595u, 1958611286u, 4036138396u, 128688u, 889064093u, 1796179329u, 3345415936u, 3594683385u, 1203121840u, 3000822798u, 643444u, 150353169u, 390962054u, 3842177794u, 793547744u, 1720641908u, 2119212103u, 3217223u, 751765845u, 1954810270u, 2031019786u, 3967738724u, 13274948u, 2006125925u, 16086117u, 3758829225u, 1184116758u, 1565164340u, 2658824438u, 66374744u, 1440695033u, 80430587u, 1614276941u, 1625616498u, 3530854405u, 409220303u, 331873723u, 2908507869u, 402152936u, 3776417409u, 3833115195u, 474402842u, 2046101519u, 1659368615u, 1657637457u, 2010764683u, 1702217861u, 1985706795u, 2372014214u, 1640573003u, 4001875781u, 3993219990u, 1463888824u, 2u, 4216122009u, 1338599384u, 3270136480u, 3907897721u, 2829509722u, 2786230770u, 3024476828u, 11u, 3900740861u, 2398029628u, 3465780513u, 2359619424u, 1262646726u, 1046251965u, 2237482255u, 58u, 2323835121u, 3400213552u, 149033383u, 3208162532u, 2018266336u, 936292530u, 2597476684u, 292u, 3029241013u, 4116165874u, 745166918u, 3155910772u, 1501397091u, 386495356u, 102481533u, 1463u, 2261303177u, 3400960189u, 3725834594u, 2894651972u, 3212018162u, 1932476781u, 512407665u, 7315u, 2716581293u, 4119899059u, 1449303789u, 1588357976u, 3175188925u, 1072449316u, 2562038327u, 36575u, 698004577u, 3419626114u, 2951551653u, 3646822585u, 2991042738u, 1067279287u, 4220257044u, 182877u, 3490022885u, 4213228682u, 1872856380u, 1054243744u, 2070311806u, 1041429142u, 3921416037u, 914389u, 270245241u, 3886274230u, 774347312u, 976251426u, 1761624439u, 912178416u, 2427211002u, 4571949u, 1351226205u, 2251501966u, 3871736564u, 586289834u, 218187604u, 265924786u, 3546120419u, 22859747u, 2461163729u, 2667575239u, 2178813638u, 2931449174u, 1090938020u, 1329623930u, 550732911u, 114298739u, 3715884053u, 452974309u, 2304133601u, 1772343984u, 1159722807u, 2353152355u, 2753664556u, 571493695u, 1399551081u, 2264871549u, 2930733413u, 271785330u, 1503646741u, 3175827184u, 883420894u, 2857468478u, 2702788109u, 2734423154u, 1768765179u, 1358926653u, 3223266409u, 2994234033u, 122137177u, 1402440503u, 3u, 629038657u, 787213885u, 253891306u, 2499665971u, 3231430158u, 2086268280u, 610685888u, 2717235219u, 16u, 3145193285u, 3936069425u, 1269456530u, 3908395263u, 3272248904u, 1841406811u, 3053429442u, 701274207u, 83u, 2841064537u, 2500477944u, 2052315358u, 2362107132u, 3476342636u, 617099466u, 2382245324u, 3506371038u, 415u, 1320420797u, 3912455131u, 1671642200u, 3220601070u, 201843998u, 3085497334u, 3321292028u, 351986008u, 2079u, 2307136689u, 2382406472u, 4063243708u, 3218103463u, 1009219993u, 2542584782u, 3721558255u, 1759930043u, 10395u, 2945748853u, 3322097770u, 3136349358u, 3205615431u, 751132672u, 4122989319u, 1427922093u, 209715627u, 51977u, 1843842377u, 3725586965u, 2796844905u, 3143175270u, 3755663363u, 3435077411u, 2844643173u, 1048578136u, 259885u, 629277293u, 1448065643u, 1099322641u, 2830974465u, 1598447634u, 4290485171u, 1338313980u, 947923387u, 1299426u, 3146386465u, 2945360919u, 1201645910u, 1269970438u, 3697270877u, 4272556672u, 2396602608u, 444649640u, 6497131u, 2847030437u, 1841902710u, 1713262257u, 2054884895u, 1306485202u, 4182914180u, 3393078452u, 2223248202u, 32485655u, 1350250297u, 619578961u, 4271343991u, 1684489884u, 2237458716u, 3734701717u, 4080490376u, 2526306421u, 162428277u, 2456284189u, 3097894806u, 4176850771u, 4127482128u, 2597358989u, 1493639403u, 3222582700u, 4041597517u, 812141387u, 3691486353u, 2604572144u, 3704384674u, 3457541460u, 101893061u, 3173229722u, 3228011613u, 3028118404u, 4060706939u, 1277562581u, 137958836u, 1342054189u, 107838120u, 509465309u, 2981246722u, 3255156180u, 2255690135u, 3123665514u, 4u, 2092845609u, 689794181u, 2415303649u, 539190601u, 2547326545u, 2021331722u, 3390879015u, 2688516086u, 2733425684u, 23u, 1874293453u, 3448970907u, 3486583653u, 2695953007u, 4146698133u, 1516724020u, 4069493189u, 557678545u, 782226535u, 118u, 781532673u, 64985353u, 253049085u, 594863151u, 3553621484u, 3288652808u, 3167596762u, 2788392729u, 3911132675u, 590u, 3907663365u, 324926765u, 1265245425u, 2974315755u, 588238236u, 3558362156u, 2953081925u, 1057061760u, 2375794194u, 2954u, 2358447641u, 1624633829u, 2031259829u, 1986676888u, 2941191183u, 611941596u, 1880507741u, 990341507u, 3289036379u, 14772u, 3202303613u, 3828201851u, 1566364554u, 1343449850u, 1821054029u, 3059707983u, 812604113u, 656740241u, 3560280008u, 73863u, 3126616177u, 1961140074u, 3536855478u, 2422281955u, 515335554u, 2413638029u, 4063020568u, 3283701205u, 621530856u, 369319u, 2748178997u, 1215765781u, 504408208u, 3521475187u, 2576677772u, 3478255553u, 3135233658u, 3533604141u, 3107654283u, 1846595u, 855993097u, 1783861612u, 2522041041u, 427506751u, 4293454272u, 211408583u, 2791266406u, 488151524u, 2653369531u, 9232978u, 4279965485u, 329373468u, 4020270615u, 2137533757u, 4287402176u, 1057042919u, 1071430142u, 2440757623u, 381945767u, 46164893u, 4219958241u, 1646867344u, 2921483891u, 2097734197u, 4257141698u, 990247303u, 1062183415u, 3613853524u, 1909728837u, 230824465u, 3919922021u, 3939369428u, 1722517568u, 1898736396u, 4105839308u, 656269223u, 1015949780u, 889398437u, 958709597u, 1154122327u, 2419740921u, 2516977960u, 22653252u, 903747390u, 3349327358u, 3281346119u, 784781604u, 152024890u, 498580690u, 1475644340u, 1u, 3508770013u, 3994955210u, 113266262u, 223769654u, 3861734903u, 3521828710u, 3923908023u, 760124450u, 2492903450u, 3083254404u, 6u, 363980881u, 2794906870u, 566331314u, 1118848270u, 2128805331u, 429274370u, 2439670935u, 3800622254u, 3874582658u, 2531370134u, 33u, 1819904405u, 1089632462u, 2831656573u, 1299274054u, 2054092064u, 2146371852u, 3608420083u, 1823242088u, 2193044110u, 4066916082u, 167u, 509587433u, 1153195016u, 1273380978u, 2201402977u, 1680525729u, 2141924670u, 862231233u, 526275852u, 2375285960u, 3154711228u, 839u, 2547937165u, 1471007784u, 2071937595u, 2417080294u, 4107661351u, 2119688759u, 16188871u, 2631379261u, 3286495208u, 2888654254u, 4198u, 4149751233u, 3060071626u, 1769753384u, 3495466880u, 3358437573u, 2008509207u, 80944357u, 271994417u, 3547574155u, 1558369385u, 20993u, 3568886981u, 2415456246u, 258832331u, 297465218u, 3907285981u, 1452611446u, 404721787u, 1359972085u, 558001591u, 3496879633u, 104966u, 664565721u, 3487346642u, 1294161657u, 1487326090u, 2356560721u, 2968089938u, 2023608936u, 2504893129u, 2790007956u, 304528981u, 524834u, 3322828605u, 256864026u, 2175840993u, 3141663155u, 3192869014u, 1955547804u, 1528110091u, 3934531055u, 1065137894u, 1522644908u, 2624170u, 3729241137u, 1284320133u, 2289270373u, 2823413889u, 3079443185u, 1187804431u, 3345583161u, 2492786092u, 1030722178u, 3318257245u, 13120851u, 1466336501u, 2126633373u, 2856417274u, 1232167559u, 2512314040u, 1644054862u, 3843013918u, 3873995871u, 858643596u, 3706384338u, 65604258u, 3036715209u, 2043232274u, 1397184484u, 1865870502u, 3971635609u, 3925307016u, 2035200407u, 2190110175u, 4293217984u, 1352052506u, 328021294u, 2298674157u, 1626226781u, 2690955126u, 739417919u, 2678308863u, 2446665900u, 1586067447u, 2360616285u, 4286220738u, 2465295238u, 1640106471u, 2903436193u, 3836166611u, 569873743u, 3697089598u, 506642427u, 3643394911u, 3635369941u, 3213146834u, 4251234508u, 3736541602u, 3905565061u, 1u, 1632279077u, 2000963874u, 2849368719u, 1305578806u, 2533212139u, 1037105371u, 996980525u, 3180832286u, 4076303359u, 1502838830u, 2347956125u, 9u, 3866428089u, 1414884779u, 1361941709u, 2232926737u, 4076126104u, 890559561u, 689935330u, 3019259543u, 3201647614u, 3219226858u, 3149846034u, 47u, 2152271261u, 2779456603u, 2514741250u, 2574699094u, 3200761338u, 157830513u, 3449676651u, 2211395827u, 3123336185u, 3211232405u, 2864328285u, 238u, 2171421713u, 1012381129u, 3983771661u, 4283560880u, 3118904804u, 789152568u, 68514071u, 2467044547u, 2731779039u, 3171260140u, 1436739540u, 1193u, 2267173973u, 766938351u, 2738989122u, 4237935220u, 2709622136u, 3945762843u, 342570355u, 3745288143u, 773993309u, 2971398815u, 2888730407u, 5966u, 2745935273u, 3834691757u, 810043722u, 4009806919u, 663208796u, 2548945034u, 1712851779u, 1546571531u, 3869966549u, 1972092187u, 1558750150u, 29833u, 844774477u, 1993589604u, 4050218614u, 2869165411u, 3316043984u, 4154790578u, 4269291601u, 3437890360u, 2169963562u, 1270526347u, 3498783456u, 149166u, 4223872385u, 1378013428u, 3071223888u, 1460925171u, 3695318035u, 3594083709u, 4166588825u, 9582620u, 2259883222u, 2057664441u, 314048097u, 745834u, 3939492741u, 2595099848u, 2471217553u, 3009658562u, 1296720992u, 790549365u, 3653074945u, 47913104u, 2709481518u, 1698387615u, 1570240487u, 3729170u, 2517594521u, 90597356u, 3766153176u, 2163390924u, 2188637667u, 3952746826u, 1085505541u, 239565524u, 662505702u, 4196970782u, 3556235140u, 18645851u, 3998038013u, 452986782u, 1650896696u, 2227020032u, 2353253745u, 2583864948u, 1132560413u, 1197827621u, 3312528510u, 3804984726u, 601306520u, 93229259u, 2810320881u, 2264933914u, 3959516184u, 2545165569u, 3176334135u, 34422854u, 1367834772u, 1694170810u, 3677740663u, 1845054449u, 3006532604u, 466146295u, 1166702517u, 2734734981u, 2617711738u, 4135893257u, 2996768789u, 172114273u, 2544206564u, 4175886755u, 1208834132u, 635337657u, 2147761134u, 2330731478u, 1538545289u, 788773018u, 203656805u, 3499597104u, 2098942061u, 860571368u, 4131098228u, 3699564593u, 1749203368u, 3176688286u, 2148871078u, 3063722800u, 2u, 3397759149u, 3943865091u, 1018284025u, 318116336u, 1904775717u, 7889546u, 3475621957u, 1317953785u, 156082252u, 2998539544u, 2154420801u, 2433712114u, 13u, 4103893857u, 2539456274u, 796452833u, 1590581681u, 933943993u, 39447732u, 198240601u, 2294801633u, 780411261u, 2107795832u, 2182169416u, 3578625980u, 67u, 3339600101u, 4107346782u, 3982264167u, 3657941109u, 374752670u, 197238661u, 991203005u, 2884073573u, 3902056307u, 1949044568u, 2320912490u, 713260718u, 339u, 3813098617u, 3356864729u, 2731451655u, 1109836365u, 1873763354u, 986193305u, 661047729u, 1535465978u, 2330412354u, 1155288252u, 3014627860u, 3566303592u, 1695u, 1885623901u, 3899421761u, 772356390u, 1254214532u, 778882179u, 635999231u, 3305238646u, 3382362594u, 3062127179u, 1481473966u, 2188237413u, 651648779u, 8479u, 838184913u, 2317239623u, 3861781954u, 1976105364u, 3894410896u, 3179996155u, 3641291342u, 4026911085u, 2425734010u, 3112402537u, 2351252474u, 3258243897u, 42395u, 4190924565u, 2996263523u, 2129040588u, 1290592232u, 2292185298u, 3015078891u, 1026587529u, 2954686245u, 3538735462u, 2677110799u, 3166327781u, 3406317599u, 211978u, 3774753641u, 2096415731u, 2055268351u, 2157993866u, 2870991899u, 2190492569u, 837970352u, 1888529338u, 513808129u, 500652111u, 2946737020u, 4146686110u, 1059893u, 1693899021u, 1892144067u, 1686407165u, 2200034740u, 1470057609u, 2362528256u, 4189851762u, 852712098u, 2569040647u, 2503260555u, 1848783212u, 3553561369u, 5299469u, 4174527809u, 870785744u, 4137068531u, 2410239109u, 3055320751u, 3222706689u, 3769389628u, 4263560494u, 4255268643u, 3926368185u, 653981470u, 587937663u, 26497349u, 3692769861u, 58961428u, 3505473472u, 3461260957u, 2391701869u, 3228631560u, 1667078959u, 4137933290u, 4096474035u, 2451971745u, 3269907354u, 2939688315u, 132486745u, 1283980121u, 294807144u, 347498176u, 126435605u, 3368574757u, 3258255914u, 4040427502u, 3509797267u, 3302500995u, 3669924137u, 3464634884u, 1813539690u, 662433728u, 2124933309u, 1474035721u, 1737490880u, 632178025u, 3957971897u, 3406377685u, 3022268329u, 369117155u, 3627603091u, 1169751504u, 143305240u, 477763862u, 3312168642u, 2034731953u, 3075211311u, 97519809u, 3160890127u, 2609990301u, 4146986541u, 2226439760u, 1845585778u, 958146271u, 1553790228u, 716526201u, 2388819310u, 3675941322u, 3u, 1583725173u, 2491154669u, 487599048u, 2919548747u, 165049620u, 3555063524u, 2542264212u, 637994300u, 495764061u, 3473983845u, 3582631006u, 3354161958u, 1199837428u, 19u, 3623658569u, 3865838754u, 2437995242u, 1712841847u, 825248103u, 595448436u, 4121386472u, 3189971502u, 2478820305u, 190050041u, 733285850u, 3885907906u, 1704219847u, 96u, 938423661u, 2149324590u, 3600041622u, 4269241941u, 4126240516u, 2977242180u, 3427063176u, 3064955626u, 3804166936u, 950250207u, 3666429250u, 2249670346u, 4226131943u, 481u, 397151009u, 2156688359u, 820338928u, 4166340525u, 3451333400u, 2001309016u, 4250413995u, 2439876245u, 1840965499u, 456283743u, 1152277067u, 2658417142u, 3950790533u, 2409u, 1985755045u, 2193507203u, 4101694642u, 3651833441u, 76797820u, 1416610492u, 4072200793u, 3609446637u, 614892905u, 2281418717u, 1466418039u, 407183823u, 2574083484u, 12049u, 1338840633u, 2377601425u, 3328604028u, 1079298025u, 383989104u, 2788085164u, 3181134782u, 867364005u, 3074464529u, 2817158993u, 3037122901u, 2035919116u, 4280482828u, 60247u, 2399235869u, 3298072534u, 3758118254u, 1101522832u, 1919945521u, 1055523932u, 3020772025u, 41852732u, 2487420758u, 1200893080u, 2300712620u, 1589660991u, 4222544958u, 301239u, 3406244753u, 3605460784u, 1610722089u, 1212646868u, 1009793014u, 982652366u, 2218958238u, 209263663u, 3847169198u, 1709498106u, 2913628509u, 3653337661u, 3932855607u, 1506199u, 4146321877u, 847434739u, 3758643153u, 1768267045u, 753997775u, 618294535u, 2504856599u, 1046318317u, 2055976806u, 4252523238u, 1683240658u, 1086819124u, 2484408855u, 7530999u, 3551740201u, 4237173699u, 1613346581u, 251400637u, 3769988877u, 3091472675u, 3934348403u, 936624291u, 1689949439u, 4082747008u, 4121235998u, 1139128325u, 3832109684u, 37654997u, 578831821u, 4005999315u, 3771765613u, 1257003186u, 1670075201u, 2572461491u, 2491872834u, 388154163u, 4154779900u, 3233865857u, 3426310810u, 1400674333u, 1980679237u, 188274989u, 2894159105u, 2850127391u, 1678958885u, 1990048638u, 4055408710u, 4272372864u, 3869429580u, 1940770817u, 3594030316u, 3284427401u, 4246652165u, 2708404372u, 1313461594u, 941374947u, 1585893637u, 1365735070u, 4099827132u, 1360308599u, 3097174368u, 4181995140u, 2167278720u, 1113919497u, 790282398u, 3537235121u, 4053391644u, 657119976u, 2272340677u, 411907440u, 1u, 3634500889u, 2533708055u, 3319266477u, 2506575703u, 2600969953u, 3730106519u, 2246459012u, 1274630191u, 3951411991u, 506306421u, 3087089040u, 3285599884u, 2771768793u, 2059537202u, 5u, 992635261u, 4078605687u, 3711430499u, 3942943926u, 119947879u, 1470663414u, 2642360472u, 2078183661u, 2577190772u, 2531532109u, 2550543312u, 3543097535u, 973942080u, 1707751421u, 27u, 668209009u, 3213159252u, 1377283315u, 2534850450u, 599739399u, 3058349774u, 326900473u, 1800983716u, 1051974u, 4067725956u, 4162781970u, 535618493u, 574743108u, 4243789810u, 136u, 3341045045u, 3180894372u, 2591449282u, 4084317659u, 2998696997u, 2406846982u, 1634502368u, 414983988u, 5259872u, 3158760596u, 3634040670u, 2678092469u, 2873715540u, 4039079866u, 684u, 3820323337u, 3019569975u, 72344525u, 3241719114u, 2108583101u, 3444300321u, 3877544546u, 2074919941u, 26299360u, 2908901092u, 990334169u, 505560461u, 1483675815u, 3015530149u, 3424u, 1921747501u, 2212947991u, 361722628u, 3323693682u, 1952980916u, 41632423u, 2207853550u, 1784665117u, 131496802u, 1659603572u, 656703552u, 2527802306u, 3123411779u, 2192748858u, 17123u, 1018802913u, 2474805365u, 1808613142u, 3733566522u, 1174969991u, 208162117u, 2449333158u, 333390995u, 657484012u, 4003050564u, 3283517761u, 4049076938u, 2732157009u, 2373809701u, 85617u, 799047269u, 3784092234u, 453131120u, 1487963428u, 1579882663u, 1040810586u, 3656731198u, 1666954977u, 3287420060u, 2835383636u, 3532686921u, 3065515509u, 775883161u, 3279113916u, 428087u, 3995236345u, 1740591986u, 2265655604u, 3144849844u, 3604446020u, 909085635u, 1103786807u, 4039807593u, 3552198413u, 1292016295u, 483565424u, 2442675661u, 3879415808u, 3510667692u, 2140438u, 2796312541u, 113025342u, 2738343430u, 2839347334u, 842360919u, 250460883u, 1223966740u, 3019168782u, 581122885u, 2165114183u, 2417827121u, 3623443713u, 2217209858u, 373469280u, 10702194u, 1096660817u, 565126713u, 806815262u, 1311834785u, 4211804598u, 1252304415u, 1824866404u, 2210942023u, 2905614428u, 2235636323u, 3499201015u, 937349383u, 2496114702u, 1867346402u, 53510970u, 1188336789u, 2825633566u, 4034076310u, 2264206629u, 3879153807u, 1966554783u, 534397429u, 2464775525u, 1643170254u, 2588247026u, 316135893u, 391779623u, 3890638919u, 746797420u, 267554852u, 1646716649u, 1243265943u, 2990512369u, 2731098557u, 2215899853u, 1242839327u, 2671987147u, 3733943033u, 3920883976u, 56333243u, 1580679468u, 1958898115u, 2273325411u, 3733987104u, 1337774260u, 3938615949u, 1921362420u, 2067659958u, 770590900u, 2489564676u, 1919229341u, 475033848u, 1489845984u, 2424550700u, 281666219u, 3608430044u, 1204555984u, 2776692465u, 1490066338u, 2393904008u, 1u, 2513210561u, 1016877512u, 1748365200u, 3852954502u, 3857888788u, 1006212115u, 2375169242u, 3154262624u, 3532818909u, 1408331097u, 862281036u, 1727812628u, 998560438u, 3155364397u, 3379585449u, 7u, 3976118213u, 789420266u, 151891409u, 2084903328u, 2109574760u, 736093283u, 3285911619u, 2886411234u, 484225364u, 2746688193u, 16437885u, 49128549u, 697834896u, 2891920098u, 4013025360u, 38u, 2700721881u, 3947101334u, 759457045u, 1834582048u, 1957939210u, 3680466417u, 3544656207u, 1547154285u, 2421126823u, 848539077u, 82189428u, 245642745u, 3489174480u, 1574698602u, 2885257619u, 194u, 618707517u, 2555637489u, 3797285229u, 582975648u, 1199761460u, 1222462903u, 543411855u, 3440804133u, 3515699524u, 4242695387u, 410947140u, 1228213725u, 266003216u, 3578525718u, 1541386208u, 973u, 3093537585u, 4188252853u, 1806556963u, 2914878244u, 1703840004u, 1817347220u, 2717059276u, 24151481u, 398628440u, 4033607755u, 2054735704u, 1846101329u, 1330016081u, 712759406u, 3411963748u, 4866u, 2582786037u, 3761395084u, 442850227u, 1689489334u, 4224232727u, 496801509u, 700394494u, 120757408u, 1993142200u, 2988169591u, 1683743932u, 640572055u, 2355113111u, 3563797031u, 4174916852u, 24333u, 29028297u, 1627106239u, 2214251139u, 4152479374u, 3941294452u, 2484007549u, 3501972470u, 603787040u, 1375776408u, 2055946069u, 4123752367u, 3202860276u, 3185630963u, 639115973u, 3694715080u, 121669u, 145141485u, 3840563899u, 2481321104u, 3582527688u, 2526603080u, 3830103157u, 329993168u, 3018935204u, 2583914744u, 1689795754u, 3438892653u, 3129399496u, 3043252930u, 3195579868u, 1293706216u, 608349u, 725707425u, 2022950311u, 3816670932u, 732769258u, 4043080812u, 1970646603u, 1649965844u, 2209774132u, 34671835u, 4154011477u, 14594082u, 2762095596u, 2331362765u, 3092997455u, 2173563787u, 3041746u, 3628537125u, 1524816963u, 1903485478u, 3663846294u, 3035534876u, 1263298427u, 3954861926u, 2458936069u, 173359177u, 3590188201u, 72970414u, 925576092u, 3066879236u, 2580085389u, 2277884346u, 15208732u, 962816441u, 3329117523u, 927492799u, 1139362288u, 2292772496u, 2021524842u, 2594440447u, 3704745757u, 866795887u, 771071821u, 364852074u, 332913164u, 2449494293u, 15525060u, 2799487141u, 76043662u, 519114909u, 3760685728u, 342496702u, 1401844145u, 2873927889u, 1517689620u, 87300349u, 1343859604u, 39012143u, 3855359106u, 1824260370u, 1664565820u, 3657536873u, 77625302u, 1112533817u, 380218313u, 2595574545u, 1623559456u, 1712483514u, 2714253429u, 1484737558u, 3293480807u, 436501746u, 2424330724u, 195060716u, 2096926346u, 531367262u, 4027861806u, 1107815182u, 388126514u, 1267701789u, 1901091566u, 92970837u, 3822829987u, 4267450275u, 686365258u, 3128720497u, 3582502148u, 2182508733u, 3531719028u, 975303582u, 1894697138u, 2656836312u, 2959439846u, 1244108618u, 1940632571u, 2043541649u, 915523239u, 2u, 464854185u, 1934280751u, 4157382195u, 3431826294u, 2758700597u, 732641559u, 2322609077u, 478725958u, 581550618u, 883551099u, 399279674u, 1912297345u, 1925575797u, 1113228264u, 1627773655u, 282648901u, 11u, 2324270925u, 1081469163u, 3607041793u, 4274229586u, 908601100u, 3663207798u, 3023110793u, 2393629792u, 2907753090u, 122788199u, 1996398371u, 971552133u, 1037944395u, 1271174026u, 3843900980u, 1413244506u, 55u, 3031420033u, 1112378521u, 855339782u, 4191278750u, 248038208u, 1136169807u, 2230652081u, 3378214371u, 1653863564u, 613940998u, 1392057263u, 562793371u, 894754680u, 2060902835u, 2039635717u, 2771255238u, 276u, 2272198277u, 1266925312u, 4276698911u, 3776524566u, 1240191044u, 1385881739u, 2563325814u, 4006169969u, 3974350527u, 3069704991u, 2665319019u, 2813966856u, 178806104u, 1714579584u, 1608243995u, 971374304u, 1383u, 2771056793u, 2039659266u, 4203625372u, 1702753650u, 1905987928u, 2634441400u, 4226694479u, 2850980663u, 2691883455u, 2463623071u, 441693210u, 1184932395u, 894030523u, 4277930624u, 3746252680u, 561904225u, 6916u, 970382077u, 1608361741u, 3838257678u, 4218800958u, 940005049u, 287305114u, 3953603214u, 1370001431u, 574515390u, 3728180766u, 2208466052u, 1629694679u, 175185320u, 4209783937u, 1551394220u, 2809521129u, 34580u, 556943089u, 3746841410u, 2011419207u, 3914135610u, 405057953u, 1436525571u, 2588146886u, 2555039863u, 2872576951u, 1461034646u, 2452395672u, 3853506101u, 875926601u, 3869050501u, 3462003808u, 1162703758u, 172903u, 2784715445u, 1554337866u, 1467161447u, 2390808868u, 2025289769u, 2887660559u, 55832543u, 4185264726u, 1477982869u, 3010205937u, 3672043769u, 2087661323u, 84665713u, 2165383322u, 130149860u, 1518551498u, 864516u, 1038675337u, 3476722037u, 3040839940u, 3364109749u, 1536514255u, 1553400909u, 279162718u, 3746454446u, 3094947053u, 2166127798u, 1180349664u, 1848372027u, 423328567u, 2236982018u, 650749302u, 3297790194u, 4322581u, 898409389u, 203741002u, 2319297816u, 3935646860u, 3387603982u, 3472037250u, 1395813591u, 1552403046u, 2589833381u, 2240704401u, 1606781026u, 651925544u, 2116642837u, 2594975498u, 3253746512u, 3604049082u, 21612908u, 197079649u, 1018705011u, 3006554488u, 2498365118u, 4053118026u, 180317069u, 2684100663u, 3467047935u, 64265018u, 2613587416u, 3738937836u, 3259627721u, 1993279593u, 89975604u, 3383830675u, 840376229u, 108064544u, 985398245u, 798557759u, 2147870553u, 3901891001u, 3085720948u, 901585349u, 535601427u, 155370494u, 321325094u, 183035192u, 1514819999u, 3413236721u, 1376463376u, 449878022u, 4034251487u, 4201881148u, 540322720u, 632023929u, 3992788796u, 2149418173u, 2329585823u, 2543702856u, 212959452u, 2678007136u, 776852470u, 1606625470u, 915175960u, 3279132699u, 4181281718u, 2587349587u, 2249390111u, 2991388251u, 3829536560u, 2701613604u, 3160119645u, 2784074796u, 2157156277u, 3057994525u, 4128579690u, 1064797262u, 505133792u, 3884262353u, 3738160054u, 280912505u, 3510761608u, 3726539409u, 51846051u, 2657015966u, 2072039369u, 1967813619u, 623166136u, 3u, 2915696337u, 1035472095u, 2195846796u, 2405070739u, 3463029269u, 1029019018u, 2525668961u, 2241442581u, 1510931090u, 1404562529u, 373938856u, 1452827865u, 259230259u, 400177942u, 1770262256u, 1249133505u, 3115830682u, 15u, 1693579797u, 882393182u, 2389299389u, 3435419105u, 135277163u, 850127798u, 4038410214u, 2617278315u, 3259688156u, 2727845350u, 1869694281u, 2969172029u, 1296151296u, 2000889710u, 261376688u, 1950700231u, 2694251523u, 78u, 4172931689u, 116998615u, 3356562354u, 4292193639u, 676385818u, 4250638990u, 3012181886u, 201489691u, 3413538895u, 754324865u, 758536816u, 1960958259u, 2185789187u, 1414513959u, 1306883442u, 1163566563u, 586355729u, 393u, 3684789261u, 584993079u, 3897909882u, 4281099014u, 3381929094u, 4073325766u, 2176007546u, 1007448458u, 4182792587u, 3771624328u, 3792684080u, 1214856703u, 2339011345u, 2777602501u, 2239449915u, 1522865520u, 2931778646u, 1965u, 1244077121u, 2924965399u, 2309680226u, 4225625890u, 4024743586u, 3186759649u, 2290103142u, 742274996u, 3734093752u, 1678252460u, 1783551220u, 1779316223u, 3105122134u, 1003110619u, 2607314986u, 3319360306u, 1773991343u, 9828u, 1925418309u, 1739925108u, 2958466541u, 3948260268u, 2943848750u, 3048896361u, 2860581121u, 3711374982u, 1490599576u, 4096295008u, 327821509u, 306646525u, 2640708784u, 720585802u, 151673043u, 3711899645u, 280022126u, 49142u, 1037156953u, 109690950u, 1907430819u, 2561432159u, 1834341866u, 2359579920u, 1418003720u, 1377005729u, 3158030588u, 3301605857u, 1639107549u, 1533232625u, 318642032u, 3602929013u, 758365215u, 1379629041u, 1400110634u, 245710u, 890817469u, 548454751u, 947219503u, 4217226205u, 581774740u, 3207965010u, 2795051306u, 2590061350u, 2905251053u, 3623127400u, 3900570452u, 3371195830u, 1593210161u, 834775881u, 3791826079u, 2603177909u, 2705585875u, 1228551u, 159120049u, 2742273756u, 441130219u, 3906261842u, 2908873704u, 3154923162u, 1090354645u, 65404865u, 1641353380u, 935767819u, 2322983080u, 3971077266u, 3671083512u, 4173879406u, 1779261211u, 130987661u, 643027490u, 6142758u, 795600245u, 826466892u, 2205651098u, 2351440026u, 1659466636u, 2889713925u, 1156805932u, 327024326u, 3911799604u, 383871800u, 3024980809u, 2675517148u, 1175548380u, 3689527850u, 306371467u, 654938307u, 3215137450u, 30713790u, 3978001225u, 4132334460u, 2438320898u, 3167265540u, 4002365886u, 1563667738u, 1489062367u, 1635121631u, 2379128836u, 1919359004u, 2240002157u, 492683855u, 1582774607u, 1267770067u, 1531857339u, 3274691535u, 3190785362u, 153568953u, 2710136941u, 3481803120u, 3601669902u, 2951425814u, 2831960249u, 3523371398u, 3150344540u, 3880640860u, 3305709589u, 1006860430u, 2610076195u, 2463419277u, 3618905739u, 2043883040u, 3364319400u, 3488555788u, 3069024925u, 767844768u, 665782817u, 229146419u, 828480330u, 1872227186u, 1274899360u, 436987809u, 2866820816u, 2223335119u, 3643646061u, 739334857u, 165479088u, 3727161796u, 914659513u, 1629480612u, 3936695114u, 262909759u, 2460222741u, 3839223843u, 3328914085u, 1145732095u, 4142401650u, 771201338u, 2079529506u, 2184939046u, 1449202192u, 2526741006u, 1038361123u, 3696674289u, 827395440u, 1455939796u, 278330273u, 3852435765u, 2503606387u, 1314548799u, 3711179113u, 2016250033u, 4u, 3759668537u, 1433693182u, 3532139067u, 3856006694u, 1807712938u, 2334760640u, 2951043666u, 4043770439u, 896838321u, 1303502262u, 4136977204u, 2984731684u, 1391651366u, 2082309641u, 3928097347u, 2277776701u, 1376026382u, 1491315577u, 22u, 1618473501u, 2873498618u, 480826152u, 2100164290u, 448630102u, 3083868610u, 1870316444u, 3038983014u, 189224313u, 2222544015u, 3505016837u, 2038756536u, 2663289537u, 1821613614u, 2460617553u, 2798948917u, 2585164616u, 3161610590u, 111u, 3797400209u, 1482591203u, 2404130763u, 1910886858u, 2243150512u, 2534441162u, 761647631u, 2310013184u, 946121568u, 2522785483u, 345215003u, 1603848092u, 431545799u, 518133481u, 3713153175u, 1109842699u, 40921195u, 2923151065u, 558u, 1807131861u, 3117988723u, 3430719224u, 964499700u, 2625817970u, 4082271220u, 3808238157u, 2960131328u, 435640546u, 4023992824u, 1726075017u, 3724273164u, 2157728996u, 2590667405u, 1385896691u, 1254246203u, 204605976u, 1730853437u, 2793u, 445724713u, 2705041729u, 4268694235u, 527531207u, 244187963u, 3231486919u, 1861321605u, 1915754756u, 2178202733u, 2940094936u, 40440497u, 1441496638u, 2198710392u, 68435139u, 2634516162u, 1976263720u, 1023029881u, 64332593u, 13967u, 2228623565u, 640306757u, 4163601994u, 2637656039u, 1220939815u, 3272532707u, 716673436u, 988839190u, 2301079075u, 1815572794u, 202202488u, 2912515894u, 2403617369u, 342175697u, 287678922u, 1291384011u, 820182111u, 321662966u, 69835u, 2553183233u, 3201533787u, 3638140786u, 303378311u, 1809731782u, 3477761648u, 3583367183u, 649228654u, 2915460784u, 487929380u, 1011012442u, 1677677582u, 3428152256u, 1710878487u, 1438394610u, 2161952759u, 4100910556u, 1608314830u, 349175u, 4175981573u, 3122767049u, 1010834749u, 1516891559u, 458724318u, 208939058u, 736966735u, 3246143274u, 1692402032u, 2439646903u, 760094914u, 4093420615u, 4255859393u, 4259425142u, 2897005755u, 2219829204u, 3324683598u, 3746606858u, 1745876u, 3700038681u, 2728933361u, 759206452u, 3289490500u, 2293621591u, 1044695290u, 3684833675u, 3345814482u, 4167042867u, 3608299924u, 3800474572u, 3287233891u, 4099427785u, 4117256530u, 1600126891u, 2509211431u, 3738516104u, 1553165109u, 8729384u, 1320324221u, 759764921u, 3796032263u, 3562550612u, 2878173366u, 928509156u, 1244299192u, 3844170526u, 3655345154u, 861630440u, 1822503680u, 3551267571u, 3317269744u, 3406413470u, 3705667163u, 3956122564u, 1512711338u, 3470858253u, 43646921u, 2306653809u, 3798824606u, 1800292131u, 632883880u, 1505964946u, 347578487u, 1926528665u, 2040983447u, 1096856590u, 13184908u, 522583809u, 576468673u, 3701446836u, 4147165465u, 1348466634u, 2600743640u, 3268589398u, 174422082u, 218234609u, 2943334453u, 1814253848u, 411526067u, 3164419402u, 3234857434u, 1737892436u, 1042708733u, 1614982645u, 1189315656u, 65924541u, 2612919045u, 2882343365u, 1327364996u, 3555958145u, 2447365878u, 118816313u, 3458045105u, 872110413u, 1091173045u, 1831770377u, 481334651u, 2057630337u, 2937195122u, 3289385285u, 99527591u, 918576371u, 3779945930u, 1651610985u, 329622706u, 179693337u, 1526814940u, 2341857687u, 599921542u, 3646894802u, 594081567u, 110356341u, 65584773u, 1160897930u, 1u, 568917293u, 2406673257u, 1698217093u, 1801073724u, 3562024540u, 497637958u, 297914559u, 1719860467u, 3963087633u, 1648113531u, 898466685u, 3339107404u, 3119353844u, 2999607712u, 1054604826u, 2970407839u, 551781705u, 327923865u, 1509522354u, 6u, 2844586465u, 3443431693u, 4196118171u, 415434029u, 630253518u, 2488189794u, 1489572795u, 9367743u, 2635568983u, 3945600363u, 197366130u, 3810635133u, 2711867335u, 2113136675u, 978056837u, 1967137308u, 2758908528u, 1639619325u, 3252644474u, 31u, 1338030437u, 37289284u, 3800721675u, 2077170149u, 3151267590u, 3851014378u, 3152896681u, 46838716u, 292943027u, 2548132634u, 986830654u, 1873306481u, 674434791u, 1975748786u, 595316891u, 1245751949u, 909640754u, 3903129332u, 3378320483u, 158u, 2395184889u, 186446421u, 1823739191u, 1795916157u, 2871436064u, 2075202709u, 2879581521u, 234193583u, 1464715135u, 4150728578u, 639185976u, 776597814u, 3372173957u, 1288809338u, 2976584457u, 1933792449u, 253236475u, 2335777477u, 4006700531u, 793u, 3385989853u, 932232107u, 528761363u, 389646195u, 1472278434u, 1786078956u, 1513005719u, 1170967918u, 3028608379u, 3573773707u, 3195929884u, 3882989070u, 3975967897u, 2149079397u, 1998020398u, 1079027656u, 1266182377u, 3088952793u, 2853633473u, 3969u, 4045047377u, 366193242u, 2643806816u, 1948230975u, 3066424874u, 340460189u, 3270061301u, 1559872295u, 2258140008u, 688999354u, 3094747536u, 2235076169u, 2699970305u, 2155462397u, 1400167400u, 1100170986u, 2035944590u, 2559862078u, 1383265480u, 19848u, 3045367701u, 1830966214u, 334132192u, 1151220286u, 2447222484u, 1702300948u, 3465404617u, 3504394182u, 2700765449u, 3444996772u, 2588835792u, 2585446256u, 614949639u, 2187377396u, 2705869706u, 1205887635u, 1589788359u, 4209375800u, 2621360106u, 99241u, 2341936617u, 564896481u, 1670660962u, 1461134134u, 3646177829u, 4216537446u, 147153902u, 342101730u, 618925361u, 45114679u, 59277076u, 42329395u, 3074748198u, 2346952388u, 644446644u, 1734470882u, 3653974500u, 3867009817u, 221898646u, 496208u, 3119748493u, 2824482407u, 4058337514u, 3010703375u, 1051019962u, 3902818050u, 735769514u, 1710508650u, 3094626805u, 225573395u, 296385380u, 211646975u, 2488839102u, 3144827351u, 3222233222u, 82419818u, 1090003318u, 2155179905u, 1109493234u, 2481040u, 2713840577u, 1237510150u, 3111818389u, 2168614991u, 960132517u, 2334221067u, 3678847574u, 4257575954u, 2588232138u, 1127866978u, 1481926900u, 1058234875u, 3854260918u, 2839234869u, 3226264225u, 412099093u, 1155049294u, 2185964934u, 1252498876u, 12405201u, 684300997u, 1892583457u, 2674190058u, 2253140366u, 505695291u, 3081170744u, 1214368688u, 4108010590u, 56258806u, 1344367597u, 3114667205u, 996207080u, 2091435407u, 1311272461u, 3246419240u, 2060495468u, 1480279174u, 2339890079u, 1967527086u, 62026006u, 3421504985u, 872982693u, 486048404u, 2675767241u, 2528476457u, 2520951832u, 1776876147u, 3360183767u, 281294034u, 2426870689u, 2688434138u, 686068107u, 1867242444u, 2261395011u, 3347194313u, 1712542751u, 3106428576u, 3109515804u, 1247700840u, 310130032u, 4222623037u, 69946172u, 2430242021u, 493934317u, 4052447696u, 4014824570u, 294446145u, 3916016949u, 1406470173u, 3544418853u, 557268804u, 3430340538u, 746277628u, 2717040465u, 3851069679u, 4267746462u, 2647240993u, 2662677135u, 1943536907u, 1550650161u, 3933246001u, 349730864u, 3561275513u, 2469671587u, 3082369296u, 2894253670u, 1472230729u, 2400215561u, 2737383573u, 542225082u, 2786344024u, 4266800802u, 3731388143u, 700300437u, 2075479214u, 4158863130u, 351303081u, 428483790u, 1127749946u, 3458283511u, 1u, 2486360821u, 1748654324u, 626508381u, 3758423347u, 2526944594u, 1586366465u, 3066186352u, 3411143214u, 802015979u, 2711125413u, 1046818232u, 4154134829u, 1477071535u, 3501502189u, 1787461478u, 3614446468u, 1756515409u, 2142418950u, 1343782434u, 111548372u, 9u, 3841869513u, 153337030u, 3132541907u, 1612247551u, 4044788382u, 3636865031u, 2446029873u, 4170814185u, 4010079898u, 670725177u, 939123867u, 3590804962u, 3090390383u, 327641762u, 347372802u, 892363158u, 192642457u, 2122160160u, 2423944876u, 557741861u, 45u, 2029478381u, 766685154u, 2777807647u, 3766270462u, 3044072727u, 1004455975u, 3640214777u, 3674201743u, 2870530310u, 3353625889u, 400652039u, 774155627u, 2567050031u, 1638208813u, 1736864010u, 166848494u, 963212286u, 2020866208u, 3529789790u, 2788709307u, 225u, 1557457313u, 3833425772u, 1004136347u, 1651483129u, 2335461751u, 727312582u, 1021204702u, 1191139535u, 1467749666u, 3883227560u, 2003260198u, 3870778135u, 4245315563u, 3896076771u, 94385459u, 834242472u, 521094134u, 1514396449u, 469079768u, 1058644651u, 1128u, 3492319269u, 1987259677u, 725714443u, 3962448350u, 3087374164u, 3636562912u, 811056214u, 1660730380u, 3043781035u, 2236268617u, 1426366402u, 2174021493u, 4046708635u, 2300514675u, 471927299u, 4171212360u, 2605470670u, 3277014949u, 2345398841u, 998255959u, 5641u, 281727161u, 1346363797u, 3628572217u, 2632372566u, 2551968936u, 1002945379u, 4055281074u, 4008684604u, 2334003288u, 2591408496u, 2836864716u, 2280172874u, 3053673993u, 2912638787u, 2359636497u, 3676192616u, 142451466u, 3500172860u, 3137059616u, 696312501u, 28206u, 1408635805u, 2436851689u, 962991902u, 276960946u, 4169910091u, 719759601u, 3096536187u, 2863553840u, 3080081852u, 72140594u, 1299421695u, 2810929781u, 2383468079u, 1678292050u, 3208247896u, 1201093898u, 712257334u, 320995116u, 2800396196u, 3481562508u, 141030u, 2748211729u, 3594323854u, 519992216u, 1384804731u, 3669681271u, 3598798009u, 2597779047u, 1432867315u, 2515507375u, 360702973u, 2202141179u, 1169747018u, 3327405806u, 4096492956u, 3156337593u, 1710502197u, 3561286671u, 1604975580u, 1117079092u, 227943359u, 705154u, 856156757u, 791750089u, 2599961084u, 2629056359u, 1168537172u, 814120865u, 103993351u, 2869369282u, 3987602284u, 1803514867u, 2420771303u, 1553767796u, 3752127143u, 3302595599u, 2896786081u, 4257543692u, 626564172u, 3729910608u, 1290428165u, 1139716796u, 3525770u, 4280783785u, 3958750445u, 114903532u, 260379910u, 1547718567u, 4070604326u, 519966755u, 1461944522u, 2758142239u, 427639747u, 3513921925u, 3473871686u, 1580766532u, 3628076111u, 1599028520u, 4107849279u, 3132820864u, 1469683856u, 2157173533u, 1403616685u, 17628851u, 4224049741u, 2613883045u, 574517664u, 1301899550u, 3443625539u, 3173152447u, 2599833779u, 3014755314u, 905809308u, 2138198738u, 389740441u, 189489250u, 3608865368u, 960511372u, 3700175308u, 3359377212u, 2779202436u, 3053451987u, 2195933074u, 2723116131u, 88144256u, 3940379521u, 184513341u, 2872588323u, 2214530454u, 38258512u, 2980860351u, 114267010u, 2188874685u, 234079247u, 2101059099u, 1948702207u, 947446250u, 864457656u, 507589568u, 1321007357u, 3911984176u, 1011110295u, 2382358050u, 2389730781u, 730678769u, 440721283u, 2522028421u, 922566709u, 1478039727u, 2482717681u, 191292562u, 2019399867u, 571335053u, 2354438833u, 1170396237u, 1915360903u, 1153576445u, 442263956u, 27320985u, 2537947841u, 2310069489u, 2380051697u, 760584183u, 3321855659u, 3358719315u, 3653393847u, 2203606415u, 4020207513u, 317866251u, 3095231340u, 3823653814u, 956462812u, 1507064743u, 2856675267u, 3182259573u, 1557013891u, 986869924u, 1472914931u, 2211319781u, 136604925u, 4099804613u, 2960412855u, 3310323895u, 3802920917u, 3724376407u, 3908694690u, 1087100054u, 2428097487u, 2u, 2921168381u, 1589331259u, 2591254812u, 1938399889u, 487346768u, 3240356420u, 1398474448u, 3026395980u, 3490102162u, 639382325u, 3069607360u, 2466664314u, 683024627u, 3319153881u, 1917162391u, 3666717590u, 1834735404u, 1442012855u, 2363604270u, 1140532978u, 3550552844u, 12u, 1720940017u, 3651689002u, 71372173u, 1102064856u, 2436733842u, 3316880212u, 2697404947u, 2247078013u, 270641629u, 3196911629u, 2463134912u, 3743386981u, 3415123137u, 3710867517u, 995877366u, 1153718768u, 583742432u, 2915096981u, 3228086759u, 1407697596u, 572895037u, 64u, 14765493u, 1078575828u, 356860869u, 1215356984u, 3593734619u, 3699499174u, 602122850u, 2645455476u, 1353208147u, 3099656257u, 3725739971u, 1537065723u, 4190713801u, 1374468404u, 684419538u, 1473626545u, 2918712161u, 1690583017u, 3255531910u, 2743520687u, 2864475186u, 320u, 73827465u, 1097911844u, 1784304346u, 1781817624u, 788803912u, 1317626690u, 3010614254u, 342375492u, 2471073442u, 2613379398u, 1448830674u, 3390361323u, 3773699822u, 2577374728u, 3422097691u, 3073165429u, 1708658918u, 4157947792u, 3392757663u, 832701550u, 1437474045u, 1603u, 369137325u, 1194591924u, 331587139u, 319153530u, 3944019562u, 2293166154u, 2168169383u, 1711877463u, 3765432618u, 181995104u, 2949186077u, 4066904728u, 1688629929u, 1971756u, 4225586570u, 2480925260u, 4248327297u, 3609869777u, 4078886431u, 4163507753u, 2892402929u, 8016u, 1845686625u, 1677992324u, 1657935696u, 1595767650u, 2540228626u, 2875896182u, 2250912325u, 4264420021u, 1647293907u, 909975524u, 1861028497u, 3154654459u, 4148182353u, 9858781u, 3948063666u, 3814691712u, 4061767303u, 869479705u, 3214562975u, 3637669585u, 1577112761u, 40083u, 638498533u, 4094994326u, 3994711185u, 3683870955u, 4111208539u, 1494579024u, 2664627036u, 4142230923u, 3941502243u, 254910325u, 715207894u, 2888370409u, 3561042584u, 49293909u, 2560449146u, 1893589380u, 3128967335u, 52431233u, 3187912988u, 1008478744u, 3590596513u, 200416u, 3192492665u, 3295102446u, 2793686745u, 1239485595u, 3376173515u, 3177927828u, 438233293u, 3531285434u, 2527642035u, 1274551629u, 3576039470u, 1556950157u, 625343739u, 246469549u, 4212311138u, 878012310u, 2759934789u, 262156168u, 3054663052u, 747426427u, 773113382u, 1002084u, 3077561437u, 3590610345u, 1083531840u, 1902460682u, 3995965688u, 3004737255u, 2191166468u, 476557986u, 4048275587u, 2077790851u, 700328167u, 3489783493u, 3126718696u, 1232347745u, 3881686506u, 95094258u, 914772058u, 1310780843u, 2388413372u, 3737132138u, 3865566910u, 5010420u, 2502905297u, 773182544u, 1122691908u, 922368819u, 2799959258u, 2138784391u, 2365897751u, 2382789932u, 3061508751u, 1799019667u, 3501640837u, 269048281u, 2748691596u, 1866771432u, 2228563347u, 475471294u, 278892994u, 2258936920u, 3352132269u, 1505791508u, 2147965370u, 25052104u, 3924591893u, 3865912722u, 1318492244u, 316876800u, 1114894403u, 2103987366u, 3239554165u, 3324015070u, 2422641869u, 405163746u, 328335003u, 1345241409u, 858556092u, 743922571u, 2552882145u, 2377356472u, 1394464970u, 2704750008u, 3875759459u, 3233990247u, 2149892259u, 125260522u, 2443090281u, 2149694430u, 2297493928u, 1584384001u, 1279504719u, 1930002239u, 3312868939u, 3735173465u, 3523274756u, 2025818732u, 1641675015u, 2431239749u, 4292780461u, 3719612855u, 4174476133u, 3296847770u, 2677357556u, 638848153u, 2198928114u, 3285049351u, 2159526706u, 626302612u, 3625516813u, 2158537560u, 2897535050u, 3626952711u, 2102556300u, 1060076604u, 3679442809u, 1495998144u, 436504600u, 1539159072u, 3913407781u, 3566264154u, 4284033123u, 1418195095u, 3692511485u, 3599336966u, 501885895u, 3194240768u, 2404705978u, 3540344869u, 2207698941u, 3131513062u, 947714881u, 2202753212u, 1602773364u, 954894374u, 1922846912u, 1005415726u, 1217344862u, 3185023428u, 2182523001u, 3400828064u, 2387169722u, 651451590u, 4240296435u, 2796008183u, 1282688242u, 816815650u, 2509429479u, 3086301952u, 3433595301u, 521855163u, 2448560117u, 2772663424u, 3u, 443607109u, 2423831469u, 3718899526u, 479504575u, 1024299969u, 732111336u, 1791757015u, 3040215253u, 2322680416u, 4119238434u, 3345914021u, 3257257952u, 4021612991u, 1095139031u, 2118473917u, 4084078251u, 3957212803u, 2546607874u, 4283074620u, 2609275818u, 3652865993u, 978415234u, 18u, 2218035545u, 3529222753u, 1414628448u, 2397522879u, 826532549u, 3660556681u, 368850483u, 2316174379u, 3023467491u, 3416322988u, 3844668221u, 3401387875u, 2928195774u, 1180727863u, 2002434994u, 3240522073u, 2606194835u, 4143104782u, 4235503918u, 161477206u, 1084460784u, 597108878u, 91u, 2500243133u, 466244583u, 2778174948u, 3397679804u, 4132662747u, 1122914221u, 1844252419u, 2990937303u, 2232435569u, 4196713055u, 2043471924u, 4122037491u, 1756076985u, 1608672022u, 1422240379u, 3317708479u, 146072290u, 3535654729u, 3997650410u, 807386034u, 1127336624u, 2985544391u, 455u, 3911281073u, 2331222917u, 1005972852u, 4103497135u, 3483444554u, 1319603813u, 631327504u, 2069784629u, 2572243256u, 3803696093u, 1627425032u, 3430318273u, 190450337u, 3748392816u, 2816234600u, 3703640508u, 730361453u, 498404461u, 2808382870u, 4036930174u, 1341715824u, 2042820068u, 2278u, 2376536181u, 3066179997u, 734896966u, 3337616492u, 237353590u, 2303051773u, 3156637521u, 1758988553u, 4271281690u, 1838611283u, 3842157868u, 4266689478u, 952251688u, 1562094896u, 1196271116u, 1338333359u, 3651807269u, 2492022305u, 1157012462u, 3004781689u, 2413611828u, 1624165749u, 11392u, 3292746313u, 2445998099u, 3674484833u, 3803180572u, 1186767953u, 2925324273u, 2898285719u, 205008176u, 4176539268u, 603121827u, 2030920158u, 4153578210u, 466291148u, 3515507185u, 1686388285u, 2396699500u, 1079167162u, 3870176937u, 1490095016u, 2139006558u, 3478124551u, 3825861451u, 56961u, 3578829677u, 3640055906u, 1192554983u, 1836033680u, 1638872473u, 1741719478u, 1606526710u, 1025040883u, 3702827156u, 3015609139u, 1564666198u, 3588021868u, 2331455744u, 397666741u, 4136974133u, 3393562909u, 1100868516u, 2171015502u, 3155507788u, 2105098199u, 210753573u, 1949438075u, 284809u, 714279201u, 1020410350u, 1667807623u, 590233809u, 3899395071u, 118662799u, 3737666256u, 830237120u, 1334266597u, 2193143811u, 3528363697u, 760240157u, 3067344132u, 1988333707u, 3505001481u, 4082912661u, 1209375287u, 2265142919u, 2892637054u, 1935556406u, 1053767867u, 1157255783u, 1424047u, 3571396005u, 807084454u, 4044070820u, 2951169046u, 2317106171u, 593313999u, 1508462096u, 4151185604u, 2376365689u, 2375784464u, 461949303u, 3801200789u, 2451818772u, 1351733946u, 345138223u, 3234694125u, 1751909143u, 2735780004u, 1578283384u, 1087847441u, 973872041u, 1491311620u, 7120236u, 677110841u, 4035422274u, 3040484916u, 1870943346u, 2995596266u, 2966569997u, 3247343184u, 3576058837u, 3291893857u, 3288987730u, 2309746517u, 1826134761u, 3669159272u, 2463702436u, 1725691116u, 3288568737u, 169611126u, 793998134u, 3596449627u, 1144269910u, 574392910u, 3161590805u, 35601181u, 3385554205u, 2997242186u, 2317522696u, 764782141u, 2093079444u, 1947948100u, 3351814035u, 700425004u, 3574567401u, 3560036765u, 2958797996u, 540739215u, 1165927178u, 3728577592u, 38520990u, 3557941799u, 848055633u, 3969990670u, 802378951u, 1426382258u, 2871964551u, 2923052137u, 178005908u, 4042869137u, 2101309045u, 2997678891u, 3823910707u, 1875462628u, 1149805910u, 3874168289u, 3502125023u, 692967821u, 620314645u, 1909088096u, 2703696078u, 1534668594u, 1463018777u, 192604954u, 609839811u, 4240278169u, 2670084166u, 4011894759u, 2836943994u, 1474920868u, 1730358800u, 890029543u, 3034476501u, 1916610637u, 2103492569u, 1939684354u, 787378552u, 1454062256u, 2190972262u, 330755935u, 3464839109u, 3101573225u, 955505888u, 633578504u, 3378375677u, 3020126590u, 963024771u, 3049199055u, 4021521661u, 465518946u, 2879604614u, 1299818086u, 3079637047u, 61859409u, 155180421u, 1u, 2287480617u, 993118596u, 1927528255u, 1108487180u, 3936892762u, 2975343984u, 2364926719u, 1653779677u, 144326361u, 2622964241u, 482562147u, 3167892521u, 4006976497u, 2215731065u, 520156562u, 2361093388u, 2927739124u, 2327594734u, 1513121182u, 2204123137u, 2513283348u, 309297048u, 775902105u, 5u, 2847468493u, 670625686u, 1047706684u, 1247468606u, 2504594627u, 1991818036u, 3234699006u, 3973931091u, 721631806u, 229919317u, 2412810738u, 2954560717u, 2855013304u, 2488720737u, 2600782812u, 3215532348u, 1753793734u, 3048039081u, 3270638616u, 2430681094u, 3976482150u, 1546485242u, 3879510525u, 25u, 1352440577u, 3353128433u, 943566124u, 1942375735u, 3933038544u, 1369155590u, 3288593144u, 2689786274u, 3608159034u, 1149596585u, 3474119098u, 1887901699u, 1390164635u, 3853669096u, 119012174u, 3192759855u, 179034081u, 2355293519u, 3468291195u, 3563470881u, 2702541568u, 3437458918u, 2217683442u, 129u, 2467235589u, 3880740278u, 422863327u, 1121944084u, 2485323538u, 2550810658u, 3558063833u, 564029485u, 860925989u, 1453015633u, 190726307u, 849573907u, 2655855881u, 2088476297u, 595060874u, 3078897387u, 895170408u, 3186533003u, 161586793u, 637485225u, 627805956u, 7425409u, 2498482622u, 647u, 3746243353u, 2223832208u, 2114316639u, 1314753124u, 3836683099u, 4164118700u, 610449983u, 2820147429u, 9662649u, 2970110870u, 953631536u, 4247869535u, 394377517u, 1852446896u, 2975304372u, 2509585047u, 180884747u, 3047763128u, 807933968u, 3187426125u, 3139029780u, 37127045u, 3902478518u, 3237u, 1551347581u, 2529226452u, 1981648605u, 2278798326u, 2003546312u, 3640724320u, 3052249919u, 1215835257u, 48313248u, 1965652462u, 473190387u, 4059478492u, 1971887589u, 672299888u, 1991619974u, 3957990646u, 904423737u, 2353913752u, 4039669843u, 3052228737u, 2810247015u, 185635228u, 2332523406u, 16189u, 3461770609u, 4056197669u, 1318308435u, 2804057040u, 1427796970u, 1023752418u, 2376347711u, 1784208992u, 241566241u, 1238327718u, 2365951937u, 3117523276u, 1269503357u, 3361499442u, 1368165278u, 2610084048u, 227151393u, 3179634169u, 3018480033u, 2376241801u, 1166333190u, 928176143u, 3072682438u, 80947u, 128983861u, 3101119165u, 2296574883u, 1135383313u, 2844017557u, 823794795u, 3291803964u, 331110370u, 1207831207u, 1896671294u, 3239825094u, 2702714494u, 2052549492u, 3922595323u, 2545859097u, 165518353u, 1135756968u, 3013268957u, 2207498280u, 3291274416u, 1536698656u, 345913420u, 2478510303u, 404738u, 644919305u, 2620693937u, 2892939826u, 1381949271u, 1335185898u, 4118973978u, 3574117932u, 1655551853u, 1744188739u, 893421879u, 3314223584u, 628670585u, 1672812871u, 2433107433u, 4139360897u, 827591767u, 1383817544u, 2181442898u, 2447556811u, 3571470194u, 3388525987u, 1729567101u, 3802616923u, 2023692u, 3224596525u, 218567797u, 1579797245u, 2614779062u, 2380962195u, 3415000707u, 690720480u, 3982791973u, 131009104u, 172142101u, 3686216033u, 3143352928u, 4069097059u, 3575602574u, 3516935303u, 4137958839u, 2624120424u, 2317279899u, 3647849465u, 677481788u, 4057728051u, 57900916u, 1833215433u, 10118464u, 3238080737u, 1092838988u, 3604018929u, 188993423u, 3314876386u, 4190101649u, 3453602403u, 2734090681u, 655045524u, 860710505u, 1251210981u, 2831862756u, 3165616114u, 698143690u, 404807335u, 3509925015u, 235700236u, 2996464906u, 1059378143u, 3387408944u, 3108771071u, 289504584u, 576142573u, 50592322u, 3305501797u, 1169227647u, 840225462u, 944967119u, 3689480042u, 3770639064u, 88142835u, 785551521u, 3275227623u, 8585229u, 1961087610u, 1274411893u, 2943178685u, 3490718453u, 2024036675u, 369755891u, 1178501184u, 2097422642u, 1001923422u, 4052142833u, 2658953470u, 1447522923u, 2880712865u, 252961610u, 3642607097u, 1551170942u, 4201127311u, 429868299u, 1267531027u, 1673326140u, 440714179u, 3927757605u, 3491236227u, 42926148u, 1215503458u, 2077092171u, 1830991538u, 273723084u, 1530248787u, 1848779457u, 1597538624u, 1897178619u, 714649816u, 3080844982u, 409865466u, 2942647322u, 1518662438u, 1264808053u, 1033166301u, 3460887418u, 3825767372u, 2149341499u, 2042687839u, 4071663405u, 2203570896u, 2458918841u, 276311955u, 214630744u, 1782549994u, 1795526264u, 565023100u, 1368615422u, 3356276639u, 653962694u, 3692725826u, 895958504u, 3573249082u, 2519323022u, 2049327333u, 1828334722u, 3298344897u, 2029072970u, 1u, 870864209u, 124567907u, 1948967680u, 2156772907u, 1623504605u, 3178447843u, 2427919892u, 3704659615u, 1381559777u, 1073153720u, 322815378u, 387696730u, 2825115502u, 2548109814u, 3896481308u, 3269813473u, 1283759946u, 184825228u, 686376227u, 4006680522u, 1656702075u, 551739020u, 3606822599u, 1555430261u, 7u, 59353749u, 622839536u, 1154903808u, 2193929945u, 3822555731u, 3007337328u, 3549664871u, 1343428893u, 2612831593u, 1070801305u, 1614076891u, 1938483650u, 1240675622u, 4150614481u, 2302537358u, 3464165481u, 2123832437u, 924126141u, 3431881135u, 2853533426u, 3988543083u, 2758695101u, 854243811u, 3482184013u, 36u, 296768745u, 3114197680u, 1479551744u, 2379715134u, 1932909473u, 2151784756u, 568455174u, 2422177173u, 179256078u, 1059039232u, 3775417160u, 1102483659u, 1908410816u, 3573203222u, 2922752202u, 140958223u, 2029227597u, 325663411u, 4274503788u, 1382765245u, 2762846234u, 908573621u, 4271219058u, 231050881u, 184u, 1483843725u, 2686086512u, 3102791427u, 3308641079u, 1074612775u, 2168989190u, 2842275872u, 3520951273u, 896280392u, 1000228864u, 1697216617u, 1217451003u, 952119489u, 686146928u, 1728859126u, 704791118u, 1556203393u, 1628317057u, 4192649756u, 2618858933u, 929329283u, 247900812u, 4176226107u, 1155254409u, 920u, 3124251329u, 545530673u, 2629055250u, 3658303510u, 1078096582u, 2255011359u, 1326477474u, 424887184u, 186434668u, 706177025u, 4191115790u, 1792287720u, 465630150u, 3430734641u, 54361038u, 3523955592u, 3486049669u, 3846617990u, 3783379597u, 209392781u, 351679122u, 1239504061u, 3701261351u, 1481304753u, 4601u, 2736354757u, 2727653368u, 260374362u, 1111648369u, 1095515618u, 2685122204u, 2337420076u, 2124435921u, 932173340u, 3530885125u, 3775709766u, 371504012u, 2328150752u, 4268771317u, 271805193u, 439908776u, 250379165u, 2053220770u, 1737028805u, 1046963909u, 1758395610u, 1902553009u, 1326437572u, 3111556473u, 23006u, 796871897u, 753364955u, 1301871813u, 1263274549u, 1182610795u, 540709133u, 3097165791u, 2032245015u, 365899406u, 474556442u, 1698679650u, 1857520064u, 3050819168u, 4163987403u, 1359025969u, 2199543880u, 1251895825u, 1676169258u, 95209435u, 939852251u, 202043459u, 922830455u, 2337220566u, 2672880478u, 115033u, 3984359485u, 3766824775u, 2214391769u, 2021405450u, 1618086680u, 2703545666u, 2600927067u, 1571290486u, 1829497032u, 2372782210u, 4198430954u, 697665729u, 2369193954u, 3640067834u, 2500162553u, 2407784809u, 1964511831u, 4085878995u, 476047176u, 404293959u, 1010217296u, 319184979u, 3096168239u, 479500504u, 575168u, 2741928241u, 1654254695u, 2482024257u, 1517092660u, 3795466106u, 632826443u, 119733450u, 3561485137u, 557550569u, 3273976460u, 3812285588u, 3488328649u, 3256035178u, 1020469988u, 3910878177u, 3448989455u, 1232624565u, 3249525793u, 2380235884u, 2021469795u, 756119184u, 1595924896u, 2595939307u, 2397502523u, 2875840u, 824739317u, 3976306182u, 3820186694u, 3290496006u, 1797461347u, 3164132219u, 598667250u, 627556501u, 2787752849u, 3484980412u, 1881558759u, 261774065u, 3395274006u, 807382647u, 2374521702u, 65078095u, 1868155533u, 3362727078u, 3311244831u, 1517414385u, 3780595922u, 3684657184u, 94794648u, 3397578026u, 14379202u, 4123696585u, 2701661726u, 1921064290u, 3567578146u, 397372146u, 2935759209u, 2993336253u, 3137782505u, 1053862357u, 245032879u, 817859207u, 1308870327u, 4091468142u, 4036913238u, 3282673918u, 325390477u, 750843073u, 3928733504u, 3671322270u, 3292104632u, 1723110427u, 1243416740u, 473973244u, 4102988242u, 71896013u, 3438613741u, 623406746u, 1015386861u, 658021548u, 1986860734u, 1793894157u, 2081779380u, 2804010640u, 974344492u, 1225164396u, 4089296035u, 2249384339u, 3277471527u, 3004697010u, 3528467706u, 1626952388u, 3754215365u, 2463798336u, 1176742170u, 3575621276u, 25617546u, 1922116406u, 2369866221u, 3335072026u, 359480069u, 13199521u, 3117033734u, 781967009u, 3290107741u, 1344369078u, 379536195u, 1818962310u, 1135151314u, 576755167u, 1830854685u, 3266610992u, 2656987107u, 3502455749u, 2138583165u, 462469349u, 3839794648u, 1591207642u, 3729057092u, 1588743556u, 698237197u, 128087734u, 1020647438u, 3259396515u, 3790458244u, 1797400348u, 65997605u, 2700266782u, 3909835048u, 3565636817u, 2426878097u, 1897680976u, 504876958u, 1380789276u, 2883775836u, 564338833u, 3448153074u, 400033650u, 332409564u, 2102981237u, 2312346747u, 2019104056u, 3661070918u, 1465416277u, 3648750488u, 3491185986u, 640438670u, 808269894u, 3412080688u, 1772422039u, 397067152u, 2u, }; /* These are the indicies of the start of each power of 5 in pow5[] */ /* The width is calculated by subtracting indices, so there is one extra */ /* generated using (pow5w 346) from testgen.scm */ static const uint16_t pow5w[] = { 0u, 1u, 2u, 3u, 4u, 5u, 6u, 7u, 8u, 9u, 10u, 11u, 12u, 13u, 14u, 16u, 18u, 20u, 22u, 24u, 26u, 28u, 30u, 32u, 34u, 36u, 38u, 40u, 42u, 45u, 48u, 51u, 54u, 57u, 60u, 63u, 66u, 69u, 72u, 75u, 78u, 81u, 84u, 88u, 92u, 96u, 100u, 104u, 108u, 112u, 116u, 120u, 124u, 128u, 132u, 136u, 140u, 145u, 150u, 155u, 160u, 165u, 170u, 175u, 180u, 185u, 190u, 195u, 200u, 205u, 211u, 217u, 223u, 229u, 235u, 241u, 247u, 253u, 259u, 265u, 271u, 277u, 283u, 289u, 296u, 303u, 310u, 317u, 324u, 331u, 338u, 345u, 352u, 359u, 366u, 373u, 380u, 387u, 395u, 403u, 411u, 419u, 427u, 435u, 443u, 451u, 459u, 467u, 475u, 483u, 491u, 499u, 508u, 517u, 526u, 535u, 544u, 553u, 562u, 571u, 580u, 589u, 598u, 607u, 616u, 625u, 635u, 645u, 655u, 665u, 675u, 685u, 695u, 705u, 715u, 725u, 735u, 745u, 755u, 766u, 777u, 788u, 799u, 810u, 821u, 832u, 843u, 854u, 865u, 876u, 887u, 898u, 909u, 921u, 933u, 945u, 957u, 969u, 981u, 993u, 1005u, 1017u, 1029u, 1041u, 1053u, 1065u, 1077u, 1090u, 1103u, 1116u, 1129u, 1142u, 1155u, 1168u, 1181u, 1194u, 1207u, 1220u, 1233u, 1246u, 1259u, 1273u, 1287u, 1301u, 1315u, 1329u, 1343u, 1357u, 1371u, 1385u, 1399u, 1413u, 1427u, 1441u, 1456u, 1471u, 1486u, 1501u, 1516u, 1531u, 1546u, 1561u, 1576u, 1591u, 1606u, 1621u, 1636u, 1651u, 1667u, 1683u, 1699u, 1715u, 1731u, 1747u, 1763u, 1779u, 1795u, 1811u, 1827u, 1843u, 1859u, 1875u, 1892u, 1909u, 1926u, 1943u, 1960u, 1977u, 1994u, 2011u, 2028u, 2045u, 2062u, 2079u, 2096u, 2113u, 2131u, 2149u, 2167u, 2185u, 2203u, 2221u, 2239u, 2257u, 2275u, 2293u, 2311u, 2329u, 2347u, 2365u, 2384u, 2403u, 2422u, 2441u, 2460u, 2479u, 2498u, 2517u, 2536u, 2555u, 2574u, 2593u, 2612u, 2632u, 2652u, 2672u, 2692u, 2712u, 2732u, 2752u, 2772u, 2792u, 2812u, 2832u, 2852u, 2872u, 2892u, 2913u, 2934u, 2955u, 2976u, 2997u, 3018u, 3039u, 3060u, 3081u, 3102u, 3123u, 3144u, 3165u, 3186u, 3208u, 3230u, 3252u, 3274u, 3296u, 3318u, 3340u, 3362u, 3384u, 3406u, 3428u, 3450u, 3472u, 3494u, 3517u, 3540u, 3563u, 3586u, 3609u, 3632u, 3655u, 3678u, 3701u, 3724u, 3747u, 3770u, 3793u, 3817u, 3841u, 3865u, 3889u, 3913u, 3937u, 3961u, 3985u, 4009u, 4033u, 4057u, 4081u, 4105u, 4129u, 4154u, 4179u, 4204u, 4229u, 4254u, 4279u, 4304u, 4329u, 4354u, 4379u, 4404u, 4429u, 4454u, 4479u, 4505u, }; /* returns result: 0 = OK; non-zero = error */ int get_pow5 (uint32_t exp, const uint32_t **p5, int *sz_in_32bit_words) { if (exp <= MAX_POW5_IN_TABLE) { uint16_t idx = pow5w[exp]; *p5 = &pow5[idx]; *sz_in_32bit_words = pow5w[exp + 1] - idx; return 0; } else { *p5 = &pow5[0]; *sz_in_32bit_words = 0; return 1; } } #endif
ekohl/vagrant-openstack-provider
source/lib/vagrant-openstack-provider/action/delete_stack.rb
<reponame>ekohl/vagrant-openstack-provider require 'log4r' require 'socket' require 'timeout' require 'sshkey' require 'yaml' require 'vagrant-openstack-provider/config_resolver' require 'vagrant-openstack-provider/utils' require 'vagrant-openstack-provider/action/abstract_action' require 'vagrant/util/retryable' module VagrantPlugins module Openstack module Action class DeleteStack < AbstractAction def initialize(app, _env) @app = app @logger = Log4r::Logger.new('vagrant_openstack::action::delete_stack') end def execute(env) @logger.info 'Start delete stacks action' heat = env[:openstack_client].heat list_stack_files(env).each do |stack| env[:ui].info(I18n.t('vagrant_openstack.delete_stack')) env[:ui].info(" -- Stack Name : #{stack[:name]}") env[:ui].info(" -- Stack ID : #{stack[:id]}") heat.delete_stack(env, stack[:name], stack[:id]) waiting_for_stack_to_be_deleted(env, stack[:name], stack[:id]) end # This will remove all files in the .vagrant instance directory env[:machine].id = nil @app.call(env) end private def list_stack_files(env) stack_files = [] Dir.glob("#{env[:machine].data_dir}/stack_*_id") do |stack_file| file_name = stack_file.split('/')[-1] stack_files << { name: file_name[6, (file_name.length) - 9], id: File.read("#{stack_file}") } end stack_files end def waiting_for_stack_to_be_deleted(env, stack_name, stack_id, retry_interval = 3) @logger.info "Waiting for the stack with id #{stack_id} to be deleted..." env[:ui].info(I18n.t('vagrant_openstack.waiting_for_stack_deleted')) config = env[:machine].provider_config Timeout.timeout(config.stack_delete_timeout, Errors::Timeout) do stack_status = 'DELETE_IN_PROGRESS' until stack_status == 'DELETE_COMPLETE' @logger.debug('Waiting for stack to be DELETED') stack_status = env[:openstack_client].heat.get_stack_details(env, stack_name, stack_id)['stack_status'] fail Errors::StackStatusError, stack: stack_id if stack_status == 'DELETE_FAILED' sleep retry_interval end end end end end end end
JordonPhillips/aws-sdk-go-v2
service/apigateway/api_op_GetExport.go
// Code generated by smithy-go-codegen DO NOT EDIT. package apigateway import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/awslabs/smithy-go/middleware" smithyhttp "github.com/awslabs/smithy-go/transport/http" ) // Exports a deployed version of a RestApi in a specified format. func (c *Client) GetExport(ctx context.Context, params *GetExportInput, optFns ...func(*Options)) (*GetExportOutput, error) { if params == nil { params = &GetExportInput{} } result, metadata, err := c.invokeOperation(ctx, "GetExport", params, optFns, addOperationGetExportMiddlewares) if err != nil { return nil, err } out := result.(*GetExportOutput) out.ResultMetadata = metadata return out, nil } // Request a new export of a RestApi for a particular Stage. type GetExportInput struct { // [Required] The type of export. Acceptable values are 'oas30' for OpenAPI 3.0.x // and 'swagger' for Swagger/OpenAPI 2.0. // // This member is required. ExportType *string // [Required] The string identifier of the associated RestApi. // // This member is required. RestApiId *string // [Required] The name of the Stage that will be exported. // // This member is required. StageName *string // The content-type of the export, for example application/json. Currently // application/json and application/yaml are supported for exportType ofoas30 and // swagger. This should be specified in the Accept header for direct API requests. Accepts *string // A key-value map of query string parameters that specify properties of the // export, depending on the requested exportType. For exportTypeoas30 and swagger, // any combination of the following parameters are supported: // extensions='integrations' or extensions='apigateway' will export the API with // x-amazon-apigateway-integration extensions. extensions='authorizers' will export // the API with x-amazon-apigateway-authorizer extensions. postman will export the // API with Postman extensions, allowing for import to the Postman tool Parameters map[string]string } // The binary blob response to GetExport, which contains the generated SDK. type GetExportOutput struct { // The binary blob response to GetExport, which contains the export. Body []byte // The content-disposition header value in the HTTP response. ContentDisposition *string // The content-type header value in the HTTP response. This will correspond to a // valid 'accept' type in the request. ContentType *string // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func addOperationGetExportMiddlewares(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsRestjson1_serializeOpGetExport{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpGetExport{}, middleware.After) if err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { return err } if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { return err } if err = addRetryMiddlewares(stack, options); err != nil { return err } if err = addHTTPSignerV4Middleware(stack, options); err != nil { return err } if err = awsmiddleware.AddAttemptClockSkewMiddleware(stack); err != nil { return err } if err = addClientUserAgent(stack); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addOpGetExportValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetExport(options.Region), middleware.Before); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addAcceptHeader(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } return nil } func newServiceMetadataMiddleware_opGetExport(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "apigateway", OperationName: "GetExport", } }
philippzhang/leetcodeLearnJava
src/main/java/com/learn/java/leetcode/lc0236/Main.java
package com.learn.java.leetcode.lc0236; import com.learn.java.leetcode.base.CallBack; import com.learn.java.leetcode.base.Utilitys; import com.learn.java.leetcode.base.structure.TreeNode; import com.learn.java.leetcode.base.utils.Build; import java.util.List; public class Main extends CallBack { public static void main(String[] args) { Utilitys.test(Main.class); } /** * 构建树和结点 * * @param parameterTypes * @param inputObjArr * @param dataList * @param tempList */ @Override public void inputBuild(Class<?>[] parameterTypes, Object[] inputObjArr, List<String> dataList, List tempList) { String data = dataList.get(0); int ip = Integer.parseInt(dataList.get(1)); int iq = Integer.parseInt(dataList.get(2)); TreeNode root = Build.buildBinaryTree(data); TreeNode p = Utilitys.searchBinaryTree(root, ip); TreeNode q = Utilitys.searchBinaryTree(root, iq); inputObjArr[0] = root; inputObjArr[1] = p; inputObjArr[2] = q; } @Override public boolean outputVerify(Object[] inputObjArr, List<String> trueResultList, Object outputObj, List<String> dataList, List tempList) { boolean resultFlag = false; String testResult; if (outputObj != null) { TreeNode treeNode = (TreeNode) outputObj; testResult = String.valueOf(treeNode.val); } else { testResult = "null"; } for (int i = 0; i < trueResultList.size(); i++) { String trueResult = trueResultList.get(i); if (trueResult.equals("null") && outputObj == null) { printOutVerify(trueResultList, null, true); return true; } resultFlag = trueResult.equals(testResult); if (resultFlag) { printOutVerify(trueResultList, testResult, resultFlag); return true; } } printOutVerify(trueResultList, testResult, resultFlag); return resultFlag; } }
Ya-Za/KaMIS
lib/mis/kernel/ParFastKer/fast_reductions/extern/KaHIP/lib/tools/macros_assertions.h
<gh_stars>10-100 /****************************************************************************** * macros_assertions.h * * Source of KaHIP -- Karlsruhe High Quality Partitioning. * *****************************************************************************/ #ifndef ASSERT_H #define ASSERT_H #include <cassert> #include <cmath> // fabs #include <cstdio> // fprintf(), stderr #include <cstdlib> // abort() #include <iostream> // cerr #include "macros_common.h" // A custom assertion macro that does not kill the program but prints to // stderr instead. #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_TRUE(x) do {} while (false); #else # define ASSERT_TRUE(expression) \ do { \ if (not (expression)) { \ std::cerr << "ASSERTION FAILED [" << __FILE__ << ":" << __LINE__ << \ "]. Asserted: " << STR(expression) << std::endl; \ abort(); \ } \ } while (false) #endif // Assert: left != right. //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_NEQ(left, right) do {} while (false); #else # define ASSERT_NEQ(left, right) \ do { \ if ((left) == (right)) { \ std::cerr << "ASSERTION FAILED [" << __FILE__ << ":" << __LINE__ << \ "]. Asserted: " << STR(left) << " != " << STR(right) << " but was " \ << left << " == " << right << std::endl; \ abort(); \ } \ } while (false) #endif // Assert: left == right. //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_EQ(left, right) do {} while (false); #else # define ASSERT_EQ(left, right) \ do { \ if ((left) != (right)) { \ std::cerr << "ASSERTION FAILED [" << __FILE__ << ":" << __LINE__ << \ "]. Asserted: " << STR(left) << " == " << STR(right) << " but was " \ << left << " != " << right << std::endl; \ abort(); \ } \ } while (false) #endif // Assert: left < right. //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_LT(left, right) do {} while (false); #else # define ASSERT_LT(left, right) \ do { \ if ((left) >= (right)) { \ std::cerr << "ASSERTION FAILED [" << __FILE__ << ":" << __LINE__ << \ "]. Asserted: " << STR(left) << " < " << STR(right) << " but was " \ << left << " >= " << right << std::endl; \ abort(); \ } \ } while (false) #endif // Assert: left > right. //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_GT(left, right) do {} while (false); #else # define ASSERT_GT(left, right) \ do { \ if ((left) <= (right)) { \ std::cerr << "ASSERTION FAILED [" << __FILE__ << ":" << __LINE__ << \ "]. Asserted: " << STR(left) << " > " << STR(right) << " but was " \ << left << " <= " << right << std::endl; \ abort(); \ } \ } while (false) #endif // Assert: left <= right. //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_LEQ(left, right) do {} while (false); #else # define ASSERT_LEQ(left, right) \ do { \ if ((left) > (right)) { \ std::cerr << "ASSERTION FAILED [" << __FILE__ << ":" << __LINE__ << \ "]. Asserted: " << STR(left) << " <= " << STR(right) << " but was " \ << left << " > " << right << std::endl; \ abort(); \ } \ } while (false) #endif // Assert: left >= right. //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_GEQ(left, right) do {} while (false); #else # define ASSERT_GEQ(left, right) \ do { \ if ((left) < (right)) { \ std::cerr << "ASSERTION FAILED [" << __FILE__ << ":" << __LINE__ << \ "]. Asserted: " << STR(left) << " >= " << STR(right) << " but was " \ << left << " < " << right << std::endl; \ abort(); \ } \ } while (false) #endif // Assert: x <= y <= z. //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_BETWEEN(x, y, z) do {} while (false); #else # define ASSERT_BETWEEN(left, x, right) \ do { \ if (((left) > (x)) or ((right) < (x))) { \ std::cerr << "ASSERTION FAILED [" << __FILE__ << ":" << __LINE__ << \ "]. Asserted: " << STR(x) << " in {" << STR(left) << ", ..., " << \ STR(right) << "} but was " << x << " not in {" << left << \ ", ..., " << right << "}." << std::endl; \ abort(); \ } \ } while (false) #endif // Assert: \forall begin <= i < end: sequence[i] > x. //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_RANGE_GT(sequence, begin, end, x, i) do {} while (false); #else # define ASSERT_RANGE_GT(sequence, begin, end, x, i) \ for (int i = begin; i < end; ++i) { \ ASSERT_GT( sequence[i], x ); \ } #endif // Assert: \forall begin <= i < end: sequence[i] >= x. //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_RANGE_GEQ(sequence, begin, end, x, i) do {} while (false); #else # define ASSERT_RANGE_GEQ(sequence, begin, end, x, i) \ for (int i = begin; i < end; ++i) { \ ASSERT_GEQ( sequence[i], x ); \ } #endif //#ifdef NDEBUG #if (defined(NDEBUG) || defined(SPEEDPROFILING)) # define ASSERT_RANGE_EQ(sequence, begin, end, x) do {} while (false); #else # define ASSERT_RANGE_EQ(sequence, begin, end, x) \ for (unsigned int i = begin; i < end; ++i) { \ ASSERT_EQ( sequence[i], x ); \ } #endif #endif // ifndef ASSERT_H
dCipherDev/ERC20-Web-Wallet
node_modules/trezor-link/lib/lowlevel/sharedConnectionWorker.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.postModuleMessage = postModuleMessage; var _defered = require('../defered'); // To ensure that two website don't read from/to Trezor at the same time, I need a sharedworker // to synchronize them. // However, sharedWorker cannot directly use webusb API... so I need to send messages // about intent to acquire/release and then send another message when that is done. // Other windows then can acquire/release // eslint-disable-next-line no-undef // $FlowIssue if (typeof onconnect !== 'undefined') { // eslint-disable-next-line no-undef onconnect = function onconnect(e) { var port = e.ports[0]; port.onmessage = function (e) { handleMessage(e.data, port); }; }; } // path => session var state = {}; var lock = null; var waitPromise = Promise.resolve(); function startLock() { var newLock = (0, _defered.create)(); lock = newLock; setTimeout(function () { return newLock.reject(new Error('Timed out')); }, 10 * 1000); } function releaseLock(obj) { if (lock == null) { // TODO: ??? return; } lock.resolve(obj); } function waitForLock() { if (lock == null) { // TODO: ??? return Promise.reject(new Error('???')); } return lock.promise; } function waitInQueue(fn) { var res = waitPromise.then(function () { return fn(); }); waitPromise = res.catch(function () {}); } function handleMessage(_ref, port) { var id = _ref.id, message = _ref.message; if (message.type === 'acquire-intent') { var _path = message.path; var checkPrevious = message.checkPrevious; var previous = message.previous; waitInQueue(function () { return handleAcquireIntent(_path, checkPrevious, previous, id, port); }); } if (message.type === 'acquire-done') { handleAcquireDone(id); // port is the same as original } if (message.type === 'acquire-failed') { handleAcquireFailed(id); // port is the same as original } if (message.type === 'get-sessions') { waitInQueue(function () { return handleGetSessions(id, port); }); } if (message.type === 'get-sessions-and-disconnect') { var devices = message.devices; waitInQueue(function () { return handleGetSessions(id, port, devices); }); } if (message.type === 'release-onclose') { var session = message.session; waitInQueue(function () { return handleReleaseOnClose(session); }); } if (message.type === 'release-intent') { var _session = message.session; waitInQueue(function () { return handleReleaseIntent(_session, id, port); }); } if (message.type === 'release-done') { handleReleaseDone(id); // port is the same as original } if (message.type === 'enumerate-intent') { waitInQueue(function () { return handleEnumerateIntent(id, port); }); } if (message.type === 'enumerate-done') { handleReleaseDone(id); // port is the same as original } } function handleEnumerateIntent(id, port) { startLock(); sendBack({ type: 'ok' }, id, port); // if lock times out, promise rejects and queue goes on return waitForLock().then(function (obj) { sendBack({ type: 'ok' }, obj.id, port); }); } function handleReleaseDone(id) { releaseLock({ id: id }); } function handleReleaseOnClose(session) { var path_ = null; Object.keys(state).forEach(function (kpath) { if (state[kpath] === session) { path_ = kpath; } }); if (path_ == null) { return Promise.resolve(); } var path = path_; delete state[path]; return Promise.resolve(); } function handleReleaseIntent(session, id, port) { var path_ = null; Object.keys(state).forEach(function (kpath) { if (state[kpath] === session) { path_ = kpath; } }); if (path_ == null) { sendBack({ type: 'double-release' }, id, port); return Promise.resolve(); } var path = path_; startLock(); sendBack({ type: 'path', path: path }, id, port); // if lock times out, promise rejects and queue goes on return waitForLock().then(function (obj) { // failure => nothing happens, but still has to reply "ok" delete state[path]; sendBack({ type: 'ok' }, obj.id, port); }); } function handleGetSessions(id, port, devices) { if (devices != null) { var connected = {}; devices.forEach(function (d) { connected[d.path] = true; }); Object.keys(state).forEach(function (path) { if (!connected[path]) { delete state[path]; } }); } sendBack({ type: 'sessions', sessions: state }, id, port); return Promise.resolve(); } var lastSession = 0; function handleAcquireDone(id) { releaseLock({ good: true, id: id }); } function handleAcquireFailed(id) { releaseLock({ good: false, id: id }); } function handleAcquireIntent(path, checkPrevious, previous, id, port) { var error = false; if (checkPrevious) { var realPrevious = state[path]; if (realPrevious == null) { error = previous != null; } else { error = previous !== realPrevious; } } if (error) { sendBack({ type: 'wrong-previous-session' }, id, port); return Promise.resolve(); } else { startLock(); sendBack({ type: 'ok' }, id, port); // if lock times out, promise rejects and queue goes on return waitForLock().then(function (obj) { if (obj.good) { lastSession++; var session = lastSession.toString(); state[path] = session; sendBack({ type: 'session-number', number: session }, obj.id, port); } else { // failure => nothing happens, but still has to reply "ok" sendBack({ type: 'ok' }, obj.id, port); } }); } } function sendBack(message, id, port) { port.postMessage({ id: id, message: message }); } // when shared worker is not loaded as a shared loader, use it as a module instead function postModuleMessage(_ref2, fn) { var id = _ref2.id, message = _ref2.message; handleMessage({ id: id, message: message }, { postMessage: fn }); }
HowellYan/freeswitch-esl-all
opensips-event-mi-spring-boot-starter/src/main/java/link/thingscloud/opensips/spring/boot/starter/template/DefaultEventClientOptionHandlerTemplate.java
package link.thingscloud.opensips.spring.boot.starter.template; import link.thingscloud.opensips.event.option.EventClientOption; import link.thingscloud.opensips.spring.boot.starter.handler.AbstractEventClientOptionHandler; /** * <p>DefaultInboundClientOptionHandlerTemplate class.</p> * * @author zhouhailin * @version 1.0.0 */ public class DefaultEventClientOptionHandlerTemplate extends AbstractEventClientOptionHandler { /** * {@inheritDoc} */ @Override protected void intercept(EventClientOption eventClientOption) { } }
voskvv/ui
src/constants/volumeConstants/resizeVolume.js
<filename>src/constants/volumeConstants/resizeVolume.js<gh_stars>10-100 export const RESIZE_VOLUME_INVALID = 'RESIZE_VOLUME_INVALID'; export const RESIZE_VOLUME_REQUESTING = 'RESIZE_VOLUME_REQUESTING'; export const RESIZE_VOLUME_SUCCESS = 'RESIZE_VOLUME_SUCCESS'; export const RESIZE_VOLUME_FAILURE = 'RESIZE_VOLUME_FAILURE';
rjw57/tiw-computer
emulator/src/mame/drivers/wink.cpp
<reponame>rjw57/tiw-computer // license:BSD-3-Clause // copyright-holders:<NAME>, <NAME> // thanks-to:HIGHWAYMAN /* Wink - (c) 1985 Midcoin TODO: - better interrupts? - finish sound - fix protection properly - better handling of nvram? it loses the default values - I need a better comparison screenshot to be sure about the colors. */ #include "emu.h" #include "cpu/z80/z80.h" #include "machine/74259.h" #include "machine/gen_latch.h" #include "machine/nvram.h" #include "sound/ay8910.h" #include "screen.h" #include "speaker.h" class wink_state : public driver_device { public: wink_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_maincpu(*this, "maincpu"), m_audiocpu(*this, "audiocpu"), m_gfxdecode(*this, "gfxdecode"), m_videoram(*this, "videoram") { } required_device<cpu_device> m_maincpu; required_device<cpu_device> m_audiocpu; required_device<gfxdecode_device> m_gfxdecode; required_shared_ptr<uint8_t> m_videoram; tilemap_t *m_bg_tilemap; uint8_t m_sound_flag; uint8_t m_tile_bank; bool m_nmi_enable; DECLARE_WRITE8_MEMBER(bgram_w); DECLARE_WRITE_LINE_MEMBER(nmi_clock_w); DECLARE_WRITE_LINE_MEMBER(nmi_enable_w); DECLARE_WRITE_LINE_MEMBER(player_mux_w); DECLARE_WRITE_LINE_MEMBER(tile_banking_w); template<int Player> DECLARE_WRITE_LINE_MEMBER(coin_counter_w); DECLARE_READ8_MEMBER(analog_port_r); DECLARE_READ8_MEMBER(player_inputs_r); DECLARE_WRITE8_MEMBER(sound_irq_w); DECLARE_READ8_MEMBER(prot_r); DECLARE_WRITE8_MEMBER(prot_w); DECLARE_READ8_MEMBER(sound_r); TILE_GET_INFO_MEMBER(get_bg_tile_info); DECLARE_DRIVER_INIT(wink); virtual void machine_start() override; virtual void machine_reset() override; virtual void video_start() override; uint32_t screen_update_wink(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); INTERRUPT_GEN_MEMBER(wink_sound); void wink(machine_config &config); void wink_io(address_map &map); void wink_map(address_map &map); void wink_sound_io(address_map &map); void wink_sound_map(address_map &map); }; TILE_GET_INFO_MEMBER(wink_state::get_bg_tile_info) { uint8_t *videoram = m_videoram; int code = videoram[tile_index]; code |= 0x200 * m_tile_bank; // the 2 parts of the screen use different tile banking if(tile_index < 0x360) { code |= 0x100; } SET_TILE_INFO_MEMBER(0, code, 0, 0); } void wink_state::video_start() { m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(wink_state::get_bg_tile_info),this), TILEMAP_SCAN_ROWS, 8, 8, 32, 32); } uint32_t wink_state::screen_update_wink(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0); return 0; } WRITE8_MEMBER(wink_state::bgram_w) { uint8_t *videoram = m_videoram; videoram[offset] = data; m_bg_tilemap->mark_tile_dirty(offset); } WRITE_LINE_MEMBER(wink_state::nmi_clock_w) { if (state && m_nmi_enable) m_maincpu->set_input_line(INPUT_LINE_NMI, ASSERT_LINE); } WRITE_LINE_MEMBER(wink_state::nmi_enable_w) { m_nmi_enable = state; if (!m_nmi_enable) m_maincpu->set_input_line(INPUT_LINE_NMI, CLEAR_LINE); } WRITE_LINE_MEMBER(wink_state::player_mux_w) { //player_mux = state; //no mux / cocktail mode in the real pcb? strange... } WRITE_LINE_MEMBER(wink_state::tile_banking_w) { m_tile_bank = state; m_bg_tilemap->mark_all_dirty(); } template<int Player> WRITE_LINE_MEMBER(wink_state::coin_counter_w) { machine().bookkeeping().coin_counter_w(Player, state); } READ8_MEMBER(wink_state::analog_port_r) { return ioport(/* player_mux ? "DIAL2" : */ "DIAL1")->read(); } READ8_MEMBER(wink_state::player_inputs_r) { return ioport(/* player_mux ? "INPUTS2" : */ "INPUTS1")->read(); } WRITE8_MEMBER(wink_state::sound_irq_w) { m_audiocpu->set_input_line(0, HOLD_LINE); //sync with sound cpu (but it still loses some soundlatches...) //machine().scheduler().synchronize(); } void wink_state::wink_map(address_map &map) { map(0x0000, 0x7fff).rom(); map(0x8000, 0x87ff).ram(); map(0x9000, 0x97ff).ram().share("nvram"); map(0xa000, 0xa3ff).ram().w(this, FUNC(wink_state::bgram_w)).share("videoram"); } READ8_MEMBER(wink_state::prot_r) { //take a0-a7 and do some math using the variable created from the upper address-lines, //put the result onto the databus. /* math take 2 bytes: byte1 = a8,a9,a10,a11,a12,a13,a14,a15 byte2 = a0,a2,a4,a6,a1,a3,a5,a7 add the 2 bytes together so that if the final value overflows past 255 it wraps to 0 the 8bit result is placed on the databus. */ return 0x20; //hack to pass the jump calculated using this value } WRITE8_MEMBER(wink_state::prot_w) { //take a9-a15 and stuff them in a variable for later use. } void wink_state::wink_io(address_map &map) { map.global_mask(0xff); map(0x00, 0x1f).ram().w("palette", FUNC(palette_device::write8)).share("palette"); //0x10-0x1f is likely to be something else map(0x20, 0x27).w("mainlatch", FUNC(ls259_device::write_d0)); map(0x40, 0x40).w("soundlatch", FUNC(generic_latch_8_device::write)); map(0x60, 0x60).w(this, FUNC(wink_state::sound_irq_w)); map(0x80, 0x80).r(this, FUNC(wink_state::analog_port_r)); map(0xa0, 0xa0).r(this, FUNC(wink_state::player_inputs_r)); map(0xa4, 0xa4).portr("DSW1"); //dipswitch bank2 map(0xa8, 0xa8).portr("DSW2"); //dipswitch bank1 // AM_RANGE(0xac, 0xac) AM_WRITENOP //protection - loads video xor unit (written only once at startup) map(0xb0, 0xb0).portr("DSW3"); //unused inputs map(0xb4, 0xb4).portr("DSW4"); //dipswitch bank3 map(0xc0, 0xdf).w(this, FUNC(wink_state::prot_w)); //load load protection-buffer from upper address bus map(0xc3, 0xc3).nopr(); //watchdog? map(0xe0, 0xff).r(this, FUNC(wink_state::prot_r)); //load math unit from buffer & lower address-bus } void wink_state::wink_sound_map(address_map &map) { map(0x0000, 0x1fff).rom(); map(0x4000, 0x43ff).ram(); map(0x8000, 0x8000).r("soundlatch", FUNC(generic_latch_8_device::read)); } void wink_state::wink_sound_io(address_map &map) { map.global_mask(0xff); map(0x00, 0x00).rw("aysnd", FUNC(ay8910_device::data_r), FUNC(ay8910_device::data_w)); map(0x80, 0x80).w("aysnd", FUNC(ay8910_device::address_w)); } static INPUT_PORTS_START( wink ) PORT_START("DIAL1") PORT_BIT( 0xff, 0x00, IPT_DIAL ) PORT_SENSITIVITY(50) PORT_KEYDELTA(3) PORT_REVERSE PORT_START("INPUTS1") PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON2 ) // right curve PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 ) // left curve PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON3 ) // slam PORT_START("DSW1") PORT_DIPNAME( 0x01, 0x01, "1" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) 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 ) ) PORT_START("DSW2") PORT_DIPNAME( 0x01, 0x01, "2" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) 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 ) ) PORT_START("DSW3") PORT_DIPNAME( 0x01, 0x01, "3" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) 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 ) ) PORT_START("DSW4") PORT_DIPNAME( 0x01, 0x01, "Summary" ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, "4" ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_SERVICE( 0x10, IP_ACTIVE_LOW ) 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 const gfx_layout charlayout = { 8,8, /* 8*8 characters */ RGN_FRAC(1,3), 3, { RGN_FRAC(0,3), RGN_FRAC(1,3), RGN_FRAC(2,3) }, { 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 /* every char takes 8 consecutive bytes */ }; static GFXDECODE_START( wink ) GFXDECODE_ENTRY( "gfx1", 0, charlayout, 0, 4 ) GFXDECODE_END READ8_MEMBER(wink_state::sound_r) { return m_sound_flag; } //AY portA is fed by an input clock at 15625 Hz INTERRUPT_GEN_MEMBER(wink_state::wink_sound) { m_sound_flag ^= 0x80; } void wink_state::machine_start() { save_item(NAME(m_sound_flag)); save_item(NAME(m_tile_bank)); save_item(NAME(m_nmi_enable)); } void wink_state::machine_reset() { m_sound_flag = 0; } MACHINE_CONFIG_START(wink_state::wink) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", Z80, 12000000 / 4) MCFG_CPU_PROGRAM_MAP(wink_map) MCFG_CPU_IO_MAP(wink_io) MCFG_DEVICE_ADD("mainlatch", LS259, 0) MCFG_ADDRESSABLE_LATCH_Q0_OUT_CB(WRITELINE(wink_state, nmi_enable_w)) MCFG_ADDRESSABLE_LATCH_Q1_OUT_CB(WRITELINE(wink_state, player_mux_w)) //??? no mux on the pcb. MCFG_ADDRESSABLE_LATCH_Q2_OUT_CB(WRITELINE(wink_state, tile_banking_w)) MCFG_ADDRESSABLE_LATCH_Q3_OUT_CB(NOOP) //? MCFG_ADDRESSABLE_LATCH_Q4_OUT_CB(NOOP) //cab Knocker like in q-bert! MCFG_ADDRESSABLE_LATCH_Q5_OUT_CB(WRITELINE(wink_state, coin_counter_w<0>)) MCFG_ADDRESSABLE_LATCH_Q6_OUT_CB(WRITELINE(wink_state, coin_counter_w<1>)) MCFG_ADDRESSABLE_LATCH_Q7_OUT_CB(WRITELINE(wink_state, coin_counter_w<2>)) MCFG_CPU_ADD("audiocpu", Z80, 12000000 / 8) MCFG_CPU_PROGRAM_MAP(wink_sound_map) MCFG_CPU_IO_MAP(wink_sound_io) MCFG_CPU_PERIODIC_INT_DRIVER(wink_state, wink_sound, 15625) MCFG_NVRAM_ADD_1FILL("nvram") /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0)) MCFG_SCREEN_SIZE(32*8, 32*8) MCFG_SCREEN_VISIBLE_AREA(0*8, 32*8-1, 0*8, 32*8-1) MCFG_SCREEN_UPDATE_DRIVER(wink_state, screen_update_wink) MCFG_SCREEN_PALETTE("palette") MCFG_SCREEN_VBLANK_CALLBACK(WRITELINE(wink_state, nmi_clock_w)) MCFG_GFXDECODE_ADD("gfxdecode", "palette", wink) MCFG_PALETTE_ADD("palette", 16) MCFG_PALETTE_FORMAT(xxxxBBBBRRRRGGGG) /* sound hardware */ MCFG_SPEAKER_STANDARD_MONO("mono") MCFG_GENERIC_LATCH_8_ADD("soundlatch") MCFG_SOUND_ADD("aysnd", AY8912, 12000000 / 8) MCFG_AY8910_PORT_A_READ_CB(READ8(wink_state, sound_r)) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0) MACHINE_CONFIG_END /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( wink ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "midcoin-wink00.rom", 0x0000, 0x4000, CRC(044f82d6) SHA1(4269333578c4fb14891b937c683aa5b105a193e7) ) ROM_LOAD( "midcoin-wink01.rom", 0x4000, 0x4000, CRC(acb0a392) SHA1(428c24845a27b8021823a4a930071b3b47108f01) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "midcoin-wink05.rom", 0x0000, 0x2000, CRC(c6c9d9cf) SHA1(99984905282c2310058d1ce93aec68d8a920b2c0) ) ROM_REGION( 0x6000, "gfx1", 0 ) ROM_LOAD( "midcoin-wink02.rom", 0x0000, 0x2000, CRC(d1cd9d06) SHA1(3b3ce61a0516cc94663f6d3aff3fea46aceb771f) ) ROM_LOAD( "midcoin-wink03.rom", 0x2000, 0x2000, CRC(2346f50c) SHA1(a8535fcde0e9782ea61ad18443186fd5a6ebdc7d) ) ROM_LOAD( "midcoin-wink04.rom", 0x4000, 0x2000, CRC(06dd229b) SHA1(9057cf10e9ec4119297c2d40b26f0ce0c1d7b86a) ) ROM_END ROM_START( winka ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "wink0.bin", 0x0000, 0x4000, CRC(554d86e5) SHA1(bf2de874a62d9137f79063d6ca1906b1ed0c87e6) ) ROM_LOAD( "wink1.bin", 0x4000, 0x4000, CRC(9d8ad539) SHA1(77246df8195f7e3f3b06edc08d344801bf62e1ba) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "wink5.bin", 0x0000, 0x2000, CRC(c6c9d9cf) SHA1(99984905282c2310058d1ce93aec68d8a920b2c0) ) ROM_REGION( 0x6000, "gfx1", 0 ) ROM_LOAD( "wink2.bin", 0x0000, 0x2000, CRC(d1cd9d06) SHA1(3b3ce61a0516cc94663f6d3aff3fea46aceb771f) ) ROM_LOAD( "wink3.bin", 0x2000, 0x2000, CRC(2346f50c) SHA1(a8535fcde0e9782ea61ad18443186fd5a6ebdc7d) ) ROM_LOAD( "wink4.bin", 0x4000, 0x2000, CRC(06dd229b) SHA1(9057cf10e9ec4119297c2d40b26f0ce0c1d7b86a) ) ROM_END DRIVER_INIT_MEMBER(wink_state,wink) { uint32_t i; uint8_t *ROM = memregion("maincpu")->base(); std::vector<uint8_t> buffer(0x8000); // protection module reverse engineered by HIGHWAYMAN memcpy(&buffer[0],ROM,0x8000); for (i = 0x0000; i <= 0x1fff; i++) ROM[i] = buffer[bitswap<16>(i,15,14,13, 11,12, 7, 9, 8,10, 6, 4, 5, 1, 2, 3, 0)]; for (i = 0x2000; i <= 0x3fff; i++) ROM[i] = buffer[bitswap<16>(i,15,14,13, 10, 7,12, 9, 8,11, 6, 3, 1, 5, 2, 4, 0)]; for (i = 0x4000; i <= 0x5fff; i++) ROM[i] = buffer[bitswap<16>(i,15,14,13, 7,10,11, 9, 8,12, 6, 1, 3, 4, 2, 5, 0)]; for (i = 0x6000; i <= 0x7fff; i++) ROM[i] = buffer[bitswap<16>(i,15,14,13, 11,12, 7, 9, 8,10, 6, 4, 5, 1, 2, 3, 0)]; for (i = 0; i < 0x8000; i++) ROM[i] += bitswap<8>(i & 0xff, 7,5,3,1,6,4,2,0); } GAME( 1985, wink, 0, wink, wink, wink_state, wink, ROT0, "Midcoin", "Wink (set 1)", MACHINE_IMPERFECT_SOUND | MACHINE_UNEMULATED_PROTECTION | MACHINE_SUPPORTS_SAVE ) GAME( 1985, winka, wink, wink, wink, wink_state, wink, ROT0, "Midcoin", "Wink (set 2)", MACHINE_IMPERFECT_SOUND | MACHINE_UNEMULATED_PROTECTION | MACHINE_SUPPORTS_SAVE )
EnderNightLord-ChromeBook/zircon-rpi
zircon/system/ulib/fs/include/fs/managed_vfs.h
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef FS_MANAGED_VFS_H_ #define FS_MANAGED_VFS_H_ #ifndef __Fuchsia__ #error "Fuchsia-only header" #endif #include <lib/async/cpp/task.h> #include <atomic> #include <memory> #include <mutex> #include <unordered_map> #include <fbl/auto_call.h> #include <fbl/intrusive_double_list.h> #include <fs/internal/connection.h> #include <fs/vfs.h> namespace fs { // A specialization of |Vfs| which tracks FIDL connections. and integrates them with Vnode requests. // This implementation is the normal one used on Fuchsia. It will not work in host builds. // // This class is thread-safe, but it is unsafe to shutdown the dispatch loop before shutting down // the ManagedVfs object. class ManagedVfs : public Vfs { public: ManagedVfs(); explicit ManagedVfs(async_dispatcher_t* dispatcher); // The ManagedVfs destructor is only safe to execute if // no connections are actively registered. // // To ensure that this state is achieved, it is recommended that // clients issue a call to |Shutdown| before calling the destructor. ~ManagedVfs() override; // Asynchronously drop all connections managed by the VFS. // // Invokes |handler| once when all connections are destroyed. // It is safe to delete ManagedVfs from within the closure. // // It is unsafe to call Shutdown multiple times. void Shutdown(ShutdownCallback handler) override __TA_EXCLUDES(lock_); void CloseAllConnectionsForVnode(const Vnode& node, CloseAllConnectionsForVnodeCallback callback) final; private: // Posts the task for OnShutdownComplete if it is safe to do so. void CheckForShutdownComplete() __TA_REQUIRES(lock_); // Identifies if the filesystem has fully terminated, and is // ready for "OnShutdownComplete" to execute. bool IsTerminated() const __TA_REQUIRES(lock_); // Invokes the handler from |Shutdown| once all connections have been // released. Additionally, unmounts all sub-mounted filesystems, if any // exist. void OnShutdownComplete(async_dispatcher_t*, async::TaskBase*, zx_status_t status) __TA_EXCLUDES(lock_); zx_status_t RegisterConnection(std::unique_ptr<internal::Connection> connection, zx::channel channel) final __TA_EXCLUDES(lock_); void UnregisterConnection(internal::Connection* connection) final __TA_EXCLUDES(lock_); bool IsTerminating() const final; std::mutex lock_; fbl::DoublyLinkedList<std::unique_ptr<internal::Connection>> connections_ __TA_GUARDED(lock_); std::atomic_bool is_shutting_down_; async::TaskMethod<ManagedVfs, &ManagedVfs::OnShutdownComplete> shutdown_task_ __TA_GUARDED(lock_){ this}; ShutdownCallback shutdown_handler_ __TA_GUARDED(lock_); std::unordered_map<internal::Connection*, std::shared_ptr<fbl::AutoCall<fit::callback<void()>>>> closing_connections_ __TA_GUARDED(lock_); }; } // namespace fs #endif // FS_MANAGED_VFS_H_
CoSoSys/cppdevtk
include/cppdevtk/util/service.hpp
<reponame>CoSoSys/cppdevtk ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// \file /// /// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <<EMAIL>>\n /// Licensed under the Apache License, Version 2.0 (the "License");\n /// you may not use this file except in compliance with the License.\n /// You may obtain a copy of the License at\n /// http://www.apache.org/licenses/LICENSE-2.0\n /// Unless required by applicable law or agreed to in writing, software\n /// distributed under the License is distributed on an "AS IS" BASIS,\n /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n /// See the License for the specific language governing permissions and\n /// limitations under the License.\n /// Please see the file COPYING. /// /// \authors <NAME> <<EMAIL>>, <<EMAIL>> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef CPPDEVTK_UTIL_SERVICE_HPP_INCLUDED_ #define CPPDEVTK_UTIL_SERVICE_HPP_INCLUDED_ #include "config.hpp" #if (!CPPDEVTK_ENABLE_QT_SOLUTIONS) #error "This file require QtSolutions enabled!!!" #endif #include "service_base.hpp" #include "core_application.hpp" #include <cppdevtk/base/static_assert.hpp> #if (CPPDEVTK_PLATFORM_UNIX) #include <cppdevtk/base/posix_signals_watcher_unx.hpp> #include <cppdevtk/base/verify.h> #endif #include <cstddef> #include <new> #include CPPDEVTK_TR1_HEADER(type_traits) namespace cppdevtk { namespace util { template <class TApplication> class Service: public ServiceBase { public: typedef TApplication ApplicationType; Service(int argc, char** argv, const QString& name); protected: TApplication* application() const; virtual void createApplication(int& argc, char** argv); virtual int executeApplication(); private: Q_DISABLE_COPY(Service) TApplication* pApplication_; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Inline functions template <class TApplication> inline Service<TApplication>::Service(int argc, char** argv, const QString& name): ServiceBase(argc, argv, name), pApplication_(NULL) {} template <class TApplication> inline TApplication* Service<TApplication>::application() const { return pApplication_; } template <class TApplication> void Service<TApplication>::createApplication(int& argc, char** argv) { CPPDEVTK_STATIC_ASSERT_W_MSG((CPPDEVTK_TR1_NS::is_base_of<CoreApplication, TApplication>::value), "CoreApplication must be a base class of TApplication"); pApplication_ = new TApplication(argc, argv); # if (CPPDEVTK_PLATFORM_UNIX) const ServiceFlags kServiceFlags = serviceFlags(); ::cppdevtk::base::PosixSignalsWatcher& thePosixSignalsWatcher = ::cppdevtk::base::PosixSignalsWatcher::GetInstance(); if (!(kServiceFlags & CannotBeStopped)) { CPPDEVTK_VERIFY(connect(&thePosixSignalsWatcher, SIGNAL(SigTerm()), SLOT(StopAndQuit()))); CPPDEVTK_VERIFY(thePosixSignalsWatcher.Watch(SIGTERM)); CPPDEVTK_VERIFY(connect(&thePosixSignalsWatcher, SIGNAL(SigInt()), SLOT(StopAndQuit()))); CPPDEVTK_VERIFY(thePosixSignalsWatcher.Watch(SIGINT)); } if (kServiceFlags & CanBeSuspended) { CPPDEVTK_VERIFY(connect(&thePosixSignalsWatcher, SIGNAL(SigHUp()), SLOT(reloadConfig()))); CPPDEVTK_VERIFY(thePosixSignalsWatcher.Watch(SIGHUP)); } # endif // (CPPDEVTK_PLATFORM_UNIX) } template <class TApplication> inline int Service<TApplication>::executeApplication() { return TApplication::exec(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Templates explicit instantiation declaration. #ifndef CPPDEVTK_UTIL_SERVICE_CPP CPPDEVTK_UTIL_TMPL_EXPL_INST template class CPPDEVTK_UTIL_API Service<CoreApplication>; #endif } // namespace util } // namespace cppdevtk #endif // CPPDEVTK_UTIL_SERVICE_HPP_INCLUDED_
ursgraf/runtime-library
src/org/deepjava/runtime/zynq7000/demo/WifiDemo.java
<reponame>ursgraf/runtime-library /* * Copyright 2011 - 2013 NTB University of Applied Sciences in Technology * Buchs, Switzerland, http://www.ntb.ch/inf * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.deepjava.runtime.zynq7000.demo; import java.io.PrintStream; import org.deepjava.runtime.util.IntPacket; import org.deepjava.runtime.zynq7000.driver.RN131; import org.deepjava.runtime.zynq7000.driver.UART; import org.deepjava.runtime.arm32.Task; public class WifiDemo extends Task { private RN131 wifi; private static WifiDemo task; public WifiDemo() { period = 500; UART uart = UART.getInstance(UART.pUART0); uart.start(115200, (short) 0, (short)8); wifi = new RN131(uart.in , uart.out, 0); } public void action() { System.out.print(wifi.getState().toString()); if (wifi.connected) System.out.print("\t(connected)\t"); else System.out.print("\t(not connected)\t"); IntPacket.Type type = wifi.intPacket.readInt(); if (type == IntPacket.Type.Int) { System.out.print("int packet ="); System.out.print(wifi.intPacket.getInt()); } else if (type == IntPacket.Type.Unknown) { System.out.print("unknown("); System.out.print(wifi.intPacket.getHeader()); System.out.print(")="); System.out.print(wifi.intPacket.getInt()); } System.out.println(); if (nofActivations % 20 == 0) wifi.intPacket.writeInt(nofActivations); } public static void reset() { task.wifi.reset(); } public static void sendCmd() { if (task.wifi.connected) { task.wifi.intPacket.writeInt(123); } } public static void sendOther() { if (task.wifi.connected) { task.wifi.intPacket.writeInt((byte)0xab, 789); } } static { UART uart = UART.getInstance(UART.pUART1); uart.start(115200, (short)0, (short)8); System.out = new PrintStream(uart.out); System.err = System.out; System.out.println("WifiDemo"); task = new WifiDemo(); Task.install(task); } }
ngokevin/LabSound
labsound/include/LabSound/core/AudioSourceProvider.h
// License: BSD 3 Clause // Copyright (C) 2010, Google Inc. All rights reserved. // Copyright (C) 2015+, The LabSound Authors. All rights reserved. #ifndef AudioSourceProvider_h #define AudioSourceProvider_h #include "LabSound/extended/AudioContextLock.h" namespace lab { class AudioBus; class AudioSourceProviderClient { public: virtual void setFormat(ContextRenderLock& r, size_t numberOfChannels, float sampleRate) = 0; protected: virtual ~AudioSourceProviderClient() { } }; // Abstract base-class for a pull-model client. class AudioSourceProvider { public: // provideInput() gets called repeatedly to render time-slices of a continuous audio stream. virtual void provideInput(AudioBus* bus, size_t framesToProcess) = 0; // If a client is set, we call it back when the audio format is available or changes. virtual void setClient(AudioSourceProviderClient*) { }; virtual ~AudioSourceProvider() { } }; } // lab #endif // AudioSourceProvider_h
Augustyn/jira-suite-utilities
src/main/java/com/googlecode/jsu/helpers/checkers/CheckerComposite.java
<reponame>Augustyn/jira-suite-utilities package com.googlecode.jsu.helpers.checkers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.googlecode.jsu.helpers.ConditionChecker; /** * @author <A href="mailto:abashev at gmail dot com"><NAME></A> */ class CheckerComposite implements ConditionChecker { private final Logger log = LoggerFactory.getLogger(CheckerComposite.class); private final ValueConverter valueConverter; private final ComparingSnipet comparingSnipet; public CheckerComposite( ValueConverter valueConverter, ComparingSnipet comparingSnipet ) { this.valueConverter = valueConverter; this.comparingSnipet = comparingSnipet; } /* (non-Javadoc) * @see com.googlecode.jsu.helpers.ConditionChecker#checkValues(java.lang.Object, java.lang.Object) */ @SuppressWarnings("unchecked") public final boolean checkValues(Object value1, Object value2) { final Comparable<Comparable<?>> comp1; final Comparable<?> comp2; try { comp1 = (Comparable<Comparable<?>>) valueConverter.getComparable(value1); } catch (NumberFormatException e) { log.warn("Wrong number format at [" + value1 + "]"); return false; } catch (Exception e) { log.warn("Unable to get comparable from [" + value1 + "]", e); return false; } try { comp2 = valueConverter.getComparable(value2); } catch (NumberFormatException e) { log.warn("Wrong number format at [" + value2 + "]"); return false; } catch (Exception e) { log.warn("Unable to get comparable from [" + value2 + "]", e); return false; } boolean result = comparingSnipet.compareObjects(comp1, comp2); if (log.isDebugEnabled()) { log.debug("Compare values [" + comp1 + "] and [" + comp2 + "] with result [" + result + "]"); } return result; } }
tongueroo/codebuild
.cody/role.rb
iam_policy( action: [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "ssm:DescribeDocumentParameters", "ssm:DescribeParameters", "ssm:GetParameter*", ], effect: "Allow", resource: "*" ) managed_iam_policy("AWSCloudFormationReadOnlyAccess")
ahmadmahmoud/social
assets/pages/js/demo/imagepicker.js
<reponame>ahmadmahmoud/social<gh_stars>0 $(document).ready(function () { // imagepicker 1 $('#imagepicker1').imagepicker() // imagepicker 2 $('#imagepicker2').imagepicker({ show_label: true }) })
thesocompany/vets-website
src/applications/edu-benefits/0994/pages/applicantInformation.js
<filename>src/applications/edu-benefits/0994/pages/applicantInformation.js import fullSchema from 'vets-json-schema/dist/22-0994-schema.json'; import ssnUI from 'platform/forms-system/src/js/definitions/ssn'; import fullNameUI from 'platform/forms/definitions/fullName'; import ApplicantDescription from 'platform/forms/components/ApplicantDescription'; import currentOrPastDateUI from 'platform/forms-system/src/js/definitions/currentOrPastDate'; import { genderLabels } from 'platform/static-data/labels'; const { applicantFullName, applicantSocialSecurityNumber, dateOfBirth, applicantGender, } = fullSchema.properties; export const uiSchema = { 'ui:description': ApplicantDescription, applicantFullName: { ...fullNameUI, first: { ...fullNameUI.first, 'ui:errorMessages': { pattern: 'Please provide a response', }, }, last: { ...fullNameUI.last, 'ui:errorMessages': { pattern: 'Please provide a response', }, }, }, applicantSocialSecurityNumber: ssnUI, dateOfBirth: { ...currentOrPastDateUI('Date of birth'), 'ui:errorMessages': { pattern: 'Please provide a valid date', futureDate: 'Please provide a valid date', }, }, applicantGender: { 'ui:widget': 'radio', 'ui:title': 'Gender', 'ui:options': { labels: genderLabels, }, }, }; export const schema = { required: ['applicantSocialSecurityNumber', 'dateOfBirth'], type: 'object', properties: { applicantFullName, applicantSocialSecurityNumber, dateOfBirth, applicantGender, }, };
andrewdotn/concurrent-ruby
examples/benchmark_new_futures.rb
<reponame>andrewdotn/concurrent-ruby #!/usr/bin/env ruby require 'benchmark/ips' require 'concurrent' require 'concurrent-edge' raise 'concurrent-ext not loaded' if Concurrent.on_cruby? && Concurrent.c_extensions_loaded? scale = 1 time = 10 * scale warmup = 2 * scale warmup *= 10 if Concurrent.on_jruby? Benchmark.ips(time, warmup) do |x| x.report('flat-old') do Concurrent::Promise.execute { 1 }.flat_map { |v| Concurrent::Promise.execute { v + 2 } }.value! end x.report('flat-new') do Concurrent::Promises.future(:fast) { 1 }.then { |v| Concurrent::Promises.future(:fast) { v + 2 } }.flat.value! end x.compare! end Benchmark.ips(time, warmup) do |x| x.report('status-old') { f = Concurrent::Promise.execute { nil }; 100.times { f.complete? } } x.report('status-new') { f = Concurrent::Promises.future(:fast) { nil }; 100.times { f.resolved? } } x.compare! end Benchmark.ips(time, warmup) do |x| of = Concurrent::Promise.execute { 1 } nf = Concurrent::Promises.fulfilled_future(1, :fast) x.report('value-old') { of.value! } x.report('value-new') { nf.value! } x.compare! end Benchmark.ips(time, warmup) do |x| x.report('graph-old') do head = Concurrent::Promise.fulfill(1) 10.times do branch1 = head.then(&:succ) branch2 = head.then(&:succ).then(&:succ) head = Concurrent::Promise.zip(branch1, branch2).then { |a, b| a + b } end head.value! end x.report('graph-new') do head = Concurrent::Promises.fulfilled_future(1, :fast) 10.times do branch1 = head.then(&:succ) branch2 = head.then(&:succ).then(&:succ) head = (branch1 & branch2).then { |a, b| a + b } end head.value! end x.compare! end Benchmark.ips(time, warmup) do |x| x.report('immediate-old') { Concurrent::Promise.fulfill(nil).value! } x.report('immediate-new') { Concurrent::Promises.fulfilled_future(nil, :fast).value! } x.compare! end Benchmark.ips(time, warmup) do |x| of = Concurrent::Promise.execute { 1 } nf = Concurrent::Promises.fulfilled_future(1, :fast) x.report('then-old') { 50.times.reduce(of) { |nf, _| nf.then(&:succ) }.value! } x.report('then-new') { 50.times.reduce(nf) { |nf, _| nf.then(&:succ) }.value! } x.compare! end
fjh2021/spring-sevice
h2/src/main/java/com/fjh/business/controller/UserController.java
<gh_stars>1-10 package com.fjh.business.controller; import com.fjh.business.mapper.UserMapper; import com.fjh.model.User; import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * <p> * * </p> * * @author fjh * @since 2022/2/11 9:57 */ @Api(tags = "h2接口") @RestController @Slf4j public class UserController { @Autowired private UserMapper userMapper; @GetMapping("test") public List<User> testSelect() { List<User> userList = userMapper.selectList(null); return userList; } }
advantageous/qbit-extensions
examples/standalone/src/main/java/io/advantageous/qbit/example/perf/websocket/TradeService.java
package io.advantageous.qbit.example.perf.websocket; import io.advantageous.qbit.admin.ManagedServiceBuilder; import io.advantageous.qbit.annotation.RequestMapping; import io.advantageous.qbit.annotation.Service; import io.advantageous.qbit.annotation.http.GET; import io.advantageous.qbit.annotation.http.PUT; import io.advantageous.qbit.reactive.Callback; import io.advantageous.reakt.promise.Promise; import io.advantageous.reakt.promise.Promises; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static io.advantageous.qbit.admin.ManagedServiceBuilder.managedServiceBuilder; /** * curl -H "Content-Type: application/json" -X PUT http://localhost:8080/trade -d '{"name":"ibm", "amount":1}' * curl http://localhost:8080/count */ @RequestMapping("/") @Service("t") public class TradeService { private long count; final ExecutorService executorService = Executors.newFixedThreadPool(10); @PUT("/trade") public void t(Callback<Boolean> cb, final Trade trade) { executorService.submit(() -> { trade.getNm().hashCode(); trade.getAmt(); count++; cb.resolve(true); try { Thread.sleep(199); } catch (InterruptedException e) { e.printStackTrace(); } }); } @PUT("/a") public void a(Callback<Boolean> cb, final Trade trade) { trade.getNm().hashCode(); trade.getAmt(); count++; cb.resolve(true); } @PUT("/trade2") public Promise<Boolean> t2(final Trade trade) { return Promises.invokablePromise(promise -> { executorService.submit(() -> { trade.getNm().hashCode(); trade.getAmt(); count++; promise.resolve(true); try { Thread.sleep(201); } catch (InterruptedException e) { e.printStackTrace(); } }); }); } @PUT("/trade2") public Promise<Boolean> b(final Trade trade) { return Promises.invokablePromise(promise -> { trade.getNm().hashCode(); trade.getAmt(); count++; promise.resolve(true); }); } @GET("/count") public long count() { return count; } public static void main(final String... args) { final ManagedServiceBuilder managedServiceBuilder = managedServiceBuilder(); managedServiceBuilder .addEndpointService(new TradeService()) .setRootURI("/"); //managedServiceBuilder.getEndpointServerBuilder().setHost("192.168.0.1"); managedServiceBuilder.startApplication(); } }
replicant4j/replicant
client/src/main/java/replicant/spy/AreaOfInterestFilterUpdatedEvent.java
package replicant.spy; import arez.spy.SerializableEvent; import java.util.Map; import java.util.Objects; import javax.annotation.Nonnull; import replicant.AreaOfInterest; import replicant.ChannelAddress; /** * Notification when an AreaOfInterest filter has been updated. */ public final class AreaOfInterestFilterUpdatedEvent implements SerializableEvent { @Nonnull private final AreaOfInterest _areaOfInterest; public AreaOfInterestFilterUpdatedEvent( @Nonnull final AreaOfInterest areaOfInterest ) { _areaOfInterest = Objects.requireNonNull( areaOfInterest ); } @Nonnull public AreaOfInterest getAreaOfInterest() { return _areaOfInterest; } @Override public void toMap( @Nonnull final Map<String, Object> map ) { map.put( "type", "AreaOfInterest.Updated" ); final AreaOfInterest areaOfInterest = getAreaOfInterest(); final ChannelAddress address = areaOfInterest.getAddress(); map.put( "channel.systemId", address.getSystemId() ); map.put( "channel.channelId", address.getChannelId() ); map.put( "channel.id", address.getId() ); map.put( "channel.filter", areaOfInterest.getFilter() ); } }
rememberlenny/rev-ruby-sdk
spec/lib/rev/models/order_request_spec.rb
<filename>spec/lib/rev/models/order_request_spec.rb require_relative '../../../spec_helper' GLOSSARY_ENTRIES_LIMIT_TEST = 1000 GLOSSARY_ENTRY_LENGTH_LIMIT_TEST = 255 SPEAKER_ENTRIES_LIMIT_TEST = 100 SPEAKER_ENTRY_LENGTH_LIMIT_TEST = 15 SUPPORTED_ACCENTS_COUNT = 8 describe 'OrderRequest' do it 'defaults to standard TAT guarantee' do order = Rev::OrderRequest.new({}) order.non_standard_tat_guarantee.must_equal false end it 'accepts non standard TAT guarantee flag during init' do non_standard_tat_guarantee = true order = Rev::OrderRequest.new({ 'non_standard_tat_guarantee' => non_standard_tat_guarantee }) order.non_standard_tat_guarantee.must_equal non_standard_tat_guarantee end it 'has caption options' do order = Rev::OrderRequest.new({}) order.must_respond_to :caption_options end describe 'InputOptions' do it 'is ApiSerializable' do options = Rev::InputOptions.new([{}], {}) options.must_be_kind_of Rev::ApiSerializable end it 'requires non-empty inputs' do proc { Rev::InputOptions.new([]) }.must_raise ArgumentError end it 'requires non-nil inputs' do proc { Rev::InputOptions.new(nil) }.must_raise ArgumentError end it 'sets inputs from init' do inputs = ['foo'] options = Rev::InputOptions.new(inputs) options.inputs.must_equal inputs end end describe 'TranscriptionOptions' do it 'is InputOptions' do inputs = create_input() options = Rev::TranscriptionOptions.new(inputs, {}) options.must_be_kind_of Rev::InputOptions end it 'has correct info attributes' do inputs = create_input() options = Rev::TranscriptionOptions.new(inputs, {}) options.must_respond_to :output_file_formats options.must_respond_to :verbatim options.must_respond_to :timestamps end it 'has output file formats hash' do Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:ms_word].must_equal 'MS Word' Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:json].must_equal 'JSON' Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:text].must_equal 'Text' Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:pdf].must_equal 'Pdf' end it 'rejects invalid output file format' do inputs = create_input() proc { Rev::TranscriptionOptions.new(inputs, { :output_file_formats => ['invalid'] }) }.must_raise ArgumentError end it 'accepts all valid output file formats' do inputs = create_input() order = Rev::TranscriptionOptions.new(inputs, { :output_file_formats => [ Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:ms_word], Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:json], Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:text], Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:pdf] ] }) order.output_file_formats.length.must_equal 4 order.output_file_formats[0].must_equal Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:ms_word] order.output_file_formats[1].must_equal Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:json] order.output_file_formats[2].must_equal Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:text] order.output_file_formats[3].must_equal Rev::TranscriptionOptions::OUTPUT_FILE_FORMATS[:pdf] end it 'rejects glossary of invalid size' do oversize_glossary = ['testing']*(GLOSSARY_ENTRIES_LIMIT_TEST + 1) inputs = create_input(glossary: oversize_glossary) proc { Rev::TranscriptionOptions.new(inputs) }.must_raise ArgumentError end it 'rejects glossary if any terms are too long' do oversize_glossary_term = "A" * (GLOSSARY_ENTRY_LENGTH_LIMIT_TEST + 1) inputs = create_input(glossary: [oversize_glossary_term]) proc { Rev::TranscriptionOptions.new(inputs) }.must_raise ArgumentError end it 'rejects speaker list of invalid size' do oversize_speakers = ['testing']*(SPEAKER_ENTRIES_LIMIT_TEST + 1) inputs = create_input(speakers: oversize_speakers) proc { Rev::TranscriptionOptions.new(inputs) }.must_raise ArgumentError end it 'rejects speaker names if name is too long' do oversize_speaker_name = "A" * (SPEAKER_ENTRY_LENGTH_LIMIT_TEST + 1) inputs = create_input(speakers: [oversize_speaker_name]) proc { Rev::TranscriptionOptions.new(inputs) }.must_raise ArgumentError end it 'rejects invalid accents' do inputs = create_input(accents: ['invalid']) proc { Rev::TranscriptionOptions.new(inputs) }.must_raise ArgumentError end it 'rejects accents when theres more listed than supported' do accents = [Rev::Input::SUPPORTED_ACCENTS[:american_neutral]]*(SUPPORTED_ACCENTS_COUNT + 1) inputs = create_input(accents: accents) proc { Rev::TranscriptionOptions.new(inputs) }.must_raise ArgumentError end end describe 'CaptionOptions' do it 'is InputOptions' do inputs = create_input() options = Rev::CaptionOptions.new(inputs, {}) options.must_be_kind_of Rev::InputOptions end it 'has output file formats attribute' do inputs = create_input() options = Rev::CaptionOptions.new(inputs, {}) options.must_respond_to :output_file_formats end it 'has output file formats hash' do Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:subrip].must_equal 'SubRip' Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:scc].must_equal 'Scc' Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:mcc].must_equal 'Mcc' Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:ttml].must_equal 'Ttml' Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:qttext].must_equal 'QTtext' Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:transcript].must_equal 'Transcript' Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:webvtt].must_equal 'WebVtt' Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:dfxp].must_equal 'Dfxp' Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:cheetahcap].must_equal 'CheetahCap' end it 'rejects unknowns file formats' do inputs = create_input() proc { Rev::CaptionOptions.new(inputs, { :output_file_formats => ['invalid'] }) }.must_raise ArgumentError end it 'accepts valid file formats' do inputs = create_input() order = Rev::CaptionOptions.new(inputs, { :output_file_formats => [Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:scc]] }) order.output_file_formats.length.must_equal 1 order.output_file_formats[0].must_equal Rev::CaptionOptions::OUTPUT_FILE_FORMATS[:scc] end it 'rejects glossary of invalid size' do oversize_glossary = [] for x in 0..GLOSSARY_ENTRIES_LIMIT_TEST do oversize_glossary << 'testing' end inputs = create_input(glossary: oversize_glossary) proc { Rev::CaptionOptions.new(inputs) }.must_raise ArgumentError end it 'rejects glossary if any terms are too long' do oversize_glossary_term = "A" * (GLOSSARY_ENTRY_LENGTH_LIMIT_TEST + 1) inputs = create_input(glossary: [oversize_glossary_term]) proc { Rev::CaptionOptions.new(inputs) }.must_raise ArgumentError end it 'rejects speaker names of invalid size' do oversize_speakers = [] for x in 0..SPEAKER_ENTRIES_LIMIT_TEST do oversize_speakers << 'testing' end inputs = create_input(speakers: oversize_speakers) proc { Rev::CaptionOptions.new(inputs) }.must_raise ArgumentError end it 'rejects speaker names if name is too long' do oversize_speaker_name = "A" * (SPEAKER_ENTRY_LENGTH_LIMIT_TEST + 1) inputs = create_input(speakers: [oversize_speaker_name]) proc { Rev::CaptionOptions.new(inputs) }.must_raise ArgumentError end end # CaptionOptions describe 'Notification' do it 'Defaults level' do notification = Rev::Notification.new('http://example.com/') notification.level.must_equal Rev::Notification::LEVELS[:final_only] end end # Notification end
tblink-rpc/tblink-rpc-core
tests/cpp/TblinkRpcSmoke.h
/* * TblinkRpcSmoke.h * * Created on: Jul 4, 2021 * Author: mballance */ #pragma once #include "TblinkRpcTestBase.h" class TblinkRpcSmoke : public TblinkRpcTestBase { public: TblinkRpcSmoke(); virtual ~TblinkRpcSmoke(); };
huandrew99/LeetCode
grokking-the-coding-interview/modified-binary-search/Search-in-Rotated-Sorted-Array-II.py
""" LC 81 search in a sorted and rotated array that also has duplicates? Example 1: Input: [3, 7, 3, 3, 3], key = 7 Output: 1 Explanation: '7' is present in the array at index '1'. """ def search_rotated_with_duplicates(arr, key): # make sure arr[l] > arr[-1] l = 0 while l < len(arr) and arr[l] == arr[-1]: l += 1 start = l # in case starting from l, arr[l:] is sorted if 0 < l < len(arr) and arr[l - 1] > arr[l]: l, r = l - 1, l - 1 else: r = len(arr) - 1 # find peak while l < r: m = r - (r - l >> 1) if arr[m] < arr[start]: r = m - 1 else: l = m h = r idx = binary_search(arr, key, 0, h) if idx == -1: idx = binary_search(arr, key, h + 1, len(arr) - 1) return idx def binary_search(arr, key, l, r): if l > r: return -1 while l < r: m = l + (r - l >> 1) if key <= arr[m]: r = m else: l = m + 1 if arr[l] == key: return l else: return -1 def main(): print(search_rotated_with_duplicates([3, 7, 3, 3, 3], 7)) print(search_rotated_with_duplicates([3, 3, 3, 7, 3, 3, 3, 3, 3, 3], 7)) main() """ Time O(N) Space O(1) """
obs145628/cle
middle-end-optis/superlocal-value-numbering/src/lib/digraph.hh
#pragma once #include <cassert> #include <ostream> #include <vector> class Digraph { public: class adj_iter_t { public: adj_iter_t operator++() { _next(); return *this; } adj_iter_t operator++(int) { auto res = *this; _next(); return res; } std::size_t operator*() const { assert(_adj_i < _g._v); return _adj_i; } private: const Digraph &_g; std::size_t _v; std::size_t _adj_i; adj_iter_t(const Digraph &g, std::size_t v, std::size_t adj_i) : _g(g), _v(v), _adj_i(adj_i) {} void _next() { assert(_adj_i != _g._v); ++_adj_i; while (_adj_i < _g._v && !_g.has_edge(_v, _adj_i)) ++_adj_i; } friend class Digraph; friend bool operator==(const adj_iter_t &x, const adj_iter_t &y); }; Digraph(std::size_t v); // returns numbers of vertices std::size_t v() const { return _v; } // returns number of edges std::size_t e() const { return _e; } void add_edge(std::size_t u, std::size_t v) { auto &edge = _adj[_mid(u, v)]; _e += !edge; edge = 1; } bool has_edge(std::size_t u, std::size_t v) const { return _adj[_mid(u, v)] == 1; } // Return iterator over all vertices adjacent to u adj_iter_t adj_begin(std::size_t u) const { assert(u < _v); adj_iter_t res(*this, u, -1); return ++res; } adj_iter_t adj_end(std::size_t u) const { assert(u < _v); return adj_iter_t(*this, u, _v); } // Build a new graph with all edges reversed Digraph reverse() const; // Number of successors of u std::size_t out_deg(std::size_t u) const; // dump to tree-file syntax void dump_tree(std::ostream &os) const; void labels_set_vertex_name(std::size_t u, const std::string &name) { assert(u < _v); _labels_vs[u] = name; } private: const std::size_t _v; std::size_t _e; std::vector<int> _adj; std::vector<std::string> _labels_vs; std::size_t _mid(std::size_t u, std::size_t v) const { assert(u < _v); assert(v < _v); return u * _v + v; } }; inline bool operator==(const Digraph::adj_iter_t &x, const Digraph::adj_iter_t &y) { assert(&x._g == &y._g); assert(x._v == y._v); return x._adj_i == y._adj_i; } inline bool operator!=(const Digraph::adj_iter_t &x, const Digraph::adj_iter_t &y) { return !(x == y); } inline std::size_t Digraph::out_deg(std::size_t u) const { std::size_t res = 0; for (auto it = adj_begin(u); it != adj_end(u); ++it) ++res; return res; }
OpenMPDK/SMDK
lib/linux-5.18-rc3-smdk/drivers/ata/pata_mpc52xx.c
/* * drivers/ata/pata_mpc52xx.c * * libata driver for the Freescale MPC52xx on-chip IDE interface * * Copyright (C) 2006 <NAME> <<EMAIL>> * Copyright (C) 2003 Mipsys - <NAME> * * UDMA support based on patches by Freescale (<NAME>, <NAME>), * <NAME> and <NAME>. * * This file is licensed under the terms of the GNU General Public License * version 2. This program is licensed "as is" without any warranty of any * kind, whether express or implied. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/gfp.h> #include <linux/delay.h> #include <linux/libata.h> #include <linux/of_platform.h> #include <linux/types.h> #include <asm/cacheflush.h> #include <asm/prom.h> #include <asm/mpc52xx.h> #include <linux/fsl/bestcomm/bestcomm.h> #include <linux/fsl/bestcomm/bestcomm_priv.h> #include <linux/fsl/bestcomm/ata.h> #define DRV_NAME "mpc52xx_ata" /* Private structures used by the driver */ struct mpc52xx_ata_timings { u32 pio1; u32 pio2; u32 mdma1; u32 mdma2; u32 udma1; u32 udma2; u32 udma3; u32 udma4; u32 udma5; int using_udma; }; struct mpc52xx_ata_priv { unsigned int ipb_period; struct mpc52xx_ata __iomem *ata_regs; phys_addr_t ata_regs_pa; int ata_irq; struct mpc52xx_ata_timings timings[2]; int csel; /* DMA */ struct bcom_task *dmatsk; const struct udmaspec *udmaspec; const struct mdmaspec *mdmaspec; int mpc52xx_ata_dma_last_write; int waiting_for_dma; }; /* ATAPI-4 PIO specs (in ns) */ static const u16 ataspec_t0[5] = {600, 383, 240, 180, 120}; static const u16 ataspec_t1[5] = { 70, 50, 30, 30, 25}; static const u16 ataspec_t2_8[5] = {290, 290, 290, 80, 70}; static const u16 ataspec_t2_16[5] = {165, 125, 100, 80, 70}; static const u16 ataspec_t2i[5] = { 0, 0, 0, 70, 25}; static const u16 ataspec_t4[5] = { 30, 20, 15, 10, 10}; static const u16 ataspec_ta[5] = { 35, 35, 35, 35, 35}; #define CALC_CLKCYC(c,v) ((((v)+(c)-1)/(c))) /* ======================================================================== */ /* ATAPI-4 MDMA specs (in clocks) */ struct mdmaspec { u8 t0M; u8 td; u8 th; u8 tj; u8 tkw; u8 tm; u8 tn; }; static const struct mdmaspec mdmaspec66[3] = { { .t0M = 32, .td = 15, .th = 2, .tj = 2, .tkw = 15, .tm = 4, .tn = 1 }, { .t0M = 10, .td = 6, .th = 1, .tj = 1, .tkw = 4, .tm = 2, .tn = 1 }, { .t0M = 8, .td = 5, .th = 1, .tj = 1, .tkw = 2, .tm = 2, .tn = 1 }, }; static const struct mdmaspec mdmaspec132[3] = { { .t0M = 64, .td = 29, .th = 3, .tj = 3, .tkw = 29, .tm = 7, .tn = 2 }, { .t0M = 20, .td = 11, .th = 2, .tj = 1, .tkw = 7, .tm = 4, .tn = 1 }, { .t0M = 16, .td = 10, .th = 2, .tj = 1, .tkw = 4, .tm = 4, .tn = 1 }, }; /* ATAPI-4 UDMA specs (in clocks) */ struct udmaspec { u8 tcyc; u8 t2cyc; u8 tds; u8 tdh; u8 tdvs; u8 tdvh; u8 tfs; u8 tli; u8 tmli; u8 taz; u8 tzah; u8 tenv; u8 tsr; u8 trfs; u8 trp; u8 tack; u8 tss; }; static const struct udmaspec udmaspec66[6] = { { .tcyc = 8, .t2cyc = 16, .tds = 1, .tdh = 1, .tdvs = 5, .tdvh = 1, .tfs = 16, .tli = 10, .tmli = 2, .taz = 1, .tzah = 2, .tenv = 2, .tsr = 3, .trfs = 5, .trp = 11, .tack = 2, .tss = 4, }, { .tcyc = 5, .t2cyc = 11, .tds = 1, .tdh = 1, .tdvs = 4, .tdvh = 1, .tfs = 14, .tli = 10, .tmli = 2, .taz = 1, .tzah = 2, .tenv = 2, .tsr = 2, .trfs = 5, .trp = 9, .tack = 2, .tss = 4, }, { .tcyc = 4, .t2cyc = 8, .tds = 1, .tdh = 1, .tdvs = 3, .tdvh = 1, .tfs = 12, .tli = 10, .tmli = 2, .taz = 1, .tzah = 2, .tenv = 2, .tsr = 2, .trfs = 4, .trp = 7, .tack = 2, .tss = 4, }, { .tcyc = 3, .t2cyc = 6, .tds = 1, .tdh = 1, .tdvs = 2, .tdvh = 1, .tfs = 9, .tli = 7, .tmli = 2, .taz = 1, .tzah = 2, .tenv = 2, .tsr = 2, .trfs = 4, .trp = 7, .tack = 2, .tss = 4, }, { .tcyc = 2, .t2cyc = 4, .tds = 1, .tdh = 1, .tdvs = 1, .tdvh = 1, .tfs = 8, .tli = 8, .tmli = 2, .taz = 1, .tzah = 2, .tenv = 2, .tsr = 2, .trfs = 4, .trp = 7, .tack = 2, .tss = 4, }, { .tcyc = 2, .t2cyc = 2, .tds = 1, .tdh = 1, .tdvs = 1, .tdvh = 1, .tfs = 6, .tli = 5, .tmli = 2, .taz = 1, .tzah = 2, .tenv = 2, .tsr = 2, .trfs = 4, .trp = 6, .tack = 2, .tss = 4, }, }; static const struct udmaspec udmaspec132[6] = { { .tcyc = 15, .t2cyc = 31, .tds = 2, .tdh = 1, .tdvs = 10, .tdvh = 1, .tfs = 30, .tli = 20, .tmli = 3, .taz = 2, .tzah = 3, .tenv = 3, .tsr = 7, .trfs = 10, .trp = 22, .tack = 3, .tss = 7, }, { .tcyc = 10, .t2cyc = 21, .tds = 2, .tdh = 1, .tdvs = 7, .tdvh = 1, .tfs = 27, .tli = 20, .tmli = 3, .taz = 2, .tzah = 3, .tenv = 3, .tsr = 4, .trfs = 10, .trp = 17, .tack = 3, .tss = 7, }, { .tcyc = 6, .t2cyc = 12, .tds = 1, .tdh = 1, .tdvs = 5, .tdvh = 1, .tfs = 23, .tli = 20, .tmli = 3, .taz = 2, .tzah = 3, .tenv = 3, .tsr = 3, .trfs = 8, .trp = 14, .tack = 3, .tss = 7, }, { .tcyc = 7, .t2cyc = 12, .tds = 1, .tdh = 1, .tdvs = 3, .tdvh = 1, .tfs = 15, .tli = 13, .tmli = 3, .taz = 2, .tzah = 3, .tenv = 3, .tsr = 3, .trfs = 8, .trp = 14, .tack = 3, .tss = 7, }, { .tcyc = 2, .t2cyc = 5, .tds = 0, .tdh = 0, .tdvs = 1, .tdvh = 1, .tfs = 16, .tli = 14, .tmli = 2, .taz = 1, .tzah = 2, .tenv = 2, .tsr = 2, .trfs = 7, .trp = 13, .tack = 2, .tss = 6, }, { .tcyc = 3, .t2cyc = 6, .tds = 1, .tdh = 1, .tdvs = 1, .tdvh = 1, .tfs = 12, .tli = 10, .tmli = 3, .taz = 2, .tzah = 3, .tenv = 3, .tsr = 3, .trfs = 7, .trp = 12, .tack = 3, .tss = 7, }, }; /* ======================================================================== */ /* Bit definitions inside the registers */ #define MPC52xx_ATA_HOSTCONF_SMR 0x80000000UL /* State machine reset */ #define MPC52xx_ATA_HOSTCONF_FR 0x40000000UL /* FIFO Reset */ #define MPC52xx_ATA_HOSTCONF_IE 0x02000000UL /* Enable interrupt in PIO */ #define MPC52xx_ATA_HOSTCONF_IORDY 0x01000000UL /* Drive supports IORDY protocol */ #define MPC52xx_ATA_HOSTSTAT_TIP 0x80000000UL /* Transaction in progress */ #define MPC52xx_ATA_HOSTSTAT_UREP 0x40000000UL /* UDMA Read Extended Pause */ #define MPC52xx_ATA_HOSTSTAT_RERR 0x02000000UL /* Read Error */ #define MPC52xx_ATA_HOSTSTAT_WERR 0x01000000UL /* Write Error */ #define MPC52xx_ATA_FIFOSTAT_EMPTY 0x01 /* FIFO Empty */ #define MPC52xx_ATA_FIFOSTAT_ERROR 0x40 /* FIFO Error */ #define MPC52xx_ATA_DMAMODE_WRITE 0x01 /* Write DMA */ #define MPC52xx_ATA_DMAMODE_READ 0x02 /* Read DMA */ #define MPC52xx_ATA_DMAMODE_UDMA 0x04 /* UDMA enabled */ #define MPC52xx_ATA_DMAMODE_IE 0x08 /* Enable drive interrupt to CPU in DMA mode */ #define MPC52xx_ATA_DMAMODE_FE 0x10 /* FIFO Flush enable in Rx mode */ #define MPC52xx_ATA_DMAMODE_FR 0x20 /* FIFO Reset */ #define MPC52xx_ATA_DMAMODE_HUT 0x40 /* Host UDMA burst terminate */ #define MAX_DMA_BUFFERS 128 #define MAX_DMA_BUFFER_SIZE 0x20000u /* Structure of the hardware registers */ struct mpc52xx_ata { /* Host interface registers */ u32 config; /* ATA + 0x00 Host configuration */ u32 host_status; /* ATA + 0x04 Host controller status */ u32 pio1; /* ATA + 0x08 PIO Timing 1 */ u32 pio2; /* ATA + 0x0c PIO Timing 2 */ u32 mdma1; /* ATA + 0x10 MDMA Timing 1 */ u32 mdma2; /* ATA + 0x14 MDMA Timing 2 */ u32 udma1; /* ATA + 0x18 UDMA Timing 1 */ u32 udma2; /* ATA + 0x1c UDMA Timing 2 */ u32 udma3; /* ATA + 0x20 UDMA Timing 3 */ u32 udma4; /* ATA + 0x24 UDMA Timing 4 */ u32 udma5; /* ATA + 0x28 UDMA Timing 5 */ u32 share_cnt; /* ATA + 0x2c ATA share counter */ u32 reserved0[3]; /* FIFO registers */ u32 fifo_data; /* ATA + 0x3c */ u8 fifo_status_frame; /* ATA + 0x40 */ u8 fifo_status; /* ATA + 0x41 */ u16 reserved7[1]; u8 fifo_control; /* ATA + 0x44 */ u8 reserved8[5]; u16 fifo_alarm; /* ATA + 0x4a */ u16 reserved9; u16 fifo_rdp; /* ATA + 0x4e */ u16 reserved10; u16 fifo_wrp; /* ATA + 0x52 */ u16 reserved11; u16 fifo_lfrdp; /* ATA + 0x56 */ u16 reserved12; u16 fifo_lfwrp; /* ATA + 0x5a */ /* Drive TaskFile registers */ u8 tf_control; /* ATA + 0x5c TASKFILE Control/Alt Status */ u8 reserved13[3]; u16 tf_data; /* ATA + 0x60 TASKFILE Data */ u16 reserved14; u8 tf_features; /* ATA + 0x64 TASKFILE Features/Error */ u8 reserved15[3]; u8 tf_sec_count; /* ATA + 0x68 TASKFILE Sector Count */ u8 reserved16[3]; u8 tf_sec_num; /* ATA + 0x6c TASKFILE Sector Number */ u8 reserved17[3]; u8 tf_cyl_low; /* ATA + 0x70 TASKFILE Cylinder Low */ u8 reserved18[3]; u8 tf_cyl_high; /* ATA + 0x74 TASKFILE Cylinder High */ u8 reserved19[3]; u8 tf_dev_head; /* ATA + 0x78 TASKFILE Device/Head */ u8 reserved20[3]; u8 tf_command; /* ATA + 0x7c TASKFILE Command/Status */ u8 dma_mode; /* ATA + 0x7d ATA Host DMA Mode configuration */ u8 reserved21[2]; }; /* ======================================================================== */ /* Aux fns */ /* ======================================================================== */ /* MPC52xx low level hw control */ static int mpc52xx_ata_compute_pio_timings(struct mpc52xx_ata_priv *priv, int dev, int pio) { struct mpc52xx_ata_timings *timing = &priv->timings[dev]; unsigned int ipb_period = priv->ipb_period; u32 t0, t1, t2_8, t2_16, t2i, t4, ta; if ((pio < 0) || (pio > 4)) return -EINVAL; t0 = CALC_CLKCYC(ipb_period, 1000 * ataspec_t0[pio]); t1 = CALC_CLKCYC(ipb_period, 1000 * ataspec_t1[pio]); t2_8 = CALC_CLKCYC(ipb_period, 1000 * ataspec_t2_8[pio]); t2_16 = CALC_CLKCYC(ipb_period, 1000 * ataspec_t2_16[pio]); t2i = CALC_CLKCYC(ipb_period, 1000 * ataspec_t2i[pio]); t4 = CALC_CLKCYC(ipb_period, 1000 * ataspec_t4[pio]); ta = CALC_CLKCYC(ipb_period, 1000 * ataspec_ta[pio]); timing->pio1 = (t0 << 24) | (t2_8 << 16) | (t2_16 << 8) | (t2i); timing->pio2 = (t4 << 24) | (t1 << 16) | (ta << 8); return 0; } static int mpc52xx_ata_compute_mdma_timings(struct mpc52xx_ata_priv *priv, int dev, int speed) { struct mpc52xx_ata_timings *t = &priv->timings[dev]; const struct mdmaspec *s = &priv->mdmaspec[speed]; if (speed < 0 || speed > 2) return -EINVAL; t->mdma1 = ((u32)s->t0M << 24) | ((u32)s->td << 16) | ((u32)s->tkw << 8) | s->tm; t->mdma2 = ((u32)s->th << 24) | ((u32)s->tj << 16) | ((u32)s->tn << 8); t->using_udma = 0; return 0; } static int mpc52xx_ata_compute_udma_timings(struct mpc52xx_ata_priv *priv, int dev, int speed) { struct mpc52xx_ata_timings *t = &priv->timings[dev]; const struct udmaspec *s = &priv->udmaspec[speed]; if (speed < 0 || speed > 2) return -EINVAL; t->udma1 = ((u32)s->t2cyc << 24) | ((u32)s->tcyc << 16) | ((u32)s->tds << 8) | s->tdh; t->udma2 = ((u32)s->tdvs << 24) | ((u32)s->tdvh << 16) | ((u32)s->tfs << 8) | s->tli; t->udma3 = ((u32)s->tmli << 24) | ((u32)s->taz << 16) | ((u32)s->tenv << 8) | s->tsr; t->udma4 = ((u32)s->tss << 24) | ((u32)s->trfs << 16) | ((u32)s->trp << 8) | s->tack; t->udma5 = (u32)s->tzah << 24; t->using_udma = 1; return 0; } static void mpc52xx_ata_apply_timings(struct mpc52xx_ata_priv *priv, int device) { struct mpc52xx_ata __iomem *regs = priv->ata_regs; struct mpc52xx_ata_timings *timing = &priv->timings[device]; out_be32(&regs->pio1, timing->pio1); out_be32(&regs->pio2, timing->pio2); out_be32(&regs->mdma1, timing->mdma1); out_be32(&regs->mdma2, timing->mdma2); out_be32(&regs->udma1, timing->udma1); out_be32(&regs->udma2, timing->udma2); out_be32(&regs->udma3, timing->udma3); out_be32(&regs->udma4, timing->udma4); out_be32(&regs->udma5, timing->udma5); priv->csel = device; } static int mpc52xx_ata_hw_init(struct mpc52xx_ata_priv *priv) { struct mpc52xx_ata __iomem *regs = priv->ata_regs; int tslot; /* Clear share_cnt (all sample code do this ...) */ out_be32(&regs->share_cnt, 0); /* Configure and reset host */ out_be32(&regs->config, MPC52xx_ATA_HOSTCONF_IE | MPC52xx_ATA_HOSTCONF_IORDY | MPC52xx_ATA_HOSTCONF_SMR | MPC52xx_ATA_HOSTCONF_FR); udelay(10); out_be32(&regs->config, MPC52xx_ATA_HOSTCONF_IE | MPC52xx_ATA_HOSTCONF_IORDY); /* Set the time slot to 1us */ tslot = CALC_CLKCYC(priv->ipb_period, 1000000); out_be32(&regs->share_cnt, tslot << 16); /* Init timings to PIO0 */ memset(priv->timings, 0x00, 2*sizeof(struct mpc52xx_ata_timings)); mpc52xx_ata_compute_pio_timings(priv, 0, 0); mpc52xx_ata_compute_pio_timings(priv, 1, 0); mpc52xx_ata_apply_timings(priv, 0); return 0; } /* ======================================================================== */ /* libata driver */ /* ======================================================================== */ static void mpc52xx_ata_set_piomode(struct ata_port *ap, struct ata_device *adev) { struct mpc52xx_ata_priv *priv = ap->host->private_data; int pio, rv; pio = adev->pio_mode - XFER_PIO_0; rv = mpc52xx_ata_compute_pio_timings(priv, adev->devno, pio); if (rv) { dev_err(ap->dev, "error: invalid PIO mode: %d\n", pio); return; } mpc52xx_ata_apply_timings(priv, adev->devno); } static void mpc52xx_ata_set_dmamode(struct ata_port *ap, struct ata_device *adev) { struct mpc52xx_ata_priv *priv = ap->host->private_data; int rv; if (adev->dma_mode >= XFER_UDMA_0) { int dma = adev->dma_mode - XFER_UDMA_0; rv = mpc52xx_ata_compute_udma_timings(priv, adev->devno, dma); } else { int dma = adev->dma_mode - XFER_MW_DMA_0; rv = mpc52xx_ata_compute_mdma_timings(priv, adev->devno, dma); } if (rv) { dev_alert(ap->dev, "Trying to select invalid DMA mode %d\n", adev->dma_mode); return; } mpc52xx_ata_apply_timings(priv, adev->devno); } static void mpc52xx_ata_dev_select(struct ata_port *ap, unsigned int device) { struct mpc52xx_ata_priv *priv = ap->host->private_data; if (device != priv->csel) mpc52xx_ata_apply_timings(priv, device); ata_sff_dev_select(ap, device); } static int mpc52xx_ata_build_dmatable(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct mpc52xx_ata_priv *priv = ap->host->private_data; struct bcom_ata_bd *bd; unsigned int read = !(qc->tf.flags & ATA_TFLAG_WRITE), si; struct scatterlist *sg; int count = 0; if (read) bcom_ata_rx_prepare(priv->dmatsk); else bcom_ata_tx_prepare(priv->dmatsk); for_each_sg(qc->sg, sg, qc->n_elem, si) { dma_addr_t cur_addr = sg_dma_address(sg); u32 cur_len = sg_dma_len(sg); while (cur_len) { unsigned int tc = min(cur_len, MAX_DMA_BUFFER_SIZE); bd = (struct bcom_ata_bd *) bcom_prepare_next_buffer(priv->dmatsk); if (read) { bd->status = tc; bd->src_pa = (__force u32) priv->ata_regs_pa + offsetof(struct mpc52xx_ata, fifo_data); bd->dst_pa = (__force u32) cur_addr; } else { bd->status = tc; bd->src_pa = (__force u32) cur_addr; bd->dst_pa = (__force u32) priv->ata_regs_pa + offsetof(struct mpc52xx_ata, fifo_data); } bcom_submit_next_buffer(priv->dmatsk, NULL); cur_addr += tc; cur_len -= tc; count++; if (count > MAX_DMA_BUFFERS) { dev_alert(ap->dev, "dma table" "too small\n"); goto use_pio_instead; } } } return 1; use_pio_instead: bcom_ata_reset_bd(priv->dmatsk); return 0; } static void mpc52xx_bmdma_setup(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct mpc52xx_ata_priv *priv = ap->host->private_data; struct mpc52xx_ata __iomem *regs = priv->ata_regs; unsigned int read = !(qc->tf.flags & ATA_TFLAG_WRITE); u8 dma_mode; if (!mpc52xx_ata_build_dmatable(qc)) dev_alert(ap->dev, "%s: %i, return 1?\n", __func__, __LINE__); /* Check FIFO is OK... */ if (in_8(&priv->ata_regs->fifo_status) & MPC52xx_ATA_FIFOSTAT_ERROR) dev_alert(ap->dev, "%s: FIFO error detected: 0x%02x!\n", __func__, in_8(&priv->ata_regs->fifo_status)); if (read) { dma_mode = MPC52xx_ATA_DMAMODE_IE | MPC52xx_ATA_DMAMODE_READ | MPC52xx_ATA_DMAMODE_FE; /* Setup FIFO if direction changed */ if (priv->mpc52xx_ata_dma_last_write != 0) { priv->mpc52xx_ata_dma_last_write = 0; /* Configure FIFO with granularity to 7 */ out_8(&regs->fifo_control, 7); out_be16(&regs->fifo_alarm, 128); /* Set FIFO Reset bit (FR) */ out_8(&regs->dma_mode, MPC52xx_ATA_DMAMODE_FR); } } else { dma_mode = MPC52xx_ATA_DMAMODE_IE | MPC52xx_ATA_DMAMODE_WRITE; /* Setup FIFO if direction changed */ if (priv->mpc52xx_ata_dma_last_write != 1) { priv->mpc52xx_ata_dma_last_write = 1; /* Configure FIFO with granularity to 4 */ out_8(&regs->fifo_control, 4); out_be16(&regs->fifo_alarm, 128); } } if (priv->timings[qc->dev->devno].using_udma) dma_mode |= MPC52xx_ATA_DMAMODE_UDMA; out_8(&regs->dma_mode, dma_mode); priv->waiting_for_dma = ATA_DMA_ACTIVE; ata_wait_idle(ap); ap->ops->sff_exec_command(ap, &qc->tf); } static void mpc52xx_bmdma_start(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct mpc52xx_ata_priv *priv = ap->host->private_data; bcom_set_task_auto_start(priv->dmatsk->tasknum, priv->dmatsk->tasknum); bcom_enable(priv->dmatsk); } static void mpc52xx_bmdma_stop(struct ata_queued_cmd *qc) { struct ata_port *ap = qc->ap; struct mpc52xx_ata_priv *priv = ap->host->private_data; bcom_disable(priv->dmatsk); bcom_ata_reset_bd(priv->dmatsk); priv->waiting_for_dma = 0; /* Check FIFO is OK... */ if (in_8(&priv->ata_regs->fifo_status) & MPC52xx_ATA_FIFOSTAT_ERROR) dev_alert(ap->dev, "%s: FIFO error detected: 0x%02x!\n", __func__, in_8(&priv->ata_regs->fifo_status)); } static u8 mpc52xx_bmdma_status(struct ata_port *ap) { struct mpc52xx_ata_priv *priv = ap->host->private_data; /* Check FIFO is OK... */ if (in_8(&priv->ata_regs->fifo_status) & MPC52xx_ATA_FIFOSTAT_ERROR) { dev_alert(ap->dev, "%s: FIFO error detected: 0x%02x!\n", __func__, in_8(&priv->ata_regs->fifo_status)); return priv->waiting_for_dma | ATA_DMA_ERR; } return priv->waiting_for_dma; } static irqreturn_t mpc52xx_ata_task_irq(int irq, void *vpriv) { struct mpc52xx_ata_priv *priv = vpriv; while (bcom_buffer_done(priv->dmatsk)) bcom_retrieve_buffer(priv->dmatsk, NULL, NULL); priv->waiting_for_dma |= ATA_DMA_INTR; return IRQ_HANDLED; } static struct scsi_host_template mpc52xx_ata_sht = { ATA_PIO_SHT(DRV_NAME), }; static struct ata_port_operations mpc52xx_ata_port_ops = { .inherits = &ata_bmdma_port_ops, .sff_dev_select = mpc52xx_ata_dev_select, .set_piomode = mpc52xx_ata_set_piomode, .set_dmamode = mpc52xx_ata_set_dmamode, .bmdma_setup = mpc52xx_bmdma_setup, .bmdma_start = mpc52xx_bmdma_start, .bmdma_stop = mpc52xx_bmdma_stop, .bmdma_status = mpc52xx_bmdma_status, .qc_prep = ata_noop_qc_prep, }; static int mpc52xx_ata_init_one(struct device *dev, struct mpc52xx_ata_priv *priv, unsigned long raw_ata_regs, int mwdma_mask, int udma_mask) { struct ata_host *host; struct ata_port *ap; struct ata_ioports *aio; host = ata_host_alloc(dev, 1); if (!host) return -ENOMEM; ap = host->ports[0]; ap->flags |= ATA_FLAG_SLAVE_POSS; ap->pio_mask = ATA_PIO4; ap->mwdma_mask = mwdma_mask; ap->udma_mask = udma_mask; ap->ops = &mpc52xx_ata_port_ops; host->private_data = priv; aio = &ap->ioaddr; aio->cmd_addr = NULL; /* Don't have a classic reg block */ aio->altstatus_addr = &priv->ata_regs->tf_control; aio->ctl_addr = &priv->ata_regs->tf_control; aio->data_addr = &priv->ata_regs->tf_data; aio->error_addr = &priv->ata_regs->tf_features; aio->feature_addr = &priv->ata_regs->tf_features; aio->nsect_addr = &priv->ata_regs->tf_sec_count; aio->lbal_addr = &priv->ata_regs->tf_sec_num; aio->lbam_addr = &priv->ata_regs->tf_cyl_low; aio->lbah_addr = &priv->ata_regs->tf_cyl_high; aio->device_addr = &priv->ata_regs->tf_dev_head; aio->status_addr = &priv->ata_regs->tf_command; aio->command_addr = &priv->ata_regs->tf_command; ata_port_desc(ap, "ata_regs 0x%lx", raw_ata_regs); /* activate host */ return ata_host_activate(host, priv->ata_irq, ata_bmdma_interrupt, 0, &mpc52xx_ata_sht); } /* ======================================================================== */ /* OF Platform driver */ /* ======================================================================== */ static int mpc52xx_ata_probe(struct platform_device *op) { unsigned int ipb_freq; struct resource res_mem; int ata_irq = 0; struct mpc52xx_ata __iomem *ata_regs; struct mpc52xx_ata_priv *priv = NULL; int rv, task_irq; int mwdma_mask = 0, udma_mask = 0; const __be32 *prop; int proplen; struct bcom_task *dmatsk; /* Get ipb frequency */ ipb_freq = mpc5xxx_get_bus_frequency(op->dev.of_node); if (!ipb_freq) { dev_err(&op->dev, "could not determine IPB bus frequency\n"); return -ENODEV; } /* Get device base address from device tree, request the region * and ioremap it. */ rv = of_address_to_resource(op->dev.of_node, 0, &res_mem); if (rv) { dev_err(&op->dev, "could not determine device base address\n"); return rv; } if (!devm_request_mem_region(&op->dev, res_mem.start, sizeof(*ata_regs), DRV_NAME)) { dev_err(&op->dev, "error requesting register region\n"); return -EBUSY; } ata_regs = devm_ioremap(&op->dev, res_mem.start, sizeof(*ata_regs)); if (!ata_regs) { dev_err(&op->dev, "error mapping device registers\n"); return -ENOMEM; } /* * By default, all DMA modes are disabled for the MPC5200. Some * boards don't have the required signals routed to make DMA work. * Also, the MPC5200B has a silicon bug that causes data corruption * with UDMA if it is used at the same time as the LocalPlus bus. * * Instead of trying to guess what modes are usable, check the * ATA device tree node to find out what DMA modes work on the board. * UDMA/MWDMA modes can also be forced by adding "libata.force=<mode>" * to the kernel boot parameters. * * The MPC5200 ATA controller supports MWDMA modes 0, 1 and 2 and * UDMA modes 0, 1 and 2. */ prop = of_get_property(op->dev.of_node, "mwdma-mode", &proplen); if ((prop) && (proplen >= 4)) mwdma_mask = ATA_MWDMA2 & ((1 << (*prop + 1)) - 1); prop = of_get_property(op->dev.of_node, "udma-mode", &proplen); if ((prop) && (proplen >= 4)) udma_mask = ATA_UDMA2 & ((1 << (*prop + 1)) - 1); ata_irq = irq_of_parse_and_map(op->dev.of_node, 0); if (ata_irq == NO_IRQ) { dev_err(&op->dev, "error mapping irq\n"); return -EINVAL; } /* Prepare our private structure */ priv = devm_kzalloc(&op->dev, sizeof(*priv), GFP_KERNEL); if (!priv) { rv = -ENOMEM; goto err1; } priv->ipb_period = 1000000000 / (ipb_freq / 1000); priv->ata_regs = ata_regs; priv->ata_regs_pa = res_mem.start; priv->ata_irq = ata_irq; priv->csel = -1; priv->mpc52xx_ata_dma_last_write = -1; if (ipb_freq/1000000 == 66) { priv->mdmaspec = mdmaspec66; priv->udmaspec = udmaspec66; } else { priv->mdmaspec = mdmaspec132; priv->udmaspec = udmaspec132; } /* Allocate a BestComm task for DMA */ dmatsk = bcom_ata_init(MAX_DMA_BUFFERS, MAX_DMA_BUFFER_SIZE); if (!dmatsk) { dev_err(&op->dev, "bestcomm initialization failed\n"); rv = -ENOMEM; goto err1; } task_irq = bcom_get_task_irq(dmatsk); rv = devm_request_irq(&op->dev, task_irq, &mpc52xx_ata_task_irq, 0, "ATA task", priv); if (rv) { dev_err(&op->dev, "error requesting DMA IRQ\n"); goto err2; } priv->dmatsk = dmatsk; /* Init the hw */ rv = mpc52xx_ata_hw_init(priv); if (rv) { dev_err(&op->dev, "error initializing hardware\n"); goto err2; } /* Register ourselves to libata */ rv = mpc52xx_ata_init_one(&op->dev, priv, res_mem.start, mwdma_mask, udma_mask); if (rv) { dev_err(&op->dev, "error registering with ATA layer\n"); goto err2; } return 0; err2: irq_dispose_mapping(task_irq); bcom_ata_release(dmatsk); err1: irq_dispose_mapping(ata_irq); return rv; } static int mpc52xx_ata_remove(struct platform_device *op) { struct ata_host *host = platform_get_drvdata(op); struct mpc52xx_ata_priv *priv = host->private_data; int task_irq; /* Deregister the ATA interface */ ata_platform_remove_one(op); /* Clean up DMA */ task_irq = bcom_get_task_irq(priv->dmatsk); irq_dispose_mapping(task_irq); bcom_ata_release(priv->dmatsk); irq_dispose_mapping(priv->ata_irq); return 0; } #ifdef CONFIG_PM_SLEEP static int mpc52xx_ata_suspend(struct platform_device *op, pm_message_t state) { struct ata_host *host = platform_get_drvdata(op); ata_host_suspend(host, state); return 0; } static int mpc52xx_ata_resume(struct platform_device *op) { struct ata_host *host = platform_get_drvdata(op); struct mpc52xx_ata_priv *priv = host->private_data; int rv; rv = mpc52xx_ata_hw_init(priv); if (rv) { dev_err(host->dev, "error initializing hardware\n"); return rv; } ata_host_resume(host); return 0; } #endif static const struct of_device_id mpc52xx_ata_of_match[] = { { .compatible = "fsl,mpc5200-ata", }, { .compatible = "mpc5200-ata", }, { /* sentinel */ } }; static struct platform_driver mpc52xx_ata_of_platform_driver = { .probe = mpc52xx_ata_probe, .remove = mpc52xx_ata_remove, #ifdef CONFIG_PM_SLEEP .suspend = mpc52xx_ata_suspend, .resume = mpc52xx_ata_resume, #endif .driver = { .name = DRV_NAME, .of_match_table = mpc52xx_ata_of_match, }, }; module_platform_driver(mpc52xx_ata_of_platform_driver); MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_DESCRIPTION("Freescale MPC52xx IDE/ATA libata driver"); MODULE_LICENSE("GPL"); MODULE_DEVICE_TABLE(of, mpc52xx_ata_of_match);
BadenLab/2Panalysis
.ipynb_checkpoints/Suite2me-checkpoint.py
<reponame>BadenLab/2Panalysis # -*- coding: utf-8 -*- """ Created on Fri Feb 4 14:34:52 2022 Credits to: https://www.github.com/MouseLand/suite2p/blob/main/jupyter/run_suite2p_colab_2021.ipynb @author: SimenLab """ import os import numpy as np import pathlib import tifffile import suite2p import shutil import warnings import time import Import_Igor """Currently hard-coded...""" import options # import matplotlib.pyplot as plt # import sys # import matplotlib as mpl # import utilities # import options_BC_testing """ TODO Need to crop the imaging file to the trigger channel already during the Import_Igor phase... Maybe the class I wrote earler would be useful for this. """ def gen_ops(ops, db): output_ops = suite2p.run_s2p(ops=ops, db=db) # Run the actual algo... print("Initiating suite2p.run_s2p") # print(len(output_ops)) output_ops_file = np.load(pathlib.Path(output_ops['save_path']).joinpath( 'ops.npy'), allow_pickle=True).item() if output_ops_file.keys() != output_ops.keys(): raise ValueError( "Keys in output_ops_file is different from keys in output_ops") return output_ops # , output_ops_file def extract_singleplane(input_folder, output_folder, crop, **kwargs): """ Script for running Suite2p analysis on .tiffs with a single plane. E.g., every frame is from the same plane. The .tiffs are processed in sequence. Parameters ---------- input_folder: Str or pathlib.Path object Folder from which Igor .smh's/.smp's are taken. save_dir (depricated): Str or pathlib.Path object Directory where outputs from Suite2p are stored. output_folder: Path where algorithm should output to. crop: Int Takes a single intiger and assumes it as squared (i.e. 256 (x 256), 512 (x 512), etc.) ops_path: Path-like Path of options file to use. Returns ------- None. """ # Define some handy inner functions ## Checks paths and returns True/False conditionally def probe_path(path, look_for): check_here = pathlib.Path(path) content = check_here.rglob(f'*/{look_for}') for i in content: if look_for in i.parts: target_content_present = True break else: target_content_present = False return target_content_present ## Algorithmically generate .tiffs and .npy (image and trigger) from Igor ## binaries, then save them in target folder. def gen_tiffs_from_igor(directory): img_count = 0 for file in directory.iterdir(): if file.suffix == ".smp": img_count += 1 file = pathlib.Path(file).resolve() img = Import_Igor.get_stack(file) img_name = file.stem img_arr, trigger_arr = Import_Igor.get_ch_arrays(img, crop) trigger_trace = Import_Igor.trigger_trace(trigger_arr) # Algorithmically get the trigger trace out of trigger channel # save_folder = pathlib.Path(r".\Data\data_output\{}".format(img_name)) # Bit more elegant than above tiff_path = output_folder.joinpath( img_name).with_suffix(".tiff") trig_path = output_folder.joinpath( img_name).with_suffix(".npy") tifffile.imsave(tiff_path, img_arr) np.save(trig_path, trigger_trace) del img, img_name, img_arr, trigger_arr, file if img_count == 1: raise TypeError("No Igor .smh or .smp files were identified!") def copy_preexisting_tiffs(): print("Identified .tiff files: Copying to output directory.") tiff_paths = list(pathlib.Path(input_folder).glob('*.tiff')) trig_paths = list(pathlib.Path(input_folder).glob('*.npy')) ### Copy over tiff files for input_file in tiff_paths: shutil.copy2(input_file, output_folder.joinpath(input_file.name)) ### Copy over npy files for input_file in trig_paths: shutil.copy2(input_file, output_folder.joinpath(input_file.name)) ## Run through target folder and clean it up (establishing a file hierarchy) def prep_file_hierarchy(directory): tiff_paths = [] trig_paths = [] directory = pathlib.Path(directory) path_of_tiffs = sorted(directory.glob('*.tiff')) path_of_trigs = sorted(directory.glob('*.npy')) if len(path_of_trigs) == 0: warnings.warn("No trigger channel detected. No .npy file generated.") for tiff in path_of_tiffs: ### Step 3.1: Make folder with tiff filename new_single_plane_folder = directory.joinpath( tiff.stem) if new_single_plane_folder.exists() == False: new_single_plane_folder.mkdir() ### Step 3.2: Move tiff file into folder tiff_new_location = pathlib.Path(shutil.move( tiff, new_single_plane_folder)) current_tiff_name = tiff_new_location.stem tiff_paths.append(current_tiff_name) else: for tiff, trig in zip(path_of_tiffs, path_of_trigs): ### Step 3.1: Make folder with tiff filename new_single_plane_folder = directory.joinpath( tiff.stem) if new_single_plane_folder.exists() == False: new_single_plane_folder.mkdir() ### Step 3.2: Move tiff file into folder tiff_new_location = pathlib.Path(shutil.move( tiff, new_single_plane_folder)) current_tiff_name = tiff_new_location.stem tiff_paths.append(current_tiff_name) ### Step 3.3: Move .npy file (trigger trace) into folder trig = pathlib.Path(trig) ### Step 3.2: Move trig file into folder trig_new_location = pathlib.Path(shutil.move( trig, new_single_plane_folder)).with_suffix(".npy") current_trig_name = trig_new_location.stem trig_paths.append(current_trig_name) ### Optional: Rename files to add channel number # current_tiff_final_location = tiff_new_location.rename( # tiff_new_location.with_stem( # f"{current_tiff_name}_ch1").with_suffix(".tiff")) # tiff_paths.append(current_tiff_final_location) # current_tiff_final_location = tiff_new_location.rename( # tiff_new_location.with_stem( # f"{current_trig_name}_ch2").with_suffix(".npy")) # tiff_paths.append(current_tiff_final_location) path_of_tiffs = sorted(directory.rglob('*.tiff')) path_of_trigs = sorted(directory.rglob('*.npy')) return path_of_tiffs, path_of_trigs ## Run Suite2p on each .tiff file in the file hieararchy def tiff_f_extract(path_of_tiffs): tiff_num = len(path_of_tiffs) print(f"Indexed {tiff_num} .tiff files. Running Suite2P API sequentially.") for tiff in path_of_tiffs: ### Point Suite2p to the right folder for analysis # needs to be a dictionary with a list of path(s) tiff_loc = pathlib.Path(tiff).parent db = {'data_path': [str(tiff_loc)], } """Select ops file (this should not be hard-coded)...""" ops = options.ops # ops = options_BC_testing.ops # ops = np.load(ops_path, allow_pickle=True) # Step 4: Run Suite2p on this newly created folder with corresponding tiff file output_ops = gen_ops(ops, db) # ops = suite2p.registration.metrics.get_pc_metrics(output_ops) # output_ops = gen_ops(ops, db) # ops = suite2p.get_pc_metrics(ops) def select_data_extraction_type(output_folder): for file in sorted(input_folder.rglob('*')): if file.suffix == "tiff" or ".tiff": copy_preexisting_tiffs() break if file.suffix == "igor" or ".smh" or ".smp": gen_tiffs_from_igor(input_folder) break else: raise TypeError("Filetype not specified. Please select with filetype = ...") ## Check if folder already exists input_folder = pathlib.Path(input_folder) # save_dir = pathlib.Path(save_dir).resolve() output_folder = pathlib.Path(output_folder) # final_destination = save_dir.joinpath(output_folder) print("Directory info") print("- Save location:", output_folder) print("- Currently exists?", output_folder.exists()) try: # Ideally... ## Simply make the directory: os.mkdir(output_folder.resolve()) print(f"Target directory succesfully created: {output_folder}") print("Running data extraction algorithms.") ## Fill directory with data: select_data_extraction_type(output_folder) ## Organise the file hieararchy tiff_paths, trig_paths = prep_file_hierarchy(output_folder) ## Run Suite2P on organised .tiff files tiff_f_extract(tiff_paths) except FileExistsError: print("Cannot create a directory when it already exists:", output_folder) ## Contingencies for handling pre-existing files if output_folder.exists() is True: any_check = any(output_folder.rglob('*')) suite2p_check = any(output_folder.rglob("suite2p")) print("Checking pre-existing content") print("- Content in directory?", any_check) print("- Pre-existing Suite2p?", suite2p_check) ## If directory already exists but is empty, fill it with data if any_check is False and suite2p_check is False: print("Target directory is empty, running data extraction algorithms.") ## Fill directory with data: select_data_extraction_type(output_folder) ## Organise the file hieararchy tiff_paths, trig_paths = prep_file_hierarchy(output_folder) ## Run Suite2P on organised .tiff files tiff_f_extract(tiff_paths) ## If Suite2P folders detected, abort to avoid overwriting previous analyses if suite2p_check is True: print(output_folder) raise Warning("Suite2p-related content identified. Exiting.") ## If .tiff files are present, index them elif any_check is True: pre_existing_tiffs = sorted(output_folder.rglob('*.tiff')) print(".tiff file(s) already exist here. Skipping conversion.") ## Organise the file hieararchy tiff_paths, trig_paths = prep_file_hierarchy(output_folder) time.sleep(2) ## Run Suite2P on organised .tiff files tiff_f_extract(tiff_paths) else: raise Warning("Unknown error when handling files.") print(f"Pipeline executed. Resulting files in {output_folder}")
russelyang/jmockit1
samples/TimingFramework/test/org/jdesktop/animation/timing/interpolation/DiscreteInterpolatorTest.java
<gh_stars>0 /* * Copyright (c) 2006-2011 <NAME> * This file is subject to the terms of the MIT license (see LICENSE.txt). */ package org.jdesktop.animation.timing.interpolation; import org.junit.*; import static org.junit.Assert.*; public final class DiscreteInterpolatorTest { @Test public void testInterpolate() { Interpolator interp = DiscreteInterpolator.getInstance(); assertEquals(0.0f, interp.interpolate(0.0f), 0.0f); //noinspection MagicNumber assertEquals(0.0f, interp.interpolate(0.2f), 0.0f); assertEquals(1.0f, interp.interpolate(1.0f), 0.0f); } }
todorkrastev/softuni-software-engineering
Spring/C01_SpringData/L01_DatabaseAppsIntroduction/Exercises/Solutions/SecondOption/src/main/java/Controllers/ExerciseController.java
<filename>Spring/C01_SpringData/L01_DatabaseAppsIntroduction/Exercises/Solutions/SecondOption/src/main/java/Controllers/ExerciseController.java package Controllers; import Exercises.*; import Include.ExercisesImp; import java.sql.Connection; import java.util.LinkedHashMap; import java.util.Map; import static Include.CoreMessages.*; import static Include.ExercisesMessages.*; public class ExerciseController { private Map<Integer,String> exerciseNames; private Map<Integer, ExercisesImp> exercisesPathes; private Connection connection; public ExerciseController(Connection connection){ exerciseNames = new LinkedHashMap<>(); exercisesPathes = new LinkedHashMap<>(); this.connection = connection; inputValues(); } public void infoText(){ System.out.print(RULES); this.getExerciseNames().forEach((key, value) -> System.out.printf(INFO_TEXT, key, value)); System.out.println();} public ExercisesImp getExercise (int pick){ return exercisesPathes.get(pick); } public String getExerciseName(int pick){ return exerciseNames.get(pick); } public Map<Integer, String> getExerciseNames() { return exerciseNames; } private void inputValues(){ exerciseNames.put(1,EXERCISE1); exerciseNames.put(2,EXERCISE2); exerciseNames.put(3,EXERCISE3); exerciseNames.put(4,EXERCISE4); exerciseNames.put(5,EXERCISE5); exerciseNames.put(6,EXERCISE6); exerciseNames.put(7,EXERCISE7); exerciseNames.put(8,EXERCISE8); exerciseNames.put(9,EXERCISE9); exercisesPathes.put(1, new Exercise1()); exercisesPathes.put(2, new Exercise2()); exercisesPathes.put(3, new Exercise3()); exercisesPathes.put(4, new Exercise4()); exercisesPathes.put(5, new Exercise5()); exercisesPathes.put(6, new Exercise6()); exercisesPathes.put(7, new Exercise7()); exercisesPathes.put(8, new Exercise8()); exercisesPathes.put(9, new Exercise9()); } }
Mu-L/jemalloc
test/unit/decay.c
#include "test/jemalloc_test.h" #include "jemalloc/internal/decay.h" TEST_BEGIN(test_decay_init) { decay_t decay; memset(&decay, 0, sizeof(decay)); nstime_t curtime; nstime_init(&curtime, 0); ssize_t decay_ms = 1000; assert_true(decay_ms_valid(decay_ms), ""); expect_false(decay_init(&decay, &curtime, decay_ms), "Failed to initialize decay"); expect_zd_eq(decay_ms_read(&decay), decay_ms, "Decay_ms was initialized incorrectly"); expect_u64_ne(decay_epoch_duration_ns(&decay), 0, "Epoch duration was initialized incorrectly"); } TEST_END TEST_BEGIN(test_decay_ms_valid) { expect_false(decay_ms_valid(-7), "Misclassified negative decay as valid"); expect_true(decay_ms_valid(-1), "Misclassified -1 (never decay) as invalid decay"); expect_true(decay_ms_valid(8943), "Misclassified valid decay"); if (SSIZE_MAX > NSTIME_SEC_MAX) { expect_false( decay_ms_valid((ssize_t)(NSTIME_SEC_MAX * KQU(1000) + 39)), "Misclassified too large decay"); } } TEST_END TEST_BEGIN(test_decay_npages_purge_in) { decay_t decay; memset(&decay, 0, sizeof(decay)); nstime_t curtime; nstime_init(&curtime, 0); uint64_t decay_ms = 1000; nstime_t decay_nstime; nstime_init(&decay_nstime, decay_ms * 1000 * 1000); expect_false(decay_init(&decay, &curtime, (ssize_t)decay_ms), "Failed to initialize decay"); size_t new_pages = 100; nstime_t time; nstime_copy(&time, &decay_nstime); expect_u64_eq(decay_npages_purge_in(&decay, &time, new_pages), new_pages, "Not all pages are expected to decay in decay_ms"); nstime_init(&time, 0); expect_u64_eq(decay_npages_purge_in(&decay, &time, new_pages), 0, "More than zero pages are expected to instantly decay"); nstime_copy(&time, &decay_nstime); nstime_idivide(&time, 2); expect_u64_eq(decay_npages_purge_in(&decay, &time, new_pages), new_pages / 2, "Not half of pages decay in half the decay period"); } TEST_END TEST_BEGIN(test_decay_maybe_advance_epoch) { decay_t decay; memset(&decay, 0, sizeof(decay)); nstime_t curtime; nstime_init(&curtime, 0); uint64_t decay_ms = 1000; bool err = decay_init(&decay, &curtime, (ssize_t)decay_ms); expect_false(err, ""); bool advanced; advanced = decay_maybe_advance_epoch(&decay, &curtime, 0); expect_false(advanced, "Epoch advanced while time didn't"); nstime_t interval; nstime_init(&interval, decay_epoch_duration_ns(&decay)); nstime_add(&curtime, &interval); advanced = decay_maybe_advance_epoch(&decay, &curtime, 0); expect_false(advanced, "Epoch advanced after first interval"); nstime_add(&curtime, &interval); advanced = decay_maybe_advance_epoch(&decay, &curtime, 0); expect_true(advanced, "Epoch didn't advance after two intervals"); } TEST_END TEST_BEGIN(test_decay_empty) { /* If we never have any decaying pages, npages_limit should be 0. */ decay_t decay; memset(&decay, 0, sizeof(decay)); nstime_t curtime; nstime_init(&curtime, 0); uint64_t decay_ms = 1000; uint64_t decay_ns = decay_ms * 1000 * 1000; bool err = decay_init(&decay, &curtime, (ssize_t)decay_ms); assert_false(err, ""); uint64_t time_between_calls = decay_epoch_duration_ns(&decay) / 5; int nepochs = 0; for (uint64_t i = 0; i < decay_ns / time_between_calls * 10; i++) { size_t dirty_pages = 0; nstime_init(&curtime, i * time_between_calls); bool epoch_advanced = decay_maybe_advance_epoch(&decay, &curtime, dirty_pages); if (epoch_advanced) { nepochs++; expect_zu_eq(decay_npages_limit_get(&decay), 0, "Unexpectedly increased npages_limit"); } } expect_d_gt(nepochs, 0, "Epochs never advanced"); } TEST_END /* * Verify that npages_limit correctly decays as the time goes. * * During first 'nepoch_init' epochs, add new dirty pages. * After that, let them decay and verify npages_limit decreases. * Then proceed with another 'nepoch_init' epochs and check that * all dirty pages are flushed out of backlog, bringing npages_limit * down to zero. */ TEST_BEGIN(test_decay) { const uint64_t nepoch_init = 10; decay_t decay; memset(&decay, 0, sizeof(decay)); nstime_t curtime; nstime_init(&curtime, 0); uint64_t decay_ms = 1000; uint64_t decay_ns = decay_ms * 1000 * 1000; bool err = decay_init(&decay, &curtime, (ssize_t)decay_ms); assert_false(err, ""); expect_zu_eq(decay_npages_limit_get(&decay), 0, "Empty decay returned nonzero npages_limit"); nstime_t epochtime; nstime_init(&epochtime, decay_epoch_duration_ns(&decay)); const size_t dirty_pages_per_epoch = 1000; size_t dirty_pages = 0; uint64_t epoch_ns = decay_epoch_duration_ns(&decay); bool epoch_advanced = false; /* Populate backlog with some dirty pages */ for (uint64_t i = 0; i < nepoch_init; i++) { nstime_add(&curtime, &epochtime); dirty_pages += dirty_pages_per_epoch; epoch_advanced |= decay_maybe_advance_epoch(&decay, &curtime, dirty_pages); } expect_true(epoch_advanced, "Epoch never advanced"); size_t npages_limit = decay_npages_limit_get(&decay); expect_zu_gt(npages_limit, 0, "npages_limit is incorrectly equal " "to zero after dirty pages have been added"); /* Keep dirty pages unchanged and verify that npages_limit decreases */ for (uint64_t i = nepoch_init; i * epoch_ns < decay_ns; ++i) { nstime_add(&curtime, &epochtime); epoch_advanced = decay_maybe_advance_epoch(&decay, &curtime, dirty_pages); if (epoch_advanced) { size_t npages_limit_new = decay_npages_limit_get(&decay); expect_zu_lt(npages_limit_new, npages_limit, "napges_limit failed to decay"); npages_limit = npages_limit_new; } } expect_zu_gt(npages_limit, 0, "npages_limit decayed to zero earlier " "than decay_ms since last dirty page was added"); /* Completely push all dirty pages out of the backlog */ epoch_advanced = false; for (uint64_t i = 0; i < nepoch_init; i++) { nstime_add(&curtime, &epochtime); epoch_advanced |= decay_maybe_advance_epoch(&decay, &curtime, dirty_pages); } expect_true(epoch_advanced, "Epoch never advanced"); npages_limit = decay_npages_limit_get(&decay); expect_zu_eq(npages_limit, 0, "npages_limit didn't decay to 0 after " "decay_ms since last bump in dirty pages"); } TEST_END TEST_BEGIN(test_decay_ns_until_purge) { const uint64_t nepoch_init = 10; decay_t decay; memset(&decay, 0, sizeof(decay)); nstime_t curtime; nstime_init(&curtime, 0); uint64_t decay_ms = 1000; uint64_t decay_ns = decay_ms * 1000 * 1000; bool err = decay_init(&decay, &curtime, (ssize_t)decay_ms); assert_false(err, ""); nstime_t epochtime; nstime_init(&epochtime, decay_epoch_duration_ns(&decay)); uint64_t ns_until_purge_empty = decay_ns_until_purge(&decay, 0, 0); expect_u64_eq(ns_until_purge_empty, DECAY_UNBOUNDED_TIME_TO_PURGE, "Failed to return unbounded wait time for zero threshold"); const size_t dirty_pages_per_epoch = 1000; size_t dirty_pages = 0; bool epoch_advanced = false; for (uint64_t i = 0; i < nepoch_init; i++) { nstime_add(&curtime, &epochtime); dirty_pages += dirty_pages_per_epoch; epoch_advanced |= decay_maybe_advance_epoch(&decay, &curtime, dirty_pages); } expect_true(epoch_advanced, "Epoch never advanced"); uint64_t ns_until_purge_all = decay_ns_until_purge(&decay, dirty_pages, dirty_pages); expect_u64_ge(ns_until_purge_all, decay_ns, "Incorrectly calculated time to purge all pages"); uint64_t ns_until_purge_none = decay_ns_until_purge(&decay, dirty_pages, 0); expect_u64_eq(ns_until_purge_none, decay_epoch_duration_ns(&decay) * 2, "Incorrectly calculated time to purge 0 pages"); uint64_t npages_threshold = dirty_pages / 2; uint64_t ns_until_purge_half = decay_ns_until_purge(&decay, dirty_pages, npages_threshold); nstime_t waittime; nstime_init(&waittime, ns_until_purge_half); nstime_add(&curtime, &waittime); decay_maybe_advance_epoch(&decay, &curtime, dirty_pages); size_t npages_limit = decay_npages_limit_get(&decay); expect_zu_lt(npages_limit, dirty_pages, "npages_limit failed to decrease after waiting"); size_t expected = dirty_pages - npages_limit; int deviation = abs((int)expected - (int)(npages_threshold)); expect_d_lt(deviation, (int)(npages_threshold / 2), "After waiting, number of pages is out of the expected interval " "[0.5 * npages_threshold .. 1.5 * npages_threshold]"); } TEST_END int main(void) { return test( test_decay_init, test_decay_ms_valid, test_decay_npages_purge_in, test_decay_maybe_advance_epoch, test_decay_empty, test_decay, test_decay_ns_until_purge); }
seanyen/Azure-Kinect-Sensor-SDK
src/dynlib/dynlib_linux.c
<filename>src/dynlib/dynlib_linux.c // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #define _GNU_SOURCE // ldaddr() extention in dlfcn.h // This library #include <k4ainternal/dynlib.h> // Dependent libraries #include <k4ainternal/logging.h> // System dependencies #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <dlfcn.h> #define TOSTRING(x) STRINGIFY(x) typedef struct _dynlib_context_t { void *handle; } dynlib_context_t; K4A_DECLARE_CONTEXT(dynlib_t, dynlib_context_t); static char *generate_file_name(const char *name, uint32_t version) { const char *lib_prefix = "lib"; const char *lib_suffix = "so"; // Format of the depth engine name is: libdepthengine.so.<K4A_PLUGIN_VERSION>.0 // libdepthengine.so.2.0 size_t max_buffer_size = strlen(name) + strlen(TOSTRING(DYNLIB_MAX_VERSION)) + strlen(".0") + strlen(".") + strlen(".") + strlen(lib_suffix) + strlen(lib_prefix) + 1; char *versioned_file_name = malloc(max_buffer_size); if (versioned_file_name == NULL) { LOG_ERROR("malloc failed with size %llu", max_buffer_size); return NULL; } versioned_file_name[0] = '\0'; // NOTE: 0 is appended to the name for legacy reasons, a time when the depth engine plugin version was tracked with // major and minor versions snprintf(versioned_file_name, max_buffer_size, "%s%s.%s.%u.0", lib_prefix, name, lib_suffix, version); return versioned_file_name; } k4a_result_t dynlib_create(const char *name, uint32_t version, dynlib_t *dynlib_handle) { // Note: A nullptr is allowed on linux systems for "name", however, this is // functionality we do not support RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, name == NULL); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, dynlib_handle == NULL); if (version > DYNLIB_MAX_VERSION) { LOG_ERROR("Failed to load dynamic library %s. version %u is too large to load. Max is %u\n", name, version, DYNLIB_MAX_VERSION); return K4A_RESULT_FAILED; } char *versioned_name = generate_file_name(name, version); if (versioned_name == NULL) { return K4A_RESULT_FAILED; } dynlib_context_t *dynlib = dynlib_t_create(dynlib_handle); k4a_result_t result = K4A_RESULT_FROM_BOOL(dynlib != NULL); if (K4A_SUCCEEDED(result)) { dynlib->handle = dlopen(versioned_name, RTLD_NOW); result = (dynlib->handle != NULL) ? K4A_RESULT_SUCCEEDED : K4A_RESULT_FAILED; if (K4A_FAILED(result)) { LOG_ERROR("Failed to load shared object %s with error: %s", versioned_name, dlerror()); } } if (versioned_name) { free(versioned_name); } if (K4A_FAILED(result)) { dynlib_t_destroy(*dynlib_handle); *dynlib_handle = NULL; } return result; } k4a_result_t dynlib_find_symbol(dynlib_t dynlib_handle, const char *symbol, void **address) { RETURN_VALUE_IF_HANDLE_INVALID(K4A_RESULT_FAILED, dynlib_t, dynlib_handle); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, symbol == NULL); RETURN_VALUE_IF_ARG(K4A_RESULT_FAILED, address == NULL); k4a_result_t result = K4A_RESULT_SUCCEEDED; dynlib_context_t *dynlib = dynlib_t_get_context(dynlib_handle); void *ptr = dlsym(dynlib->handle, symbol); result = K4A_RESULT_FROM_BOOL(ptr != NULL); if (K4A_SUCCEEDED(result)) { *address = ptr; } else { LOG_ERROR("Failed to find symbol %s in dynamic library. Error: ", symbol, dlerror()); } if (K4A_SUCCEEDED(result)) { Dl_info info; if (dladdr(*address, &info) != 0) { LOG_INFO("Depth Engine loaded %s", info.dli_fname); } else { LOG_ERROR("Failed calling dladdr %x", dlerror()); } } return result; } void dynlib_destroy(dynlib_t dynlib_handle) { RETURN_VALUE_IF_HANDLE_INVALID(VOID_VALUE, dynlib_t, dynlib_handle); dynlib_context_t *dynlib = dynlib_t_get_context(dynlib_handle); dlclose(dynlib->handle); dynlib_t_destroy(dynlib_handle); dynlib = NULL; }
mohamed-saad/competitive-prog
daily-challenge/src/main/java/competitive/leetcode/easy/string/ReverseString.java
package competitive.leetcode.easy.string; public class ReverseString { public void reverseString(char[] s) { int mid = s.length/2; int last = s.length-1; for (int i=0; i<mid; i++) { char temp = s[i]; s[i] = s[last-i]; s[last-i] = temp; } } }
tuty/Eloquent-JavaScript-Exercises
chapter04-DataStructures/deepComparison/index.js
<filename>chapter04-DataStructures/deepComparison/index.js /** * Deep comparison The == operator compares objects by identity. But sometimes, you would prefer to compare the values of their actual properties. Write a function, deepEqual, that takes two values and returns true only if they are the same value or are objects with the same properties whose values are also equal when compared with a recursive call to deepEqual. To find out whether to compare two things by identity (use the === operator for that) or by looking at their properties, you can use the typeof operator. If it produces "object" for both values, you should do a deep comparison. But you have to take one silly exception into account: by a historical accident, typeof null also produces "object". */ (function () { var obj = {here: {is: "an"}, object: 2}; console.log(deepEqual(obj, obj)); // → true console.log(deepEqual(obj, {here: 1, object: 2})); // → false console.log(deepEqual(obj, {here: {is: "an"}, object: 2})); // → true function deepEqual(obj1, obj2) { if(Object.keys(obj1).length !== Object.keys(obj2).length) { return false; } for(var prop in obj1) { if(typeof (obj1[prop]) !== 'object') { if(obj2.hasOwnProperty(prop) == false || typeof (obj2[prop]) === 'object' || obj1[prop] !== obj2[prop]) { return false; } } else if (typeof (obj1[prop]) === 'object'){ if(obj2.hasOwnProperty(prop) === false || typeof (obj2[prop]) !== 'object') { return false; } if(!deepEqual(obj1[prop], obj2[prop])) { return false; }; } } return true; } })();
CruGlobal/campus-contacts-web
app/assets/javascripts/angular/components/transferModal/transferModal.component.js
<gh_stars>0 import template from './transferModal.html'; import './transferModal.scss'; angular.module('campusContactsApp').component('transferModal', { controller: transferModalController, template: template, bindings: { resolve: '<', close: '&', dismiss: '&', }, }); function transferModalController( $scope, JsonApiDataStore, transferService, organizationService, RequestDeduper, ) { var vm = this; vm.search = ''; vm.searching = false; vm.searchOptions = []; vm.selectedOrg = null; vm.selectOrg = selectOrg; vm.options = { copyContact: false, copyAnswers: false, copyInteractions: false, }; vm.save = save; vm.cancel = cancel; vm.$onInit = activate; function activate() { vm.selection = vm.resolve.selection; vm.sourceOrg = JsonApiDataStore.store.find( 'organization', vm.selection.orgId, ); var requestDeduper = new RequestDeduper(); // Refresh the org list whenever the search term changes $scope.$watch('$ctrl.search', function (search) { // Unselect the org because it may not be shown anymore vm.selectedOrg = null; if (search === '') { // Ignore empty searches vm.searchOptions = []; return; } vm.searching = true; organizationService .searchOrgs(vm.sourceOrg, search, requestDeduper) .then(function (orgs) { // Filter out people that are already selected vm.searchOptions = orgs; }) .finally(function () { vm.searching = false; }); }); } function selectOrg(org) { vm.selectedOrg = org; } function save() { vm.saving = true; transferService .transfer( vm.selection, vm.selectedOrg, vm.options, vm.resolve.surveyId, ) .then(function () { vm.close({ $value: vm.options.copyContact }); }) .catch(function () { vm.saving = false; }); } function cancel() { vm.dismiss(); } }
Swainstha/DMS_React
src/store/actions/auth.js
// import axios from 'axios'; import * as axios from '../../response/falseFetch'; import * as actionTypes from './actionTypes'; export const authStart = () => { return { type: actionTypes.AUTH_START }; }; export const authSuccess = (token, userId) => { return { type: actionTypes.AUTH_SUCCESS, token: token, userId: userId }; }; export const authFail = (error) => { return { type: actionTypes.AUTH_FAIL, error: error }; }; export const authenticate = (token, expiryTime) => { return dispatch => { // dispatch({ type: actionTypes.AUTHENTICATE, token: token }); dispatch(checkAuthTimeout(expiryTime)); } } export const logout = () => { localStorage.removeItem('token'); localStorage.removeItem('expirationDate'); localStorage.removeItem('userId'); return { type: actionTypes.AUTH_LOGOUT }; }; export const checkAuthTimeout = (expirationTime, refreshToken) => { // console.log("CheckoutTime", expirationTime); return dispatch => { const refresh_token = refreshToken; setTimeout(() => { // dispatch(logout()); dispatch(sendRefreshToken(refresh_token)); }, (expirationTime) * 1000); }; }; const sendRefreshToken = (refreshToken) => { return dispatch => { // let url = 'https://securetoken.googleapis.com/v1/token?key=AIzaSyDL3N1A50XmBEQGRPrAN2zCudp9mpIe28I'; let url = './auth.js'; const data = { grant_type: "refresh_token", refresh_token: refreshToken } axios.post(url, data) .then(response => { response = response.authResponse; const expirationDate = new Date(new Date().getTime() + response.data.expires_in * 1000); localStorage.setItem('token', response.data.id_token); localStorage.setItem('expirationDate', expirationDate); localStorage.setItem('userId', response.data.user_id); localStorage.setItem('refreshToken', response.data.refresh_token); dispatch(authSuccess(response.data.id_token, response.data.user_id)); dispatch(checkAuthTimeout(response.data.expires_in, response.data.refresh_token)); }); } } export const auth = (email, password) => { return dispatch => { dispatch(authStart()); const authData = { email: email, password: password, returnSecureToken: true }; // let url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=AIzaSyDL3N1A50XmBEQGRPrAN2zCudp9mpIe28I'; const url = './auth.js'; axios.post(url, authData) .then(response => { response = response.authResponse; const expirationDate = new Date(new Date().getTime() + response.data.expiresIn * 1000); // console.log(new Date().getTime()); // console.log(response.data.expiresIn, expirationDate, expirationDate.getTime() - new Date().getTime()); localStorage.setItem('token', response.data.idToken); localStorage.setItem('expirationDate', expirationDate); localStorage.setItem('userId', response.data.localId); localStorage.setItem('refreshToken', response.data.refreshToken); dispatch(authSuccess(response.data.idToken, response.data.localId)); dispatch(checkAuthTimeout(response.data.expiresIn, response.data.refreshToken)); }) .catch(err => { // console.log(err); dispatch(authFail(err)); }); }; }; export const setAuthRedirectPath = (path) => { return { type: actionTypes.SET_AUTH_REDIRECT_PATH, path: path }; }; export const authCheckState = () => { console.log("authCheckState"); return dispatch => { const token = localStorage.getItem('token'); if (!token) { dispatch(logout()); } else { const expirationDate = new Date(localStorage.getItem('expirationDate')); if (expirationDate <= new Date()) { dispatch(logout()); } else { const userId = localStorage.getItem('userId'); dispatch(authSuccess(token, userId)); dispatch(checkAuthTimeout((expirationDate.getTime() - new Date().getTime()) / 1000)); } } }; }; export const resetPassword = (email) => { console.log(email); return dispatch => { const data = { requestType: "PASSWORD_RESET", email: email }; const url = 'https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=AIzaSyDL3N1A50XmBEQGRPrAN2zCudp9mpIe28I'; axios.post(url, data) .then(response => { console.log(response); }).catch(err => { console.log("Something error"); }); dispatch(sendResetPassword()); } } export const sendResetPassword = () => { return { type: actionTypes.RESET_PASSWORD } }
tristanseifert/Avocado
Avocado/Image Processing/TSBufferOwningBitmapRep.h
// // TSBufferOwningBitmapRep.h // Avocado // // Created by <NAME> on 20160516. // Copyright © 2016 <NAME>. All rights reserved. // #import <Cocoa/Cocoa.h> @interface TSBufferOwningBitmapRep : NSBitmapImageRep /** * Frees all pointers that this image representation is associated with; * any subsequent accesses to the data will cause a crash. */ - (void) TSFreeBuffers; @end
PureSolTechnologies/DuctileDB
engine.test/src/test/java/com/puresoltechnologies/ductiledb/engine/NamespaceCreateAndReopenIT.java
package com.puresoltechnologies.ductiledb.engine; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import org.junit.Test; import com.puresoltechnologies.ductiledb.bigtable.BigTableConfiguration; import com.puresoltechnologies.ductiledb.logstore.LogStructuredStoreTestUtils; import com.puresoltechnologies.ductiledb.storage.api.StorageFactory; import com.puresoltechnologies.ductiledb.storage.spi.Storage; import com.puresoltechnologies.ductiledb.storage.spi.StorageConfiguration; public class NamespaceCreateAndReopenIT { @Test public void testCreationAndReopen() throws IOException { StorageConfiguration configuration = LogStructuredStoreTestUtils.createStorageConfiguration(); Storage storage = StorageFactory.getStorageInstance(configuration); File directory = new File("/" + NamespaceCreateAndReopenIT.class.getSimpleName() + ".testCreationAndReopen"); if (storage.exists(directory)) { storage.removeDirectory(directory, true); } NamespaceDescriptor namespaceDescriptor = new NamespaceDescriptor(directory); try (Namespace namespace = Namespace.create(storage, namespaceDescriptor, new BigTableConfiguration())) { namespace.addTable("table", "description"); } try (Namespace namespace = Namespace.reopen(storage, directory)) { assertTrue(namespace.hasTable("table")); } } @Test public void testCreationAndReopenMultipleTables() throws IOException { StorageConfiguration configuration = LogStructuredStoreTestUtils.createStorageConfiguration(); Storage storage = StorageFactory.getStorageInstance(configuration); File directory = new File("/" + NamespaceCreateAndReopenIT.class.getSimpleName() + ".testCreationAndReopenMultipleColumnFamilies"); if (storage.exists(directory)) { storage.removeDirectory(directory, true); } NamespaceDescriptor namespaceDescriptor = new NamespaceDescriptor(directory); try (Namespace namespace = Namespace.create(storage, namespaceDescriptor, new BigTableConfiguration())) { namespace.addTable("table", "description"); namespace.addTable("table2", "description2"); namespace.addTable("table3", "description3"); } try (Namespace namespace = Namespace.reopen(storage, directory)) { assertTrue(namespace.hasTable("table")); } } @Test(expected = IOException.class) public void testDoubleCreationNotAllowed() throws IOException { StorageConfiguration configuration = LogStructuredStoreTestUtils.createStorageConfiguration(); Storage storage = StorageFactory.getStorageInstance(configuration); File directory = new File( "/" + NamespaceCreateAndReopenIT.class.getSimpleName() + ".testDoubleCreationNotAllowed"); if (storage.exists(directory)) { storage.removeDirectory(directory, true); } NamespaceDescriptor namespaceDescriptor = new NamespaceDescriptor(directory); try (Namespace namespace = Namespace.create(storage, namespaceDescriptor, new BigTableConfiguration())) { namespace.addTable("table", "description"); } try (Namespace namespace = Namespace.create(storage, namespaceDescriptor, new BigTableConfiguration())) { fail("Should not work."); } } }
LearnJavaByus/eureka
eureka-core/src/main/java/com/netflix/eureka/util/batcher/TrafficShaper.java
/* * Copyright 2015 Netflix, 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. */ package com.netflix.eureka.util.batcher; import com.netflix.eureka.util.batcher.TaskProcessor.ProcessingResult; /** * {@link TrafficShaper} provides admission control policy prior to dispatching tasks to workers. * It reacts to events coming via reprocess requests (transient failures, congestion), and delays the processing * depending on this feedback. * * @author <NAME> */ class TrafficShaper { /** * Upper bound on delay provided by configuration. */ private static final long MAX_DELAY = 30 * 1000; private final long congestionRetryDelayMs; private final long networkFailureRetryMs; private volatile long lastCongestionError; private volatile long lastNetworkFailure; TrafficShaper(long congestionRetryDelayMs, long networkFailureRetryMs) { this.congestionRetryDelayMs = Math.min(MAX_DELAY, congestionRetryDelayMs); this.networkFailureRetryMs = Math.min(MAX_DELAY, networkFailureRetryMs); } void registerFailure(ProcessingResult processingResult) { if (processingResult == ProcessingResult.Congestion) { lastCongestionError = System.currentTimeMillis(); } else if (processingResult == ProcessingResult.TransientError) { lastNetworkFailure = System.currentTimeMillis(); } } long transmissionDelay() { if (lastCongestionError == -1 && lastNetworkFailure == -1) { return 0; } long now = System.currentTimeMillis(); if (lastCongestionError != -1) { long congestionDelay = now - lastCongestionError; if (congestionDelay >= 0 && congestionDelay < congestionRetryDelayMs) { return congestionRetryDelayMs - congestionDelay; } lastCongestionError = -1; } if (lastNetworkFailure != -1) { long failureDelay = now - lastNetworkFailure; if (failureDelay >= 0 && failureDelay < networkFailureRetryMs) { return networkFailureRetryMs - failureDelay; } lastNetworkFailure = -1; } return 0; } }
operativeF/Kvasir
Lib/Chip/Unknown/STMicro/STM32F21x/DMA2.hpp
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //DMA controller namespace Dma2Lisr{ ///<low interrupt status register using Addr = Register::Address<0x40026400,0xf082f082,0x00000000,std::uint32_t>; ///Stream x transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> tcif3{}; ///Stream x half transfer interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> htif3{}; ///Stream x transfer error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> teif3{}; ///Stream x direct mode error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> dmeif3{}; ///Stream x FIFO error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> feif3{}; ///Stream x transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> tcif2{}; ///Stream x half transfer interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> htif2{}; ///Stream x transfer error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> teif2{}; ///Stream x direct mode error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dmeif2{}; ///Stream x FIFO error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> feif2{}; ///Stream x transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> tcif1{}; ///Stream x half transfer interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> htif1{}; ///Stream x transfer error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> teif1{}; ///Stream x direct mode error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> dmeif1{}; ///Stream x FIFO error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> feif1{}; ///Stream x transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> tcif0{}; ///Stream x half transfer interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> htif0{}; ///Stream x transfer error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> teif0{}; ///Stream x direct mode error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmeif0{}; ///Stream x FIFO error interrupt flag (x=3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> feif0{}; } namespace Dma2Hisr{ ///<high interrupt status register using Addr = Register::Address<0x40026404,0xf082f082,0x00000000,std::uint32_t>; ///Stream x transfer complete interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> tcif7{}; ///Stream x half transfer interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> htif7{}; ///Stream x transfer error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> teif7{}; ///Stream x direct mode error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> dmeif7{}; ///Stream x FIFO error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> feif7{}; ///Stream x transfer complete interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> tcif6{}; ///Stream x half transfer interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> htif6{}; ///Stream x transfer error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> teif6{}; ///Stream x direct mode error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dmeif6{}; ///Stream x FIFO error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> feif6{}; ///Stream x transfer complete interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> tcif5{}; ///Stream x half transfer interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> htif5{}; ///Stream x transfer error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> teif5{}; ///Stream x direct mode error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> dmeif5{}; ///Stream x FIFO error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> feif5{}; ///Stream x transfer complete interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> tcif4{}; ///Stream x half transfer interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> htif4{}; ///Stream x transfer error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> teif4{}; ///Stream x direct mode error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmeif4{}; ///Stream x FIFO error interrupt flag (x=7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> feif4{}; } namespace Dma2Lifcr{ ///<low interrupt flag clear register using Addr = Register::Address<0x40026408,0xf082f082,0x00000000,std::uint32_t>; ///Stream x clear transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> ctcif3{}; ///Stream x clear half transfer interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> chtif3{}; ///Stream x clear transfer error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> cteif3{}; ///Stream x clear direct mode error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> cdmeif3{}; ///Stream x clear FIFO error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> cfeif3{}; ///Stream x clear transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> ctcif2{}; ///Stream x clear half transfer interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> chtif2{}; ///Stream x clear transfer error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> cteif2{}; ///Stream x clear direct mode error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> cdmeif2{}; ///Stream x clear FIFO error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> cfeif2{}; ///Stream x clear transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> ctcif1{}; ///Stream x clear half transfer interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> chtif1{}; ///Stream x clear transfer error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> cteif1{}; ///Stream x clear direct mode error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> cdmeif1{}; ///Stream x clear FIFO error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> cfeif1{}; ///Stream x clear transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> ctcif0{}; ///Stream x clear half transfer interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> chtif0{}; ///Stream x clear transfer error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> cteif0{}; ///Stream x clear direct mode error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> cdmeif0{}; ///Stream x clear FIFO error interrupt flag (x = 3..0) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> cfeif0{}; } namespace Dma2Hifcr{ ///<high interrupt flag clear register using Addr = Register::Address<0x4002640c,0xf082f082,0x00000000,std::uint32_t>; ///Stream x clear transfer complete interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> ctcif7{}; ///Stream x clear half transfer interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> chtif7{}; ///Stream x clear transfer error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> cteif7{}; ///Stream x clear direct mode error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> cdmeif7{}; ///Stream x clear FIFO error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> cfeif7{}; ///Stream x clear transfer complete interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> ctcif6{}; ///Stream x clear half transfer interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> chtif6{}; ///Stream x clear transfer error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> cteif6{}; ///Stream x clear direct mode error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> cdmeif6{}; ///Stream x clear FIFO error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> cfeif6{}; ///Stream x clear transfer complete interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> ctcif5{}; ///Stream x clear half transfer interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> chtif5{}; ///Stream x clear transfer error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> cteif5{}; ///Stream x clear direct mode error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> cdmeif5{}; ///Stream x clear FIFO error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> cfeif5{}; ///Stream x clear transfer complete interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> ctcif4{}; ///Stream x clear half transfer interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> chtif4{}; ///Stream x clear transfer error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> cteif4{}; ///Stream x clear direct mode error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> cdmeif4{}; ///Stream x clear FIFO error interrupt flag (x = 7..4) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> cfeif4{}; } namespace Dma2S0cr{ ///<stream x configuration register using Addr = Register::Address<0x40026410,0xf0100000,0x00000000,std::uint32_t>; ///Channel selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,25),Register::ReadWriteAccess,unsigned> chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,23),Register::ReadWriteAccess,unsigned> mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> pburst{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> ct{}; ///Double buffer mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dbm{}; ///Priority level constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> pincos{}; ///Memory data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,13),Register::ReadWriteAccess,unsigned> msize{}; ///Peripheral data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::ReadWriteAccess,unsigned> psize{}; ///Memory increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> minc{}; ///Peripheral increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> pinc{}; ///Circular mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> circ{}; ///Data transfer direction constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> dir{}; ///Peripheral flow controller constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> en{}; } namespace Dma2S0ndtr{ ///<stream x number of data register using Addr = Register::Address<0x40026414,0xffff0000,0x00000000,std::uint32_t>; ///Number of data items to transfer constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ndt{}; } namespace Dma2S0par{ ///<stream x peripheral address register using Addr = Register::Address<0x40026418,0x00000000,0x00000000,std::uint32_t>; ///Peripheral address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pa{}; } namespace Dma2S0m0ar{ ///<stream x memory 0 address register using Addr = Register::Address<0x4002641c,0x00000000,0x00000000,std::uint32_t>; ///Memory 0 address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m0a{}; } namespace Dma2S0m1ar{ ///<stream x memory 1 address register using Addr = Register::Address<0x40026420,0x00000000,0x00000000,std::uint32_t>; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m1a{}; } namespace Dma2S0fcr{ ///<stream x FIFO control register using Addr = Register::Address<0x40026424,0xffffff40,0x00000000,std::uint32_t>; ///FIFO error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> feie{}; ///FIFO status constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> fth{}; } namespace Dma2S1cr{ ///<stream x configuration register using Addr = Register::Address<0x40026428,0xf0100000,0x00000000,std::uint32_t>; ///Channel selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,25),Register::ReadWriteAccess,unsigned> chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,23),Register::ReadWriteAccess,unsigned> mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> pburst{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> ct{}; ///Double buffer mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dbm{}; ///Priority level constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> pincos{}; ///Memory data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,13),Register::ReadWriteAccess,unsigned> msize{}; ///Peripheral data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::ReadWriteAccess,unsigned> psize{}; ///Memory increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> minc{}; ///Peripheral increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> pinc{}; ///Circular mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> circ{}; ///Data transfer direction constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> dir{}; ///Peripheral flow controller constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> en{}; } namespace Dma2S1ndtr{ ///<stream x number of data register using Addr = Register::Address<0x4002642c,0xffff0000,0x00000000,std::uint32_t>; ///Number of data items to transfer constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ndt{}; } namespace Dma2S1par{ ///<stream x peripheral address register using Addr = Register::Address<0x40026430,0x00000000,0x00000000,std::uint32_t>; ///Peripheral address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pa{}; } namespace Dma2S1m0ar{ ///<stream x memory 0 address register using Addr = Register::Address<0x40026434,0x00000000,0x00000000,std::uint32_t>; ///Memory 0 address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m0a{}; } namespace Dma2S1m1ar{ ///<stream x memory 1 address register using Addr = Register::Address<0x40026438,0x00000000,0x00000000,std::uint32_t>; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m1a{}; } namespace Dma2S1fcr{ ///<stream x FIFO control register using Addr = Register::Address<0x4002643c,0xffffff40,0x00000000,std::uint32_t>; ///FIFO error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> feie{}; ///FIFO status constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> fth{}; } namespace Dma2S2cr{ ///<stream x configuration register using Addr = Register::Address<0x40026440,0xf0100000,0x00000000,std::uint32_t>; ///Channel selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,25),Register::ReadWriteAccess,unsigned> chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,23),Register::ReadWriteAccess,unsigned> mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> pburst{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> ct{}; ///Double buffer mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dbm{}; ///Priority level constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> pincos{}; ///Memory data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,13),Register::ReadWriteAccess,unsigned> msize{}; ///Peripheral data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::ReadWriteAccess,unsigned> psize{}; ///Memory increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> minc{}; ///Peripheral increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> pinc{}; ///Circular mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> circ{}; ///Data transfer direction constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> dir{}; ///Peripheral flow controller constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> en{}; } namespace Dma2S2ndtr{ ///<stream x number of data register using Addr = Register::Address<0x40026444,0xffff0000,0x00000000,std::uint32_t>; ///Number of data items to transfer constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ndt{}; } namespace Dma2S2par{ ///<stream x peripheral address register using Addr = Register::Address<0x40026448,0x00000000,0x00000000,std::uint32_t>; ///Peripheral address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pa{}; } namespace Dma2S2m0ar{ ///<stream x memory 0 address register using Addr = Register::Address<0x4002644c,0x00000000,0x00000000,std::uint32_t>; ///Memory 0 address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m0a{}; } namespace Dma2S2m1ar{ ///<stream x memory 1 address register using Addr = Register::Address<0x40026450,0x00000000,0x00000000,std::uint32_t>; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m1a{}; } namespace Dma2S2fcr{ ///<stream x FIFO control register using Addr = Register::Address<0x40026454,0xffffff40,0x00000000,std::uint32_t>; ///FIFO error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> feie{}; ///FIFO status constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> fth{}; } namespace Dma2S3cr{ ///<stream x configuration register using Addr = Register::Address<0x40026458,0xf0100000,0x00000000,std::uint32_t>; ///Channel selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,25),Register::ReadWriteAccess,unsigned> chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,23),Register::ReadWriteAccess,unsigned> mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> pburst{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> ct{}; ///Double buffer mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dbm{}; ///Priority level constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> pincos{}; ///Memory data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,13),Register::ReadWriteAccess,unsigned> msize{}; ///Peripheral data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::ReadWriteAccess,unsigned> psize{}; ///Memory increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> minc{}; ///Peripheral increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> pinc{}; ///Circular mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> circ{}; ///Data transfer direction constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> dir{}; ///Peripheral flow controller constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> en{}; } namespace Dma2S3ndtr{ ///<stream x number of data register using Addr = Register::Address<0x4002645c,0xffff0000,0x00000000,std::uint32_t>; ///Number of data items to transfer constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ndt{}; } namespace Dma2S3par{ ///<stream x peripheral address register using Addr = Register::Address<0x40026460,0x00000000,0x00000000,std::uint32_t>; ///Peripheral address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pa{}; } namespace Dma2S3m0ar{ ///<stream x memory 0 address register using Addr = Register::Address<0x40026464,0x00000000,0x00000000,std::uint32_t>; ///Memory 0 address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m0a{}; } namespace Dma2S3m1ar{ ///<stream x memory 1 address register using Addr = Register::Address<0x40026468,0x00000000,0x00000000,std::uint32_t>; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m1a{}; } namespace Dma2S3fcr{ ///<stream x FIFO control register using Addr = Register::Address<0x4002646c,0xffffff40,0x00000000,std::uint32_t>; ///FIFO error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> feie{}; ///FIFO status constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> fth{}; } namespace Dma2S4cr{ ///<stream x configuration register using Addr = Register::Address<0x40026470,0xf0100000,0x00000000,std::uint32_t>; ///Channel selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,25),Register::ReadWriteAccess,unsigned> chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,23),Register::ReadWriteAccess,unsigned> mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> pburst{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> ct{}; ///Double buffer mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dbm{}; ///Priority level constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> pincos{}; ///Memory data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,13),Register::ReadWriteAccess,unsigned> msize{}; ///Peripheral data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::ReadWriteAccess,unsigned> psize{}; ///Memory increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> minc{}; ///Peripheral increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> pinc{}; ///Circular mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> circ{}; ///Data transfer direction constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> dir{}; ///Peripheral flow controller constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> en{}; } namespace Dma2S4ndtr{ ///<stream x number of data register using Addr = Register::Address<0x40026474,0xffff0000,0x00000000,std::uint32_t>; ///Number of data items to transfer constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ndt{}; } namespace Dma2S4par{ ///<stream x peripheral address register using Addr = Register::Address<0x40026478,0x00000000,0x00000000,std::uint32_t>; ///Peripheral address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pa{}; } namespace Dma2S4m0ar{ ///<stream x memory 0 address register using Addr = Register::Address<0x4002647c,0x00000000,0x00000000,std::uint32_t>; ///Memory 0 address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m0a{}; } namespace Dma2S4m1ar{ ///<stream x memory 1 address register using Addr = Register::Address<0x40026480,0x00000000,0x00000000,std::uint32_t>; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m1a{}; } namespace Dma2S4fcr{ ///<stream x FIFO control register using Addr = Register::Address<0x40026484,0xffffff40,0x00000000,std::uint32_t>; ///FIFO error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> feie{}; ///FIFO status constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> fth{}; } namespace Dma2S5cr{ ///<stream x configuration register using Addr = Register::Address<0x40026488,0xf0100000,0x00000000,std::uint32_t>; ///Channel selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,25),Register::ReadWriteAccess,unsigned> chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,23),Register::ReadWriteAccess,unsigned> mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> pburst{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> ct{}; ///Double buffer mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dbm{}; ///Priority level constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> pincos{}; ///Memory data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,13),Register::ReadWriteAccess,unsigned> msize{}; ///Peripheral data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::ReadWriteAccess,unsigned> psize{}; ///Memory increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> minc{}; ///Peripheral increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> pinc{}; ///Circular mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> circ{}; ///Data transfer direction constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> dir{}; ///Peripheral flow controller constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> en{}; } namespace Dma2S5ndtr{ ///<stream x number of data register using Addr = Register::Address<0x4002648c,0xffff0000,0x00000000,std::uint32_t>; ///Number of data items to transfer constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ndt{}; } namespace Dma2S5par{ ///<stream x peripheral address register using Addr = Register::Address<0x40026490,0x00000000,0x00000000,std::uint32_t>; ///Peripheral address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pa{}; } namespace Dma2S5m0ar{ ///<stream x memory 0 address register using Addr = Register::Address<0x40026494,0x00000000,0x00000000,std::uint32_t>; ///Memory 0 address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m0a{}; } namespace Dma2S5m1ar{ ///<stream x memory 1 address register using Addr = Register::Address<0x40026498,0x00000000,0x00000000,std::uint32_t>; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m1a{}; } namespace Dma2S5fcr{ ///<stream x FIFO control register using Addr = Register::Address<0x4002649c,0xffffff40,0x00000000,std::uint32_t>; ///FIFO error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> feie{}; ///FIFO status constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> fth{}; } namespace Dma2S6cr{ ///<stream x configuration register using Addr = Register::Address<0x400264a0,0xf0100000,0x00000000,std::uint32_t>; ///Channel selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,25),Register::ReadWriteAccess,unsigned> chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,23),Register::ReadWriteAccess,unsigned> mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> pburst{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> ct{}; ///Double buffer mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dbm{}; ///Priority level constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> pincos{}; ///Memory data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,13),Register::ReadWriteAccess,unsigned> msize{}; ///Peripheral data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::ReadWriteAccess,unsigned> psize{}; ///Memory increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> minc{}; ///Peripheral increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> pinc{}; ///Circular mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> circ{}; ///Data transfer direction constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> dir{}; ///Peripheral flow controller constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> en{}; } namespace Dma2S6ndtr{ ///<stream x number of data register using Addr = Register::Address<0x400264a4,0xffff0000,0x00000000,std::uint32_t>; ///Number of data items to transfer constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ndt{}; } namespace Dma2S6par{ ///<stream x peripheral address register using Addr = Register::Address<0x400264a8,0x00000000,0x00000000,std::uint32_t>; ///Peripheral address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pa{}; } namespace Dma2S6m0ar{ ///<stream x memory 0 address register using Addr = Register::Address<0x400264ac,0x00000000,0x00000000,std::uint32_t>; ///Memory 0 address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m0a{}; } namespace Dma2S6m1ar{ ///<stream x memory 1 address register using Addr = Register::Address<0x400264b0,0x00000000,0x00000000,std::uint32_t>; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m1a{}; } namespace Dma2S6fcr{ ///<stream x FIFO control register using Addr = Register::Address<0x400264b4,0xffffff40,0x00000000,std::uint32_t>; ///FIFO error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> feie{}; ///FIFO status constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> fth{}; } namespace Dma2S7cr{ ///<stream x configuration register using Addr = Register::Address<0x400264b8,0xf0100000,0x00000000,std::uint32_t>; ///Channel selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,25),Register::ReadWriteAccess,unsigned> chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,23),Register::ReadWriteAccess,unsigned> mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,21),Register::ReadWriteAccess,unsigned> pburst{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> ct{}; ///Double buffer mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> dbm{}; ///Priority level constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> pincos{}; ///Memory data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,13),Register::ReadWriteAccess,unsigned> msize{}; ///Peripheral data size constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,11),Register::ReadWriteAccess,unsigned> psize{}; ///Memory increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> minc{}; ///Peripheral increment mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> pinc{}; ///Circular mode constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> circ{}; ///Data transfer direction constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> dir{}; ///Peripheral flow controller constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> en{}; } namespace Dma2S7ndtr{ ///<stream x number of data register using Addr = Register::Address<0x400264bc,0xffff0000,0x00000000,std::uint32_t>; ///Number of data items to transfer constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> ndt{}; } namespace Dma2S7par{ ///<stream x peripheral address register using Addr = Register::Address<0x400264c0,0x00000000,0x00000000,std::uint32_t>; ///Peripheral address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pa{}; } namespace Dma2S7m0ar{ ///<stream x memory 0 address register using Addr = Register::Address<0x400264c4,0x00000000,0x00000000,std::uint32_t>; ///Memory 0 address constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m0a{}; } namespace Dma2S7m1ar{ ///<stream x memory 1 address register using Addr = Register::Address<0x400264c8,0x00000000,0x00000000,std::uint32_t>; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> m1a{}; } namespace Dma2S7fcr{ ///<stream x FIFO control register using Addr = Register::Address<0x400264cc,0xffffff40,0x00000000,std::uint32_t>; ///FIFO error interrupt enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> feie{}; ///FIFO status constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,3),Register::Access<Register::AccessType::readOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> fth{}; } }
ModifcationStations/StationLoader
station-renderer-api-v0/src/main/java/net/modificationstation/stationapi/api/client/texture/StationTextureManager.java
<filename>station-renderer-api-v0/src/main/java/net/modificationstation/stationapi/api/client/texture/StationTextureManager.java package net.modificationstation.stationapi.api.client.texture; import net.minecraft.client.texture.TextureManager; import net.modificationstation.stationapi.api.registry.Identifier; import net.modificationstation.stationapi.impl.client.render.StationTextureManagerImpl; import java.util.Set; public interface StationTextureManager { AbstractTexture getTexture(Identifier id); Identifier registerDynamicTexture(String prefix, NativeImageBackedTexture texture); static StationTextureManager get(TextureManager textureManager) { return StationTextureManagerImpl.get(textureManager); } void registerTexture(Identifier identifier, AbstractTexture texture); void bindTexture(Identifier id); Set<TextureTickListener> getTickListeners(); }