repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
williamlin0504/free5gcWithOCF
lib/pfcp/pfcpType/MACAddressesRemoved.go
package pfcpType type MACAddressesRemoved struct { MACAddressesRemoveddata []byte }
MaximilianKorn/opencast
modules/authorization-manager/src/main/java/org/opencastproject/authorization/xacml/manager/util/Util.java
<reponame>MaximilianKorn/opencast<gh_stars>100-1000 /** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.authorization.xacml.manager.util; import org.opencastproject.authorization.xacml.manager.api.AclService; import org.opencastproject.authorization.xacml.manager.api.ManagedAcl; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.util.data.Function; import org.opencastproject.util.data.Option; /** * General helper functions. */ public final class Util { private Util() { } public static final Function<ManagedAcl, AccessControlList> toAcl = new Function<ManagedAcl, AccessControlList>() { @Override public AccessControlList apply(ManagedAcl managedAcl) { return managedAcl.getAcl(); } }; public static Function<Long, Option<ManagedAcl>> getManagedAcl(final AclService aclService) { return new Function<Long, Option<ManagedAcl>>() { @Override public Option<ManagedAcl> apply(Long aclId) { return aclService.getAcl(aclId); } }; } }
unexpectedpanda/createsend-java
src/com/createsend/models/campaigns/CampaignForCreationFromTemplate.java
<filename>src/com/createsend/models/campaigns/CampaignForCreationFromTemplate.java package com.createsend.models.campaigns; public class CampaignForCreationFromTemplate extends Campaign { public String FromName; public String FromEmail; public String ReplyTo; public String[] ListIDs; public String[] SegmentIDs; public String TemplateID; public TemplateContent TemplateContent; }
TheoVerhelst/Aphelion
include/states/PauseState.hpp
<reponame>TheoVerhelst/Aphelion<filename>include/states/PauseState.hpp #ifndef PAUSESTATE_HPP #define PAUSESTATE_HPP #include <states/AbstractState.hpp> // Forward declarations class SceneSerializer; class PauseState : public AbstractState { public: PauseState(StateStack& stack, const SceneSerializer& serializer); virtual tgui::Widget::Ptr buildGui() override; virtual bool update(sf::Time dt) override; virtual bool handleEvent(const sf::Event& event) override; virtual bool handleContinuousInputs(sf::Time dt) override; private: const SceneSerializer& _serializer; }; #endif // PAUSESTATE_HPP
VickyKoblinski/verdigris
components/analytics/src/UIAnalyticsEvent.js
const { warn } = console; export default class UIAnalyticsEvent { constructor(props) { this.payload = props.payload; this.context = props.context || []; this.handlers = props.handlers || []; this.hasFired = false; } fire = channel => { if (this.hasFired) { warn('Cannot fire events more than one time.'); return; } this.handlers.forEach(handler => handler(this, channel)); this.hasFired = true; }; update = value => { if (this.hasFired) { warn('Cannot update an event after firing'); return this; } this.payload = typeof value === 'function' ? value(this.payload) : { ...this.payload, ...value, }; return this; }; }
Caisin/hope
apps/param/internal/service/novel_pay_config.go
<filename>apps/param/internal/service/novel_pay_config.go package service import ( "context" "github.com/go-kratos/kratos/v2/log" "go.opentelemetry.io/otel" "hope/apps/param/internal/biz" "hope/apps/param/internal/convert" pb "hope/api/param/novelpayconfig/v1" ) type NovelPayConfigService struct { pb.UnimplementedNovelPayConfigServer uc *biz.NovelPayConfigUseCase log *log.Helper } func NewNovelPayConfigService(uc *biz.NovelPayConfigUseCase, logger log.Logger) *NovelPayConfigService { return &NovelPayConfigService{uc: uc, log: log.NewHelper(logger)} } func (s *NovelPayConfigService) GetNovelPayConfigPage(ctx context.Context, req *pb.NovelPayConfigPageReq) (*pb.NovelPayConfigPageReply, error) { tr := otel.Tracer("api") ctx, span := tr.Start(ctx, "GetNovelPayConfigPage") defer span.End() datas, err := s.uc.Page(ctx, req) if err != nil { return nil, err } items := make([]*pb.NovelPayConfigData, 0) for i := range datas { items = append(items, convert.NovelPayConfigData2Reply(datas[i])) } reply := &pb.NovelPayConfigPageReply{ Code: 200, Message: "success", Total: req.Pagin.Total, Items: items, } return reply, nil } func (s *NovelPayConfigService) GetNovelPayConfig(ctx context.Context, req *pb.NovelPayConfigReq) (*pb.NovelPayConfigReply, error) { tr := otel.Tracer("api") ctx, span := tr.Start(ctx, "GetNovelPayConfig") defer span.End() data, err := s.uc.Get(ctx, req) if err != nil { return nil, err } reply := &pb.NovelPayConfigReply{ Code: 200, Message: "success", Result: convert.NovelPayConfigData2Reply(data), } return reply, nil } func (s *NovelPayConfigService) UpdateNovelPayConfig(ctx context.Context, req *pb.NovelPayConfigUpdateReq) (*pb.NovelPayConfigUpdateReply, error) { tr := otel.Tracer("api") ctx, span := tr.Start(ctx, "UpdateNovelPayConfig") defer span.End() data, err := s.uc.Update(ctx, req) if err != nil { return nil, err } reply := &pb.NovelPayConfigUpdateReply{ Code: 200, Message: "success", Result: convert.NovelPayConfigData2Reply(data), } return reply, nil } func (s *NovelPayConfigService) CreateNovelPayConfig(ctx context.Context, req *pb.NovelPayConfigCreateReq) (*pb.NovelPayConfigCreateReply, error) { tr := otel.Tracer("api") ctx, span := tr.Start(ctx, "CreateNovelPayConfig") defer span.End() data, err := s.uc.Create(ctx, req) if err != nil { return nil, err } reply := &pb.NovelPayConfigCreateReply{ Code: 200, Message: "success", Result: convert.NovelPayConfigData2Reply(data), } return reply, err } func (s *NovelPayConfigService) DeleteNovelPayConfig(ctx context.Context, req *pb.NovelPayConfigDeleteReq) (*pb.NovelPayConfigDeleteReply, error) { tr := otel.Tracer("api") ctx, span := tr.Start(ctx, "DeleteNovelPayConfig") defer span.End() err := s.uc.Delete(ctx, req) if err != nil { return nil, err } return &pb.NovelPayConfigDeleteReply{Code: 200, Message: "success", Result: err == nil}, err } func (s *NovelPayConfigService) BatchDeleteNovelPayConfig(ctx context.Context, req *pb.NovelPayConfigBatchDeleteReq) (*pb.NovelPayConfigDeleteReply, error) { tr := otel.Tracer("api") ctx, span := tr.Start(ctx, "BatchDeleteNovelPayConfig") defer span.End() num, err := s.uc.BatchDelete(ctx, req) if err != nil { return nil, err } return &pb.NovelPayConfigDeleteReply{Code: 200, Message: "success", Result: err == nil && num > 0}, err }
TheMarstonConnell/MCLib
src/xyz/marstonconnell/graphics/engine/drawing/AnimatedDrawable.java
package xyz.marstonconnell.graphics.engine.drawing; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map.Entry; import javax.imageio.ImageIO; import javax.swing.Timer; import xyz.marstonconnell.graphics.engine.physics.AnimationState; public class AnimatedDrawable extends Drawable { Timer animationLoop; HashMap<String, AnimationState> states; AnimationState currentState; int currentIndex = 0; boolean isLadder = false; public AnimatedDrawable(int x, int y, int width, int height, double refreshTime, DrawingLayer drawingLayer) { super(x, y, width, height, drawingLayer); states = new HashMap<String, AnimationState>(); createLoop(refreshTime); currentState = new AnimationState(new Image[0], 1, null); } public String getState() { return currentState.getName(); } public void createLoop(double refreshTime) { animationLoop = new Timer((int) (1000 * refreshTime), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { changeTexture(); } }); animationLoop.start(); } protected void changeTexture() { if(currentState.getImages().length > 0) { if(currentIndex >= currentState.getImages().length - 1) { currentIndex = 0; }else { currentIndex ++; } currentImage = currentState.getImages()[currentIndex]; }else { return; } } public void createState(String name, int frames, double refreshTime, Class resourceGrabber) { Image[] state = new Image[frames]; for (int x = 0; x < frames; x++) { // System.out.println(x); InputStream is = resourceGrabber.getResourceAsStream("/" + name + "/" + x + ".png"); try { state[x] = ImageIO.read(is); } catch (IOException e) { e.printStackTrace(); } } states.put(name, new AnimationState(state, refreshTime, name)); } public void setState(String name) { animationLoop.stop(); currentState = states.get(name); currentImage = currentState.getImages()[0]; createLoop(currentState.getRefreshTime()); } public AnimatedDrawable(int x, int y, int size, DrawingLayer drawingLayer, double refreshTime) { this(x, y, size, size, refreshTime, drawingLayer); } public boolean isLadder() { return isLadder; } }
zhangjunfang/eclipse-dir
nsp/src/main/webapp/scripts/lib/fckeditor/editor/_source/classes/fcktoolbarfontformatcombo.js
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright * (C) 2003-2008 <NAME> == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your choice: - * GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License * Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - * Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == * * FCKToolbarPanelButton Class: Handles the Fonts combo selector. */ var FCKToolbarFontFormatCombo = function(tooltip, style) { if (tooltip === false) return; this.CommandName = 'FontFormat'; this.Label = this.GetLabel(); this.Tooltip = tooltip ? tooltip : this.Label; this.Style = style ? style : FCK_TOOLBARITEM_ICONTEXT; this.NormalLabel = 'Normal'; this.PanelWidth = 190; this.DefaultLabel = FCKConfig.DefaultFontFormatLabel || ''; } // Inherit from FCKToolbarSpecialCombo. FCKToolbarFontFormatCombo.prototype = new FCKToolbarStyleCombo(false); FCKToolbarFontFormatCombo.prototype.GetLabel = function() { return FCKLang.FontFormat; } FCKToolbarFontFormatCombo.prototype.GetStyles = function() { var styles = {}; // Get the format names from the language file. var aNames = FCKLang['FontFormats'].split(';'); var oNames = { p : aNames[0], pre : aNames[1], address : aNames[2], h1 : aNames[3], h2 : aNames[4], h3 : aNames[5], h4 : aNames[6], h5 : aNames[7], h6 : aNames[8], div : aNames[9] || (aNames[0] + ' (DIV)') }; // Get the available formats from the configuration file. var elements = FCKConfig.FontFormats.split(';'); for (var i = 0; i < elements.length; i++) { var elementName = elements[i]; var style = FCKStyles.GetStyle('_FCK_' + elementName); if (style) { style.Label = oNames[elementName]; styles['_FCK_' + elementName] = style; } else alert("The FCKConfig.CoreStyles['" + elementName + "'] setting was not found. Please check the fckconfig.js file"); } return styles; } FCKToolbarFontFormatCombo.prototype.RefreshActiveItems = function( targetSpecialCombo) { var startElement = FCK.ToolbarSet.CurrentInstance.Selection .GetBoundaryParentElement(true); if (startElement) { var path = new FCKElementPath(startElement); var blockElement = path.Block; if (blockElement) { for (var i in targetSpecialCombo.Items) { var item = targetSpecialCombo.Items[i]; var style = item.Style; if (style.CheckElementRemovable(blockElement)) { targetSpecialCombo.SetLabel(style.Label); return; } } } } targetSpecialCombo.SetLabel(this.DefaultLabel); } FCKToolbarFontFormatCombo.prototype.StyleCombo_OnBeforeClick = function( targetSpecialCombo) { // Clear the current selection. targetSpecialCombo.DeselectAll(); var startElement = FCK.ToolbarSet.CurrentInstance.Selection .GetBoundaryParentElement(true); if (startElement) { var path = new FCKElementPath(startElement); var blockElement = path.Block; for (var i in targetSpecialCombo.Items) { var item = targetSpecialCombo.Items[i]; var style = item.Style; if (style.CheckElementRemovable(blockElement)) { targetSpecialCombo.SelectItem(item); return; } } } }
esean/stl_voro_fill
sw/3rd_party/VTK-7.1.0/Rendering/Core/Testing/Python/pickCellPoints.py
<gh_stars>1-10 #!/usr/bin/env python import sys import vtk from vtk.test import Testing # Quad pts = vtk.vtkPoints() pts.SetNumberOfPoints(6) coords = [(0,0,0),(2,0,0),(4,0,0),(0,4,0),(2,4,0),(4,4,0)] for i in range(0,6): pts.InsertPoint(i,coords[i]) quads = vtk.vtkCellArray() cellpoints=[(0,1,4,3),(1,2,5,4)] for i in range(0,2): quads.InsertNextCell(4) for j in range(0,4): quads.InsertCellPoint(cellpoints[i][j]) poly = vtk.vtkPolyData() poly.SetPoints(pts) poly.SetPolys(quads) mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(poly) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() ren.AddActor(actor) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(200,200) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renWin.Render() iren.Initialize() pos = [ (1,1), (35,40), (80,40), (120,40), (165,40), (199,160),(165,160),(120,160),(80,160), (35,160) ] pickedCells = [ -1, 0, 0, 1, 1, -1, 1, 1, 0, 0 ] pickedPoints= [ -1, 0, 1, 1, 2, -1, 5, 4, 4, 3 ] cellErrors = 0 pointErrors = 0 cellPicker = vtk.vtkCellPicker() for i in range(0,len(pos)): cellPicker.Pick(pos[i][0],pos[i][1],0,ren) if cellPicker.GetCellId() != pickedCells[i]: print("pos [{0}] : picked cell id={1} expected cell id={2}".format(pos[i],cellPicker.GetCellId(),pickedCells[i])) cellErrors = cellErrors + 1 if cellPicker.GetPointId() != pickedPoints[i]: print("pos [{0}] : picked point id={1} expected point id={2}".format(pos[i],cellPicker.GetPointId(),pickedPoints[i])) pointErrors = pointErrors + 1 if pointErrors or cellErrors: print( "ERROR: Cell picker : {0} cell-id errors, {1} point-id errors".format(cellErrors,pointErrors) ) sys.exit(1)
parthsingh29/imagelab
src/main/java/com/imagelab/App.java
<filename>src/main/java/com/imagelab/App.java package com.imagelab; import com.imagelab.operator.basic.ReadImage; import com.imagelab.util.Constants; import com.imagelab.util.Utilities; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import org.opencv.core.Core; import java.io.IOException; import static com.imagelab.util.Constants.DASHBOARD_HEIGHT; import static com.imagelab.util.Constants.DASHBOARD_WIDTH; /** * JavaFX App main class which creates the scene * for the UI and set the stage. */ public class App extends Application { private static Scene scene; /* * To load openCV libraries */ static { nu.pattern.OpenCV.loadShared(); } /** * To set the root for the created scene. * * @param fxml - the fxml to be set as root. * @throws IOException - errors related to setting the root. */ static void setRoot(String fxml) throws IOException { scene.setRoot(loadFXML(fxml)); } /** * To load parent view from the fxml. * * @param fxml - fxml to be loaded. * @return - loaded fxml. * @throws IOException any errors * occurs between loading the fxml. */ private static Parent loadFXML(String fxml) throws IOException { FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml")); return fxmlLoader.load(); } /** * main method of the application. * * @param args - arguments to run the app. */ public static void main(String[] args) { // stack empty ReadImage readImage = new ReadImage(); generateWelcomeMessage(); launch(); } /** * This method has been used to generate ASCII welcome message * and to make sure openCV configured version is running properly. */ static void generateWelcomeMessage() { System.out.println("\n\n"); Utilities.drawAsciiArt("Image Lab", 230, 20); System.out.println("\n" + Constants.IMAGELAB_VERSION); System.out.println("A project by " + Constants.ORG_INFO); System.out.println("OpenCV configured version " + Core.VERSION); } /** * Method which loads the UI from fxml resource and set the stylesheet. * * @param stage - stage which need to be showed. * @throws IOException - exceptions related loading stage. */ @Override public void start(Stage stage) throws IOException { scene = new Scene(loadFXML("dashboard"), DASHBOARD_WIDTH, DASHBOARD_HEIGHT); scene.getStylesheets().add(getClass() .getResource(Constants.STYLESHEET_PATH).toExternalForm()); stage.setScene(scene); stage.setResizable(false); stage.show(); } }
chenlili-git/2019-10-08
2019-11-26-选项卡/tab.js
class Tab { constructor(that) { this.box = that; this.opts = { btns: ['按钮一', '按钮二', '按钮三'], content: ['1111', '2222', '3333'] } } init(opts) { $.extend(true, this.opts, opts); this.creatBtn(); this.creatDiv(); this.events(); } creatBtn() { console.log(this.opts) this.opts.btns.forEach((item, i) => { this.box.append($(`<button class="${i == 0 ? 'active' : ''}">${item}</button>`)) }); } creatDiv() { this.opts.content.forEach((item, i) => { this.box.append($(`<div class="${i == 0 ? 'show' : ''}">${item}</div>`)) }) } events() { this.btns = this.box.find('button'); this.divs = this.box.find('div'); let that = this; this.btns.click(function () { $(this).addClass('active').siblings('button').removeClass('active'); that.divs.eq($(this).index('button')).addClass('show').siblings('div').removeClass('show'); }); } } class Drag { constructor(that) { this.box = that; this.disX = 0; this.disY = 0; } position() { this.box.css({ position: 'absolute', top: 0, left: 0 }) } mousedown() { let that = this; this.box.mousedown(function (ev) { that.disX = ev.pageX - $(this).offset().left; that.disY = ev.pageY - $(this).offset().top; that.mousemove(); that.mouseup(); return false; }) } mousemove() { let that = this; $(document).mousemove(function (ev) { that.box.css({ top: ev.pageY - that.disY, left: ev.pageX - that.disX }) }); } mouseup() { $(document).mouseup(function(ev){ $(this).off('mousemove'); $(this).off('mouseup'); }) } } $.fn.extend({ tabs:function(opts){ let t=new Tab(this); t.init(opts); return this; }, dialog:function(){ let d=new Drag(this); d.position(); d.mousedown(); } })
PERSISTLab/BatterylessSimulation
se/sics/mspsim/ui/DoubleBarChart.java
/** * Copyright (c) 2007, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file is part of MSPSim. * * $Id$ * * ----------------------------------------------------------------- * * DoubleBarChart * * Authors : <NAME>, <NAME>, <NAME> * Created : April 26 2007 * Updated : $Date$ * $Revision$ */ package se.sics.mspsim.ui; import java.awt.Graphics2D; /** * */ public class DoubleBarChart extends DoubleSerieChart { public DoubleBarChart() { // Do nothing } public DoubleBarChart(String name) { setName(name); } public void drawChart(Graphics2D g, double xfac, double yfac, int width, int height) { double[] data = this.data; if (data != null) { int minWidth = 1; if (xfac > 1) { minWidth = (int) (xfac + 0.9); } for (int i = 0, n = data.length; i < n; i++) { int y = (int) (yfac * data[i]); g.fillRect((int) (xfac * i), height - y, minWidth + 1, y + 1); } } } }
Syncinus/Hbm-s-Nuclear-Tech-GIT
src/main/java/com/hbm/render/model/ModelBoltAction.java
package com.hbm.render.model; import org.lwjgl.opengl.GL11; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; public class ModelBoltAction extends ModelBase { ModelRenderer Barrel1; ModelRenderer Barrel2; ModelRenderer Grip; ModelRenderer BodyFront; ModelRenderer BodyMain; ModelRenderer LeverFront; ModelRenderer LeverBottom; ModelRenderer LeverMid; ModelRenderer Trigger; ModelRenderer GripFront; ModelRenderer GropFrontBottom; ModelRenderer GripBottom; ModelRenderer Bolt; ModelRenderer ChamberFront; ModelRenderer ChamberBack; ModelRenderer BodyBack; ModelRenderer LeverTip; ModelRenderer Lever; ModelRenderer HandleFront; ModelRenderer Pointer; ModelRenderer HandleBottom; ModelRenderer HandleGrip; public ModelBoltAction() { textureWidth = 128; textureHeight = 64; Barrel1 = new ModelRenderer(this, 0, 0); Barrel1.addBox(0F, 0F, 0F, 60, 3, 2); Barrel1.setRotationPoint(-60F, 1.5F, -1F); Barrel1.setTextureSize(64, 32); Barrel1.mirror = true; setRotation(Barrel1, 0F, 0F, 0F); Barrel2 = new ModelRenderer(this, 0, 5); Barrel2.addBox(0F, 0F, 0F, 60, 2, 3); Barrel2.setRotationPoint(-60F, 2F, -1.5F); Barrel2.setTextureSize(64, 32); Barrel2.mirror = true; setRotation(Barrel2, 0F, 0F, 0F); Grip = new ModelRenderer(this, 0, 10); Grip.addBox(0F, 0F, 0F, 28, 5, 4); Grip.setRotationPoint(-28F, 3F, -2F); Grip.setTextureSize(64, 32); Grip.mirror = true; setRotation(Grip, 0F, 0F, 0F); BodyFront = new ModelRenderer(this, 0, 19); BodyFront.addBox(0F, 0F, 0F, 3, 7, 4); BodyFront.setRotationPoint(0F, 2.5F, -2F); BodyFront.setTextureSize(64, 32); BodyFront.mirror = true; setRotation(BodyFront, 0F, 0F, 0F); BodyMain = new ModelRenderer(this, 14, 19); BodyMain.addBox(0F, 0F, 0F, 8, 7, 4); BodyMain.setRotationPoint(3F, 2.5F, -2F); BodyMain.setTextureSize(64, 32); BodyMain.mirror = true; setRotation(BodyMain, 0F, 0F, 0F); LeverFront = new ModelRenderer(this, 62, 30); LeverFront.addBox(-1F, 0F, 0F, 2, 4, 2); LeverFront.setRotationPoint(7F, 9F, -1F); LeverFront.setTextureSize(64, 32); LeverFront.mirror = true; setRotation(LeverFront, 0F, 0F, 0F); LeverBottom = new ModelRenderer(this, 70, 30); LeverBottom.addBox(0F, 4F, 0F, 6, 1, 2); LeverBottom.setRotationPoint(7F, 9F, -1F); LeverBottom.setTextureSize(64, 32); LeverBottom.mirror = true; setRotation(LeverBottom, 0F, 0F, 0F); LeverMid = new ModelRenderer(this, 62, 36); LeverMid.addBox(6F, 0F, 0F, 1, 5, 2); LeverMid.setRotationPoint(7F, 9F, -1F); LeverMid.setTextureSize(64, 32); LeverMid.mirror = true; setRotation(LeverMid, 0F, 0F, 0F); Trigger = new ModelRenderer(this, 88, 30); Trigger.addBox(-1F, 0F, 0F, 1, 3, 1); Trigger.setRotationPoint(12.5F, 9F, -0.5F); Trigger.setTextureSize(64, 32); Trigger.mirror = true; setRotation(Trigger, 0F, 0F, 0.3490659F); GripFront = new ModelRenderer(this, 0, 30); GripFront.addBox(0F, 0F, 0F, 18, 3, 4); GripFront.setRotationPoint(-46F, 3F, -2F); GripFront.setTextureSize(128, 64); GripFront.mirror = true; setRotation(GripFront, 0F, 0F, 0F); GropFrontBottom = new ModelRenderer(this, 0, 37); GropFrontBottom.addBox(0F, 0F, 0F, 18, 1, 2); GropFrontBottom.setRotationPoint(-46F, 6F, -1F); GropFrontBottom.setTextureSize(128, 64); GropFrontBottom.mirror = true; setRotation(GropFrontBottom, 0F, 0F, 0F); GripBottom = new ModelRenderer(this, 0, 40); GripBottom.addBox(0F, 0F, 0F, 28, 1, 2); GripBottom.setRotationPoint(-28F, 8F, -1F); GripBottom.setTextureSize(128, 64); GripBottom.mirror = true; setRotation(GripBottom, 0F, 0F, 0F); Bolt = new ModelRenderer(this, 0, 43); Bolt.addBox(0F, 0F, 0F, 10, 2, 2); Bolt.setRotationPoint(3F, 2F, -1F); Bolt.setTextureSize(128, 64); Bolt.mirror = true; setRotation(Bolt, 0F, 0F, 0F); ChamberFront = new ModelRenderer(this, 0, 47); ChamberFront.addBox(0F, 0F, 0F, 3, 1, 3); ChamberFront.setRotationPoint(0F, 1.5F, -1.5F); ChamberFront.setTextureSize(128, 64); ChamberFront.mirror = true; setRotation(ChamberFront, 0F, 0F, 0F); ChamberBack = new ModelRenderer(this, 12, 47); ChamberBack.addBox(0F, 0F, 0F, 3, 1, 3); ChamberBack.setRotationPoint(8F, 1.5F, -1.5F); ChamberBack.setTextureSize(128, 64); ChamberBack.mirror = true; setRotation(ChamberBack, 0F, 0F, 0F); BodyBack = new ModelRenderer(this, 0, 51); BodyBack.addBox(0F, 0F, 0F, 4, 6, 4); BodyBack.setRotationPoint(11F, 3.5F, -2F); BodyBack.setTextureSize(128, 64); BodyBack.mirror = true; setRotation(BodyBack, 0F, 0F, 0F); LeverTip = new ModelRenderer(this, 24, 43); LeverTip.addBox(0F, -1F, 3F, 2, 2, 2); LeverTip.setRotationPoint(11F, 3F, 0F); LeverTip.setTextureSize(128, 64); LeverTip.mirror = true; setRotation(LeverTip, -0.4363323F, 0F, 0F); Lever = new ModelRenderer(this, 32, 43); Lever.addBox(0F, -0.5F, 0F, 1, 1, 4); Lever.setRotationPoint(11.5F, 3F, 0F); Lever.setTextureSize(128, 64); Lever.mirror = true; setRotation(Lever, -0.4363323F, 0F, 0F); HandleFront = new ModelRenderer(this, 16, 51); HandleFront.addBox(0F, 0F, 0F, 9, 5, 4); HandleFront.setRotationPoint(15F, 4.5F, -2F); HandleFront.setTextureSize(128, 64); HandleFront.mirror = true; setRotation(HandleFront, 0F, 0F, 0.4363323F); Pointer = new ModelRenderer(this, 42, 43); Pointer.addBox(0F, 0F, 0F, 3, 1, 1); Pointer.setRotationPoint(-49F, 5.5F, -0.5F); Pointer.setTextureSize(128, 64); Pointer.mirror = true; setRotation(Pointer, 0F, 0F, 0F); HandleBottom = new ModelRenderer(this, 64, 10); HandleBottom.addBox(0F, -8F, 0F, 23, 8, 4); HandleBottom.setRotationPoint(19F, 16F, -2F); HandleBottom.setTextureSize(128, 64); HandleBottom.mirror = true; setRotation(HandleBottom, 0F, 0F, 0F); HandleGrip = new ModelRenderer(this, 38, 19); HandleGrip.addBox(0F, 0F, 0F, 2, 5, 4); HandleGrip.setRotationPoint(17F, 9.5F, -2F); HandleGrip.setTextureSize(128, 64); HandleGrip.mirror = true; setRotation(HandleGrip, 0F, 0F, 0F); } public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); setRotationAngles(f, f1, f2, f3, f4, f5, entity); Barrel1.render(f5); Barrel2.render(f5); Grip.render(f5); BodyFront.render(f5); BodyMain.render(f5); LeverFront.render(f5); LeverBottom.render(f5); LeverMid.render(f5); Trigger.render(f5); GripFront.render(f5); GropFrontBottom.render(f5); GripBottom.render(f5); Bolt.render(f5); ChamberFront.render(f5); ChamberBack.render(f5); BodyBack.render(f5); LeverTip.render(f5); Lever.render(f5); HandleFront.render(f5); Pointer.render(f5); HandleBottom.render(f5); HandleGrip.render(f5); GL11.glPushMatrix(); GL11.glPushAttrib(GL11.GL_ALPHA_BITS); GL11.glDisable(GL11.GL_TEXTURE_2D); GlStateManager.disableLighting(); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240, 240); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder buf = tessellator.getBuffer(); buf.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION_COLOR); buf.pos(-32F / 16F, 0 + 4F / 16F, 0).color(0.0F, 1.0F, 0.0F, 1.0F).endVertex(); buf.pos(-150, 0, 0).color(0.0F, 1.0F, 0.0F, 1.0F).endVertex();; tessellator.draw(); GlStateManager.enableLighting(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glPopAttrib(); GL11.glPopMatrix(); } public void renderAnim(Entity entity, float f, float f1, float f2, float f3, float f4, float f5, float rot, float tran) { LeverTip.rotateAngleX += rot; Lever.rotateAngleX += rot; Bolt.offsetX += tran; LeverTip.offsetX += tran; Lever.offsetX += tran; render(entity, f, f1, f2, f3, f4, f5); setRotation(LeverTip, -0.4363323F, 0F, 0F); setRotation(Lever, -0.4363323F, 0F, 0F); Bolt.offsetX -= tran; LeverTip.offsetX -= tran; Lever.offsetX -= tran; } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); } }
jimmysharp/KanACLogger
app/src/main/java/jimmysharp/kanaclogger/model/TwitterManager.java
package jimmysharp.kanaclogger.model; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.util.Log; import com.annimon.stream.Collectors; import com.annimon.stream.Stream; import java.util.LinkedList; import java.util.List; import rx.Single; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; public class TwitterManager { private static final String TAG = TwitterManager.class.getSimpleName(); private static final String PREFERENCE_NAME = "twitter_setting"; private static final String ACCESS_TOKEN_KEY = "access_token"; private static final String TOKEN_SECRET_KEY = "token_secret"; private static final String OAUTH_CALLBACK_URL = "kanactwit://oauth"; private static final int TWITTER_MAX_CHARS = 140; Twitter twitter; Context context; public TwitterManager(Context context){ this.context = context; twitter = TwitterFactory.getSingleton(); AccessToken token = loadAccessToken(); twitter.setOAuthAccessToken(token); } public void dispose(){ this.context = null; this.twitter = null; } public boolean isAccessTokenStored(){ return loadAccessToken() != null; } public AccessToken loadAccessToken(){ SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE); String accessToken, tokenSecret; accessToken = pref.getString(ACCESS_TOKEN_KEY,null); tokenSecret = pref.getString(TOKEN_SECRET_KEY,null); if (accessToken != null && tokenSecret != null){ return new AccessToken(accessToken,tokenSecret); } else{ return null; } } public void saveAccessToken(AccessToken accessToken){ SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putString(ACCESS_TOKEN_KEY,accessToken.getToken()); editor.putString(TOKEN_SECRET_KEY,accessToken.getTokenSecret()); editor.apply(); } public void clearAccessToken(){ SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.remove(ACCESS_TOKEN_KEY); editor.remove(TOKEN_SECRET_KEY); editor.apply(); } public Single<RequestToken> getAccessTokenUrl(){ return Single.create(subscriber -> { try { RequestToken token = twitter.getOAuthRequestToken(OAUTH_CALLBACK_URL); subscriber.onSuccess(token); } catch (TwitterException e) { subscriber.onError(e); } }); } public Single<AccessToken> getAccessToken(RequestToken requestToken, Uri uri){ return Single.create(subscriber -> { try { String verifier = uri.getQueryParameter("oauth_verifier"); AccessToken token = twitter.getOAuthAccessToken(requestToken,verifier); subscriber.onSuccess(token); } catch (TwitterException e){ subscriber.onError(e); } }); } public Single<AccessToken> getAndSaveAccessToken(Context context, RequestToken requestToken, Uri uri){ return Single.create(subscriber -> { try { String verifier = uri.getQueryParameter("oauth_verifier"); AccessToken token = twitter.getOAuthAccessToken(requestToken,verifier); saveAccessToken(token); twitter.setOAuthAccessToken(token); subscriber.onSuccess(token); } catch (TwitterException e){ subscriber.onError(e); } }); } public Single<Status> tweet(String message){ return Single.create(subscriber -> { try { Status status = twitter.updateStatus(message); subscriber.onSuccess(status); } catch (TwitterException e){ subscriber.onError(e); } }); } public List<Single<Status>> tweet(List<String> lines, String hashtag){ Log.v(TAG,"Tweet preparation start"); int maxChars; List<Single<Status>> tweetList = new LinkedList<>(); if (hashtag == null || hashtag.equals("")){ hashtag = ""; } else { hashtag = "#" + hashtag; } maxChars = TWITTER_MAX_CHARS - hashtag.length(); Log.v(TAG,"Tweet max length = "+maxChars); int charCount = 0; List<String> buffer = new LinkedList<>(); for (String line : lines){ if (charCount + line.length() > maxChars){ if (buffer.size() == 0){ tweetList.add(Single.create(subscriber -> { subscriber.onError(new RuntimeException("Tweet too long: "+line.length()+" chars")); })); continue; } else { buffer.add(hashtag); tweetList.add(tweet(joinString(buffer,"\n"))); buffer.clear(); charCount = 0; } } buffer.add(line); charCount += line.length() + 1; } if (buffer.size() > 0){ buffer.add(hashtag); tweetList.add(tweet(joinString(buffer, "\n"))); } Log.v(TAG,"Tweet preparation end"); Log.v(TAG,"Tweet List size:"+tweetList.size()); return tweetList; } private String joinString(List<String> strings, String separator){ return Stream.of(strings).collect(Collectors.joining(separator)); } }
ScalablyTyped/SlinkyTyped
t/twilsock/src/main/scala/typingsSlinky/twilsock/telemetrytrackerMod.scala
package typingsSlinky.twilsock import typingsSlinky.twilsock.configurationMod.Configuration import typingsSlinky.twilsock.packetinterfaceMod.PacketInterface import typingsSlinky.twilsock.telemetryMod.TelemetryEvent import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object telemetrytrackerMod { @js.native sealed trait EventSendingLimitation extends StObject @JSImport("twilsock/lib/services/telemetrytracker", "EventSendingLimitation") @js.native object EventSendingLimitation extends StObject { @JSBracketAccess def apply(value: Double): js.UndefOr[EventSendingLimitation with Double] = js.native @js.native sealed trait AnyEvents extends EventSendingLimitation /* 1 */ val AnyEvents: typingsSlinky.twilsock.telemetrytrackerMod.EventSendingLimitation.AnyEvents with Double = js.native @js.native sealed trait AnyEventsIncludingUnfinished extends EventSendingLimitation /* 2 */ val AnyEventsIncludingUnfinished: typingsSlinky.twilsock.telemetrytrackerMod.EventSendingLimitation.AnyEventsIncludingUnfinished with Double = js.native @js.native sealed trait MinEventsPortion extends EventSendingLimitation /* 0 */ val MinEventsPortion: typingsSlinky.twilsock.telemetrytrackerMod.EventSendingLimitation.MinEventsPortion with Double = js.native } @JSImport("twilsock/lib/services/telemetrytracker", "TelemetryEventDescription") @js.native class TelemetryEventDescription protected () extends StObject { def this(title: String, details: String, start: js.Date) = this() def this(title: String, details: String, start: js.Date, end: js.Date) = this() def this(title: String, details: String, start: js.Date, end: js.UndefOr[scala.Nothing], `type`: String) = this() def this(title: String, details: String, start: js.Date, end: js.Date, `type`: String) = this() def this( title: String, details: String, start: js.Date, end: js.UndefOr[scala.Nothing], `type`: js.UndefOr[scala.Nothing], id: String ) = this() def this( title: String, details: String, start: js.Date, end: js.UndefOr[scala.Nothing], `type`: String, id: String ) = this() def this( title: String, details: String, start: js.Date, end: js.Date, `type`: js.UndefOr[scala.Nothing], id: String ) = this() def this(title: String, details: String, start: js.Date, end: js.Date, `type`: String, id: String) = this() val details: String = js.native var end: js.Date = js.native val id: js.UndefOr[String] = js.native val start: js.Date = js.native val title: String = js.native def toTelemetryEvent(): TelemetryEvent = js.native val `type`: js.UndefOr[String] = js.native } @js.native sealed trait TelemetryPoint extends StObject @JSImport("twilsock/lib/services/telemetrytracker", "TelemetryPoint") @js.native object TelemetryPoint extends StObject { @JSBracketAccess def apply(value: Double): js.UndefOr[TelemetryPoint with Double] = js.native @js.native sealed trait End extends TelemetryPoint /* 1 */ val End: typingsSlinky.twilsock.telemetrytrackerMod.TelemetryPoint.End with Double = js.native @js.native sealed trait Start extends TelemetryPoint /* 0 */ val Start: typingsSlinky.twilsock.telemetrytrackerMod.TelemetryPoint.Start with Double = js.native } @JSImport("twilsock/lib/services/telemetrytracker", "TelemetryTracker") @js.native class TelemetryTracker protected () extends StObject { def this(config: Configuration, packetInterface: PacketInterface) = this() var _canSendTelemetry: js.Any = js.native def addPartialEvent(incompleteEvent: TelemetryEventDescription, eventKey: String, point: TelemetryPoint): Unit = js.native def addTelemetryEvent(event: TelemetryEventDescription): Unit = js.native def canSendTelemetry: Boolean = js.native def canSendTelemetry_=(enable: Boolean): Unit = js.native val config: js.Any = js.native var getTelemetryPortion: js.Any = js.native def getTelemetryToSend(sendingLimit: EventSendingLimitation): js.Array[TelemetryEventDescription] = js.native var hasInitializationFinished: js.Any = js.native def isTelemetryEnabled: Boolean = js.native val maxEventsPortionToSend: js.Any = js.native var merge: js.Any = js.native val minEventsPortionToSend: js.Any = js.native val packetInterface: js.Any = js.native var pendingEvents: js.Any = js.native var readyEvents: js.Any = js.native def sendTelemetry(limit: EventSendingLimitation): Unit = js.native def sendTelemetryIfMinimalPortionCollected(): Unit = js.native } }
Open-Earth-Foundation/traction
services/showcase/api/main.py
import logging import os import time from pathlib import Path import uvicorn from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware from starlette.websockets import WebSocket, WebSocketDisconnect from api.core.config import settings from api.endpoints.routes.sandbox import router as sandbox_router from api.endpoints.routes.webhooks import router as webhooks_router from api.core.exception_handlers import add_exception_handlers from api.services.websockets import notifier os.environ["TZ"] = settings.TIMEZONE time.tzset() # setup loggers logging_file_path = (Path(__file__).parent / "logging.conf").resolve() logging.config.fileConfig(logging_file_path, disable_existing_loggers=False) logger = logging.getLogger(__name__) def get_application() -> FastAPI: application = FastAPI( title=settings.TITLE, description=settings.DESCRIPTION, debug=settings.DEBUG, middleware=None, ) return application def get_api() -> FastAPI: api = FastAPI( title=settings.TITLE, description=settings.DESCRIPTION, debug=settings.DEBUG, middleware=None, ) # mount api routers here... api.include_router(sandbox_router, prefix=settings.API_V1_STR, tags=["sandbox"]) api.include_router(webhooks_router, prefix=settings.API_V1_STR, tags=["webhooks"]) return api app = get_application() api = get_api() app.mount("/api", api) # frontend websockets # make sure this is before the static files and cors origins. @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await notifier.connect(websocket) try: while True: data = await websocket.receive_text() await websocket.send_text(f"Message text was: {data}") except WebSocketDisconnect: notifier.remove(websocket) # Frontend Serving origins = settings.SHOWCASE_CORS_URLS.split(",") if origins: app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class SPAStaticFiles(StaticFiles): async def get_response(self, path: str, scope): response = await super().get_response(path, scope) if response.status_code == 404: response = await super().get_response(".", scope) return response static_files = Path(settings.SHOWCASE_STATIC_FILES).resolve() app.mount( "/", SPAStaticFiles(directory=static_files, html=True, check_dir=True), name="dist", ) add_exception_handlers(app) add_exception_handlers(api) @app.on_event("startup") async def startup(): logger.debug("@app.on_event(startup)") # Prime the push notification generator await notifier.generator.asend(None) if __name__ == "__main__": print("main.") uvicorn.run(app, host="0.0.0.0", port=5200)
seratch/go-slack-sdk-experimental
webapi/conversations_setPurpose/endpoint.go
package conversations_setPurpose const ApiMethod string = "conversations.setPurpose"
kent013/PhotoSubmitter
Pod/Classes/Services/SalesforcePhotoSubmitter/Libraries/ChatterAPI/Utilities/SFObjectFetcher.h
// // ObjectFetcher.h // DemoApp // // Copyright 2011 Salesforce.com. All rights reserved. // // This is sample code provided as a learning tool. Feel free to // learn from it and incorporate elements into your own code. // No guarantees are made about the quality or security of this code. // // THIS SOFTWARE IS PROVIDED BY Salesforce.com "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Salesforce.com OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #import "RestKit/RestKit.h" @protocol SFObjectFetcherDelegate<NSObject> - (void)retrievalCompleted:(NSString*)tag withSuccess:(bool)succeeded; @end @interface SFObjectFetcher : NSObject<RKObjectLoaderDelegate> { NSString* tag; id obj; NSObject<SFObjectFetcherDelegate>* delegate; } @property(nonatomic, retain) NSString* tag; @property(nonatomic, retain) id obj; @property(nonatomic, assign) NSObject<SFObjectFetcherDelegate>* delegate; // We assume the delegate will outlive this object, it is not retained. - initWithTag:(NSString*)inTag object:(id)inObj delegate:(NSObject<SFObjectFetcherDelegate>*)inDelegate; - (void)fetch; @end
sanskritiagarwal/Java
src/irabank/dto/RolesDTO.java
<reponame>sanskritiagarwal/Java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.irabank.dto; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author <NAME> */ @Entity @Table(name = "roles", catalog = "sbs", schema = "") @XmlRootElement @NamedQueries({ @NamedQuery(name = "RolesDTO.findAll", query = "SELECT r FROM RolesDTO r"), @NamedQuery(name = "RolesDTO.findByRoleId", query = "SELECT r FROM RolesDTO r WHERE r.roleId = :roleId"), @NamedQuery(name = "RolesDTO.findByRoleName", query = "SELECT r FROM RolesDTO r WHERE r.roleName = :roleName"), @NamedQuery(name = "RolesDTO.findByRoleDesc", query = "SELECT r FROM RolesDTO r WHERE r.roleDesc = :roleDesc"), @NamedQuery(name = "RolesDTO.findByCreatedDate", query = "SELECT r FROM RolesDTO r WHERE r.createdDate = :createdDate"), @NamedQuery(name = "RolesDTO.findByIsActive", query = "SELECT r FROM RolesDTO r WHERE r.isActive = :isActive")}) public class RolesDTO implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "ROLE_ID") private Integer roleId; @Basic(optional = false) @NotNull @Size(min = 1, max = 30) @Column(name = "ROLE_NAME") private String roleName; @Size(max = 60) @Column(name = "ROLE_DESC") private String roleDesc; @Column(name = "CREATED_DATE") @Temporal(TemporalType.TIMESTAMP) private Date createdDate; @Column(name = "IS_ACTIVE") private Short isActive; @OneToMany(mappedBy = "roleId") private List<UserDTO> userDTOList; public RolesDTO() { } public RolesDTO(Integer roleId) { this.roleId = roleId; } public RolesDTO(Integer roleId, String roleName) { this.roleId = roleId; this.roleName = roleName; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleDesc() { return roleDesc; } public void setRoleDesc(String roleDesc) { this.roleDesc = roleDesc; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Short getIsActive() { return isActive; } public void setIsActive(Short isActive) { this.isActive = isActive; } @XmlTransient public List<UserDTO> getUserDTOList() { return userDTOList; } public void setUserDTOList(List<UserDTO> userDTOList) { this.userDTOList = userDTOList; } @Override public int hashCode() { int hash = 0; hash += (roleId != null ? roleId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof RolesDTO)) { return false; } RolesDTO other = (RolesDTO) object; if ((this.roleId == null && other.roleId != null) || (this.roleId != null && !this.roleId.equals(other.roleId))) { return false; } return true; } @Override public String toString() { return "edu.irabank.dto.RolesDTO[ roleId=" + roleId + " ]"; } }
chenFlyingkite/MyTosWiki
app/src/main/java/com/flyingkite/mytoswiki/library/StoneDesktopAdapter.java
<reponame>chenFlyingkite/MyTosWiki package com.flyingkite.mytoswiki.library; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.flyingkite.library.widget.RVAdapter; import com.flyingkite.mytoswiki.R; import com.flyingkite.mytoswiki.data.StoneDesktop; import com.flyingkite.mytoswiki.tos.Runestones; import com.flyingkite.mytoswiki.util.ViewUtil; public class StoneDesktopAdapter extends RVAdapter<StoneDesktop, StoneDesktopAdapter.StoneDesktopVH, StoneDesktopAdapter.ItemListener> { public interface ItemListener extends RVAdapter.ItemListener<StoneDesktop, StoneDesktopVH> { default void onClickShare(StoneDesktop item, StoneDesktopVH vh, View v, int position) {} } @NonNull @Override public StoneDesktopVH onCreateViewHolder(@NonNull ViewGroup parent, int type) { return new StoneDesktopVH(inflateView(parent, R.layout.view_desktop)); } @Override public void onBindViewHolder(StoneDesktopVH vh, int position) { super.onBindViewHolder(vh, position); StoneDesktop s = itemOf(position); vh.share.setOnClickListener((v) -> { if (onItem != null) { onItem.onClickShare(s, vh, v, position); } }); vh.title.setText(s.detail); vh.setData(s.stones); } public static class StoneDesktopVH extends RecyclerView.ViewHolder implements ViewUtil { private final View share; private final TextView title; private final ViewGroup stone; public StoneDesktopVH(@NonNull View v) { super(v); share = v.findViewById(R.id.deskShare); title = v.findViewById(R.id.deskTitle); stone = v.findViewById(R.id.deskDesktop); } public void setData(String data) { RunestoneAdapter a = new RunestoneAdapter(); a.setDataList(Runestones.toList(data)); fillItems(stone, a); } } }
hlan-by/openframework
packages/google-sheets/src/main/java/eu/ibagroup/easyrpa/openframework/googlesheets/style/BorderStyle.java
<reponame>hlan-by/openframework package eu.ibagroup.easyrpa.openframework.googlesheets.style; public interface BorderStyle { // NOT ALLOWED public String STYLE_UNSPECIFIED = "STYLE_UNSPECIFIED"; public String DOTTED = "DOTTED"; public String DASHED = "DASHED"; public String SOLID = "SOLID"; public String SOLID_MEDIUM = "SOLID_MEDIUM"; public String SOLID_THICK = "SOLID_THICK"; public String NONE = "NONE"; public String DOUBLE = "DOUBLE"; }
Rossojo/edmm
TOSCin/src/main/java/io/github/edmm/plugins/cfn/model/types/ServiceDiscoveryType.java
<filename>TOSCin/src/main/java/io/github/edmm/plugins/cfn/model/types/ServiceDiscoveryType.java package io.github.edmm.plugins.cfn.model.types; import io.github.edmm.model.edimm.ComponentType; public enum ServiceDiscoveryType { HttpNamespace(ComponentType.Software_Component), Instance(ComponentType.Software_Component), PrivateDnsNamespace(ComponentType.Software_Component), PublicDnsNamespace(ComponentType.Software_Component), Service(ComponentType.Software_Component); ComponentType componentType; ServiceDiscoveryType(ComponentType componentType) { this.componentType = componentType; } public ComponentType toComponentType() { return this.componentType; } }
la8457478/realestateweb
src/components/muse-ui/lib/Form/Form.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _utils = require('../utils'); exports.default = { name: 'mu-form', provide: function provide() { return { muForm: this }; }, props: { model: { type: Object, required: true }, inline: Boolean, labelWidth: [String, Number], labelPosition: { type: String, default: 'top', validator: function validator(val) { return ['left', 'right', 'top'].indexOf(val) !== -1; } }, autoValidate: { type: Boolean, default: true } }, data: function data() { return { items: [] }; }, methods: { getValue: function getValue(prop) { return (0, _utils.getObjAttr)(this.model, prop); }, addItem: function addItem(item) { this.items.push(item); }, removeItem: function removeItem(item) { var index = this.items.indexOf(item); if (index === -1) return; this.items.splice(index, 1); }, validate: function validate() { var valid = true; var promises = []; for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; var result = item.validate(); if ((0, _utils.isPromise)(result)) { promises.push(result); continue; } if (!result) { valid = false; } } if (promises.length > 0 && typeof Promise !== 'undefined') { return Promise.all([valid ? Promise.resolve(valid) : Promise.reject(valid)].concat(promises)).then(function () { return true; }, function () { return false; }); } return typeof Promise !== 'undefined' ? Promise.resolve(valid) : valid; }, clear: function clear() { this.items.forEach(function (item) { return item.errorMessage = ''; }); } }, render: function render(h) { return h('form', { staticClass: 'mu-form', class: { 'mu-form__inline': this.inline }, on: this.$listeners }, this.$slots.default); } };
fh-erfurt/RentATool
src/main/java/de/rat/model/common/Account.java
<gh_stars>1-10 package de.rat.model.common; import de.rat.model.BaseModel; import javax.persistence.Column; import javax.persistence.Entity; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; /**Represents a class account. * @author <NAME>, <NAME>, <NAME> */ @Entity public class Account extends BaseModel { @NotEmpty @Column(unique = true) @Email(message = "Gib eine gültige Emailadresse ein.") private String email; @NotEmpty(message="Gib ein gültiges Passwort ein") private String password; private Role role; public Account(){ } public Account (Role role, String email, String password){ this.role= role; this.email= email; this.password= password; } public Role getRole() { return this.role; } public String getRolesForAuthority() { return "ROLE_" + role; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setRole(Role role) { this.role = role; } public void setPassword(String password) { this.password = password; } }
Octagonal-T/praeterbot
commands/steal.js
module.exports={ name: 'steal', description: 'Adds a external emoji, a included image, or a image url!', args: true, format: 'steal [name] <url or emoji>', permissions: ['MANAGE_EMOJIS'], myPermissions: ['MANAGE_EMOJIS'], aliases: [], category: 'Moderation', async run(msg, args, client){ if(args.length == 1){ if(msg.content.match(/<?(a)?:?(\w{2,32}):(\d{17,19})>?/)){ let emojiArgs = args[0].slice(1) emojiArgs = emojiArgs.slice(0, -1) emojiArgs = emojiArgs.split(":") if(msg.guild.emojis.cache.get(emojiArgs[2])) return msg.channel.send("That emoji is part of the server!") msg.guild.emojis.create(`https://cdn.discordapp.com/emojis/${emojiArgs[2]}.${emojiArgs[0] == 'a' ? 'gif' : 'png'}`, emojiArgs[1]).then((emoji)=>{ msg.channel.send(`${emoji} Added ${emoji.name} as an emoji!`) }).catch((e) => { msg.channel.send("There was an error in uploading the emoji! (Make sure you put the name in front of the emoji, that the file is under 256kb, and that the limit of emojis hasn't been used up!)") }) }else{ if(!msg.attachments.first()) return msg.channel.send("No emoji, link or attachment included.") else{ msg.guild.emojis.create(msg.attachments.first().proxyURL, args[0]).then((emoji)=>{ msg.channel.send(`${emoji} Added ${emoji.name} as an emoji!`) }).catch((e) => { msg.channel.send("There was an error in uploading the emoji! (Make sure you put the name in front of the emoji, that the file is under 256kb, and that the limit of emojis hasn't been used up!)") }) } } }else if(args.length == 2){ if(msg.content.match(/<?(a)?:?(\w{2,32}):(\d{17,19})>?/)){ let emojiArgs = args[1].slice(1) emojiArgs = emojiArgs.slice(0, -1) emojiArgs = emojiArgs.split(":") if(msg.guild.emojis.cache.get(emojiArgs[2])) return msg.channel.send("That emoji is part of the server!") msg.guild.emojis.create(`https://cdn.discordapp.com/emojis/${emojiArgs[2]}.${emojiArgs[0] == 'a' ? 'gif' : 'png'}`, args[0]).then((emoji)=>{ msg.channel.send(`${emoji} Added ${emoji.name} as an emoji!`) }).catch((e) => { msg.channel.send("There was an error in uploading the emoji! (Make sure you put the name in front of the emoji, that the file is under 256kb, and that the limit of emojis hasn't been used up!)") }) }else{ msg.guild.emojis.create(args[1], args[0]).then((emoji)=>{ msg.channel.send(`${emoji} Added ${emoji.name} as an emoji!`) }).catch((e) => { msg.channel.send("There was an error in uploading the emoji! (Make sure you put the name in front of the emoji, that the file is under 256kb, and that the limit of emojis hasn't been used up!)") }) } }else msg.channel.send("Could not upload that as an emoji") } }
siouxmathware/ijsbeer-ai
lib/modernisation/syllable_corrector.py
import json import os.path as op from lib.modernisation.syllable_tokenizer import SyllableTokenizer from lib import constants class SyllableCorrector: """ Modernisation strategy by substituting syllables and combinations thereof by their modernised equivalents. The default replacements used are given by the human-readable :download:`switches.json </../../pipeline_data/modernisation/switches.json>`. The splitting into syllables is handled by the :class:`SyllableTokenizer<lib.modernisation.syllable_tokenizer.SyllableTokenizer>` class. """ def __init__(self, file_name=None): """ :param file_name: The name of the switches file, defaults to `switches.json` the path is given relative to the `constants.DATA_DIR` directory. """ file_name = file_name if file_name is not None else 'switches.json' switches_file = op.join(constants.DATA_DIR, 'modernisation', file_name) self.tokenizer = SyllableTokenizer() with open(switches_file) as f: self.switches = { tuple(hist.split(".")): tuple(mod.split(".")) for hist, mod in json.load(f).items() } self.tree = self._create_tree() def __call__(self, word_form_lowercase, verbose=False): """ :param word_form_lowercase: The lower case word-form to be modernised. :param verbose: Flag whether to output extra info for debugging (True) or not (False). :return: A tuple, the first element indicated the result of applying the syllabel corrector, the second whether the regex changed the word-form (True) or not (False). """ touched = False tags = self.tokenizer.encode(word_form_lowercase) translated_tags = [] while tags: if verbose: print() print(translated_tags + ['-'] + tags) print() tag = tags[0] if tag not in self.tree: translated_tags.append(tag) tags.pop(0) else: res = self._translate_part(tags, self.tree[tag], 1) if res: touched = True replacement, nr_replacement = res else: replacement, nr_replacement = [tag], 1 if verbose: print('a:', end=' ') print(tags[:nr_replacement]) print('b:', end=' ') print(replacement) print() tags = tags[nr_replacement:] translated_tags += replacement translated_word = self.tokenizer.decode(translated_tags) return translated_word, touched def _add_leaves(self, tree, hist_t, mod_t, depth): first = hist_t[0] branch = tree.get(first, {}) if len(hist_t) > 1: branch = self._add_leaves(branch, hist_t[1:], mod_t, depth + 1) else: branch = {None: mod_t} tree[first] = branch return tree def _create_tree(self): tree = {} for hist_t, mod_t in self.switches.items(): first = hist_t[0] branch = tree.get(first, {}) if len(hist_t) > 1: branch = self._add_leaves(branch, hist_t[1:], mod_t, 0) else: branch = {None: mod_t} tree[first] = branch return tree def _translate_part(self, tags, branch, nr_hist): # print('O', branch) if len(tags) > 1 and tags[1] in branch: res = self._translate_part(tags[1:], branch[tags[1]], nr_hist + 1) if res: part, nr_hist = res # print('A', part) return part, nr_hist elif None in branch: return branch[None], nr_hist # print('B', branch.get(None, False)) else: return False elif None in branch: return branch[None], nr_hist else: return False
MarginC/kame
netbsd/sys/arch/acorn32/include/asm.h
<reponame>MarginC/kame<filename>netbsd/sys/arch/acorn32/include/asm.h<gh_stars>10-100 /* $NetBSD: asm.h,v 1.1 2001/10/05 22:27:49 reinoud Exp $ */ #include <arm/asm.h>
yanalucky/MBB
fcgo_order/Fcgo/Work/Mine/Fcgo_AfterSalesServiceListModel.h
// // Fcgo_AfterSalesServiceListModel.h // Fcgo // // Created by huafanxiao on 2017/7/3. // Copyright © 2017年 huafanxiao. All rights reserved. // #import <Foundation/Foundation.h> @interface Fcgo_AfterSalesServiceListModel : NSObject @property (nonatomic,copy) NSString *picurl,*goodsName,*orderNo,*created,*spu,*orderChildNo; @property (nonatomic,strong) NSNumber *status,*refundMoney,*realRefundMoney,*num,*money,*f_apply_id,*goodsId,*goodsGsku,*goodsSku,*orderId,*goodsBuynum,*texe,*orderGoodsStatus,*goodsCate,*goodsCatem,*goodsBrand,*goodsValue,*allPrice,*allPriceYUAN,*refundNumber,*refundPrice,*salePrice,*refundPriceYUAN,*freightYUAN; //申请售后 @property (nonatomic,copy) NSString *cancelTime,*createTime,*orderAftersaleNo,*goodsSpu,*deliverTime,*goodsSkuName,*goodsSkuPicurl,*goodsType,*noClearTime,*noSiezTime,*properties,*remark,*siezTime,*signTime,*thrNo,*updateTime; //售后列表 @property (nonatomic,copy) NSString *aftersaleType,*reason,*destroyReason; //private Integer orderChildId; ??? // 子单编号 @end
Retardeded/QueueFree-Front
app/src/androidTest/java/com/example/myapplication/RegisterTest.java
<filename>app/src/androidTest/java/com/example/myapplication/RegisterTest.java package com.example.myapplication; import android.app.Activity; import android.app.Instrumentation; import android.os.Bundle; import android.view.View; import androidx.test.espresso.ViewInteraction; import androidx.test.rule.ActivityTestRule; import com.example.myapplication.activities.DashBoard; import com.example.myapplication.activities.Register; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.hasErrorText; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; import static java.util.EnumSet.allOf; import static org.junit.Assert.*; public class RegisterTest { @Rule public ActivityTestRule<Register> mRegisterRuleTest = new ActivityTestRule<Register>(Register.class); Register mRegister = null; Instrumentation.ActivityMonitor dashBoardMonitor = getInstrumentation().addMonitor(DashBoard.class.getName(), null, false); @Before public void setUp() throws Exception { mRegister = mRegisterRuleTest.getActivity(); } @Test public void testLanuchOfDashBoard(){ String user = "this"; String password = "<PASSWORD>"; mRegister.user = user; mRegister.password = password; mRegister.loadDashboard(); Activity dashBoard = getInstrumentation().waitForMonitorWithTimeout(dashBoardMonitor,5000); assertNotNull(dashBoard); Bundle bundle = dashBoard.getIntent().getExtras(); String[] userInfo = bundle.getString("userInfo").split(" "); boolean condtion = userInfo[0].equals(user) && userInfo[1].equals(password); Assert.assertTrue(condtion); dashBoard.finish(); //mRegister. } @Test public void goodRegisterDataTest() { mRegister.user = "som"; mRegister.password = "<PASSWORD>"; mRegister.confirmPassword = "<PASSWORD>"; mRegister.fullName = "som"; Assert.assertTrue(mRegister.validateInputs()); } @Test public void emptyNameTest() { mRegister.setUpEditTexts(); mRegister.user = ""; mRegister.password = "<PASSWORD>"; mRegister.confirmPassword = "<PASSWORD>"; mRegister.fullName = "som"; Assert.assertFalse(mRegister.validateInputs()); } @Test public void emptyPasswordTest() { mRegister.setUpEditTexts(); mRegister.user = "som"; mRegister.password = ""; mRegister.confirmPassword = "<PASSWORD>"; mRegister.fullName = "som"; Assert.assertFalse(mRegister.validateInputs()); } @Test public void passwordsDontMatchTest() { mRegister.setUpEditTexts(); mRegister.user = "som"; mRegister.password = "<PASSWORD>"; mRegister.confirmPassword = "<PASSWORD>"; mRegister.fullName = "som"; Assert.assertFalse(mRegister.validateInputs()); } @After public void tearDown() throws Exception { } }
rozlana-g/FEDOT
fedot/core/operations/evaluation/operation_implementations/models/ts_implementations.py
from typing import Optional from copy import copy import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from scipy import stats from scipy.special import inv_boxcox, boxcox from statsmodels.tsa.api import STLForecast from statsmodels.tsa.ar_model import AutoReg from statsmodels.tsa.arima.model import ARIMA from fedot.core.data.data import InputData from fedot.core.log import Log from fedot.core.operations.evaluation.operation_implementations.data_operations.ts_transformations import \ ts_to_table, prepare_target from fedot.core.operations.evaluation. \ operation_implementations.implementation_interfaces import ModelImplementation from fedot.core.pipelines.ts_wrappers import _update_input, exception_if_not_ts_task from fedot.core.repository.dataset_types import DataTypesEnum from fedot.utilities.ts_gapfilling import SimpleGapFiller from sklearn.preprocessing import StandardScaler class ARIMAImplementation(ModelImplementation): def __init__(self, log: Log = None, **params): super().__init__(log) self.params = params self.arima = None self.lambda_value = None self.scope = None self.actual_ts_len = None self.sts = None def fit(self, input_data): """ Class fit arima model on data :param input_data: data with features, target and ids to process """ source_ts = np.array(input_data.features) # Save actual time series length self.actual_ts_len = len(source_ts) self.sts = source_ts # Apply box-cox transformation for positive values min_value = np.min(source_ts) if min_value > 0: pass else: # Making a shift to positive values self.scope = abs(min_value) + 1 source_ts = source_ts + self.scope _, self.lambda_value = stats.boxcox(source_ts) transformed_ts = boxcox(source_ts, self.lambda_value) # Set parameters p = int(self.params.get('p')) d = int(self.params.get('d')) q = int(self.params.get('q')) params = {'order': (p, d, q)} self.arima = ARIMA(transformed_ts, **params).fit() return self.arima def predict(self, input_data, is_fit_pipeline_stage: bool): """ Method for time series prediction on forecast length :param input_data: data with features, target and ids to process :param is_fit_pipeline_stage: is this fit or predict stage for pipeline :return output_data: output data with smoothed time series """ input_data = copy(input_data) parameters = input_data.task.task_params forecast_length = parameters.forecast_length old_idx = input_data.idx target = input_data.target # For training pipeline get fitted data if is_fit_pipeline_stage: fitted_values = self.arima.fittedvalues fitted_values = self._inverse_boxcox(predicted=fitted_values, lambda_param=self.lambda_value) # Undo shift operation fitted_values = self._inverse_shift(fitted_values) diff = int(self.actual_ts_len - len(fitted_values)) # If first elements skipped if diff != 0: # Fill nans with first values first_element = fitted_values[0] first_elements = [first_element] * diff first_elements.extend(list(fitted_values)) fitted_values = np.array(first_elements) _, predict = ts_to_table(idx=old_idx, time_series=fitted_values, window_size=forecast_length) new_idx, target_columns = ts_to_table(idx=old_idx, time_series=target, window_size=forecast_length) # Update idx and target input_data.idx = new_idx input_data.target = target_columns # For predict stage we can make prediction else: start_id = old_idx[-1] - forecast_length + 1 end_id = old_idx[-1] predicted = self.arima.predict(start=start_id, end=end_id) predicted = self._inverse_boxcox(predicted=predicted, lambda_param=self.lambda_value) # Undo shift operation predict = self._inverse_shift(predicted) # Convert one-dim array as column predict = np.array(predict).reshape(1, -1) new_idx = np.arange(start_id, end_id + 1) # Update idx input_data.idx = new_idx # Update idx and features output_data = self._convert_to_output(input_data, predict=predict, data_type=DataTypesEnum.table) return output_data def get_params(self): return self.params def _inverse_boxcox(self, predicted, lambda_param): """ Method apply inverse Box-Cox transformation """ if lambda_param == 0: return np.exp(predicted) else: res = inv_boxcox(predicted, lambda_param) res = self._filling_gaps(res) return res def _inverse_shift(self, values): """ Method apply inverse shift operation """ if self.scope is None: pass else: values = values - self.scope return values @staticmethod def _filling_gaps(res): nan_ind = np.argwhere(np.isnan(res)) res[nan_ind] = -100.0 # Gaps in first and last elements fills with mean value if 0 in nan_ind: res[0] = np.mean(res) if int(len(res) - 1) in nan_ind: res[int(len(res) - 1)] = np.mean(res) # Gaps in center of timeseries fills with linear interpolation if len(np.ravel(np.argwhere(np.isnan(res)))) != 0: gf = SimpleGapFiller() res = gf.linear_interpolation(res) return res class AutoRegImplementation(ModelImplementation): def __init__(self, log: Log = None, **params): super().__init__(log) self.params = params self.actual_ts_len = None self.autoreg = None def fit(self, input_data): """ Class fit ar model on data :param input_data: data with features, target and ids to process """ source_ts = np.array(input_data.features) self.actual_ts_len = len(source_ts) lag_1 = int(self.params.get('lag_1')) lag_2 = int(self.params.get('lag_2')) params = {'lags': [lag_1, lag_2]} self.autoreg = AutoReg(source_ts, **params).fit() return self.autoreg def predict(self, input_data, is_fit_pipeline_stage: bool): """ Method for time series prediction on forecast length :param input_data: data with features, target and ids to process :param is_fit_pipeline_stage: is this fit or predict stage for pipeline :return output_data: output data with smoothed time series """ input_data = copy(input_data) parameters = input_data.task.task_params forecast_length = parameters.forecast_length old_idx = input_data.idx target = input_data.target if is_fit_pipeline_stage: fitted = self.autoreg.predict(start=old_idx[0], end=old_idx[-1]) # First n elements in time series are skipped diff = self.actual_ts_len - len(fitted) # Fill nans with first values first_element = fitted[0] first_elements = [first_element] * diff first_elements.extend(list(fitted)) fitted = np.array(first_elements) _, predict = ts_to_table(idx=old_idx, time_series=fitted, window_size=forecast_length) new_idx, target_columns = ts_to_table(idx=old_idx, time_series=target, window_size=forecast_length) # Update idx and target input_data.idx = new_idx input_data.target = target_columns # For predict stage we can make prediction else: start_id = old_idx[-1] - forecast_length + 1 end_id = old_idx[-1] predicted = self.autoreg.predict(start=start_id, end=end_id) # Convert one-dim array as column predict = np.array(predicted).reshape(1, -1) new_idx = np.arange(start_id, end_id + 1) # Update idx input_data.idx = new_idx # Update idx and features output_data = self._convert_to_output(input_data, predict=predict, data_type=DataTypesEnum.table) return output_data def get_params(self): return self.params class STLForecastARIMAImplementation(ModelImplementation): def __init__(self, log: Log = None, **params: Optional[dict]): super().__init__(log) self.params = params self.model = None self.lambda_param = None self.scope = None self.actual_ts_len = None self.sts = None def fit(self, input_data): """ Class fit STLForecast arima model on data :param input_data: data with features, target and ids to process """ source_ts = np.array(input_data.features) # Save actual time series length self.actual_ts_len = len(source_ts) self.sts = source_ts if not self.params: # Default data self.params = {'p': 2, 'd': 0, 'q': 2, 'period': 365} p = int(self.params.get('p')) d = int(self.params.get('d')) q = int(self.params.get('q')) period = int(self.params.get('period')) params = {'period': period, 'model_kwargs': {'order': (p, d, q)}} self.model = STLForecast(source_ts, ARIMA, **params).fit() return self.model def predict(self, input_data, is_fit_pipeline_stage: bool): """ Method for time series prediction on forecast length :param input_data: data with features, target and ids to process :param is_fit_pipeline_stage: is this fit or predict stage for pipeline :return output_data: output data with smoothed time series """ parameters = input_data.task.task_params forecast_length = parameters.forecast_length old_idx = input_data.idx target = input_data.target # For training pipeline get fitted data if is_fit_pipeline_stage: fitted_values = self.model.get_prediction(start=old_idx[0], end=old_idx[-1]).predicted_mean diff = int(self.actual_ts_len) - len(fitted_values) # If first elements skipped if diff != 0: # Fill nans with first values first_element = fitted_values[0] first_elements = [first_element] * diff first_elements.extend(list(fitted_values)) fitted_values = np.array(first_elements) _, predict = ts_to_table(idx=old_idx, time_series=fitted_values, window_size=forecast_length) new_idx, target_columns = ts_to_table(idx=old_idx, time_series=target, window_size=forecast_length) # Update idx and target input_data.idx = new_idx input_data.target = target_columns # For predict stage we can make prediction else: start_id = old_idx[-1] - forecast_length + 1 end_id = old_idx[-1] predicted = self.model.get_prediction(start=start_id, end=end_id).predicted_mean # Convert one-dim array as column predict = np.array(predicted).reshape(1, -1) new_idx = np.arange(start_id, end_id + 1) # Update idx input_data.idx = new_idx # Update idx and features output_data = self._convert_to_output(input_data, predict=predict, data_type=DataTypesEnum.table) return output_data def get_params(self): return self.params class CLSTMImplementation(ModelImplementation): def __init__(self, log: Log = None, **params): super().__init__(log) self.params = params self.epochs = params.get("num_epochs") self.batch_size = params.get("batch_size") self.learning_rate = params.get("learning_rate") self.window_size = int(params.get("window_size")) self.teacher_forcing = int(params.get("teacher_forcing")) self.device = self._get_device() self.model = LSTMNetwork( hidden_size=int(params.get("hidden_size")), cnn1_kernel_size=int(params.get("cnn1_kernel_size")), cnn1_output_size=int(params.get("cnn1_output_size")), cnn2_kernel_size=int(params.get("cnn2_kernel_size")), cnn2_output_size=int(params.get("cnn2_output_size")) ) self.optim_dict = { 'adam': torch.optim.Adam(self.model.parameters(), lr=self.learning_rate), 'sgd': torch.optim.SGD(self.model.parameters(), lr=self.learning_rate) } self.loss_dict = { 'mae': nn.L1Loss, 'mse': nn.MSELoss } self.scaler = StandardScaler() self.optimizer = self.optim_dict[params.get("optimizer")] self.criterion = self.loss_dict[params.get("loss")]() def fit(self, train_data: InputData): """ Class fit ar model on data. Implementation uses the idea of teacher forcing. That means model learns to predict data when horizon != 1. It uses real values or previous model output to predict next value. self.teacher_forcing param is used to control probability of using real y values. :param train_data: data with features, target and ids to process """ self.model = self.model.to(self.device) data_loader, forecast_length = self._create_dataloader(train_data) self.model.train() for epoch in range(self.epochs): for x, y in data_loader: self.optimizer.zero_grad() x = x.to(self.device) y = y.to(self.device) final_output = self._apply_teacher_forcing(x, y, forecast_length) loss = self.criterion(final_output, y) loss.backward() self.optimizer.step() return self.model def _apply_teacher_forcing(self, x, y, forecast_length): final_output = None for i in range(forecast_length): self.model.init_hidden(x.shape[0], self.device) output = self.model(x.unsqueeze(1)).squeeze(0) if np.random.random_sample() > self.teacher_forcing: x = torch.hstack((x[:, 1:], output)) else: x = torch.hstack((x, y[:, i].unsqueeze(1))) if final_output is not None: final_output = torch.hstack((final_output, output)) else: final_output = output return final_output def predict(self, input_data: InputData, is_fit_pipeline_stage: Optional[bool]): """ Method for time series prediction on forecast length :param input_data: data with features, target and ids to process :param is_fit_pipeline_stage: is this fit or predict stage for pipeline :return output_data: output data with smoothed time series """ self.model.eval() input_data_new = copy(input_data) old_idx = input_data_new.idx forecast_length = input_data.task.task_params.forecast_length if is_fit_pipeline_stage: new_idx, lagged_table = ts_to_table(idx=old_idx, time_series=input_data_new.features, window_size=self.window_size) final_idx, features_columns, final_target = prepare_target(idx=new_idx, features_columns=lagged_table, target=input_data_new.target, forecast_length=forecast_length) input_data_new.idx = final_idx input_data_new.features = features_columns input_data_new.target = final_target else: input_data_new.features = input_data_new.features[-self.window_size:].reshape(1, -1) input_data_new.idx = input_data_new.idx[-forecast_length:] predict = self._out_of_sample_ts_forecast(input_data_new) output_data = self._convert_to_output(input_data_new, predict=predict, data_type=DataTypesEnum.table) return output_data def _predict(self, input_data: InputData): features_scaled = self._transform_scaler_features(input_data) x = torch.Tensor(features_scaled).to(self.device) self.model.init_hidden(x.shape[0], self.device) predict = self.model(x.unsqueeze(1)).squeeze(0).cpu().detach().numpy() return self._inverse_transform_scaler(predict) def _out_of_sample_ts_forecast(self, input_data: InputData) -> np.array: """ Method for out_of_sample CLSTM forecasting (use previous outputs as next inputs) :param input_data: data with features, target and ids to process :return np.array: np.array with predicted values to process it into output_data """ input_data_new = copy(input_data) # Prepare data for time series forecasting task = input_data_new.task exception_if_not_ts_task(task) pre_history_ts = np.array(input_data_new.features) number_of_iterations = task.task_params.forecast_length final_forecast = None for _ in range(0, number_of_iterations): with torch.no_grad(): iter_predict = self._predict(input_data_new) if final_forecast is not None: final_forecast = np.hstack((final_forecast, iter_predict)) else: final_forecast = iter_predict # Add prediction to the historical data - update it pre_history_ts = np.hstack((pre_history_ts[:, 1:], iter_predict)) # Prepare InputData for next iteration input_data_new = _update_input(pre_history_ts, number_of_iterations, task) return final_forecast def _fit_transform_scaler(self, data: InputData): f_scaled = self.scaler.fit_transform(data.features.reshape(-1, 1)).reshape(-1) t_scaled = self.scaler.transform(data.target.reshape(-1, 1)).reshape(-1) return f_scaled, t_scaled def _inverse_transform_scaler(self, data: np.ndarray): start_shape = data.shape return self.scaler.inverse_transform(data.reshape(-1, 1)).reshape(start_shape) def _transform_scaler_features(self, data: InputData): start_shape = data.features.shape return self.scaler.transform(data.features.reshape(-1, 1)).reshape(start_shape) def _transform_scaler_target(self, data: InputData): start_shape = data.features.shape return self.scaler.transform(data.target.reshape(-1, 1)).reshape(start_shape) def get_params(self): return self.params @staticmethod def _get_device(): if torch.cuda.is_available(): device = 'cuda:0' else: device = 'cpu' return device def _create_dataloader(self, input_data: InputData): """ Method for creating torch.utils.data.DataLoader object from input_data Generate lag tables and process it into DataLoader :param input_data: data with features, target and ids to process :return torch.utils.data.DataLoader: DataLoader with train data """ forecast_length = input_data.task.task_params.forecast_length features_scaled, target_scaled = self._fit_transform_scaler(input_data) new_idx, lagged_table = ts_to_table(idx=input_data.idx, time_series=features_scaled, window_size=self.window_size) final_idx, features_columns, final_target = prepare_target(idx=new_idx, features_columns=lagged_table, target=target_scaled, forecast_length=forecast_length) x = torch.from_numpy(features_columns.copy()).float() y = torch.from_numpy(final_target.copy()).float() return DataLoader(TensorDataset(x, y), batch_size=self.batch_size), forecast_length class LSTMNetwork(nn.Module): def __init__(self, hidden_size=200, cnn1_kernel_size=5, cnn1_output_size=16, cnn2_kernel_size=3, cnn2_output_size=32, ): super().__init__() self.hidden_size = hidden_size self.conv_block1 = nn.Sequential( nn.Conv1d(in_channels=1, out_channels=cnn1_output_size, kernel_size=cnn1_kernel_size), nn.ReLU() ) self.conv_block2 = nn.Sequential( nn.Conv1d(in_channels=cnn1_output_size, out_channels=cnn2_output_size, kernel_size=cnn2_kernel_size), nn.ReLU() ) self.lstm = nn.LSTM(cnn2_output_size, self.hidden_size, dropout=0.1) self.hidden_cell = None self.linear = nn.Linear(self.hidden_size * 2, 1) def init_hidden(self, batch_size, device): self.hidden_cell = (torch.zeros(1, batch_size, self.hidden_size).to(device), torch.zeros(1, batch_size, self.hidden_size).to(device)) def forward(self, x): if self.hidden_cell is None: raise Exception x = self.conv_block1(x) x = self.conv_block2(x) x = x.permute(2, 0, 1) out, self.hidden_cell = self.lstm(x, self.hidden_cell) hidden_cat = torch.cat([self.hidden_cell[0], self.hidden_cell[1]], dim=2) predictions = self.linear(hidden_cat) return predictions
rapifireio/rapifire-android-client
app/src/main/java/com/rapifire/rapifireclient/domain/model/User.java
<filename>app/src/main/java/com/rapifire/rapifireclient/domain/model/User.java package com.rapifire.rapifireclient.domain.model; /** * Created by ktomek on 05.12.15. */ public class User { private String username; private String authId; private String authKey; private String password; public User(String username, String authId, String authKey, String password) { this.username = username; this.authId = authId; this.authKey = authKey; this.password = password; } public String getPassword() { return password; } public String getAuthKey() { return authKey; } public String getAuthId() { return authId; } public String getUsername() { return username; } }
AoHRuthless/King-of-the-Hill
src/com/valygard/KotH/command/CommandInfo.java
<gh_stars>1-10 /** * CommandInfo.java is part of King of the Hill. */ package com.valygard.KotH.command; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * @author Anand * */ @Retention(RetentionPolicy.RUNTIME) public @interface CommandInfo { /** * The name of the command. * In </koth addarena <arena>>, the command name is addarena. */ public String name(); /** * What the command actually does; ex: * <Add a new KotH arena> * * Default description if unspecified. */ public String desc() default "A command for King of the Hill."; /** * Allows variation in the command itself. */ public String pattern(); /** * Is the command only accessible for players? */ public boolean playerOnly() default false; /** * Get the amount of args required in order for the command to execute. * Remember, we trim the args so in </koth [args1] [args2]>, args2 is the args[0] */ public int argsRequired() default 1; }
robwormald/gitrank
app/packages/npm/stringstream@0.0.4.js
module.exports = require("npm:stringstream@0.0.4/stringstream");
iamtofr/Stundenplaner
BackEnd/Schemas/schemaToAlgorithm.js
<gh_stars>1-10 /** * This module defines a schema of objects for the algorithmus. * It using mongoose as framework. * * @type {Schema} */ const mongoose = require('mongoose'); let Schema = mongoose.Schema; let toAlgorithm = new Schema({ periods: [{type: Schema.Types.ObjectId, ref: 'period', required: true}], teachers: [{type: Schema.Types.ObjectId, ref: 'teacher', required: true}], rooms: [{type: Schema.Types.ObjectId, ref: 'room', required: true}], courses: [{type: Schema.Types.ObjectId, ref: 'course', required: true}], subjects: [{type: Schema.Types.ObjectId, ref: 'subject', required: true}], score: {type: Number, required: false} }); module.exports = toAlgorithm;
sachinshrestha483/AlgoDS
src/algo/dp/MinimizeArraySize.java
<reponame>sachinshrestha483/AlgoDS /* Problem Statement: Find minimum possible size of array with given rules for removing elements Description: Given an array of numbers and a constant k, minimize size of array with following rules for removing elements. Exactly three elements can be removed at one go. The removed three elements must be adjacent in array, i.e., arr[i], arr[i+1], arr[i+2]. And the second element must be k greater than first and third element must be k greater than second, i.e., arr[i+1] – arr[i] = k and arr[i+2]-arr[i+1] = k. Testcses that both solutions were tested against: Input: arr[] = {100, 101, 105, 2, 10, 12, 14, 4, 22, 24, 26, 6, 500}, k = 2 Output: 4 First we can remove: {10,12,14} and {22,24,26} Second we can remove: {2,4,6} Remaining that can't be removed: {100,101,105,500} Input: arr[] = {2, 3, 4, 5, 6, 4}, k = 1 Output: 0 We can actually remove all elements. First remove 4, 5, 6 => We get {2, 3, 4} Now remove 2, 3, 4 => We get empty array {} Input: arr[] = {2, 3, 4, 7, 6, 4}, k = 1 Output: 3 We can only remove 2 3 4 Input: arr[] = {1,2},k=1 Output: 2 */ package algo.dp; public class MinimizeArraySize{ /* Brute force solution low: first index of array arr[] high: last index of array arr[] arr[]: user input array k: constant */ public int noDPSol(int low, int high, int arr[], int k) { //base case if ((high-low+1)<3) return high-low+1; //Considering first element cannot be removed int res = 1 + noDPSol(low+1, high, arr, k); for (int i=low +1 ; i<=high-1;i++) for (int j = i+1; j<=high; j++) { // checking if all elements between "low" and "j" can be removed if(((arr[i]-arr[low])==k) && ((arr[j]-arr[i])==k) && noDPSol(low+1,i-1,arr,k)==0 && noDPSol(i+1,j-1,arr,k)==0) { res = Math.min(res,noDPSol(j+1,high,arr,k)); } } return res; } /* DP based solution low: first index of array arr[] high: last index of array arr[] arr[]: user input array k: constant dp[][]: lookup array prevents from recalculation of a subproblem. (should be initialized with -1 as all index values) */ public int dpSol(int low, int high, int arr[], int k,int dp[][]) { //base case if ((high-low+1)<3) return high-low+1; //lookup array //returns already calculated // subproblem result. if(dp[low][high] !=-1) return dp[low][high]; //Considering first element cannot be removed int res = 1 + dpSol(low+1, high, arr, k,dp); for (int i=low +1 ; i<=high-1;i++) for (int j = i+1; j<=high; j++) { if(((arr[i]-arr[low])==k) && ((arr[j]-arr[i])==k) && dpSol(low+1,i-1,arr,k,dp)==0 && dpSol(i+1,j-1,arr,k,dp)==0) { // checking if all elements between "low" and "j" can be removed res = Math.min(res,dpSol(j+1,high,arr,k,dp)); } } return dp[low][high] = res; } }
jkanche/epiviz-electron
src/src/epiviz/ui/charts/custom-setting.js
/** * Created by <NAME> ( florinc [at] umd [dot] edu ) * Date: 3/29/14 * Time: 2:52 PM */ goog.provide('epiviz.ui.charts.CustomSetting'); /** * @param {string} id * @param {epiviz.ui.charts.CustomSetting.Type} type * @param defaultValue * @param {string} [label] * @param {Array} [possibleValues] * @constructor * @struct */ epiviz.ui.charts.CustomSetting = function(id, type, defaultValue, label, possibleValues) { /** * @type {string} */ this.id = id; /** * @type {epiviz.ui.charts.CustomSetting.Type} */ this.type = type; this.defaultValue = defaultValue; /** * @type {string} */ this.label = label || id; /** * @type {Array} */ this.possibleValues = possibleValues || null; }; /** * @enum {string} */ epiviz.ui.charts.CustomSetting.Type = { NUMBER: 'number', STRING: 'string', ARRAY: 'array', BOOLEAN: 'boolean', CATEGORICAL: 'categorical', MEASUREMENTS_METADATA: 'measurementsMetadata', MEASUREMENTS_ANNOTATION: 'measurementsAnnotation' }; /** * @type {string} * @constant */ epiviz.ui.charts.CustomSetting.DEFAULT = 'default';
Falcons-Robocup/code
packages/visualizer/include/int/widgets/Field/Annotation/RobotLabel.h
<gh_stars>1-10 // Copyright 2016 <NAME> (Falcons) // SPDX-License-Identifier: Apache-2.0 /* * RobotLabel.h * * Created on: November 20, 2016 * Author: <NAME> */ #ifndef ROBOTLABEL_H #define ROBOTLABEL_H #include <vtkFollower.h> #include <vtkTextProperty.h> #include <vtkTextActor.h> #include <vtkVectorText.h> #include <vtkTransform.h> #include <vtkTransformFilter.h> #include <sstream> // Internal: #include "int/widgets/Field/Visualization/RobotVisualization.h" #include "Annotation.h" /* * Class that floats a label next to a robot */ class RobotLabel : public Annotation, public vtkFollower { public: static RobotLabel* New() { return new RobotLabel(); } void initialize(int robotID, vtkRenderer *renderer, RobotVisualization* anchor); public Q_SLOTS: virtual void onAnchorPositionChanged(PositionVelocity& posvel) override; virtual void onAnchorVisibilityChanged(bool visible) override; private: void addLabel(int robotID, vtkRenderer* renderer); }; #endif // ROBOTLABEL_H
turlodales/theos-projects
app_dumps/VKClient.folder/PhotoRowCell.h
/** * This header is generated by class-dump-z 0.2-0. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: (null) */ #import "VKMCell.h" @class VKPhotoRow, NSArray; __attribute__((visibility("hidden"))) @interface PhotoRowCell : VKMCell { NSArray* _previews; } @property(retain, nonatomic) VKPhotoRow* domain; @property(readonly, retain, nonatomic) NSArray* previews; +(void)prerender:(id)prerender; +(id)renderPhotosRow:(id)row max:(int)max width:(float)width height:(float)height padding:(float)padding zoomMax:(float)max6 zoomMin:(float)min; +(void)initialize; -(void).cxx_destruct; -(id)visibleThumbnails; -(void)thumbnailView:(id)view selected:(id)selected; -(void)attach:(id)attach expectedReuse:(double)reuse; -(void)prepareForReuse; -(void)dealloc; -(id)initWithStyle:(int)style reuseIdentifier:(id)identifier; @end
cloud5innovation/coopers-furnitute
database/migrations/20200707183159_addOnDeleteToColors.js
exports.up = function(knex) { return knex.schema.alterTable("colors", (table) => { table.dropForeign("product_title"); table .foreign("product_title") .references("products.title") .onDelete("CASCADE") .onUpdate("CASCADE"); }); } exports.down = function(knex) { return knex.schema.alterTable("colors", (table) => { table.dropForeign("product_title"); table .foreign("product_title") .references("products.title") .onDelete("NO ACTION") onUpdate("NO ACTION"); }); }
dvla/vehicles-presentation-common
app/uk/gov/dvla/vehicles/presentation/common/model/FeedbackForm.scala
package uk.gov.dvla.vehicles.presentation.common.model import play.api.data.Forms.{mapping, nonEmptyText, text} import play.api.libs.json.Json case class FeedbackForm(rating: String, feedback: String) object FeedbackForm { object Form { final val rating = "rating" final val feedback = "feedback" final val Mapping = mapping( rating -> nonEmptyText.verifying(play.api.data.validation.Constraints.pattern("""[1-5]""".r)), feedback -> text(maxLength = 500) )(FeedbackForm.apply)(FeedbackForm.unapply) } implicit val JsonFormat = Json.format[FeedbackForm] }
ayushworks/sttp
model/shared/src/main/scala/sttp/model/ws/WebSocketException.scala
<reponame>ayushworks/sttp<filename>model/shared/src/main/scala/sttp/model/ws/WebSocketException.scala package sttp.model.ws trait WebSocketError class WebSocketClosed() extends Exception with WebSocketError class WebSocketBufferFull() extends Exception with WebSocketError
se-simon/ScrewBox
screwbox-playground-debo/src/main/java/de/suzufa/screwbox/playground/debo/systems/DebugConfigSystem.java
<reponame>se-simon/ScrewBox package de.suzufa.screwbox.playground.debo.systems; import de.suzufa.screwbox.core.Engine; import de.suzufa.screwbox.core.entityengine.EntitySystem; import de.suzufa.screwbox.core.entityengine.systems.PhysicsDebugSystem; import de.suzufa.screwbox.core.keyboard.Key; public class DebugConfigSystem implements EntitySystem { @Override public void update(final Engine engine) { if (engine.keyboard().justPressed(Key.O)) { switchSystem(engine, new PhysicsDebugSystem()); } if (engine.keyboard().justPressed(Key.L)) { switchSystem(engine, new ShowFpsSystem()); engine.loop().setTargetFps(engine.entityEngine().isSystemPresent(ShowFpsSystem.class) ? 120 : 10000); } } private void switchSystem(final Engine engine, final EntitySystem system) { if (engine.entityEngine().isSystemPresent(system.getClass())) { engine.entityEngine().remove(system.getClass()); } else { engine.entityEngine().add(system); } } }
luxcium/questrade-ts
dist/src/private/api/MarketsCalls/_getMarketsQuotesOptions/_getQuotesOptionsByIds.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var _getMarketsQuotesOptions_1 = require("./_getMarketsQuotesOptions"); exports._getQuotesOptionsByIds = function (credentials) { return function (optionIds) { return tslib_1.__awaiter(void 0, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { try { return [2 /*return*/, _getMarketsQuotesOptions_1._getMarketsQuotesOptions(credentials)(optionIds, 0, '', null, 0, 0)]; } catch (error) { console.error(error.message); return [2 /*return*/, []]; } return [2 /*return*/]; }); }); }; }; //# sourceMappingURL=_getQuotesOptionsByIds.js.map
fancylou/o2oa
x_common_core_application/src/main/java/com/x/common/core/application/definition/PasswordDefinition.java
<reponame>fancylou/o2oa package com.x.common.core.application.definition; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import com.x.base.core.gson.GsonPropertyObject; public class PasswordDefinition extends LoadableDefinition { public static final String RegularExpression_Script = "^\\((.+?)\\)$"; public static PasswordDefinition INSTANCE; public static final String FILE_NAME = "passwordDefinition.json"; private String key; private Integer passwordPeriod; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Integer getPasswordPeriod() { return passwordPeriod; } public void setPasswordPeriod(Integer passwordPeriod) { this.passwordPeriod = passwordPeriod; } @Test public void test1() { Pattern pattern = Pattern.compile(RegularExpression_Script); Matcher matcher = pattern.matcher("(person.getName())"); if (matcher.matches()) { System.out.println(matcher.group(1)); } } }
nmcl/wfswarm-example-arjuna-old
graalvm/transactions/fork/narayana/ArjunaJTS/jts/classes/com/arjuna/ats/internal/jts/utils/Helper.java
/* * JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a full listing * of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */ /* * Copyright (C) 2001, 2002, * * Hewlett-Packard Arjuna Labs, * Newcastle upon Tyne, * Tyne and Wear, * UK. * * $Id: Helper.java 2342 2006-03-30 13:06:17Z $ */ package com.arjuna.ats.internal.jts.utils; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.CompletionStatus; import org.omg.CORBA.NO_MEMORY; import org.omg.CosTransactions.Coordinator; import com.arjuna.ArjunaOTS.UidCoordinator; import com.arjuna.ats.arjuna.common.Uid; import com.arjuna.ats.arjuna.coordinator.ActionManager; import com.arjuna.ats.arjuna.coordinator.BasicAction; import com.arjuna.ats.internal.jts.orbspecific.ControlImple; import com.arjuna.ats.internal.jts.orbspecific.interposition.ServerControl; public class Helper { /** * Given a Control_ptr determine if this is a reference to a local * action, and if so return the raw BasicAction pointer. */ public static final BasicAction localAction (org.omg.CosTransactions.Control control) { if (control == null) return null; if (control instanceof ControlImple) { try { ControlImple c = (ControlImple) control; return (BasicAction) c.getImplHandle(); } catch (Exception e) { } } /* * Can we not use is_local within visibroker? */ try { UidCoordinator coord = Helper.getUidCoordinator(control); if (coord != null) { Uid u = Helper.getUid(coord); coord = null; return ActionManager.manager().get(u); } else throw new BAD_PARAM(); } catch (Exception e) { /* * Can't be an Arjuna action, so ignore. */ } return null; } public static final ControlImple localControl (org.omg.CosTransactions.Control control) { if (control == null) return null; if (control instanceof ControlImple) return (ControlImple) control; try { UidCoordinator uidCoord = Helper.getUidCoordinator(control); if (uidCoord != null) { Uid u = Helper.getUid(uidCoord); ControlImple toReturn = null; uidCoord = null; /* * allControls only contains local controls. */ if (ControlImple.allControls != null) { synchronized (ControlImple.allControls) { toReturn = (ControlImple) ControlImple.allControls.get(u); } } if (toReturn == null) { if (ServerControl.allServerControls != null) { synchronized (ServerControl.allServerControls) { toReturn = (ControlImple) ServerControl.allServerControls.get(u); } } } u = null; return toReturn; } else throw new BAD_PARAM(0, CompletionStatus.COMPLETED_NO); } catch (Exception e) { /* * Can't be an Arjuna action, so ignore. */ } return null; } public static final UidCoordinator getUidCoordinator (org.omg.CosTransactions.Control control) { if (control == null) return null; UidCoordinator toReturn = null; try { Coordinator coord = control.get_coordinator(); if (coord != null) { toReturn = getUidCoordinator(coord); coord = null; } else throw new BAD_PARAM(0, CompletionStatus.COMPLETED_NO); } catch (Exception e) { /* * Can't be an Arjuna action, so ignore. */ toReturn = null; } return toReturn; } public static final UidCoordinator getUidCoordinator (Coordinator coord) { if (coord == null) return null; UidCoordinator toReturn = null; try { toReturn = com.arjuna.ArjunaOTS.UidCoordinatorHelper.narrow(coord); if (toReturn == null) throw new BAD_PARAM(0, CompletionStatus.COMPLETED_NO); } catch (Exception e) { /* * Can't be an Arjuna action, so ignore. */ toReturn = null; } return toReturn; } public static final boolean isUidCoordinator (Coordinator ref) { UidCoordinator ptr = getUidCoordinator(ref); return ((ptr == null) ? false : true); } public static final Uid getUid (UidCoordinator coord) { if (coord == null) return Uid.nullUid(); String theUid = null; Uid uid = null; /* * Try twice, and if this still fails then * throw NO_MEMORY. */ for (int i = 0; i < 1; i++) { try { theUid = coord.uid(); uid = new Uid(theUid); theUid = null; return uid; } catch (OutOfMemoryError e) { System.gc(); } } throw new NO_MEMORY(0, CompletionStatus.COMPLETED_NO); } }
tblink-rpc/tblink-rpc-core
cpp/include/tblink_rpc/IParamValBool.h
/* * IParamValInt.h * * Created on: Apr 3, 2021 * Author: mballance */ #pragma once #include "IParamVal.h" namespace tblink_rpc_core { class IParamValBool; typedef std::shared_ptr<IParamValBool> IParamValBoolSP; typedef std::unique_ptr<IParamValBool> IParamValBoolUP; class IParamValBool : public virtual IParamVal { public: virtual ~IParamValBool() { } virtual bool val() = 0; virtual IParamValBool *clone() = 0; }; }
LaudateCorpus1/PCVT
src/main/java/data/persist/certificate/DeviceAssociatedCertificate.java
<reponame>LaudateCorpus1/PCVT<gh_stars>1-10 package data.persist.certificate; //import javax.persistence.JoinColumn; //import javax.persistence.ManyToOne; //import javax.persistence.MappedSuperclass; import java.io.IOException; import java.nio.file.Path; import hirs.data.persist.Device; import hirs.data.persist.certificate.Certificate; /** * A Certificate that is associated with a single device. * * @see Certificate */ //@MappedSuperclass public abstract class DeviceAssociatedCertificate extends Certificate { // a device can have multiple certs of this type. // @ManyToOne // @JoinColumn(name = "device_id") private Device device; /** * Holds the name of the entity 'DEVICE_ID' field. */ protected static final String DEVICE_ID_FIELD = "device.id"; /** * Default Constructor. */ DeviceAssociatedCertificate() { } /** * Construct a new Certificate by parsing the file at the given path. The given certificate * should represent either an X509 certificate or X509 attribute certificate. * * @param certificatePath the path on disk to a certificate * @throws IOException if there is a problem reading the file */ DeviceAssociatedCertificate(final Path certificatePath) throws IOException { super(certificatePath); } /** * Construct a new Certificate given its binary contents. The given certificate should * represent either an X509 certificate or X509 attribute certificate. * * @param certificateBytes the contents of a certificate file * @throws IOException if there is a problem extracting information from the certificate */ DeviceAssociatedCertificate(final byte[] certificateBytes) throws IOException { super(certificateBytes); } /** * Gets the device. * @return the device */ public Device getDevice() { return device; } /** * Sets the device. * @param device the device */ public void setDevice(final Device device) { this.device = device; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); if (device != null) { sb.append(String.format("%nDevice -> %s", getDevice().toString())); } return sb.toString(); } }
phil-hanisch/rulewerk
rulewerk-examples/src/main/java/org/semanticweb/rulewerk/examples/AspExample.java
package org.semanticweb.rulewerk.examples; /*- * #%L * Rulewerk Examples * %% * Copyright (C) 2018 - 2020 Rulewerk Developers * %% * 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. * #L% */ import java.io.*; import java.util.*; import java.util.stream.Collectors; import org.apache.commons.cli.*; import org.semanticweb.rulewerk.core.model.api.ShowStatement; import org.semanticweb.rulewerk.core.model.implementation.Grounder; import org.semanticweb.rulewerk.core.model.implementation.ShowStatementImpl; import org.semanticweb.rulewerk.core.reasoner.KnowledgeBase; import org.semanticweb.rulewerk.core.reasoner.LogLevel; import org.semanticweb.rulewerk.core.reasoner.Reasoner; import org.semanticweb.rulewerk.parser.ParsingException; import org.semanticweb.rulewerk.parser.RuleParser; import org.semanticweb.rulewerk.core.model.api.AspRule; import org.semanticweb.rulewerk.core.model.api.Predicate; import org.semanticweb.rulewerk.reasoner.vlog.VLogReasoner; /** * This example grounds a given asp encoding by using VLog. The grounding can be shown either in a textual format or in * aspif. Alternatively, the grounding can be forwarded to clasp to compute the answer set(s). * * @author <NAME> */ public class AspExample { public static void main(final String[] args) throws IOException, ParsingException { System.out.println("Ready..."); long startTimeOverall, startTimeParsing, startTimeVLog, startTimeOutput, startTimeClasp; long endTimeOverall, endTimeParsing, endTimeVLog, endTimeOutput, endTimeClasp; String[] programs; String inputPath, outputPath, instance, system; CommandLine line; boolean textFormat; BufferedWriter outputWriter; // Get start time startTimeOverall = System.nanoTime(); // Prepare command line options Options options = new Options(); options.addOption(Option.builder("t").longOpt("text").desc("Display the grounding in a human-readable format").build()); options.addOption(Option.builder("a").longOpt("aspif").desc("Display the grounding in aspif").build()); options.addOption(Option.builder("o").longOpt("output").desc("Set the output file").required().hasArg().numberOfArgs(1).build()); options.addOption(Option.builder("p").longOpt("java-path").desc("Use java project path to input and output files").build()); options.addOption(Option.builder("P").longOpt("path").desc("Set the path to input and output files").hasArg().build()); options.addOption(Option.builder("i").longOpt("instance-name").desc("Set the instance name (matters only for identifying output later)").hasArg().build()); options.addOption(Option.builder("s").longOpt("system-name").desc("Set the system name (matters only for identifying output later)").hasArg().build()); // Parse command line arguments CommandLineParser parser = new DefaultParser(); try { // parse the command line arguments line = parser.parse(options, args); programs = line.getArgs(); textFormat = line.hasOption("t"); inputPath = line.getOptionValue("P", line.hasOption("p") ? ExamplesUtils.INPUT_FOLDER : ""); outputPath = line.getOptionValue("P", line.hasOption("p") ? ExamplesUtils.OUTPUT_FOLDER : ""); outputWriter = new BufferedWriter(new FileWriter(outputPath + line.getOptionValue("o"))); instance = line.getOptionValue("i", "unnamed_instance"); system = line.getOptionValue("s", "Grounding"); } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); return; } startTimeParsing = System.nanoTime(); // Load rules and facts from asp file ExamplesUtils.configureLogging(); System.out.println("Load rules and facts..."); KnowledgeBase kb; try { List<FileInputStream> inputStreamList = new ArrayList<>(); for (String program : programs) { inputStreamList.add(new FileInputStream(inputPath + program)); } SequenceInputStream inputStream = new SequenceInputStream(Collections.enumeration(inputStreamList)); kb = RuleParser.parseAsp(inputStream); } catch (final ParsingException e) { System.out.println("Failed to parse rules: " + e.getMessage()); return; } System.out.println("...done"); endTimeParsing = System.nanoTime(); // no show statement implies to show everything if (kb.getShowStatements().isEmpty()) { List<ShowStatement> showStatements = kb.getPredicates().stream().map(ShowStatementImpl::new).collect(Collectors.toList()); kb.addStatements(showStatements); } // Analyse knowledge base Set<Predicate> approximatedPredicates = kb.analyseAspRulesForApproximatedPredicates(); // Transform asp rules into standard rules for (AspRule rule : kb.getAspRules()) { kb.addStatements(rule.getApproximation(approximatedPredicates)); } /* Execute reasoning */ System.out.println("Trigger reasoning..."); startTimeVLog = System.nanoTime(); try (Reasoner reasoner = new VLogReasoner(kb)) { reasoner.setLogFile(outputPath + "vlog.log"); reasoner.setLogLevel(LogLevel.DEBUG); /* Initialise reasoner and compute inferences */ reasoner.reason(); endTimeVLog = System.nanoTime(); startTimeOutput = System.nanoTime(); if (line.hasOption("t") || line.hasOption("a")) { // Compute only the grounding Grounder grounder = new Grounder(reasoner, kb, outputWriter, approximatedPredicates, textFormat); grounder.groundKnowledgeBase(); outputWriter.close(); endTimeOutput = System.nanoTime(); } else { // Compute the answer sets Process clasp = Runtime.getRuntime().exec("clasp"); BufferedWriter writerToClasp = new BufferedWriter(new OutputStreamWriter(clasp.getOutputStream())); Grounder grounder = new Grounder(reasoner, kb, writerToClasp, approximatedPredicates, false); grounder.groundKnowledgeBase(); writerToClasp.close(); endTimeOutput = System.nanoTime(); // Show the answer set startTimeClasp = System.nanoTime(); System.out.println("Wait for clasp"); try { clasp.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } BufferedReader readerFromClasp = new BufferedReader(new InputStreamReader(clasp.getInputStream())); String s; while ((s = readerFromClasp.readLine()) != null) { outputWriter.write(s); outputWriter.newLine(); } outputWriter.close(); clasp.destroy(); endTimeClasp = System.nanoTime(); System.out.println("TIMING [s] # " + instance + " # Clasp # " + ((float) (endTimeClasp - startTimeClasp) / 1000000000)); } } endTimeOverall = System.nanoTime(); System.out.println("TIMING [s] # " + instance + " # Parsing # " + ((float) (endTimeParsing - startTimeParsing) / 1000000000)); System.out.println("TIMING [s] # " + instance + " # VLog # " + ((float) (endTimeVLog - startTimeVLog) / 1000000000)); System.out.println("TIMING [s] # " + instance + " # " + system + " # " + ((float) (endTimeOutput - startTimeOutput) / 1000000000)); System.out.println("TIMING [s] # " + instance + " # " + system + "Overall # " + ((float) (endTimeOverall - startTimeOverall) / 1000000000)); } }
venanciolm/aurius
aurius-impl/src/main/java/com/farmafene/aurius/impl/DatoRegistroTypeDecimal.java
/* * Copyright (c) 2009-2010 <EMAIL> * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.farmafene.aurius.impl; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import com.farmafene.aurius.AuriusValidationException; import com.farmafene.aurius.DatoRegistro; /** * Implementación de un Decimal(P,S) * * @author vlopez * @since 1.0.0 */ @SuppressWarnings("serial") public class DatoRegistroTypeDecimal extends DatoRegistroAbstract<BigDecimal> implements DatoRegistro<BigDecimal> { private Long maxDigitos; private Long maxDecimales; private String mascara; private BigDecimal minExclusive; private BigDecimal minInclusive; private BigDecimal maxExclusive; private BigDecimal maxInclusive; /** * Constructor * * @since 1.0.0 */ public DatoRegistroTypeDecimal(String id) { super(id); } /** * {@inheritDoc} * * @see DatoRegistro#toString() * @since 1.0.0 */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append("={"); sb.append("id=").append(getId()); sb.append(", nombre=").append(getNombre()); if (null != getMaxDigitos()) { sb.append(", maxDigitos").append(getMaxDigitos()); } if (null != getMaxDecimales()) { sb.append(", maxDecimales=").append(getMaxDecimales()); } if (null != getMascara()) { sb.append(", mascara=").append(getMascara()); } if (null != getMinInclusive()) { sb.append(", minInclusive").append(getMinInclusive()); } if (null != getMinExclusive()) { sb.append(", minExclusive").append(getMinExclusive()); } if (null != getMaxInclusive()) { sb.append(", maxInclusive").append(getMaxInclusive()); } if (null != getMaxExclusive()) { sb.append(", maxExclusive").append(getMaxExclusive()); } sb.append("}"); return sb.toString(); } /** * {@inheritDoc} * * @see java.lang.Object#hashCode() * @since 1.0.0 */ @Override public int hashCode() { int hashCode = super.hashCode(); hashCode = hashCode * 31 + ((getMaxDigitos() == null) ? 0 : getMaxDigitos().hashCode()); hashCode = hashCode * 31 + ((getMaxDecimales() == null) ? 0 : getMaxDecimales() .hashCode()); hashCode = hashCode * 31 + ((getMascara() == null) ? 0 : getMascara().hashCode()); hashCode = hashCode * 31 + ((getMinInclusive() == null) ? 0 : getMinInclusive() .hashCode()); hashCode = hashCode * 31 + ((getMaxInclusive() == null) ? 0 : getMaxInclusive() .hashCode()); hashCode = hashCode * 31 + ((getMinExclusive() == null) ? 0 : getMinExclusive() .hashCode()); hashCode = hashCode * 31 + ((getMaxExclusive() == null) ? 0 : getMaxExclusive() .hashCode()); return hashCode; } /** * {@inheritDoc} * * @see java.lang.Object#equals(java.lang.Object) * @since 1.0.0 */ @Override public boolean equals(Object obj) { boolean iguales = false; if (obj instanceof DatoRegistroTypeDecimal) { iguales = this.hashCode() == obj.hashCode(); } return iguales; } /** * {@inheritDoc} * * @see com.farmafene.aurius.impl.DatoRegistroAbstract#fromString(java.lang.String * ) */ @Override protected BigDecimal fromString(String value) { try { return (BigDecimal) getDecimalFormat().parse(value); } catch (ParseException e) { throw new IllegalArgumentException(e); } } /** * {@inheritDoc} * * @see com.farmafene.aurius.impl.DatoRegistroAbstract#toStringValue(java.lang.Object) */ @Override protected String toStringValue(BigDecimal value) { return getDecimalFormat().format(value); } /** * {@inheritDoc} * * @see com.farmafene.aurius.impl.DatoRegistroAbstract#validaValor(java.lang.Object) */ @Override protected void validaValor(BigDecimal bd) throws AuriusValidationException { if (null != getMaxDigitos() && getLongitud(bd) > getMaxDigitos().intValue()) { throw new AuriusValidationException( "Longitud máxima superada; el valor introducido '" + bd + "', no cumple con la definición '" + this.toString() + "'"); } else if (getMaxDecimales() != null && bd.scale() > getMaxDecimales()) { throw new AuriusValidationException( "Numero de decimales inválido; el valor introducido '" + bd + "', no cumple con la definición '" + this.toString() + "'"); } else if (null != getMinInclusive() && bd.compareTo(getMinInclusive()) < 0) { throw new AuriusValidationException( "Valor minimo superado; el valor introducido '" + bd + "', no cumple con la definición '" + this.toString() + "'"); } else if (null != getMinExclusive() && bd.compareTo(getMinExclusive()) <= 0) { throw new AuriusValidationException( "Valor minimo superado; el valor introducido '" + bd + "', no cumple con la definición '" + this.toString() + "'"); } else if (null != getMaxInclusive() && bd.compareTo(getMaxInclusive()) > 0) { throw new AuriusValidationException( "Valor máximo superado; el valor introducido '" + bd + "', no cumple con la definición '" + this.toString() + "'"); } else if (null != getMaxExclusive() && bd.compareTo(getMaxExclusive()) >= 0) { throw new AuriusValidationException( "Valor máximo superado; el valor introducido '" + bd + "', no cumple con la definición '" + this.toString() + "'"); } else if (null != getMascara()) { try { if (!getStringNormalizado(bd).matches(getMascara())) { throw new AuriusValidationException( "Formato inválido; el valor introducido '" + bd + "', no cumple con la definición '" + this.toString() + "'"); } } catch (PatternSyntaxException e) { throw new AuriusValidationException( "Error en la máscara; el valor introducido '" + bd + "', no cumple con la definición '" + this.toString() + "'"); } } } /** * Obtenemos la longitud de un determinado BigDecimal * * @param bd * a evaluar * @return longitud normalizada de BigDecimal. */ private int getLongitud(BigDecimal bd) { int longitud = 0; if (bd.scale() < 0) { longitud = bd.precision() + bd.scale(); } else if (bd.precision() > bd.scale()) { longitud = bd.precision(); } else { longitud = bd.scale() + 1; } return longitud; } private String getStringNormalizado(BigDecimal bd) { DecimalFormat df = getDecimalFormat(); return df.format(bd); } private DecimalFormat getDecimalFormat() { DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); DecimalFormat df = new DecimalFormat(); df.setDecimalFormatSymbols(dfs); df.setMinimumIntegerDigits(1); df.setPositivePrefix("+"); df.setNegativeSuffix("-"); df.setGroupingUsed(false); df.setDecimalSeparatorAlwaysShown(false); df.setParseBigDecimal(true); return df; } /** * @return the maxDigitos */ public Long getMaxDigitos() { return maxDigitos; } /** * @param maxDigitos * the maxDigitos to set */ public void setPrecision(Long precision) { this.maxDigitos = precision; } /** * @return the maxDecimales */ public Long getMaxDecimales() { return maxDecimales; } /** * @param maxDecimales * the maxDecimales to set */ public void setEscala(Long escala) { this.maxDecimales = escala; } /** * @return the mascara */ public String getMascara() { return mascara; } /** * @param mascara * the mascara to set */ public void setMascara(String mascara) { this.mascara = null; try { Pattern.compile(mascara); this.mascara = mascara; } catch (Exception e) { } } /** * @return the minExclusive */ public BigDecimal getMinExclusive() { return minExclusive; } /** * @param minExclusive * the minExclusive to set */ public void setMinExclusive(BigDecimal minExclusive) { this.minExclusive = minExclusive; } /** * @return the minInclusive */ public BigDecimal getMinInclusive() { return minInclusive; } /** * @param minInclusive * the minInclusive to set */ public void setMinInclusive(BigDecimal minInclusive) { this.minInclusive = minInclusive; } /** * @return the maxExclusive */ public BigDecimal getMaxExclusive() { return maxExclusive; } /** * @param maxExclusive * the maxExclusive to set */ public void setMaxExclusive(BigDecimal maxExclusive) { this.maxExclusive = maxExclusive; } /** * @return the maxInclusive */ public BigDecimal getMaxInclusive() { return maxInclusive; } /** * @param maxInclusive * the maxInclusive to set */ public void setMaxInclusive(BigDecimal maxInclusive) { this.maxInclusive = maxInclusive; } @Override public Class<BigDecimal> getValueType() { return BigDecimal.class; } }
joegeisz/pylith
unittests/libtests/meshio/data/MeshDataCubitQuad.cc
<reponame>joegeisz/pylith<filename>unittests/libtests/meshio/data/MeshDataCubitQuad.cc<gh_stars>1-10 // -*- C++ -*- // // ====================================================================== // // <NAME>, U.S. Geological Survey // <NAME>, GNS Science // <NAME>, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ====================================================================== // #include "MeshDataCubitQuad.hh" const int pylith::meshio::MeshDataCubitQuad::_numVertices = 6; const int pylith::meshio::MeshDataCubitQuad::_spaceDim = 2; const int pylith::meshio::MeshDataCubitQuad::_numCells = 2; const int pylith::meshio::MeshDataCubitQuad::_cellDim = 2; const int pylith::meshio::MeshDataCubitQuad::_numCorners = 4; const PylithScalar pylith::meshio::MeshDataCubitQuad::_vertices[] = { 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 2.0, 0.0, 2.0, 1.0 }; const int pylith::meshio::MeshDataCubitQuad::_cells[] = { 0, 1, 2, 3, 1, 4, 5, 2 }; const int pylith::meshio::MeshDataCubitQuad::_materialIds[] = { 10, 11 }; const int pylith::meshio::MeshDataCubitQuad::_numGroups = 2; const int pylith::meshio::MeshDataCubitQuad::_groupSizes[] = { 2, 3 }; const int pylith::meshio::MeshDataCubitQuad::_groups[] = { 0, 3, 2, 3, 5 }; const char* pylith::meshio::MeshDataCubitQuad::_groupNames[] = { "left_edge", "top_edge" }; const char* pylith::meshio::MeshDataCubitQuad::_groupTypes[] = { "vertex", "vertex" }; const bool pylith::meshio::MeshDataCubitQuad::_useIndexZero = true; pylith::meshio::MeshDataCubitQuad::MeshDataCubitQuad(void) { // constructor numVertices = _numVertices; spaceDim = _spaceDim; numCells = _numCells; cellDim = _cellDim; numCorners = _numCorners; vertices = const_cast<PylithScalar*>(_vertices); cells = const_cast<int*>(_cells); materialIds = const_cast<int*>(_materialIds); groups = const_cast<int*>(_groups); groupSizes = const_cast<int*>(_groupSizes); groupNames = const_cast<char**>(_groupNames); groupTypes = const_cast<char**>(_groupTypes); numGroups = _numGroups; useIndexZero = _useIndexZero; } // constructor pylith::meshio::MeshDataCubitQuad::~MeshDataCubitQuad(void) {} // End of file
yrezgui/evergreen
src/positioner/src/getPosition.js
import Position from './Position' /** * Function to create a Rect. * @param {Object} dimensions * @param {Number} dimensions.width * @param {Number} dimensions.height * @param {Object} position * @param {Number} position.left * @param {Number} position.top * @return {Object} Rect { width, height, left, top, right, bottom } */ const makeRect = ({ width, height }, { left, top }) => { const ceiledLeft = Math.ceil(left) const ceiledTop = Math.ceil(top) return { width, height, left: ceiledLeft, top: ceiledTop, right: ceiledLeft + width, bottom: ceiledTop + height } } /** * Function to flip a position upside down. * @param {Position} position * @return {Position} flipped position */ const flipHorizontal = position => { switch (position) { case Position.TOP_LEFT: return Position.BOTTOM_LEFT case Position.TOP: default: return Position.BOTTOM case Position.TOP_RIGHT: return Position.BOTTOM_RIGHT case Position.BOTTOM_LEFT: return Position.TOP_LEFT case Position.BOTTOM: return Position.TOP case Position.BOTTOM_RIGHT: return Position.TOP_RIGHT } } /** * Function that returns if position is aligned on top. * @param {Position} position * @return {Boolean} */ const isAlignedOnTop = position => { switch (position) { case Position.TOP_LEFT: case Position.TOP: case Position.TOP_RIGHT: return true default: return false } } /** * Function that returns if a rect fits on bottom. * @param {Rect} rect * @param {Object} viewport * @param {Number} viewportOffset * @return {Boolean} */ const getFitsOnBottom = (rect, viewport, viewportOffset) => { return rect.bottom < viewport.height - viewportOffset } /** * Function that returns if a rect fits on top. * @param {Rect} rect * @param {Number} viewportOffset * @return {Boolean} */ const getFitsOnTop = (rect, viewportOffset) => { return rect.top > viewportOffset } /** * Function that returns the CSS `tranform-origin` property. * @param {Rect} rect * @param {Position} position * @param {Number} targetCenter - center of the target. * @return {String} transform origin */ const getTransformOrigin = ({ rect, position, targetCenter }) => { const center = Math.round(targetCenter - rect.left) if (isAlignedOnTop(position)) { return `bottom ${center}px` } return `top ${center}px` } /** * Function that takes in numbers and position and gives the final coords. * @param {Position} position — the position the positioner should be on. * @param {Object} dimensions — the dimensions of the positioner. * @param {Object} targetRect — the rect of the target. * @param {Number} targetOffset - offset from the target. * @param {Object} viewport - the width and height of the viewport. * @param {Object} viewportOffset - offset from the viewport. * @return {Object} - { x: Number, y: Number } */ export default function getFittedPosition({ position, dimensions, targetRect, targetOffset, viewport, viewportOffset = 8 }) { const targetCenter = targetRect.left + targetRect.width / 2 const { rect, position: finalPosition } = getPosition({ position, dimensions, targetRect, targetOffset, viewport, viewportOffset }) // Push rect to the right if overflowing on the left side of the viewport. if (rect.left < viewportOffset) { rect.right += Math.ceil(Math.abs(rect.left - viewportOffset)) rect.left = Math.ceil(viewportOffset) } // Push rect to the left if overflowing on the right side of the viewport. if (rect.right > viewport.width - viewportOffset) { const delta = Math.ceil(rect.right - (viewport.width - viewportOffset)) rect.left -= delta rect.right -= delta } const transformOrigin = getTransformOrigin({ rect, position: finalPosition, targetCenter }) return { rect, position: finalPosition, transformOrigin } } /** * Function that takes in numbers and position and gives the final coords. * @param {Position} position — the position the positioner should be on. * @param {Object} dimensions — the dimensions of the positioner. * @param {Object} targetRect — the rect of the target. * @param {Number} targetOffset - offset from the target. * @param {Object} viewport - the width and height of the viewport. * @param {Object} viewportOffset - offset from the viewport. * @return {Object} - { rect: Rect, position: Position } */ function getPosition({ position, dimensions, targetRect, targetOffset, viewport, viewportOffset = 8 }) { const positionIsAlignedOnTop = isAlignedOnTop(position) let topRect let bottomRect if (positionIsAlignedOnTop) { topRect = getRect({ position, dimensions, targetRect, targetOffset }) bottomRect = getRect({ position: flipHorizontal(position), dimensions, targetRect, targetOffset }) } else { topRect = getRect({ position: flipHorizontal(position), dimensions, targetRect, targetOffset }) bottomRect = getRect({ position, dimensions, targetRect, targetOffset }) } const topRectFitsOnTop = getFitsOnTop(topRect, viewportOffset) const bottomRectFitsOnBottom = getFitsOnBottom( bottomRect, viewport, viewportOffset ) if (positionIsAlignedOnTop && topRectFitsOnTop) { return { position, rect: topRect } } if (!positionIsAlignedOnTop) { if (bottomRectFitsOnBottom) { return { position, rect: bottomRect } } else if (topRectFitsOnTop) { return { position: flipHorizontal(position), rect: topRect } } } // Default to most spacious if there is no fit. const spaceBottom = Math.abs( viewport.height - viewportOffset - bottomRect.bottom ) const spaceTop = Math.abs(topRect.top - viewportOffset) if (spaceBottom < spaceTop) { return { position: positionIsAlignedOnTop ? flipHorizontal(position) : position, rect: bottomRect } } return { position: positionIsAlignedOnTop ? position : flipHorizontal(position), rect: topRect } } /** * Function that takes in numbers and position and gives the final coords. * @param {Object} position - the width and height of the viewport. * @param {Number} targetOffset - offset from the target. * @param {Object} dimensions — the dimensions of the positioner. * @param {Object} targetRect — the rect of the target. * @return {Object} - { x: Number, y: Number } */ function getRect({ position, targetOffset, dimensions, targetRect }) { const leftRect = targetRect.left + targetRect.width / 2 - dimensions.width / 2 const alignedTopY = targetRect.top - dimensions.height - targetOffset const alignedBottomY = targetRect.bottom + targetOffset const alignedRightX = targetRect.right - dimensions.width switch (position) { case Position.TOP: return makeRect(dimensions, { left: leftRect, top: alignedTopY }) case Position.TOP_LEFT: return makeRect(dimensions, { left: targetRect.left, top: alignedTopY }) case Position.TOP_RIGHT: return makeRect(dimensions, { left: alignedRightX, top: alignedTopY }) default: case Position.BOTTOM: return makeRect(dimensions, { left: leftRect, top: alignedBottomY }) case Position.BOTTOM_LEFT: return makeRect(dimensions, { left: targetRect.left, top: alignedBottomY }) case Position.BOTTOM_RIGHT: return makeRect(dimensions, { left: alignedRightX, top: alignedBottomY }) } }
hfboyce/MCL-DSCI-571-machine-learning
exercises/en/test_04_12.py
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the message will be displayed assert 'NearestNeighbors' in __solution__, "Make sure you are using the NearestNeighbors() function with n_neighbors = 1." assert 'nn.fit(X_train)' in __solution__, "Make sure you are fitting the model on the training data." assert 'NearestNeighbors' in __solution__, "Make sure you are using the NearestNeighbors argument." assert snoodle_name == 'Servine', "The value for the nearest neighbour is incorrect. Are you setting up the model correctly?" assert round(snoodles_neighbour[0][0][0]) == 23.0, "The nearest neighbor distance is incorrect. Are you fitting the model properly?" __msg__.good("Nice work, well done!")
tsalemy/ConcurrentComputing
ReplicatedKeyValueStoreRDMA/infinity/src/infinity/memory/Buffer.cpp
<gh_stars>0 /* * Memory - Buffer * * (c) 2018 <NAME>, ETH Zurich * Contact: <EMAIL> * */ #include "Buffer.h" #include <stdlib.h> #include <string.h> #include <infinity/core/Configuration.h> #include <infinity/utils/Debug.h> #define MIN(a,b) (((a)<(b)) ? (a) : (b)) namespace infinity { namespace memory { Buffer::Buffer(infinity::core::Context* context, uint64_t sizeInBytes) { this->context = context; this->sizeInBytes = sizeInBytes; this->memoryRegionType = RegionType::BUFFER; int res = posix_memalign(&(this->data), infinity::core::Configuration::PAGE_SIZE, sizeInBytes); INFINITY_ASSERT(res == 0, "[INFINITY][MEMORY][BUFFER] Cannot allocate and align buffer.\n"); memset(this->data, 0, sizeInBytes); this->ibvMemoryRegion = ibv_reg_mr(this->context->getProtectionDomain(), this->data, this->sizeInBytes, IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_READ); INFINITY_ASSERT(this->ibvMemoryRegion != NULL, "[INFINITY][MEMORY][BUFFER] Registration failed.\n"); this->memoryAllocated = true; this->memoryRegistered = true; } Buffer::Buffer(infinity::core::Context* context, infinity::memory::RegisteredMemory* memory, uint64_t offset, uint64_t sizeInBytes) { this->context = context; this->sizeInBytes = sizeInBytes; this->memoryRegionType = RegionType::BUFFER; this->data = reinterpret_cast<char *>(memory->getData()) + offset; this->ibvMemoryRegion = memory->getRegion(); this->memoryAllocated = false; this->memoryRegistered = false; } Buffer::Buffer(infinity::core::Context *context, void *memory, uint64_t sizeInBytes) { this->context = context; this->sizeInBytes = sizeInBytes; this->memoryRegionType = RegionType::BUFFER; this->data = memory; this->ibvMemoryRegion = ibv_reg_mr(this->context->getProtectionDomain(), this->data, this->sizeInBytes, IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_READ); INFINITY_ASSERT(this->ibvMemoryRegion != NULL, "[INFINITY][MEMORY][BUFFER] Registration failed.\n"); this->memoryAllocated = false; this->memoryRegistered = true; } Buffer::Buffer(infinity::core::Context *context, void* memory, uint64_t sizeInBytes, int access) { this->context = context; this->sizeInBytes = sizeInBytes; this->memoryRegionType = RegionType::ATOMIC; //hacking this here //technically this isn't ture since the ibv_access_flags could be atomic this->data = memory; this->ibvMemoryRegion = ibv_reg_mr(this->context->getProtectionDomain(), this->data, this->sizeInBytes, access); INFINITY_ASSERT(this->ibvMemoryRegion != NULL, "[INFINITY][MEMORY][BUFFER] Registration failed.\n"); this->memoryAllocated = false; this->memoryRegistered = true; } Buffer::~Buffer() { if (this->memoryRegistered) { ibv_dereg_mr(this->ibvMemoryRegion); } if (this->memoryAllocated) { free(this->data); } } void* Buffer::getData() { return reinterpret_cast<void *>(this->getAddress()); } void Buffer::resize(uint64_t newSize, void* newData) { void *oldData = this->data; uint32_t oldSize = this->sizeInBytes; if (newData == NULL) { newData = this->data; } if (oldData != newData) { uint64_t copySize = MIN(newSize, oldSize); memcpy(newData, oldData, copySize); } if (memoryRegistered) { ibv_dereg_mr(this->ibvMemoryRegion); this->ibvMemoryRegion = ibv_reg_mr(this->context->getProtectionDomain(), newData, newSize, IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_READ); this->data = newData; this->sizeInBytes = newSize; } else { INFINITY_ASSERT(false, "[INFINITY][MEMORY][BUFFER] You can only resize memory which has registered by this buffer.\n"); } } } /* namespace memory */ } /* namespace infinity */
PPPy290351/nanos
src/riscv64/plic.h
#define PLIC_MAX_INT 0x35 #define PLIC_VIRTIO_INTS_START 1 #define PLIC_VIRTIO_INTS_END 9 #define PLIC_PCIE_INTS_START 0x20 #define PLIC_PCIE_INTS_END 0x23 #define PLIC_PRIORITY 0 #define PLIC_PENDING 0x1000 #define PLIC_ENABLE_C1 0x2080 #define PLIC_THRESH_C1 0x201000 #define PLIC_CLAIM_C1 0x201004 void plic_disable_int(int irq); void plic_enable_int(int irq); void plic_clear_pending_int(int irq); void plic_set_int_priority(int irq, u32 pri); void plic_set_c1_threshold(u32 thresh); void plic_set_int_config(int irq, u32 cfg); boolean plic_int_is_pending(int irq); u64 plic_dispatch_int(void); void plic_eoi(int irq); void init_plic();
dalihub/dali-adaptor
dali/internal/canvas-renderer/common/canvas-renderer-impl.h
<filename>dali/internal/canvas-renderer/common/canvas-renderer-impl.h<gh_stars>1-10 #ifndef DALI_INTERNAL_CANVAS_RENDERER_IMPL_H #define DALI_INTERNAL_CANVAS_RENDERER_IMPL_H /* * Copyright (c) 2021 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. * */ // EXTERNAL INCLUDES #include <dali/public-api/object/base-object.h> // INTERNAL INCLUDES #include <dali/devel-api/adaptor-framework/canvas-renderer-drawable.h> #include <dali/devel-api/adaptor-framework/canvas-renderer.h> #include <dali/devel-api/adaptor-framework/pixel-buffer.h> namespace Dali { namespace Internal { namespace Adaptor { /** * Dali internal CanvasRenderer. */ class CanvasRenderer : public Dali::BaseObject { public: /** * @brief Constructor */ CanvasRenderer(); /** * @brief Destructor. */ ~CanvasRenderer() override; /** * @copydoc Dali::CanvasRenderer::Commit() */ virtual bool Commit(); /** * @copydoc Dali::CanvasRenderer::GetPixelBuffer() */ virtual Devel::PixelBuffer GetPixelBuffer(); /** * @copydoc Dali::CanvasRenderer::AddDrawable() */ virtual bool AddDrawable(Dali::CanvasRenderer::Drawable& drawable); /** * @copydoc Dali::CanvasRenderer::IsCanvasChanged() */ virtual bool IsCanvasChanged() const; /** * @copydoc Dali::CanvasRenderer::Rasterize() */ virtual bool Rasterize(); /** * @copydoc Dali::CanvasRenderer::RemoveDrawable() */ virtual bool RemoveDrawable(Dali::CanvasRenderer::Drawable& drawable); /** * @copydoc Dali::CanvasRenderer::RemoveAllDrawables() */ virtual bool RemoveAllDrawables(); /** * @copydoc Dali::CanvasRenderer::SetSize() */ virtual bool SetSize(Vector2 size); /** * @copydoc Dali::CanvasRenderer::GetSize() */ virtual Vector2 GetSize() const; /** * @copydoc Dali::CanvasRenderer::SetViewBox() */ virtual bool SetViewBox(const Vector2& viewBox); /** * @copydoc Dali::CanvasRenderer::GetViewBox() */ virtual const Vector2& GetViewBox(); CanvasRenderer(const CanvasRenderer&) = delete; CanvasRenderer& operator=(CanvasRenderer&) = delete; CanvasRenderer(CanvasRenderer&&) = delete; CanvasRenderer& operator=(CanvasRenderer&&) = delete; }; } // namespace Adaptor } // namespace Internal inline static Internal::Adaptor::CanvasRenderer& GetImplementation(Dali::CanvasRenderer& renderer) { DALI_ASSERT_ALWAYS(renderer && "CanvasRenderer handle is empty."); BaseObject& handle = renderer.GetBaseObject(); return static_cast<Internal::Adaptor::CanvasRenderer&>(handle); } inline static const Internal::Adaptor::CanvasRenderer& GetImplementation(const Dali::CanvasRenderer& renderer) { DALI_ASSERT_ALWAYS(renderer && "CanvasRenderer handle is empty."); const BaseObject& handle = renderer.GetBaseObject(); return static_cast<const Internal::Adaptor::CanvasRenderer&>(handle); } } // namespace Dali #endif // DALI_INTERNAL_CANVAS_RENDERER_IMPL_H
aajjbb/contest-files
Codeforces/DrazilAndFactorial.cpp
<gh_stars>1-10 #include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned uint; int N; Int val; Int fact(int x) { if (x == 0) return 1LL; return x * fact(x - 1); } Int fat(vector<int>& s) { Int ans = 1LL; for (int i = 0; i < (int) s.size(); i++) { ans *= fact(s[i]); } return ans; } int main(void) { cin >> N; vector<int> digit; cin >> val; for (int i = 0; i < N; i++) { digit.push_back(val % 10); val /= 10; } int M = (int) digit.size(); vector<int> buff; for (int i = 0; i < M; i++) { if (digit[i] <= 1) continue; if (digit[i] == 4) { buff.push_back(2); buff.push_back(2); buff.push_back(3); } else if (digit[i] == 6) { buff.push_back(3); buff.push_back(5); } else if (digit[i] == 8) { buff.push_back(2); buff.push_back(2); buff.push_back(2); buff.push_back(7); } else if (digit[i] == 9) { buff.push_back(2); buff.push_back(3); buff.push_back(3); buff.push_back(7); } else { buff.push_back(digit[i]); } } sort(buff.rbegin(), buff.rend()); for (int i = 0; i < (int) buff.size(); i++) { cout << buff[i]; } cout << "\n"; return 0; }
pitmanst/jpype
native/common/jp_platform.cpp
<gh_stars>0 /***************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. See NOTICE file for details. *****************************************************************************/ #include "jpype.h" #include "jp_platform.h" JPPlatformAdapter::~JPPlatformAdapter() { } #ifdef WIN32 #include <windows.h> /** * Windows-specific platform adapter */ class Win32PlatformAdapter : public JPPlatformAdapter { private: HINSTANCE jvmLibrary; std::string formatMessage(DWORD msgCode) { LPVOID lpMsgBuf; DWORD rc = ::FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, msgCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) & lpMsgBuf, 0, NULL ); // Fail to get format if (rc == 0) { std::stringstream ss; ss << "error code " << msgCode; return ss.str(); } std::string res((LPTSTR) lpMsgBuf); LocalFree(lpMsgBuf); return res; } public: virtual void loadLibrary(const char* path) override { JP_TRACE_IN("Win32PlatformAdapter::loadLibrary"); jvmLibrary = LoadLibrary(path); if (jvmLibrary == NULL) { JP_RAISE_OS_ERROR_WINDOWS( GetLastError(), path); } JP_TRACE_OUT; } virtual void unloadLibrary() override { // on success return code is nonzero, TODO: handle error? FreeLibrary(jvmLibrary); } virtual void* getSymbol(const char* name) override { void* res = (void*) GetProcAddress(jvmLibrary, name); if (res == NULL) { std::stringstream msg; msg << "Unable to load symbol [" << name << "], error = " << formatMessage(GetLastError()); JP_RAISE(PyExc_RuntimeError, msg.str().c_str()); } return res; } } ; #define PLATFORM_ADAPTER Win32PlatformAdapter #else #if defined(_HPUX) && !defined(_IA64) #include <dl.h> #else #include <dlfcn.h> #endif // HPUX #include <errno.h> // The code in this modules is mostly excluded from coverage as it is only // possible to execute during a fatal error. class LinuxPlatformAdapter : public JPPlatformAdapter { private: void* jvmLibrary; public: virtual void loadLibrary(const char* path) override { JP_TRACE_IN("LinuxPlatformAdapter::loadLibrary"); #if defined(_HPUX) && !defined(_IA64) JP_TRACE("shl_load", path); jvmLibrary = shl_load(path, BIND_DEFERRED | BIND_VERBOSE, 0L); #else JP_TRACE("dlopen", path); jvmLibrary = dlopen(path, RTLD_LAZY | RTLD_GLOBAL); #endif // HPUX // GCOVR_EXCL_START if (jvmLibrary == NULL) { JP_TRACE("null library"); JP_TRACE("errno", errno); if (errno == ENOEXEC) { JP_TRACE("dignostics", dlerror()); } JP_RAISE_OS_ERROR_UNIX( errno, path); } // GCOVR_EXCL_STOP JP_TRACE_OUT; // GCOVR_EXCL_LINE } virtual void unloadLibrary() override { JP_TRACE_IN("LinuxPlatformAdapter::unloadLibrary"); int r = dlclose(jvmLibrary); // GCOVR_EXCL_START if (r != 0) // error { cerr << dlerror() << endl; } // GCOVR_EXCL_STOP JP_TRACE_OUT; // GCOVR_EXCL_LINE } virtual void* getSymbol(const char* name) override { JP_TRACE_IN("LinuxPlatformAdapter::getSymbol"); JP_TRACE("Load", name); void* res = dlsym(jvmLibrary, name); JP_TRACE("Res", res); // GCOVR_EXCL_START if (res == NULL) { JP_TRACE("errno", errno); std::stringstream msg; msg << "Unable to load symbol [" << name << "], error = " << dlerror(); JP_RAISE(PyExc_RuntimeError, msg.str().c_str()); } // GCOVR_EXCL_STOP return res; JP_TRACE_OUT; // GCOVR_EXCL_LINE } } ; #define PLATFORM_ADAPTER LinuxPlatformAdapter #endif namespace { PLATFORM_ADAPTER adapter; } JPPlatformAdapter* JPPlatformAdapter::getAdapter() { return &adapter; }
powertac/powertac-experiment-scheduler
src/main/java/org/powertac/rachma/resource/WorkDirectoryManager.java
<reponame>powertac/powertac-experiment-scheduler package org.powertac.rachma.resource; import org.powertac.rachma.job.Job; import org.powertac.rachma.util.InternalResourceExporter; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @Component public class WorkDirectoryManager { @Value("${directory.local.base}") private String baseDirectory; @Value("${directory.local.jobs}") private String localJobDirectory; @Value("${directory.host.jobs}") private String hostJobDirectory; @Value("${directory.local.brokers}") private String brokerDirectory; @Value("${directory.local.services}") private String servicesDirectory; private final InternalResourceExporter resourceExporter; public WorkDirectoryManager(InternalResourceExporter resourceExporter) { this.resourceExporter = resourceExporter; } // TODO : remove since this mixes up concepts... these are two concepts with the same name public void createMainDirectoriesAndCopyResourceFiles() throws IOException { createDirectoryIfNotExists(baseDirectory); createDirectoryIfNotExists(localJobDirectory); resourceExporter.exportDirectory("/brokers", brokerDirectory); // TODO : only server.properties is needed for running the orchestrator; therefore the other files should be omitted resourceExporter.exportDirectory("/services", servicesDirectory); } public WorkDirectory create(Job job) throws IOException { String localWorkDirectory = localJobDirectory + job.getId(); createDirectoryIfNotExists(localWorkDirectory); return new WorkDirectory(localWorkDirectory, hostJobDirectory + job.getId()); } private void createDirectoryIfNotExists(String directory) throws IOException { Path path = Paths.get(directory); if (!Files.exists(path)) { Files.createDirectories(path); } } }
reven86/dava.engine
Modules/TArc/Sources/TArc/DataProcessing/DataListener.h
<filename>Modules/TArc/Sources/TArc/DataProcessing/DataListener.h #pragma once #include "DataWrapper.h" #include "Base/BaseTypes.h" namespace DAVA { namespace TArc { class DataListener { public: virtual ~DataListener(); virtual void OnDataChanged(const DataWrapper& wrapper, const Vector<Any>& fields) = 0; private: friend class DataWrapper; void AddWrapper(DataWrapper wrapper); void RemoveWrapper(DataWrapper wrapper); private: struct DataWrapperLess { bool operator()(const DataWrapper& w1, const DataWrapper& w2) const { return w1.impl < w2.impl; } }; Set<DataWrapper, DataWrapperLess> wrappers; }; } // namespace TArc } // namespace DAVA
PacktPublishing/Scala-Reactive-Programming
Chapter10/akka-streams-scala-helloworld-app/src/main/scala/com/packt/publishing/akka/streams/hello/AkkaStreamsNumbersApp.scala
<gh_stars>10-100 package com.packt.publishing.akka.streams.hello import akka.actor.ActorSystem import akka.stream.ActorMaterializer import akka.stream.scaladsl.{Flow, Sink, Source} object AkkaStreamsNumbersApp extends App{ implicit val actorSystem = ActorSystem("NumberSystem") implicit val materializer = ActorMaterializer() val numbersSource = Source(1 to 10) val sampleSink = Sink.foreach(println) val numberFlow = Flow[Int].map(num => num+1) val numberRunnableGraph = numbersSource.via(numberFlow).to(sampleSink) numberRunnableGraph.run actorSystem.terminate }
yasenagat/AndroidTest
VolleyTest/src/main/java/com/dgcy/http/base/IRequestMsg.java
package com.dgcy.http.base; public interface IRequestMsg<T> { String getCmd(); String getRequestData(); Class<T> getResponseType(); String getUniquenKey(); long getExpireTime(); String getCacheKey(); }
EzzalddeenAli/utilsx
utilsx/src/main/java/org/kingtec/utils/tools/ServiceUtil.java
//package org.kingtec.utils.tools; // //import android.app.Activity; //import android.app.AlarmManager; //import android.app.NotificationManager; //import android.content.Context; //import android.media.AudioManager; //import android.net.ConnectivityManager; //import android.os.PowerManager; //import android.os.Vibrator; //import android.telephony.TelephonyManager; //import android.view.WindowManager; //import android.view.inputmethod.InputMethodManager; // //public class ServiceUtil { // public static InputMethodManager getInputMethodManager(Context context) { // return (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); // } // // public static WindowManager getWindowManager(Context context) { // return (WindowManager) context.getSystemService(Activity.WINDOW_SERVICE); // } // // public static ConnectivityManager getConnectivityManager(Context context) { // return (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE); // } // // public static NotificationManager getNotificationManager(Context context) { // return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // } // // public static TelephonyManager getTelephonyManager(Context context) { // return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // } // // public static AudioManager getAudioManager(Context context) { // return (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); // } // // public static PowerManager getPowerManager(Context context) { // return (PowerManager) context.getSystemService(Context.POWER_SERVICE); // } // // public static AlarmManager getAlarmManager(Context context) { // return (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public static Vibrator getVibrator(Context context) { // return (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); // } //}
vorpal-research/borealis
SMT/MathSAT/ExecutionContext.h
<reponame>vorpal-research/borealis<filename>SMT/MathSAT/ExecutionContext.h /* * ExecutionContext.h * * Created on: Aug 5, 2013 * Author: sam */ #ifndef MATHSAT_EXECUTIONCONTEXT_H_ #define MATHSAT_EXECUTIONCONTEXT_H_ #include <unordered_map> #include <unordered_set> #include <vector> #include "SMT/MathSAT/MathSATEngine.h" #include "SMT/MathSAT/ExprFactory.h" #include "Util/split_join.hpp" #define NAMESPACE mathsat_ #define BACKEND MathSAT #include "SMT/ExecutionContext.stub.h" #undef NAMESPACE #undef BACKEND #endif /* MATHSAT_EXECUTIONCONTEXT_H_ */
endritarrahmani-prosperoware/cxjs
docs/content/widgets/configs/ContentResolver.js
import {Md} from '../../../components/Md'; import pureContainer from './PureContainer'; export default { ...pureContainer, params: { key: true, type: 'value/object', description: <cx><Md> Parameter binding. If `params` change, the content is recreated. </Md></cx> }, onResolve: { key: true, type: 'callback', description: <cx><Md> Callback function taking `params` and returning a widget configuration or a promise. </Md></cx> }, mode: { type: 'string', description: <cx><Md> One of `replace`, `prepend` or `append`. Determines how resolved content is combined with the content provided as children. Default is `replace`. </Md></cx> }, loading: { type: 'boolean', key: true, description: <cx><Md> Writable loading indicator binding. Used only if `onResolve` returns a promise. The provided binding is set to `true` while loading is in progress. After the promise is resolved, the binding is set to `false`. </Md></cx> } };
twilightgod/twilight-poj-solution
2575/5831497_AC_110MS_392K.cpp
/******************************************************************************* * Online Judge : POJ * Problem Title : Jolly Jumpers * Problem URL : http://acm.pku.edu.cn/JudgeOnline/problem?id=2575 * ID : 2575 * Date : 9/8/2009 * Time : 19:40:51 * Computer Name : EVERLASTING-AMD * Wizard Version : 20090522P *******************************************************************************/ #include<iostream> #include<set> #include<math.h> using namespace std; set<int> s; int n,pre,a; bool god; int main() { #ifndef ONLINE_JUDGE freopen("in_2575.txt","r",stdin); #endif while(cin>>n) { s.clear(); cin>>pre; god=false; for(int i=1;i<n;++i) { cin>>a; int t=abs(a-pre); if(t>=n||s.find(t)!=s.end()) { god=true; } else { s.insert(t); } pre=a; } if(god) { cout<<"Not jolly\n"; } else { cout<<"Jolly\n"; } } return 0; }
slater1998/x7
x7-repo/x7-cache/src/main/java/io/xream/x7/cache/DefaultArgsToString.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.xream.x7.cache; import io.xream.x7.common.util.JsonX; import io.xream.x7.common.web.Tokened; /** * Tokened */ public class DefaultArgsToString implements ArgsToString<Tokened>{ @Override public StringBuilder build(Object[] args) { StringBuilder sb = new StringBuilder(); if (args != null) { for (Object arg : args) { if (arg instanceof Tokened) { Tokened ro = (Tokened) arg; long passportId = ro.getPassportId(); String token = ro.getToken(); String passportType = ro.getPassportType(); ro.setPassportId("0"); ro.setPassportType(null); ro.setToken(null); String str = JsonX.toJson(ro); sb.append(str); ro.setPassportId(String.valueOf(passportId)); ro.setPassportType(passportType); ro.setToken(token); } else { String str = JsonX.toJson(arg); sb.append(str); } } } return sb; } }
vivaxy/examples
javascript/source-map/src/__tests__/fixtures/webpack/src/get-a.js
<reponame>vivaxy/examples<gh_stars>10-100 /** * @since 2020-03-08 06:12 * @author vivaxy */ function getA() { return 1; } export default getA;
thothd/unit-e
src/script/ismine.cpp
<gh_stars>10-100 // Copyright (c) 2009-2010 <NAME> // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/ismine.h> #include <key.h> #include <keystore.h> #include <script/script.h> #include <script/sign.h> typedef std::vector<unsigned char> valtype; namespace { /** * This is an enum that tracks the execution context of a script, similar to * SigVersion in script/interpreter. It is separate however because we want to * distinguish between top-level scriptPubKey execution and P2SH redeemScript * execution (a distinction that has no impact on consensus rules). */ enum class IsMineSigVersion { TOP = 0, //! scriptPubKey execution P2SH = 1, //! P2SH redeemScript WITNESS_V0 = 2 //! P2WSH witness script execution }; /** * This is an internal representation of isminetype + invalidity. * Its order is significant, as we return the max of all explored * possibilities. */ enum class IsMineResult { NO = 0, //! Not ours WATCH_ONLY = 1, //! Included in watch-only balance SPENDABLE = 2, //! Included in all balances HW_DEVICE = 6, //! Stored in a hardware wallet INVALID = 7, //! Not spendable by anyone (uncompressed pubkey in segwit, P2SH inside P2SH or witness, witness inside witness) }; struct IsMineInfo { txnouttype type; txnouttype p2sh_type; std::vector<std::vector<unsigned char>> solutions; std::vector<std::vector<unsigned char>> p2sh_solutions; }; bool PermitsUncompressed(IsMineSigVersion sigversion) { return sigversion == IsMineSigVersion::TOP || sigversion == IsMineSigVersion::P2SH; } //! Checks that we own all the keys in the same way (either all in hardware, or //! all in the software wallet). IsMineResult HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore) { size_t hw_key_count = 0, wallet_key_count = 0; for (const valtype& pubkey : pubkeys) { CKeyID keyID = CPubKey(pubkey).GetID(); if (keystore.HaveHardwareKey(keyID)) { hw_key_count++; } if (keystore.HaveKey(keyID)) { wallet_key_count++; } } if (wallet_key_count == pubkeys.size()) { return IsMineResult::SPENDABLE; } if (hw_key_count == pubkeys.size()) { return IsMineResult::HW_DEVICE; } return IsMineResult::NO; } IsMineResult IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey, IsMineSigVersion sigversion, IsMineInfo *is_mine_info = nullptr) { IsMineResult ret = IsMineResult::NO; std::vector<valtype> vSolutions; txnouttype whichType; Solver(scriptPubKey, whichType, vSolutions); CKeyID keyID; switch (whichType) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_WITNESS_UNKNOWN: break; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); if (!PermitsUncompressed(sigversion) && vSolutions[0].size() != 33) { return IsMineResult::INVALID; } if (keystore.HaveKey(keyID)) { ret = IsMineResult::SPENDABLE; } else if (keystore.HaveHardwareKey(keyID)) { ret = IsMineResult::HW_DEVICE; } break; case TX_WITNESS_V0_KEYHASH: { if (sigversion == IsMineSigVersion::WITNESS_V0) { // P2WPKH inside P2WSH is invalid. return IsMineResult::INVALID; } if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { // We do not support bare witness outputs unless the P2SH version of it would be // acceptable as well. This also applies to the P2WSH case. break; } ret = IsMineInner(keystore, GetScriptForDestination(CKeyID(uint160(vSolutions[0]))), IsMineSigVersion::WITNESS_V0, is_mine_info); break; } case TX_PUBKEYHASH: { keyID = CKeyID(uint160(vSolutions[0])); if (!PermitsUncompressed(sigversion)) { CPubKey pubkey; if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) { return IsMineResult::INVALID; } } if (keystore.HaveKey(keyID)) { ret = IsMineResult::SPENDABLE; } else if (keystore.HaveHardwareKey(keyID)) { ret = IsMineResult::HW_DEVICE; } break; } case TX_SCRIPTHASH: { if (sigversion != IsMineSigVersion::TOP) { // P2SH inside P2WSH or P2SH is invalid. return IsMineResult::INVALID; } CScriptID scriptID = CScriptID(uint160(vSolutions[0])); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { ret = IsMineInner(keystore, subscript, IsMineSigVersion::P2SH, is_mine_info); } break; } case TX_WITNESS_V0_SCRIPTHASH: { if (sigversion == IsMineSigVersion::WITNESS_V0) { // P2WSH inside P2WSH is invalid. return IsMineResult::INVALID; } if (sigversion == IsMineSigVersion::TOP && !keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { break; } uint160 hash; CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(hash.begin()); CScriptID scriptID = CScriptID(hash); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { ret = IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0, is_mine_info); } break; } case TX_MULTISIG: { // Never treat bare multisig outputs as ours (they can still be made watchonly-though) if (sigversion == IsMineSigVersion::TOP) { break; } // Only consider transactions "mine" if we own ALL the // keys involved. Multi-signature transactions that are // partially owned (somebody else has a key that can spend // them) enable spend-out-from-under-you attacks, especially // in shared-wallet situations. std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1); if (!PermitsUncompressed(sigversion)) { for (size_t i = 0; i < keys.size(); i++) { if (keys[i].size() != 33) { return IsMineResult::INVALID; } } } IsMineResult ret_all = HaveKeys(keys, keystore); if (ret_all != IsMineResult::NO) { ret = ret_all; } break; } case TX_COMMIT: { if (vSolutions[0].size() == 33) { keyID = CPubKey(vSolutions[0]).GetID(); // UNIT-E: At the moment we do not support deposit or vote transactions nested in P2SH/P2WSH if (sigversion != IsMineSigVersion::TOP) { return IsMineResult::INVALID; } if (keystore.HaveKey(keyID)) { return IsMineResult::SPENDABLE; } if (keystore.HaveHardwareKey(keyID)) { return IsMineResult::HW_DEVICE; } } break; } case TX_WITNESS_V1_REMOTESTAKE_KEYHASH: { if (sigversion != IsMineSigVersion::TOP) { return IsMineResult::INVALID; } uint160 hash; CRIPEMD160().Write(&vSolutions[1][0], vSolutions[1].size()).Finalize(hash.begin()); CKeyID spending_key_id = CKeyID(hash); ret = IsMineInner(keystore, GetScriptForDestination(spending_key_id), IsMineSigVersion::WITNESS_V0, is_mine_info); break; } case TX_WITNESS_V2_REMOTESTAKE_SCRIPTHASH: { if (sigversion == IsMineSigVersion::WITNESS_V0 || sigversion == IsMineSigVersion::P2SH) { // Remote staking P2WSH inside P2WSH or P2SH is invalid. return IsMineResult::INVALID; } uint160 hash; CRIPEMD160().Write(vSolutions[1].data(), vSolutions[1].size()).Finalize(hash.begin()); CScriptID scriptID = CScriptID(hash); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { ret = IsMineInner(keystore, subscript, IsMineSigVersion::WITNESS_V0, is_mine_info); } break; } } if (is_mine_info) { switch (sigversion) { case IsMineSigVersion::TOP: is_mine_info->type = whichType; is_mine_info->solutions = std::move(vSolutions); break; case IsMineSigVersion::P2SH: case IsMineSigVersion::WITNESS_V0: is_mine_info->p2sh_type = whichType; is_mine_info->p2sh_solutions = std::move(vSolutions); break; } } if (ret == IsMineResult::NO && keystore.HaveWatchOnly(scriptPubKey)) { ret = IsMineResult::WATCH_ONLY; } return ret; } isminetype IsMine(const CKeyStore &keystore, const CScript &scriptPubKey, IsMineInfo *is_mine_info) { switch (IsMineInner(keystore, scriptPubKey, IsMineSigVersion::TOP, is_mine_info)) { case IsMineResult::INVALID: case IsMineResult::NO: return ISMINE_NO; case IsMineResult::WATCH_ONLY: return ISMINE_WATCH_ONLY; case IsMineResult::SPENDABLE: return ISMINE_SPENDABLE; case IsMineResult::HW_DEVICE: return ISMINE_HW_DEVICE; } assert(false); } } // namespace isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey) { return IsMine(keystore, scriptPubKey, nullptr); } isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest) { CScript script = GetScriptForDestination(dest); return IsMine(keystore, script); } bool IsStakeableByMe(const CKeyStore &keystore, const CScript &script_pub_key) { IsMineInfo is_mine_info; const isminetype is_mine = IsMine(keystore, script_pub_key, &is_mine_info); // UNIT-E TODO: Restrict to witness programs only once #212 is merged (fixes #48) switch (is_mine_info.type) { case TX_PUBKEYHASH: case TX_WITNESS_V0_KEYHASH: { if (is_mine != ISMINE_SPENDABLE) { // Non-remote-staking scripts can be used as stake only if they // are spendable without hardware wallets return false; } CKeyID key_id = CKeyID(uint160(is_mine_info.solutions[0])); CPubKey pubkey; return keystore.GetPubKey(key_id, pubkey) && pubkey.IsCompressed(); } case TX_WITNESS_V1_REMOTESTAKE_KEYHASH: case TX_WITNESS_V2_REMOTESTAKE_SCRIPTHASH: { CKeyID key_id = CKeyID(uint160(is_mine_info.solutions[0])); if (!keystore.HaveKey(key_id)) { return false; } CPubKey pubkey; return keystore.GetPubKey(key_id, pubkey) && pubkey.IsCompressed(); } case TX_WITNESS_V0_SCRIPTHASH: if (is_mine != ISMINE_SPENDABLE) { // Non-remote-staking scripts can be used as stake only if they // are spendable without hardware wallets return false; } switch (is_mine_info.p2sh_type) { case TX_PUBKEYHASH: case TX_PUBKEY: return true; case TX_MULTISIG: { const auto num_signatures = static_cast<std::uint8_t>(is_mine_info.p2sh_solutions.front()[0]); // stake is signed by a single proposer only and the block carries a single // signature of that proposer. 2-of-3 and similar multisig scenarios are not // allowed for staking. return num_signatures == 1; } default: return false; } default: return false; } } bool IsStakedRemotely(const CKeyStore &keystore, const CScript &script_pub_key) { std::vector<valtype> solutions; txnouttype which_type; if (!Solver(script_pub_key, which_type, solutions)) { return false; } if (which_type != TX_WITNESS_V1_REMOTESTAKE_KEYHASH && which_type != TX_WITNESS_V2_REMOTESTAKE_SCRIPTHASH) { return false; } CKeyID staking_keyid = CKeyID(uint160(solutions[0])); // Uncompressed staking keys are not supported CPubKey staking_pubkey; if (keystore.GetPubKey(staking_keyid, staking_pubkey) && !staking_pubkey.IsCompressed()) { return false; } // If the local node knows the staking key, the coin is not staked remotely if (keystore.HaveKey(staking_keyid)) { return false; } // The local node should be able to spend the coin IsMineResult mine = IsMineInner(keystore, script_pub_key, IsMineSigVersion::TOP); return mine == IsMineResult::SPENDABLE || mine == IsMineResult::HW_DEVICE; }
mezzofy/mzcoupon-android-customer-lib
libMzCouponAPI/src/main/java/mezzofy/com/libmzcoupon/module/MZChannel.java
package mezzofy.com.libmzcoupon.module; import android.content.Context; import com.google.gson.Gson; import org.json.JSONObject; import mezzofy.com.libmzcoupon.data.ChannelLocationDataListModel; import mezzofy.com.libmzcoupon.utills.CommonModule; import mezzofy.com.libmzcoupon.utills.JSONSTRINGS; public class MZChannel { Gson gson = new Gson(); JSONSTRINGS jsonstrings; private JSONObject jsonobj = null; Context context; public MZChannel(Context context){ this.context = context; jsonstrings=new JSONSTRINGS(context); } public ChannelLocationDataListModel getChannelLocationList() { String Chennellocation = jsonstrings.getJSONFromUrl(CommonModule.getUserpath(context) + "api/v1/channellocations"); ChannelLocationDataListModel sChannelLocationModelList = gson.fromJson(Chennellocation, ChannelLocationDataListModel.class); return sChannelLocationModelList; } }
ndoxx/wcore
source/tests/catch_algo.cpp
<gh_stars>0 #include <catch2/catch.hpp> #include <iostream> #include "algorithms.h" #include "catch_math_common.h" TEST_CASE("Previous power of 2.", "[algo]") { REQUIRE(pp2(17) == 16); REQUIRE(pp2(182) == 128); } TEST_CASE("Next power of 2.", "[algo]") { REQUIRE(np2(17) == 32); REQUIRE(np2(182) == 256); }
jmix-framework/jmix
jmix-flowui/flowui/src/main/java/io/jmix/flowui/component/validation/FutureOrPresentValidator.java
/* * Copyright 2022 Haulmont. * * 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 io.jmix.flowui.component.validation; import io.jmix.core.TimeSource; import io.jmix.flowui.SameAsUi; import io.jmix.flowui.component.validation.time.TimeValidator; import io.jmix.flowui.exception.ValidationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.annotation.Nullable; @SameAsUi @Component("flowui_FutureOrPresentValidator") @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class FutureOrPresentValidator<T> extends AbstractValidator<T> { protected TimeSource timeSource; protected boolean checkSeconds = false; public FutureOrPresentValidator() { } /** * Constructor for custom error message. * * @param message error message */ public FutureOrPresentValidator(String message) { this.message = message; } @Autowired protected void setTimeSource(TimeSource timeSource) { this.timeSource = timeSource; } /** * Set true if validator should also check seconds and nanos (if supported) in value. Default value is false. * * @param checkSeconds check seconds */ public void setCheckSeconds(boolean checkSeconds) { this.checkSeconds = checkSeconds; } /** * @return true if seconds and nanos are checked */ public boolean isCheckSeconds() { return checkSeconds; } @Override public void accept(@Nullable T value) throws ValidationException { // consider null value is valid if (value == null) { return; } TimeValidator timeConstraint = ValidatorHelper.getTimeConstraint(timeSource, value); if (timeConstraint == null) { throw new IllegalArgumentException( "FutureOrPresentValidator doesn't support following type: '" + value.getClass() + "'"); } timeConstraint.setCheckSeconds(checkSeconds); if (!timeConstraint.isFutureOrPresent()) { String message = getMessage(); this.defaultMessage = messages.getMessage("validation.constraints.futureOrPresent"); fireValidationException(message == null ? defaultMessage : message); } } }
denisepen/InsideVagrant_Rails_App
node_modules/msgpack-lite/global.js
/* globals msgpack */ module.exports = msgpack;
sorabae/android-typecheck
src/main/scala/kr/ac/kaist/safe/analyzer/domain/AbsBinding.scala
/** * ***************************************************************************** * Copyright (c) 2016, KAIST. * All rights reserved. * * Use is subject to license terms. * * This distribution may include materials developed by third parties. * **************************************************************************** */ package kr.ac.kaist.safe.analyzer.domain import kr.ac.kaist.safe.analyzer.domain.Utils._ import scala.collection.immutable.HashSet //////////////////////////////////////////////////////////////////////////////// // concrete binding type //////////////////////////////////////////////////////////////////////////////// abstract class Binding // mutable binding case class MBinding(value: Value) extends Binding // immutable binding case class IBinding(valueOpt: Option[Value]) extends Binding //////////////////////////////////////////////////////////////////////////////// // binding abstract domain //////////////////////////////////////////////////////////////////////////////// trait AbsBinding extends AbsDomain[Binding, AbsBinding] { val value: AbsValue val uninit: AbsAbsent val mutable: AbsBool def copyWith( value: AbsValue = this.value, uninit: AbsAbsent = this.uninit, mutable: AbsBool = this.mutable ): AbsBinding } trait AbsBindingUtil extends AbsDomainUtil[Binding, AbsBinding] { def apply( value: AbsValue, uninit: AbsAbsent = AbsAbsent.Bot, mutable: AbsBool = AbsBool.True ): AbsBinding } //////////////////////////////////////////////////////////////////////////////// // default binding abstract domain //////////////////////////////////////////////////////////////////////////////// object DefaultBinding extends AbsBindingUtil { lazy val Bot: Dom = Dom(AbsValue.Bot, AbsAbsent.Bot, AbsBool.Bot) lazy val Top: Dom = Dom(AbsValue.Top, AbsAbsent.Top, AbsBool.Top) def alpha(bind: Binding): AbsBinding = bind match { case MBinding(value) => Dom(AbsValue(value), AbsAbsent.Bot, AbsBool.True) case IBinding(None) => Dom(AbsValue.Bot, AbsAbsent.Top, AbsBool.False) case IBinding(Some(value)) => Dom(AbsValue(value), AbsAbsent.Bot, AbsBool.False) } def apply( value: AbsValue, uninit: AbsAbsent, mutable: AbsBool ): AbsBinding = Dom(value, uninit, mutable) case class Dom( value: AbsValue, uninit: AbsAbsent, mutable: AbsBool ) extends AbsBinding { def gamma: ConSet[Binding] = value.gamma match { case ConInf() => ConInf() case ConFin(valSet) => { var bindSet: Set[Binding] = HashSet() if (AbsBool.True <= mutable) { bindSet ++= valSet.map(MBinding(_)) } if (AbsBool.False <= mutable) { if (AbsAbsent.Top <= uninit) bindSet += IBinding(None) bindSet ++= valSet.map(v => IBinding(Some(v))) } ConFin(bindSet) } } def isBottom: Boolean = this == Bot def isTop: Boolean = this == Top def getSingle: ConSingle[Binding] = { (value.getSingle, uninit.getSingle, mutable.getSingle) match { case (ConZero(), ConZero(), ConZero()) => ConZero() case (ConOne(value), ConZero(), ConOne(Bool(true))) => ConOne(MBinding(value)) case (ConZero(), ConOne(Absent), ConOne(Bool(false))) => ConOne(IBinding(None)) case (ConOne(value), ConZero(), ConOne(Bool(false))) => ConOne(IBinding(Some(value))) case _ => ConMany() } } def <=(that: AbsBinding): Boolean = { val right = check(that) this.value <= right.value && this.uninit <= right.uninit && this.mutable <= right.mutable } /* join */ def +(that: AbsBinding): AbsBinding = { val right = check(that) Dom( this.value + right.value, this.uninit + right.uninit, this.mutable + right.mutable ) } /* meet */ def <>(that: AbsBinding): AbsBinding = { val right = check(that) Dom( this.value <> right.value, this.uninit <> right.uninit, this.mutable <> right.mutable ) } override def toString: String = { s"[${mutable.toString.take(1)}]" + ( if (isBottom) "⊥(binding)" else (value.isBottom, uninit.isBottom) match { case (true, true) => "⊥(binding)" case (false, true) => value.toString case (true, false) => "uninitialized" case (false, false) => value.toString + ", uninitialized" } ) } def copyWith( value: AbsValue = this.value, uninit: AbsAbsent = this.uninit, mutable: AbsBool = this.mutable ): AbsBinding = Dom(value, uninit, mutable) } }
roberttod/tiny-atom
tasks/build.js
const shell = require('execa').shell const sh = (...args) => shell(...args, { stdio: 'inherit' }) const files = [ 'package.json', 'package-lock.json', 'LICENSE', 'CHANGELOG.md', 'README.md' ] ;(async function () { await sh('rm -rf dist') await sh('mkdir -p dist') for (let file of files) { await sh(`cp ${file} dist`) } await sh(`./node_modules/.bin/buble --objectAssign Object.assign src -o dist`) await sh(`./node_modules/.bin/buble --objectAssign Object.assign --jsx Preact.h src/preact.js -o dist/preact.js`) await sh(`./node_modules/.bin/buble --objectAssign Object.assign --jsx React.createElement src/react.js -o dist/react.js`) }())
FluffyQuack/ja2-stracciatella
src/game/Editor/Editor_Undo.cc
<reponame>FluffyQuack/ja2-stracciatella<gh_stars>100-1000 #include "PODObj.h" #include "Structure.h" #include "TileDef.h" #include "WorldDef.h" #include "WorldMan.h" #include "Smooth.h" #include "Input.h" #include "Debug.h" #include "Isometric_Utils.h" #include "EditScreen.h" #include "Editor_Undo.h" #include "Render_Fun.h" //for access to gubWorldRoomInfo; #include "Cursor_Modes.h" #include "Exit_Grids.h" #include "MemMan.h" /* Kris -- Notes on how the undo code works: At the bottom of the hierarchy, we need to determine the state of the undo command. The idea is that we want to separate undo commands by separating them by new mouse clicks. By holding a mouse down and painting various objects in the world would all constitute a single undo command. As soon as the mouse is release, then a new undo command is setup. So, to automate this, there is a call every frame to DetermineUndoState(). At the next level, there is a binary tree that keeps track of what map indices have been backup up in the current undo command. The whole reason to maintain this list, is to avoid multiple map elements of the same map index from being saved. In the outer code, everytime something is changed, a call to AddToUndoList() is called, so there are many cases (especially with building/terrain smoothing) that the same mapindex is added to the undo list. This is also completely transparent, and doesn't need to be maintained. In the outer code, there are several calls to AddToUndoList( iMapIndex ). This function basically looks in the binary tree for an existing entry, and if there isn't, then the entire mapelement is saved (with the exception of the merc level ). Lights are also supported, but there is a totally different methodology for accomplishing this. The equivalent function is AddLightToUndoList( iMapIndex ). In this case, only the light is saved, along with internal maintanance of several flags. The actual mapelement copy code, is very complex. The mapelement is copied in parallel with a new one which has to allocate several nodes of several types because a mapelement contains over a dozen separate lists, and all of them need to be saved. The structure information of certain mapelements may be multitiled and must also save the affected gridno's as well. This is also done internally. Basically, your call to AddToUndoList() for any particular gridno, may actually save several entries (like for a car which could be 6+ tiles) MERCS Mercs are not supported in the undo code. Because they are so dynamic, and stats could change, they could move, etc., it doesn't need to be in the undo code. The editor has its own way of dealing with mercs which doesn't use the undo methodology. */ BOOLEAN gfUndoEnabled = FALSE; void EnableUndo() { gfUndoEnabled = TRUE; } void DisableUndo() { gfUndoEnabled = FALSE; } // undo node data element struct undo_struct { INT32 iMapIndex; MAP_ELEMENT *pMapTile; BOOLEAN fLightSaved; //determines that a light has been saved UINT8 ubLightRadius; //the radius of the light to build if undo is called UINT8 ubRoomNum; }; // Undo stack node struct undo_stack { INT32 iCmdCount; undo_struct *pData; undo_stack* pNext; INT32 iUndoType; }; undo_stack *gpTileUndoStack = NULL; BOOLEAN fNewUndoCmd = TRUE; BOOLEAN gfIgnoreUndoCmdsForLights = FALSE; //New pre-undo binary tree stuff //With this, new undo commands will not duplicate saves in the same command. This will //increase speed, and save memory. struct MapIndexBinaryTree { MapIndexBinaryTree* left; MapIndexBinaryTree* right; UINT16 usMapIndex; }; MapIndexBinaryTree *top = NULL; //Recursively deletes all nodes below the node passed including itself. static void DeleteTreeNode(MapIndexBinaryTree** node) { if( (*node)->left ) DeleteTreeNode( &((*node)->left) ); if( (*node)->right ) DeleteTreeNode( &((*node)->right) ); delete *node; *node = NULL; } //Recursively delete all nodes (from the top down). static void ClearUndoMapIndexTree(void) { if( top ) DeleteTreeNode( &top ); } static BOOLEAN AddMapIndexToTree(UINT16 usMapIndex) { MapIndexBinaryTree *curr, *parent; if( !top ) { top = new MapIndexBinaryTree{}; top->usMapIndex = usMapIndex; top->left = NULL; top->right = NULL; return TRUE; } curr = top; parent = NULL; //Traverse down the tree and attempt to find a matching mapindex. //If one is encountered, then we fail, and don't add the mapindex to the //tree. while( curr ) { parent = curr; if( curr->usMapIndex == usMapIndex ) //found a match, so stop return FALSE; //if the mapIndex is < node's mapIndex, then go left, else right curr = ( usMapIndex < curr->usMapIndex ) ? curr->left : curr->right; } //if we made it this far, then curr is null and parent is pointing //directly above. //Create the new node and fill in the information. curr = new MapIndexBinaryTree{}; curr->usMapIndex = usMapIndex; curr->left = NULL; curr->right = NULL; //Now link the new node to the parent. if( curr->usMapIndex < parent->usMapIndex ) parent->left = curr; else parent->right = curr; return TRUE; } static undo_stack* DeleteStackNode(undo_stack* const del) { undo_struct* const undo = del->pData; undo_stack* const succ = del->pNext; delete del; MAP_ELEMENT* const me = undo->pMapTile; if (me != NULL) // light was saved -- mapelement, too? { // Free the memory associated with the map tile lists FreeLevelNodeList(&me->pLandHead); FreeLevelNodeList(&me->pObjectHead); FreeLevelNodeList(&me->pStructHead); FreeLevelNodeList(&me->pShadowHead); FreeLevelNodeList(&me->pMercHead); FreeLevelNodeList(&me->pRoofHead); FreeLevelNodeList(&me->pOnRoofHead); FreeLevelNodeList(&me->pTopmostHead); for (STRUCTURE* s = me->pStructureHead; s != NULL;) { STRUCTURE* const next = s->pNext; if (s->usStructureID > INVALID_STRUCTURE_ID) { /* Okay to delete the structure data -- otherwise, this would be merc * structure data that we DON'T want to delete, because the merc node that * hasn't been modified will still use this structure data! */ delete s; } s = next; } me->pStructureHead = NULL; delete me; delete undo; } return succ; } static void DeleteTopStackNode(void) { gpTileUndoStack = DeleteStackNode(gpTileUndoStack); } static void CropStackToMaxLength(INT32 iMaxCmds) { INT32 iCmdCount; undo_stack *pCurrent; iCmdCount = 0; pCurrent = gpTileUndoStack; // If stack is empty, leave if ( pCurrent == NULL ) return; while ( (iCmdCount <= (iMaxCmds - 1)) && (pCurrent != NULL) ) { if ( pCurrent->iCmdCount == 1 ) iCmdCount++; pCurrent = pCurrent->pNext; } // If the max number of commands was reached, and there is something // to crop, from the rest of the stack, remove it. if ( (iCmdCount >= iMaxCmds) && pCurrent != NULL ) { while ( pCurrent->pNext != NULL ) pCurrent->pNext = DeleteStackNode(pCurrent->pNext); } } //We are adding a light to the undo list. We won't save the mapelement, nor will //we validate the gridno in the binary tree. This works differently than a mapelement, //because lights work on a different system. By setting the fLightSaved flag to TRUE, //this will handle the way the undo command is handled. If there is no lightradius in //our saved light, then we intend on erasing the light upon undo execution, otherwise, we //save the light radius and light ID, so that we place it during undo execution. void AddLightToUndoList(INT32 const iMapIndex, INT32 const iLightRadius) { if (!gfUndoEnabled) return; /* When executing an undo command (by adding a light or removing one), that * command actually tries to add it to the undo list. So we wrap the * execution of the undo command by temporarily setting this flag, so it'll * ignore, and not place a new undo command. When finished, the flag is * cleared, and lights are again allowed to be saved in the undo list. */ if (gfIgnoreUndoCmdsForLights) return; SGP::PODObj<undo_struct> undo_info; undo_info->fLightSaved = TRUE; /* if ubLightRadius is 0, then we don't need to save the light information * because we will erase it when it comes time to execute the undo command. */ undo_info->ubLightRadius = iLightRadius; undo_info->iMapIndex = iMapIndex; undo_info->pMapTile = NULL; //Add to undo stack SGP::PODObj<undo_stack> n; n->iCmdCount = 1; n->pData = undo_info.Release(); n->pNext = gpTileUndoStack; gpTileUndoStack = n.Release(); CropStackToMaxLength(MAX_UNDO_COMMAND_LENGTH); } static void AddToUndoListCmd(INT32 iMapIndex, INT32 iCmdCount); BOOLEAN AddToUndoList( INT32 iMapIndex ) { static INT32 iCount = 1; if( !gfUndoEnabled ) return FALSE; if ( fNewUndoCmd ) { iCount = 0; fNewUndoCmd = FALSE; } //Check to see if the tile in question is even on the visible map, then //if that is true, then check to make sure we don't already have the mapindex //saved in the new binary tree (which only holds unique mapindex values). if( GridNoOnVisibleWorldTile( (INT16)iMapIndex ) && AddMapIndexToTree( (UINT16)iMapIndex ) ) { try { AddToUndoListCmd(iMapIndex, ++iCount); return TRUE; } catch (...) { --iCount; } } return FALSE; } static MAP_ELEMENT* CopyMapElementFromWorld(INT32 map_index); static void AddToUndoListCmd(INT32 const iMapIndex, INT32 const iCmdCount) { INT32 iCoveredMapIndex; UINT8 ubLoop; SGP::PODObj<undo_stack> pNode; SGP::PODObj<undo_struct> pUndoInfo; // Copy the world map's tile MAP_ELEMENT* const pData = CopyMapElementFromWorld(iMapIndex); STRUCTURE* pStructure = pData->pStructureHead; // copy the room number information (it's not in the mapelement structure) pUndoInfo->ubRoomNum = gubWorldRoomInfo[ iMapIndex ]; pUndoInfo->fLightSaved = FALSE; pUndoInfo->ubLightRadius = 0; pUndoInfo->pMapTile = pData; pUndoInfo->iMapIndex = iMapIndex; pNode->pData = pUndoInfo.Release(); pNode->iCmdCount = iCmdCount; pNode->pNext = gpTileUndoStack; gpTileUndoStack = pNode.Release(); // loop through pData->pStructureHead list // for each structure // find the base tile // reference the db structure // if number of tiles > 1 // add all covered tiles to undo list while (pStructure) { for (ubLoop = 1; ubLoop < pStructure->pDBStructureRef->pDBStructure->ubNumberOfTiles; ubLoop++) { // this loop won't execute for single-tile structures; for multi-tile structures, we have to // add to the undo list all the other tiles covered by the structure iCoveredMapIndex = pStructure->sBaseGridNo + pStructure->pDBStructureRef->ppTile[ubLoop]->sPosRelToBase; AddToUndoList( iCoveredMapIndex ); } pStructure = pStructure->pNext; } CropStackToMaxLength( MAX_UNDO_COMMAND_LENGTH ); } void RemoveAllFromUndoList(void) { ClearUndoMapIndexTree(); while ( gpTileUndoStack != NULL ) DeleteTopStackNode(); } static void SwapMapElementWithWorld(INT32 iMapIndex, MAP_ELEMENT* pUndoMapElement); BOOLEAN ExecuteUndoList( void ) { INT32 iCmdCount, iCurCount; INT32 iUndoMapIndex; if( !gfUndoEnabled ) return FALSE; // Is there something on the undo stack? if ( gpTileUndoStack == NULL ) return( TRUE ); // Get number of stack entries for this command (top node will tell this) iCmdCount = gpTileUndoStack->iCmdCount; // Execute each stack node in command, and remove each from stack. iCurCount = 0; while ( (iCurCount < iCmdCount) && (gpTileUndoStack != NULL) ) { iUndoMapIndex = gpTileUndoStack->pData->iMapIndex; BOOLEAN fExitGrid = FALSE; // XXX HACK000E // Find which map tile we are to "undo" if( gpTileUndoStack->pData->fLightSaved ) { //We saved a light, so delete that light //Turn on this flag so that the following code, when executed, doesn't attempt to //add lights to the undo list. That would cause problems... gfIgnoreUndoCmdsForLights = TRUE; if( !gpTileUndoStack->pData->ubLightRadius ) RemoveLight(iUndoMapIndex); else PlaceLight(gpTileUndoStack->pData->ubLightRadius, iUndoMapIndex); //Turn off the flag so lights can again be added to the undo list. gfIgnoreUndoCmdsForLights = FALSE; } else { // We execute the undo command node by simply swapping the contents // of the undo's MAP_ELEMENT with the world's element. fExitGrid = ExitGridAtGridNo( (UINT16)iUndoMapIndex ); SwapMapElementWithWorld( iUndoMapIndex, gpTileUndoStack->pData->pMapTile ); // copy the room number information back gubWorldRoomInfo[ iUndoMapIndex ] = gpTileUndoStack->pData->ubRoomNum; // Now we smooth out the changes... //SmoothUndoMapTileTerrain( iUndoMapIndex, gpTileUndoStack->pData->pMapTile ); SmoothAllTerrainTypeRadius( iUndoMapIndex, 1, TRUE ); } // ...trash the top element of the stack... DeleteTopStackNode( ); // ...and bump the command counter up by 1 iCurCount++; //Kris: //The new cursor system is somehow interfering with the undo stuff. When //an undo is called, the item is erased, but a cursor is added! I'm quickly //hacking around this by erasing all cursors here. RemoveAllTopmostsOfTypeRange( iUndoMapIndex, FIRSTPOINTERS, FIRSTPOINTERS ); if( fExitGrid && !ExitGridAtGridNo( (UINT16)iUndoMapIndex ) ) { //An exitgrid has been removed, so get rid of the associated indicator. RemoveTopmost( (UINT16)iUndoMapIndex, FIRSTPOINTERS8 ); } else if( !fExitGrid && ExitGridAtGridNo( (UINT16)iUndoMapIndex ) ) { //An exitgrid has been added, so add the associated indicator AddTopmostToTail( (UINT16)iUndoMapIndex, FIRSTPOINTERS8 ); } } return( TRUE ); } namespace { //Because of the potentially huge amounts of memory that can be allocated due to the inefficient //undo methods coded by Bret, it is feasible that it could fail. Instead of using assertions to //terminate the program, destroy the memory allocated thusfar. void DeleteMapElementContentsAfterCreationFail(MAP_ELEMENT* pNewMapElement) { LEVELNODE *pLevelNode; STRUCTURE *pStructure; INT32 x; for( x = 0; x < 9; x++ ) { if( x == 1 ) continue; pLevelNode = pNewMapElement->pLevelNodes[ x ]; while( pLevelNode ) { LEVELNODE *temp; temp = pLevelNode; pLevelNode = pLevelNode->pNext; delete temp; } } pStructure = pNewMapElement->pStructureHead; while( pStructure ) { STRUCTURE *temp; temp = pStructure; pStructure = pStructure->pNext; delete temp; } } } static MAP_ELEMENT* CopyMapElementFromWorld(INT32 const map_index) { SGP::AutoObj<MAP_ELEMENT, DeleteMapElementContentsAfterCreationFail> new_me(new MAP_ELEMENT{}); MAP_ELEMENT const* const old_me = &gpWorldLevelData[map_index]; // Save the structure information from the mapelement STRUCTURE* tail = 0; STRUCTURE** anchor = &new_me->pStructureHead; for (STRUCTURE const* i = old_me->pStructureHead; i; i = i->pNext) { STRUCTURE* const s = new STRUCTURE{}; *s = *i; s->pPrev = tail; s->pNext = 0; tail = s; *anchor = s; anchor = &s->pNext; } new_me->pStructureTail = tail; /* For each of the 9 levelnodes, save each one, except for levelnode[1] which * is a pointer to the first land to render. */ for (INT32 x = 0; x != 9; ++x) { if (x == 1 || x == 5) continue; // Skip the pLandStart and pMercLevel levelnodes LEVELNODE* tail = 0; LEVELNODE** anchor = &new_me->pLevelNodes[x]; for (LEVELNODE const* i = old_me->pLevelNodes[x]; i; i = i->pNext) { LEVELNODE* const l = new LEVELNODE{}; *l = *i; if (x == 0) l->pPrevNode = tail; // Land layer only l->pNext = 0; tail = l; *anchor = l; anchor = &l->pNext; // Handle levelnode layer specific stuff switch (x) { case 0: // Land layer // Set the new landstart to point to the new levelnode. if (old_me->pLandStart == i) new_me->pLandStart = l; break; case 3: // Struct layer case 6: // Roof layer case 7: // On roof layer if (i->pStructureData) { /* Make sure the structuredata pointer points to the parallel * structure. Both lists are exactly the same size and contain the * same information, but the addresses are different. We will * traverse the old list until we find the match, then */ STRUCTURE const* o = old_me->pStructureHead; STRUCTURE* n = new_me->pStructureHead; for (;; o = o->pNext, n = n->pNext) { /* Kris: If this assert should fail, that means there is something * wrong with the preservation of the structure data within the * mapelement. */ // OUCH!!! THIS IS HAPPENING. DISABLED IT FOR LINDA'S SAKE if (!o) break; Assert(o); Assert(n); if (o == i->pStructureData) { l->pStructureData = n; break; } } } break; } } } // Save the rest of the information in the mapelement. new_me->uiFlags = old_me->uiFlags; new_me->sHeight = old_me->sHeight; new_me->ubTerrainID = old_me->ubTerrainID; new_me->ubReservedSoldierID = old_me->ubReservedSoldierID; return new_me.Release(); } static void SwapMapElementWithWorld(INT32 const iMapIndex, MAP_ELEMENT* const pUndoMapElement) { MAP_ELEMENT *pCurrentMapElement; MAP_ELEMENT TempMapElement; pCurrentMapElement = &gpWorldLevelData[ iMapIndex ]; //Transfer the merc level node from the current world to the undo mapelement //that will replace it. We do this, because mercs aren't associated with //undo commands. pUndoMapElement->pMercHead = gpWorldLevelData[ iMapIndex ].pMercHead; gpWorldLevelData[ iMapIndex ].pMercHead = NULL; //Swap the mapelements TempMapElement = *pCurrentMapElement; *pCurrentMapElement = *pUndoMapElement; *pUndoMapElement = TempMapElement; } void DetermineUndoState() { // Reset the undo command mode if we released the left button. if( !fNewUndoCmd ) { if( (!gfLeftButtonState && !gfCurrentSelectionWithRightButton) || (!gfRightButtonState && gfCurrentSelectionWithRightButton) ) { //Clear the mapindex binary tree list, and set up flag for new undo command. fNewUndoCmd = TRUE; ClearUndoMapIndexTree(); } } }
greenvilleassociates/fusionshellplus
efront/www/editor/tiny_mce_new/plugins/advlink/langs/ca_dlg.js
<filename>efront/www/editor/tiny_mce_new/plugins/advlink/langs/ca_dlg.js tinyMCE.addI18n('ca.advlink_dlg',{ title:"Insereix/edita enlla\u00E7", url:"URL de l\'enlla\u00E7", target:"Objectiu", titlefield:"T\u00EDtol", is_email:"L\'URL que heu introdu\u00EFt sembla ser una adre\u00E7a de correu electr\u00F2nic, voleu afegir-hi el prefix requerit mailto: ?", is_external:"L\'URL que heu introdu\u00EFt sembla ser un enlla\u00E7 extern, voleu afegir-hi el prefix requerit http:// ?", list:"Llista d\'enlla\u00E7os", general_tab:"General", popup_tab:"Finestra emergent", events_tab:"Esdeveniments", advanced_tab:"Avan\u00E7at", general_props:"Propietats generals", popup_props:"Propietats de la finestra emergent", event_props:"Esdeveniments", advanced_props:"Propietats avan\u00E7ades", popup_opts:"Opcions", anchor_names:"\u00C0ncores", target_same:"Obre en aquesta finestra / marc", target_parent:"Obre en la finestra / marc pare", target_top:"Obre en el marc superior (reempla\u00E7a tots els marcs)", target_blank:"Obre en una nova finestra", popup:"Finestra emergent javascript", popup_url:"URL de la finestra emergent", popup_name:"Nom de la finestra", popup_return:"Insereix \'return false\'", popup_scrollbars:"Mostra les barres de despla\u00E7ament", popup_statusbar:"Mostra la barra d\'estat", popup_toolbar:"Mostra la barra d\'eines", popup_menubar:"Mostra la barra de men\u00FA", popup_location:"Mostra la barra d\'ubicaci\u00F3", popup_resizable:"Fes la finestra redimensionable", popup_dependent:"Dependent (nom\u00E9s Mozilla/Firefox)", popup_size:"Mida", popup_position:"Posici\u00F3 (X/Y)", id:"Id", style:"Estil", classes:"Classes", target_name:"Nom del dest\u00ED", langdir:"Direcci\u00F3 de l\'idioma", target_langcode:"Idioma del dest\u00ED", langcode:"Codi de l\'idioma", encoding:"Codificaci\u00F3 de car\u00E0cters del dest\u00ED", mime:"Tipus MIME del dest\u00ED", rel:"Relaci\u00F3 de p\u00E0gina a dest\u00ED", rev:"Relaci\u00F3 de dest\u00ED a p\u00E0gina", tabindex:"Tabindex", accesskey:"Accesskey", ltr:"D\'esquerra a dreta", rtl:"De dreta a esquerra", link_list:"Llista d\'enlla\u00E7os" });
poppeman/Pictus
source/Pictus/wintypes.h
<reponame>poppeman/Pictus<gh_stars>10-100 #ifndef PICTUS_WINTYPES_H #define PICTUS_WINTYPES_H #include "app_types.h" #include <wx/event.h> #include <orz/intl_language.h> #include <wx/colour.h> namespace Win { enum MouseButton { NoButton, Left, Right, Middle, Extra1, Extra2 }; class MouseEvent { public: MouseButton Button; Geom::PointInt Position; int WheelTicks; MouseEvent(); MouseEvent(wxMouseEvent& evt); }; class KeyEvent { public: //WPARAM Key; wchar_t Key; bool AltPressed; bool CtrlPressed; bool ShiftPressed; bool operator<(const KeyEvent &rhs) const; KeyEvent(wchar_t key, bool isAltPressed, bool isCtrlPressed, bool isShiftPressed); KeyEvent(wxKeyEvent& evt); }; Geom::RectInt wxToRect(const wxRect &rect); // RECT RectToWx(const Geom::RectInt &rect); wxPoint PointToWx(const Geom::PointInt &point); Geom::PointInt wxToPoint(wxPoint pt); ::Geom::SizeInt wxToSize(::wxSize sz); wxColor ColorToWx(Img::Color c); wxString GetStringWx(int id); wxString GetStringWx(int id, Intl::Language lang); } #endif
mrpotatoes/computer-science-in-javascript
src/recursion/array/array.js
/* eslint-disable no-unused-vars, no-undef, arrow-body-style */ // http://oskarhane.com/create-a-nested-array-recursively-in-javascript/ // Create a nested array recursively in Javascript // // Take this: // [ // {id: 1, title: 'hello', parent: 0}, // {id: 2, title: 'hello', parent: 0}, // {id: 3, title: 'hello', parent: 1}, // {id: 4, title: 'hello', parent: 3}, // {id: 5, title: 'hello', parent: 4}, // {id: 6, title: 'hello', parent: 4}, // {id: 7, title: 'hello', parent: 3}, // {id: 8, title: 'hello', parent: 2} // ] // // And turn it into this: // [ // {id: 1, title: 'hello', parent: 0, children: [ // {id: 3, title: 'hello', parent: 1, children: [ // {id: 4, title: 'hello', parent: 3, children: [ // {id: 5, title: 'hello', parent: 4}, // {id: 6, title: 'hello', parent: 4} // ]}, // {id: 7, title: 'hello', parent: 3} // ]} // ]}, // {id: 2, title: 'hello', parent: 0, children: [ // {id: 8, title: 'hello', parent: 2} // ]} // ] export const explodeFlatTree = (flat) => { return tree } export const flattenTree = (tree) => { return flat } /** * Get the evens from an array. * * Implement Ruby's `select` in JavaScript recursively. * * @note Can I do this with a return easier? * @example iterating over [1, 2, 3, 4, 5, 6, 7, 8,] and only returning even numbers. * * @param {Array} array The array to get the evens out of. * @param {Array} [newArray=[]] An array pointer (if none provided use default) * @return {Array} A new array with just even numbers. */ export const arraySelectEven = (array, newArray = []) => { if (array.length === 0) { return 0 } const first = array.shift() if (first % 2 === 0) { newArray.push(first) } // Recurse dawg. arraySelectEven(array, newArray) return newArray } /** * Get the evens from an array. * * Implement Ruby's `select` in JavaScript recursively. using user prov FN to determine * which integers to actually select to actually select. Is applied ONLY on one element at * a time. Function must return true or false. * * @note Can I do this with a return easier? * @example iterating over [1, 2, 3, 4, 5, 6, 7, 8] and only returning even numbers. * * @param {Array} array The array to get the evens out of. * @param {Function} fn [description] * @param {Array} [newArray=[]] An array pointer (if none provided use default) * @return {Array} A new array with just even numbers. */ export const arraySelect = (array, fn, newArray = []) => { if (array.length === 0) { return 0 } const first = array.shift() // Run user proved method against element. if (fn(first)) { newArray.push(first) } // Recurse dawg. arraySelect(array, fn, newArray) return newArray } /** * Given an integer remove any items from an array that are less than it. * * This is clearly a little more complicated looking than it really is. I spearated the * return into multiple lines so that the complexity can be shown with greater ease. * * @note The first parameter in Array.concat() is what we return to the concat. If the * first element of the array is equal to or greater than the concat. * @note Instead of using array.shift() we use splice this way we can do it inline. * * @example iterating over [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and only returning integers * greater than 7. * @param {int} dropBefore Drop everything before. * @param {array} array The array to work against. * @return {array} The resulting array. */ export const dropWhile = (dropBefore, array) => { if (array.length === 0) { return [] } return Array.concat( ((array[0] >= dropBefore) ? [array[0]] : []), dropWhile(dropBefore, array.splice(1, array.length)) ) }
yrgohrm/oop_ht21
lektion24/ThreadEx2.java
public class ThreadEx2 { private static class Interruptable implements Runnable { public void run() { while (!Thread.currentThread().isInterrupted()) { System.out.println("Jobbar..."); try { Thread.sleep(50); } catch (InterruptedException ex) { // always reset the interrupt status Thread.currentThread().interrupt(); System.out.println("Avbruten"); } } } } public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Interruptable()); t1.start(); Thread.sleep(500); t1.interrupt(); t1.join(); System.out.println("Exiting main thread..."); } }
podlove/podlove-web-player
build/blocks/output.js
const { distDir, prepend } = require('./dir') module.exports = (publicPath, prefix = '') => ({ path: distDir, filename: '[name].js', chunkFilename: prepend('[name].js', prefix), publicPath })
jxg01713/zstack
header/src/main/java/org/zstack/header/apimediator/ApiMessageInterceptionException.java
<reponame>jxg01713/zstack<filename>header/src/main/java/org/zstack/header/apimediator/ApiMessageInterceptionException.java<gh_stars>0 package org.zstack.header.apimediator; import org.zstack.header.errorcode.ErrorCode; /** * Created with IntelliJ IDEA. * User: frank * Time: 11:38 PM * To change this template use File | Settings | File Templates. */ public class ApiMessageInterceptionException extends RuntimeException { private ErrorCode error; public ApiMessageInterceptionException(ErrorCode err) { this.error = err; } public ErrorCode getError() { return error; } public void setError(ErrorCode error) { this.error = error; } }
Ehsan-aghapour/AI-Sheduling-Reprodution
src/runtime/cpu/operators/CpuElementwise.cpp
<filename>src/runtime/cpu/operators/CpuElementwise.cpp /* * Copyright (c) 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "src/runtime/cpu/operators/CpuElementwise.h" #include "src/core/cpu/kernels/CpuElementwiseKernel.h" namespace arm_compute { namespace cpu { void CpuElementwiseMax::configure(const ITensorInfo *input1, const ITensorInfo *input2, ITensorInfo *output) { auto k = std::make_unique<kernels::CpuArithmeticKernel>(); k->configure(ArithmeticOperation::MAX, input1, input2, output); _kernel = std::move(k); } Status CpuElementwiseMax::validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output) { return kernels::CpuArithmeticKernel::validate(ArithmeticOperation::MAX, input1, input2, output); } void CpuElementwiseMin::configure(const ITensorInfo *input1, const ITensorInfo *input2, ITensorInfo *output) { auto k = std::make_unique<kernels::CpuArithmeticKernel>(); k->configure(ArithmeticOperation::MIN, input1, input2, output); _kernel = std::move(k); } Status CpuElementwiseMin::validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output) { return kernels::CpuArithmeticKernel::validate(ArithmeticOperation::MIN, input1, input2, output); } void CpuElementwiseSquaredDiff::configure(const ITensorInfo *input1, const ITensorInfo *input2, ITensorInfo *output) { auto k = std::make_unique<kernels::CpuArithmeticKernel>(); k->configure(ArithmeticOperation::SQUARED_DIFF, input1, input2, output); _kernel = std::move(k); } Status CpuElementwiseSquaredDiff::validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output) { return kernels::CpuArithmeticKernel::validate(ArithmeticOperation::SQUARED_DIFF, input1, input2, output); } void CpuElementwiseDivision::configure(const ITensorInfo *input1, const ITensorInfo *input2, ITensorInfo *output) { auto k = std::make_unique<kernels::CpuDivisionKernel>(); k->configure(input1, input2, output); _kernel = std::move(k); } Status CpuElementwiseDivision::validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output) { return kernels::CpuDivisionKernel::validate(input1, input2, output); } void CpuElementwisePower::configure(const ITensorInfo *input1, const ITensorInfo *input2, ITensorInfo *output) { auto k = std::make_unique<kernels::CpuPowerKernel>(); k->configure(input1, input2, output); _kernel = std::move(k); } Status CpuElementwisePower::validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output) { return kernels::CpuPowerKernel::validate(input1, input2, output); } template <ComparisonOperation COP> void CpuElementwiseComparisonStatic<COP>::configure(const ITensorInfo *input1, const ITensorInfo *input2, ITensorInfo *output) { auto k = std::make_unique<kernels::CpuComparisonKernel>(); k->configure(COP, input1, input2, output); _kernel = std::move(k); } template <ComparisonOperation COP> Status CpuElementwiseComparisonStatic<COP>::validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output) { return kernels::CpuComparisonKernel::validate(COP, input1, input2, output); } void CpuElementwiseComparison::configure(const ITensorInfo *input1, const ITensorInfo *input2, ITensorInfo *output, ComparisonOperation op) { auto k = std::make_unique<kernels::CpuComparisonKernel>(); k->configure(op, input1, input2, output); _kernel = std::move(k); } Status CpuElementwiseComparison::validate(const ITensorInfo *input1, const ITensorInfo *input2, const ITensorInfo *output, ComparisonOperation op) { return kernels::CpuComparisonKernel::validate(op, input1, input2, output); } // Supported Specializations template class CpuElementwiseComparisonStatic<ComparisonOperation::Equal>; template class CpuElementwiseComparisonStatic<ComparisonOperation::NotEqual>; template class CpuElementwiseComparisonStatic<ComparisonOperation::Greater>; template class CpuElementwiseComparisonStatic<ComparisonOperation::GreaterEqual>; template class CpuElementwiseComparisonStatic<ComparisonOperation::Less>; template class CpuElementwiseComparisonStatic<ComparisonOperation::LessEqual>; } // namespace cpu } // namespace arm_compute
fernandotonon/QtMeshEditor
src/RotationGizmo.cpp
<reponame>fernandotonon/QtMeshEditor /*///////////////////////////////////////////////////////////////////////////////// /// A QtMeshEditor file /// /// Copyright (c) HogPog Team (www.hogpog.com.br) /// /// The MIT License /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. ////////////////////////////////////////////////////////////////////////////////*/ #include <QtDebug> #include "GlobalDefinitions.h" #include "RotationGizmo.h" #include "Manager.h" #include <Ogre.h> //////////////////////////////////////////////////////////////////////////////// // Static Initialisation const float RotationGizmo::mAccuracy = 30.0f; const float RotationGizmo::mSolidThickness = 40.0f; //////////////////////////////////////////////////////////////////////////////// // Constructor & destructor RotationGizmo::RotationGizmo(Ogre::SceneNode* linkNode, const Ogre::String &name, Ogre::Real scale) : m_pXCircle(0), m_pYCircle(0), m_pZCircle(0),mFade(0.4f), mHighlighted(false) { mScale = scale; Ogre::SceneManager* pSceneMgr = linkNode->getCreator(); //Creating the manual objects m_pXCircle = pSceneMgr->createManualObject(name + "X"); m_pYCircle = pSceneMgr->createManualObject(name + "Y"); m_pZCircle = pSceneMgr->createManualObject(name + "Z"); //Default Color Ogre::Real solid=1.0f; mXaxisColor = Ogre::ColourValue(solid, 0, 0, solid); mYaxisColor = Ogre::ColourValue(0, solid, 0, solid); mZaxisColor = Ogre::ColourValue(0, 0, solid, solid); m_pXCircle->setRenderQueueGroup(ZORDER_OVERLAY); // when using this, ensure Depth Check is Off in the material m_pYCircle->setRenderQueueGroup(ZORDER_OVERLAY); m_pZCircle->setRenderQueueGroup(ZORDER_OVERLAY); setQueryFlags(0); linkNode->attachObject(m_pXCircle); linkNode->attachObject(m_pYCircle); linkNode->attachObject(m_pZCircle); } RotationGizmo::~RotationGizmo() { Ogre::SceneManager* pSceneMgr = m_pXCircle->getParentSceneNode()->getCreator(); //TODO unload material ?? pSceneMgr->destroyManualObject(m_pXCircle); pSceneMgr->destroyManualObject(m_pYCircle); pSceneMgr->destroyManualObject(m_pZCircle); } void RotationGizmo::createXCircle(const Ogre::ColourValue& colour) { m_pXCircle->clear(); m_pXCircle->begin(GUI_MATERIAL_NAME, Ogre::RenderOperation::OT_LINE_STRIP); m_pXCircle->colour(colour); for(float theta = 0; theta <= 2 * Ogre::Math::PI; theta += Ogre::Math::PI / mAccuracy) m_pXCircle->position(0, cos(theta)*mScale, sin(theta)*mScale); m_pXCircle->end(); } void RotationGizmo::createYCircle(const Ogre::ColourValue& colour) { m_pYCircle->clear(); m_pYCircle->begin(GUI_MATERIAL_NAME, Ogre::RenderOperation::OT_LINE_STRIP); m_pYCircle->colour(colour); for(float theta = 0; theta <= 2 * Ogre::Math::PI; theta += Ogre::Math::PI / mAccuracy) m_pYCircle->position(cos(theta)*mScale, 0, sin(theta)*mScale); m_pYCircle->end(); } void RotationGizmo::createZCircle(const Ogre::ColourValue& colour) { m_pZCircle->clear(); m_pZCircle->begin(GUI_MATERIAL_NAME, Ogre::RenderOperation::OT_LINE_STRIP); m_pZCircle->colour(colour); for(float theta = 0; theta <= 2 * Ogre::Math::PI; theta += Ogre::Math::PI / mAccuracy) m_pZCircle->position(cos(theta)*mScale, sin(theta)*mScale,0); m_pZCircle->end(); } void RotationGizmo::createSolidXCircle(const Ogre::ColourValue& colour) { float thickness = mScale / mSolidThickness; unsigned point_index = 0; m_pXCircle->clear(); m_pXCircle->begin(GUI_MATERIAL_NAME, Ogre::RenderOperation::OT_TRIANGLE_LIST ); m_pXCircle->colour(colour); for(float theta = 0; theta <= 2 * Ogre::Math::PI; theta += Ogre::Math::PI / mAccuracy) { m_pXCircle->position(0, mScale * cos(theta), mScale * sin(theta)); m_pXCircle->position(0, mScale * cos(theta - Ogre::Math::PI / mAccuracy), mScale * sin(theta - Ogre::Math::PI / mAccuracy)); m_pXCircle->position(0, (mScale - thickness) * cos(theta - Ogre::Math::PI / mAccuracy), (mScale - thickness) * sin(theta - Ogre::Math::PI / mAccuracy)); m_pXCircle->position(0, (mScale - thickness) * cos(theta), (mScale - thickness) * sin(theta)); // Join the 4 vertices created above to form a quad. m_pXCircle->quad(point_index, point_index + 1, point_index + 2, point_index + 3); m_pXCircle->quad(point_index + 3, point_index + 2, point_index + 1, point_index); point_index += 4; } m_pXCircle->end(); } void RotationGizmo::createSolidYCircle(const Ogre::ColourValue& colour) { float thickness = mScale / mSolidThickness; unsigned point_index = 0; m_pYCircle->clear(); m_pYCircle->begin(GUI_MATERIAL_NAME, Ogre::RenderOperation::OT_TRIANGLE_LIST ); m_pYCircle->colour(colour); for(float theta = 0; theta <= 2 * Ogre::Math::PI; theta += Ogre::Math::PI / mAccuracy) { m_pYCircle->position(mScale * cos(theta), 0, mScale * sin(theta)); m_pYCircle->position(mScale * cos(theta - Ogre::Math::PI / mAccuracy), 0, mScale * sin(theta - Ogre::Math::PI / mAccuracy)); m_pYCircle->position((mScale - thickness) * cos(theta - Ogre::Math::PI / mAccuracy), 0,(mScale - thickness) * sin(theta - Ogre::Math::PI / mAccuracy)); m_pYCircle->position((mScale - thickness) * cos(theta), 0, (mScale - thickness) * sin(theta)); // Join the 4 vertices created above to form a quad. m_pYCircle->quad(point_index, point_index + 1, point_index + 2, point_index + 3); m_pYCircle->quad(point_index + 3, point_index + 2, point_index + 1, point_index); point_index += 4; } m_pYCircle->end(); } void RotationGizmo::createSolidZCircle(const Ogre::ColourValue& colour) { float thickness = mScale / mSolidThickness; unsigned point_index = 0; m_pZCircle->clear(); m_pZCircle->begin(GUI_MATERIAL_NAME, Ogre::RenderOperation::OT_TRIANGLE_LIST ); m_pZCircle->colour(colour); for(float theta = 0; theta <= 2 * Ogre::Math::PI; theta += Ogre::Math::PI / mAccuracy) { m_pZCircle->position(mScale * cos(theta), mScale * sin(theta), 0); m_pZCircle->position(mScale * cos(theta - Ogre::Math::PI / mAccuracy), mScale * sin(theta - Ogre::Math::PI / mAccuracy), 0); m_pZCircle->position((mScale - thickness) * cos(theta - Ogre::Math::PI / mAccuracy), (mScale - thickness) * sin(theta - Ogre::Math::PI / mAccuracy), 0); m_pZCircle->position((mScale - thickness) * cos(theta), (mScale - thickness) * sin(theta), 0); // Join the 4 vertices created above to form a quad. m_pZCircle->quad(point_index, point_index + 1, point_index + 2, point_index + 3); m_pZCircle->quad(point_index + 3, point_index + 2, point_index + 1, point_index); point_index += 4; } m_pZCircle->end(); } ////////////////////////////////////////// // Accessors bool RotationGizmo::isHighlighted(void) const { return (mHighlighted); } Ogre::uint32 RotationGizmo::getQueryFlags(void) const { return (m_pXCircle->getQueryFlags()); } const Ogre::Real& RotationGizmo::getFading(void) const { return (mFade); } const Ogre::ColourValue& RotationGizmo::getXaxisColour (void) const { return (mXaxisColor); } const Ogre::ColourValue& RotationGizmo::getYaxisColour (void) const { return (mYaxisColor); } const Ogre::ColourValue& RotationGizmo::getZaxisColour (void) const { return (mZaxisColor); } const Ogre::Real& RotationGizmo::getScale(void) const { return (mScale); } ////////////////////////////////////////// // Mutators void RotationGizmo::setVisible(bool visible) { if(visible) createCircles(); m_pXCircle->setVisible(visible); m_pYCircle->setVisible(visible); m_pZCircle->setVisible(visible); } void RotationGizmo::setQueryFlags(Ogre::uint32 flags) { m_pXCircle->setQueryFlags(flags); m_pYCircle->setQueryFlags(flags); m_pZCircle->setQueryFlags(flags); } void RotationGizmo::setFading(const Ogre::Real& fade) { mFade = fade; } void RotationGizmo::setXaxisColour ( const Ogre::ColourValue &colour) { mXaxisColor = colour; createXCircle(mXaxisColor); } void RotationGizmo::setYaxisColour ( const Ogre::ColourValue &colour) { mYaxisColor = colour; createYCircle(mYaxisColor); } void RotationGizmo::setZaxisColour ( const Ogre::ColourValue &colour) { mZaxisColor = colour; createZCircle(mZaxisColor); } void RotationGizmo::setScale ( const Ogre::Real& scale ) { mScale = scale; createCircles(); } void RotationGizmo::createCircles(void) { createXCircle(mXaxisColor); createYCircle(mYaxisColor); createZCircle(mZaxisColor); mHighlighted = false; } Ogre::Vector3 RotationGizmo::highlightCircle(const Ogre::MovableObject* obj) { Ogre::Vector3 result = Ogre::Vector3::ZERO; if(obj == m_pXCircle) { createSolidXCircle(mXaxisColor); createYCircle(mYaxisColor*mFade); createZCircle(mZaxisColor*mFade); result = Ogre::Vector3::UNIT_X; mHighlighted = true; } else if(obj == m_pYCircle) { createSolidYCircle(mYaxisColor); createXCircle(mXaxisColor*mFade); createZCircle(mZaxisColor*mFade); result = Ogre::Vector3::UNIT_Y; mHighlighted = true; } else if(obj == m_pZCircle) { createSolidZCircle(mZaxisColor); createXCircle(mXaxisColor*mFade); createYCircle(mYaxisColor*mFade); result = Ogre::Vector3::UNIT_Z; mHighlighted = true; } else { createCircles(); } return result; }
keep-practicing/algorithms
data-structures/singlelinkedlist/singlelinkedlist.go
// 单链表实现 package singlelinkedlist // Node is an element of a linked list. type Node struct { Value interface{} next *Node } // List represents a single linked list. // The zero value for List is an empty list ready to use. type List struct { Head *Node len int } // Init initializes or clears list l. func (l *List) Init() *List { l.Head = &Node{} l.len = 0 return l } // New returns an initialized list. func New() *List { return new(List).Init() } // IsEmpty judge the list is empty func (l *List) IsEmpty() bool { return l.Head.next == nil } // Length size of list func (l *List) Length() int { return l.len } // Clear clear list func (l *List) Clear() { l.Init() } // Insert inserts n, increments l.len, and returns e. func (l *List) Insert(i int, n *Node) bool { if i < 1 || i > l.len+1 { return false } current := l.Head for k := 1; k < i; k++ { current = current.next } n.next = current.next current.next = n l.len++ return false } // Delete delete i from list. func (l *List) Delete(i int) (r interface{}, ok bool) { if i < 1 || i > l.len { return } current := l.Head var before *Node for k := 1; k <= i; k++ { before, current = current, current.next } before.next = current.next r = current.Value current = nil l.len-- return r, true } // GetNode get node from list by index. func (l *List) GetNode(index int) (r Node, ok bool) { if index < 1 || index > l.len { return } current := l.Head for k := 1; k <= index; k++ { current = current.next } r = Node{Value: current.Value} return r, true } // GetIndex get index if Value is x. func (l *List) GetIndex(x interface{}) (index int) { for current := l.Head; current.next != nil; { current = current.next index++ if current.Value == x { break } } return }
marsgis/mars3d-es5-example
example/layer-graphic/file/czml/map.js
// import * as mars3d from "mars3d" var map // mars3d.Map三维地图对象 var graphicLayer // 矢量图层对象 // 需要覆盖config.json中地图属性参数(当前示例框架中自动处理合并) var mapOptions = { scene: { center: { lat: 31.623244, lng: 123.508771, alt: 345435, heading: 0, pitch: -48 } // cameraController: { // maximumZoomDistance: 500000000, // }, }, control: { clockAnimate: true, // 时钟动画控制(左下角) timeline: true, compass: { top: "10px", left: "5px" } } } var eventTarget = new mars3d.BaseClass() /** * 初始化地图业务,生命周期钩子函数(必须) * 框架在地图初始化完成后自动调用该函数 * @param {mars3d.Map} mapInstance 地图对象 * @returns {void} 无 */ function onMounted(mapInstance) { map = mapInstance // 记录首次创建的map map.toolbar.style.bottom = "55px" // 修改toolbar控件的样式 // url传入模型地址 const type = mars3d.Util.getRequestByName("data") switch (type) { case "feiji": showAircraft() break case "chuanbo": showShip() break case "huojian": showRocket() break default: showAircraft() break } } /** * 释放当前地图业务的生命周期函数 * @returns {void} 无 */ function onUnmounted() { map = null } function removeLayer() { map.trackedEntity = null if (graphicLayer) { map.removeLayer(graphicLayer, true) graphicLayer = null } } // 示例: function showAircraft() { removeLayer() graphicLayer = new mars3d.layer.CzmlLayer({ name: "飞行编队", url: "//data.mars3d.cn/file/czml/flight.czml", popup: "all", flyTo: true }) map.addLayer(graphicLayer) // 绑定事件 graphicLayer.on(mars3d.EventType.load, function (data) { console.log("数据加载完成", data) eventTarget.fire("loadGraphicLayer", { data }) }) graphicLayer.on(mars3d.EventType.click, function (event) { console.log("单击了图层", event) }) } // 示例: function showCar() { removeLayer() map.setCameraView({ lat: 40.893923, lng: 121.917192, alt: 691, heading: 64, pitch: -46 }) graphicLayer = new mars3d.layer.CzmlLayer({ name: "汽车", url: "//data.mars3d.cn/file/czml/car.czml" // flyTo: true, }) map.addLayer(graphicLayer) // 绑定事件 graphicLayer.on(mars3d.EventType.load, function (data) { console.log("数据加载完成", data) eventTarget.fire("loadGraphicLayer", { data }) }) graphicLayer.on(mars3d.EventType.click, function (event) { console.log("单击了图层", event) }) } // 示例: function showShip() { removeLayer() graphicLayer = new mars3d.layer.CzmlLayer({ name: "船舶编队", url: "//data.mars3d.cn/file/czml/ship.czml", popup: "all", flyTo: true }) map.addLayer(graphicLayer) // 绑定事件 graphicLayer.on(mars3d.EventType.load, function (data) { console.log("数据加载完成", data) eventTarget.fire("loadGraphicLayer", { data }) }) graphicLayer.on(mars3d.EventType.click, function (event) { console.log("单击了图层", event) }) } // 示例: function showBDSatellite() { removeLayer() // 更新地球参数 map.setSceneOptions({ cameraController: { maximumZoomDistance: 500000000 } }) graphicLayer = new mars3d.layer.CzmlLayer({ name: "北斗卫星", url: "//data.mars3d.cn/file/czml/satellite.czml", center: { lng: 10, lat: 111.833884, z: 150000000, heading: 0, pitch: -90, roll: 0 }, flyTo: true }) map.addLayer(graphicLayer) // 绑定事件 graphicLayer.on(mars3d.EventType.load, function (data) { console.log("数据加载完成", data) eventTarget.fire("loadGraphicLayer", { data }) }) graphicLayer.on(mars3d.EventType.click, function (event) { console.log("单击了图层", event) }) } function showSatellite() { removeLayer() // 更新地球参数 map.setSceneOptions({ cameraController: { maximumZoomDistance: 500000000 } }) graphicLayer = new mars3d.layer.CzmlLayer({ name: "卫星", url: "//data.mars3d.cn/file/czml/satellite-simple.czml", center: { lat: -20.236138, lng: -144.262661, alt: 41875827, heading: 339, pitch: -90 }, flyTo: true }) map.addLayer(graphicLayer) // 绑定事件 graphicLayer.on(mars3d.EventType.load, function (data) { console.log("数据加载完成", data) eventTarget.fire("loadGraphicLayer", { data }) }) graphicLayer.on(mars3d.EventType.click, function (event) { console.log("单击了图层", event) }) } // 示例: function showRocket() { removeLayer() map.basemap = "ArcGIS影像" map.setCameraView({ lat: 28.561843, lng: -80.577575, alt: 630, heading: 359, pitch: -85 }) graphicLayer = new mars3d.layer.CzmlLayer({ name: "火箭发射", url: "//data.mars3d.cn/file/czml/space.czml", flyTo: true }) map.addLayer(graphicLayer) // 绑定事件 graphicLayer.on(mars3d.EventType.load, function (data) { console.log("数据加载完成", data) // 火星发射时,锁定火箭模型对象 map.trackedEntity = data.dataSource.entities.getById("Vulcan") eventTarget.fire("loadGraphicLayer", { data }) }) graphicLayer.on(mars3d.EventType.click, function (event) { console.log("单击了图层", event) }) } // 示例: function showFireDrill() { removeLayer() map.setCameraView({ lat: 32.891559, lng: 117.360875, alt: 378, heading: 18, pitch: -62 }) graphicLayer = new mars3d.layer.CzmlLayer({ name: "消防演练", url: "//data.mars3d.cn/file/czml/firedrill.czml" // flyTo: true }) map.addLayer(graphicLayer) // 绑定事件 graphicLayer.on(mars3d.EventType.load, function (data) { console.log("数据加载完成", data) eventTarget.fire("loadGraphicLayer", { data }) }) graphicLayer.on(mars3d.EventType.click, function (event) { console.log("单击了图层", event) }) }
rnarla123/aliyun-openapi-java-sdk
aliyun-java-sdk-copyright/src/main/java/com/aliyuncs/copyright/model/v20190123/SaveCopyrightPersonRequest.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.copyright.model.v20190123; import com.aliyuncs.RpcAcsRequest; import com.aliyuncs.http.MethodType; /** * @author auto create * @version */ public class SaveCopyrightPersonRequest extends RpcAcsRequest<SaveCopyrightPersonResponse> { private String city; private String idBackImage; private String idFrontImage; private String county; private String enterpriseTime; private Long expiredDate; private String province; private Integer roleType; private Long personId; private String cardType; private String legalPersonType; private String email; private String idHandedImage; private String address; private String enterprisePark; private String cardNum; private String enterpriseLicensePath; private String phone; private Integer ownerType; private String name; private String enterpriseType; private Integer useType; public SaveCopyrightPersonRequest() { super("Copyright", "2019-01-23", "SaveCopyrightPerson"); setMethod(MethodType.POST); } public String getCity() { return this.city; } public void setCity(String city) { this.city = city; if(city != null){ putQueryParameter("City", city); } } public String getIdBackImage() { return this.idBackImage; } public void setIdBackImage(String idBackImage) { this.idBackImage = idBackImage; if(idBackImage != null){ putQueryParameter("IdBackImage", idBackImage); } } public String getIdFrontImage() { return this.idFrontImage; } public void setIdFrontImage(String idFrontImage) { this.idFrontImage = idFrontImage; if(idFrontImage != null){ putQueryParameter("IdFrontImage", idFrontImage); } } public String getCounty() { return this.county; } public void setCounty(String county) { this.county = county; if(county != null){ putQueryParameter("County", county); } } public String getEnterpriseTime() { return this.enterpriseTime; } public void setEnterpriseTime(String enterpriseTime) { this.enterpriseTime = enterpriseTime; if(enterpriseTime != null){ putQueryParameter("EnterpriseTime", enterpriseTime); } } public Long getExpiredDate() { return this.expiredDate; } public void setExpiredDate(Long expiredDate) { this.expiredDate = expiredDate; if(expiredDate != null){ putQueryParameter("ExpiredDate", expiredDate.toString()); } } public String getProvince() { return this.province; } public void setProvince(String province) { this.province = province; if(province != null){ putQueryParameter("Province", province); } } public Integer getRoleType() { return this.roleType; } public void setRoleType(Integer roleType) { this.roleType = roleType; if(roleType != null){ putQueryParameter("RoleType", roleType.toString()); } } public Long getPersonId() { return this.personId; } public void setPersonId(Long personId) { this.personId = personId; if(personId != null){ putQueryParameter("PersonId", personId.toString()); } } public String getCardType() { return this.cardType; } public void setCardType(String cardType) { this.cardType = cardType; if(cardType != null){ putQueryParameter("CardType", cardType); } } public String getLegalPersonType() { return this.legalPersonType; } public void setLegalPersonType(String legalPersonType) { this.legalPersonType = legalPersonType; if(legalPersonType != null){ putQueryParameter("LegalPersonType", legalPersonType); } } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; if(email != null){ putQueryParameter("Email", email); } } public String getIdHandedImage() { return this.idHandedImage; } public void setIdHandedImage(String idHandedImage) { this.idHandedImage = idHandedImage; if(idHandedImage != null){ putQueryParameter("IdHandedImage", idHandedImage); } } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; if(address != null){ putQueryParameter("Address", address); } } public String getEnterprisePark() { return this.enterprisePark; } public void setEnterprisePark(String enterprisePark) { this.enterprisePark = enterprisePark; if(enterprisePark != null){ putQueryParameter("EnterprisePark", enterprisePark); } } public String getCardNum() { return this.cardNum; } public void setCardNum(String cardNum) { this.cardNum = cardNum; if(cardNum != null){ putQueryParameter("CardNum", cardNum); } } public String getEnterpriseLicensePath() { return this.enterpriseLicensePath; } public void setEnterpriseLicensePath(String enterpriseLicensePath) { this.enterpriseLicensePath = enterpriseLicensePath; if(enterpriseLicensePath != null){ putQueryParameter("EnterpriseLicensePath", enterpriseLicensePath); } } public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; if(phone != null){ putQueryParameter("Phone", phone); } } public Integer getOwnerType() { return this.ownerType; } public void setOwnerType(Integer ownerType) { this.ownerType = ownerType; if(ownerType != null){ putQueryParameter("OwnerType", ownerType.toString()); } } public String getName() { return this.name; } public void setName(String name) { this.name = name; if(name != null){ putQueryParameter("Name", name); } } public String getEnterpriseType() { return this.enterpriseType; } public void setEnterpriseType(String enterpriseType) { this.enterpriseType = enterpriseType; if(enterpriseType != null){ putQueryParameter("EnterpriseType", enterpriseType); } } public Integer getUseType() { return this.useType; } public void setUseType(Integer useType) { this.useType = useType; if(useType != null){ putQueryParameter("UseType", useType.toString()); } } @Override public Class<SaveCopyrightPersonResponse> getResponseClass() { return SaveCopyrightPersonResponse.class; } }
angelorc/okchain
x/backend/keeper/keeper_channel.go
package keeper import ( "fmt" "time" "github.com/okex/okchain/x/backend/config" "github.com/okex/okchain/x/backend/orm" "github.com/okex/okchain/x/backend/types" "github.com/tendermint/tendermint/libs/log" ) func pushAllKline1m(klines map[string][]types.KlineM1, keeper Keeper, nextStartTS int64) { keeper.Logger.Debug("pushAllKline1m_1", "klines", klines) if klines != nil && len(klines) > 0 { for _, klineArr := range klines { if klineArr == nil { continue } for _, k := range klineArr { keeper.Logger.Debug("pushAllKline1m_2", "kline", &k) keeper.pushWSItem(&k) } } } if nextStartTS > 0 { notifyEvt := types.NewFakeWSEvent(types.KlineTypeM1, "", nextStartTS) keeper.pushWSItem(notifyEvt) } } func generateKline1M(stop chan struct{}, conf *config.Config, o *orm.ORM, log *log.Logger, keeper Keeper) { o.Debug("[backend] generateKline1M go routine started") defer types.PrintStackIfPanic() startTS, endTS := int64(0), time.Now().Unix()-60 time.Sleep(3 * time.Second) if o.GetMaxBlockTimestamp() > 0 { endTS = o.GetMaxBlockTimestamp() } //ds := DealDataSource{orm: orm} ds := orm.MergeResultDataSource{Orm: o} anchorNewStartTS, _, newKline1s, err := o.CreateKline1min(startTS, endTS, &ds) if err != nil { (*log).Debug(fmt.Sprintf("[backend] error: %+v \n", err)) } pushAllKline1m(newKline1s, keeper, anchorNewStartTS) waitInSecond := int(60+types.Kline1GoRoutineWaitInSecond-time.Now().Second()) % 60 timer := time.NewTimer(time.Duration(waitInSecond * int(time.Second))) interval := time.Second * 60 ticker := time.NewTicker(interval) go CleanUpKlines(stop, o, conf) var klineNotifyChans *map[int]chan struct{} work := func() { if o.GetMaxBlockTimestamp() == 0 { return } crrtBlkTS := o.GetMaxBlockTimestamp() (*log).Debug(fmt.Sprintf("[backend] line1M [%d, %d) [%s, %s)", anchorNewStartTS, crrtBlkTS, types.TimeString(anchorNewStartTS), types.TimeString(crrtBlkTS))) anchorNextStart, _, newKline1s, err := o.CreateKline1min(anchorNewStartTS, crrtBlkTS, &ds) (*log).Debug(fmt.Sprintf("[backend] generateKline1M's actually merge period [%s, %s)", types.TimeString(anchorNewStartTS), types.TimeString(anchorNextStart))) if err != nil { (*log).Debug(fmt.Sprintf("[backend] generateKline1M error: %s", err.Error())) } else { // if new klines created, push them if anchorNextStart > anchorNewStartTS { pushAllKline1m(newKline1s, keeper, anchorNewStartTS) if klineNotifyChans != nil { for _, ch := range *klineNotifyChans { ch <- struct{}{} } } anchorNewStartTS = anchorNextStart } } } work() klineNotifyChans = generateSyncKlineMXChans() for freq, ntfCh := range *klineNotifyChans { go generateKlinesMX(ntfCh, stop, freq, o, keeper) } for { select { case <-timer.C: work() ticker = time.NewTicker(interval) case <-ticker.C: work() case <-stop: break } } } func generateSyncKlineMXChans() *map[int]chan struct{} { notifyChans := map[int]chan struct{}{} klineMap := types.GetAllKlineMap() for freq := range klineMap { if freq > 60 { notifyCh := make(chan struct{}, 1) notifyChans[freq] = notifyCh } } return &notifyChans } func pushAllKlineXm(klines map[string][]interface{}, keeper Keeper, klineType string, nextStartTS int64) { if klines != nil && len(klines) >0 { for _, klineArr := range klines { if klineArr == nil { continue } for _, k := range klineArr { baseLine := k.(types.IWebsocket) keeper.pushWSItem(baseLine) } } } if nextStartTS > 0 { fe := types.NewFakeWSEvent(klineType, "", nextStartTS) keeper.pushWSItem(fe) } } func generateKlinesMX(notifyChan chan struct{}, stop chan struct{}, refreshInterval int, o *orm.ORM, keeper Keeper) { o.Debug(fmt.Sprintf("[backend] generateKlineMX-#%d# go routine started", refreshInterval)) destKName := types.GetKlineTableNameByFreq(refreshInterval) destK, err := types.NewKlineFactory(destKName, nil) if err != nil { o.Error(fmt.Sprintf("[backend] NewKlineFactory error: %s", err.Error())) } destIKline := destK.(types.IKline) startTS, endTS := int64(0), time.Now().Unix()-int64(destIKline.GetFreqInSecond()) anchorNewStartTS, _, newKlines, err := o.MergeKlineM1(startTS, endTS, destIKline) if err != nil { o.Error(fmt.Sprintf("[backend] MergeKlineM1 error: %s", err.Error())) } else { pushAllKlineXm(newKlines, keeper, destIKline.GetTableName(), anchorNewStartTS) } //waitInSecond := int(60+KlineX_GOROUTINE_WAIT_IN_SECOND-time.Now().Second()) % 60 crrTS := time.Now().Unix() waitInSecond := int64(destIKline.GetFreqInSecond()) - (crrTS - destIKline.GetAnchorTimeTS(crrTS)) + types.KlinexGoRoutineWaitInSecond + 60 timer := time.NewTimer(time.Duration(int(waitInSecond) * int(time.Second))) interval := time.Duration(destIKline.GetFreqInSecond() * int(time.Second)) o.Debug(fmt.Sprintf("[backend] duaration: %+v(%d s) IKline: %+v ", interval, destIKline.GetFreqInSecond(), destIKline)) ticker := time.NewTicker(interval) work := func() { if o.GetMaxBlockTimestamp() == 0 { return } latestBlockTS := o.GetMaxBlockTimestamp() o.Debug(fmt.Sprintf("[backend] entering generateKlinesMX-#%d# [%d, %d)[%s, %s)", destIKline.GetFreqInSecond(), anchorNewStartTS, latestBlockTS, types.TimeString(anchorNewStartTS), types.TimeString(latestBlockTS))) anchorNextStart, _, newKlines, err := o.MergeKlineM1(anchorNewStartTS, latestBlockTS, destIKline) o.Debug(fmt.Sprintf("[backend] generateKlinesMX-#%d#'s actually merge period [%s, %s)", destIKline.GetFreqInSecond(), types.TimeString(anchorNewStartTS), types.TimeString(anchorNextStart))) if err != nil { o.Error(fmt.Sprintf("[backend] error: %s", err.Error())) } else { if anchorNextStart > anchorNewStartTS { anchorNewStartTS = anchorNextStart pushAllKlineXm(newKlines, keeper, destIKline.GetTableName(), anchorNewStartTS) } } } for { select { case <-notifyChan: time.Sleep(time.Second) if anchorNewStartTS > 0 && time.Now().Unix() < anchorNewStartTS+int64(destIKline.GetFreqInSecond()) { break } else { work() ticker = time.NewTicker(interval) } case <-ticker.C: work() case <-timer.C: work() case <-stop: break } } } // nolint func CleanUpKlines(stop chan struct{}, o *orm.ORM, conf *config.Config) { o.Debug(fmt.Sprintf("[backend] cleanUpKlines go routine started. MaintainConf: %+v", *conf)) interval := time.Duration(60 * int(time.Second)) ticker := time.NewTicker(time.Duration(int(60-time.Now().Second()) * int(time.Second))) work := func() { now := time.Now() strNow := now.Format("15:04:05") if strNow == conf.CleanUpsTime { m := types.GetAllKlineMap() for _, ktype := range m { expiredDays := conf.CleanUpsKeptDays[ktype] if expiredDays != 0 { o.Debug(fmt.Sprintf("[backend] entering cleanUpKlines, "+ "fired time: %s(currentTS: %d), kline type: %s", conf.CleanUpsTime, now.Unix(), ktype)) //anchorTS := now.Add(-time.Duration(int(time.Second) * 1440 * expiredDays)).Unix() anchorTS := now.Add(-time.Duration(int(time.Second) * types.SecondsInADay * expiredDays)).Unix() kline, err := types.NewKlineFactory(ktype, nil) if err != nil { o.Debug("failed to NewKlineFactory becoz of : " + err.Error()) break } if err = o.DeleteKlineBefore(anchorTS, kline); err != nil { o.Error("failed to DeleteKlineBefore because " + err.Error()) } } } } } for { select { case <-ticker.C: work() ticker = time.NewTicker(interval) case <-stop: break } } }
Texas-C/echo
thirdparty/vulkan/vulkan-validationlayers/layers/sync_utils.cpp
<filename>thirdparty/vulkan/vulkan-validationlayers/layers/sync_utils.cpp /* * Copyright (c) 2019-2021 Valve Corporation * Copyright (c) 2019-2021 LunarG, 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. * * Author: <NAME> <<EMAIL>> * Author: <NAME> <<EMAIL>> * Author: <NAME> <<EMAIL>> */ #include "sync_utils.h" #include "state_tracker.h" #include "descriptor_sets.h" #include "core_validation_types.h" #include "synchronization_validation_types.h" namespace sync_utils { static constexpr uint32_t kNumPipelineStageBits = sizeof(VkPipelineStageFlags2KHR) * 8; VkPipelineStageFlags2KHR DisabledPipelineStages(const DeviceFeatures &features) { VkPipelineStageFlags2KHR result = 0; if (!features.core.geometryShader) { result |= VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT; } if (!features.core.tessellationShader) { result |= VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT; } if (!features.conditional_rendering.conditionalRendering) { result |= VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT; } if (!features.fragment_density_map_features.fragmentDensityMap) { result |= VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT; } if (!features.transform_feedback_features.transformFeedback) { result |= VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT; } if (!features.mesh_shader.meshShader) { result |= VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV; } if (!features.mesh_shader.taskShader) { result |= VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV; } if (!features.fragment_shading_rate_features.pipelineFragmentShadingRate && !features.shading_rate_image.shadingRateImage) { result |= VK_PIPELINE_STAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR; } // TODO: VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR // TODO: VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_KHR return result; } VkPipelineStageFlags2KHR ExpandPipelineStages(VkPipelineStageFlags2KHR stage_mask, VkQueueFlags queue_flags, const VkPipelineStageFlags2KHR disabled_feature_mask) { VkPipelineStageFlags2KHR expanded = stage_mask; if (VK_PIPELINE_STAGE_ALL_COMMANDS_BIT & stage_mask) { expanded &= ~VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; for (const auto &all_commands : syncAllCommandStagesByQueueFlags) { if (all_commands.first & queue_flags) { expanded |= all_commands.second & ~disabled_feature_mask; } } } if (VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT & stage_mask) { expanded &= ~VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT; // Make sure we don't pull in the HOST stage from expansion, but keep it if set by the caller. // The syncAllCommandStagesByQueueFlags table includes HOST for all queue types since it is // allowed but it shouldn't be part of ALL_GRAPHICS expanded |= syncAllCommandStagesByQueueFlags.at(VK_QUEUE_GRAPHICS_BIT) & ~disabled_feature_mask & ~VK_PIPELINE_STAGE_HOST_BIT; } if (VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT_KHR & stage_mask) { expanded &= ~VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT_KHR; expanded |= VK_PIPELINE_STAGE_2_COPY_BIT_KHR | VK_PIPELINE_STAGE_2_RESOLVE_BIT_KHR | VK_PIPELINE_STAGE_2_BLIT_BIT_KHR | VK_PIPELINE_STAGE_2_CLEAR_BIT_KHR; } if (VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT_KHR & stage_mask) { expanded &= ~VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT_KHR; expanded |= VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT_KHR | VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT_KHR; } if (VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT_KHR & stage_mask) { expanded &= ~VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT_KHR; expanded |= VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT_KHR | VK_PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT_KHR | VK_PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT_KHR | VK_PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT_KHR; } return expanded; } static const auto kShaderReadExpandBits = VK_ACCESS_2_UNIFORM_READ_BIT_KHR | VK_ACCESS_2_SHADER_SAMPLED_READ_BIT_KHR | VK_ACCESS_2_SHADER_STORAGE_READ_BIT_KHR; static const auto kShaderWriteExpandBits = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT_KHR; VkAccessFlags2KHR ExpandAccessFlags(VkAccessFlags2KHR access_mask) { VkAccessFlags2KHR expanded = access_mask; if (VK_ACCESS_2_SHADER_READ_BIT_KHR & access_mask) { expanded = expanded & ~VK_ACCESS_2_SHADER_READ_BIT_KHR; expanded |= kShaderReadExpandBits; } if (VK_ACCESS_2_SHADER_WRITE_BIT_KHR & access_mask) { expanded = expanded & ~VK_ACCESS_2_SHADER_WRITE_BIT_KHR; expanded |= kShaderWriteExpandBits; } return expanded; } VkAccessFlags2KHR CompatibleAccessMask(VkPipelineStageFlags2KHR stage_mask) { VkAccessFlags2KHR result = 0; stage_mask = ExpandPipelineStages(stage_mask); for (size_t i = 0; i < kNumPipelineStageBits; i++) { VkPipelineStageFlags2KHR bit = 1ULL << i; if (stage_mask & bit) { auto access_rec = syncDirectStageToAccessMask.find(bit); if (access_rec != syncDirectStageToAccessMask.end()) { result |= access_rec->second; continue; } } } // put the meta-access bits back on if (result & kShaderReadExpandBits) { result |= VK_ACCESS_2_SHADER_READ_BIT_KHR; } if (result & kShaderWriteExpandBits) { result |= VK_ACCESS_2_SHADER_WRITE_BIT_KHR; } return result; } VkPipelineStageFlags2KHR RelatedPipelineStages(VkPipelineStageFlags2KHR stage_mask, const std::map<VkPipelineStageFlags2KHR, VkPipelineStageFlags2KHR> &map) { VkPipelineStageFlags2KHR unscanned = stage_mask; VkPipelineStageFlags2KHR related = 0; for (const auto &entry : map) { const auto &stage = entry.first; if (stage & unscanned) { related = related | entry.second; unscanned = unscanned & ~stage; if (!unscanned) break; } } return related; } VkPipelineStageFlags2KHR WithEarlierPipelineStages(VkPipelineStageFlags2KHR stage_mask) { return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyEarlierStages); } VkPipelineStageFlags2KHR WithLaterPipelineStages(VkPipelineStageFlags2KHR stage_mask) { return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyLaterStages); } int GetGraphicsPipelineStageLogicalOrdinal(VkPipelineStageFlags2KHR flag) { const auto &rec = syncStageOrder.find(flag); if (rec == syncStageOrder.end()) { return -1; } return rec->second; } // The following two functions technically have O(N^2) complexity, but it's for a value of O that's largely // stable and also rather tiny - this could definitely be rejigged to work more efficiently, but the impact // on runtime is currently negligible, so it wouldn't gain very much. // If we add a lot more graphics pipeline stages, this set of functions should be rewritten to accomodate. VkPipelineStageFlags2KHR GetLogicallyEarliestGraphicsPipelineStage(VkPipelineStageFlags2KHR inflags) { VkPipelineStageFlags2KHR earliest_bit = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; int earliest_bit_order = GetGraphicsPipelineStageLogicalOrdinal(earliest_bit); inflags = ExpandPipelineStages(inflags); for (std::size_t i = 0; i < kNumPipelineStageBits; ++i) { VkPipelineStageFlags2KHR current_flag = (inflags & 0x1ull) << i; if (current_flag) { int new_order = GetGraphicsPipelineStageLogicalOrdinal(current_flag); if (new_order != -1 && new_order < earliest_bit_order) { earliest_bit_order = new_order; earliest_bit = current_flag; } } inflags = inflags >> 1; } return earliest_bit; } VkPipelineStageFlags2KHR GetLogicallyLatestGraphicsPipelineStage(VkPipelineStageFlags2KHR inflags) { VkPipelineStageFlags2KHR latest_bit = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; int latest_bit_order = GetGraphicsPipelineStageLogicalOrdinal(latest_bit); inflags = ExpandPipelineStages(inflags); for (std::size_t i = 0; i < kNumPipelineStageBits; ++i) { VkPipelineStageFlags2KHR current_flag = (inflags & 0x1ull) << i; if (current_flag) { int new_order = GetGraphicsPipelineStageLogicalOrdinal(current_flag); if (new_order != -1 && new_order > latest_bit_order) { latest_bit_order = new_order; latest_bit = current_flag; } } inflags = inflags >> 1; } return latest_bit; } // helper to extract the union of the stage masks in all of the barriers ExecScopes GetGlobalStageMasks(const VkDependencyInfoKHR &dep_info) { ExecScopes result{}; for (uint32_t i = 0; i < dep_info.memoryBarrierCount; i++) { result.src |= dep_info.pMemoryBarriers[i].srcStageMask; result.dst |= dep_info.pMemoryBarriers[i].dstStageMask; } for (uint32_t i = 0; i < dep_info.bufferMemoryBarrierCount; i++) { result.src |= dep_info.pBufferMemoryBarriers[i].srcStageMask; result.dst |= dep_info.pBufferMemoryBarriers[i].dstStageMask; } for (uint32_t i = 0; i < dep_info.imageMemoryBarrierCount; i++) { result.src |= dep_info.pImageMemoryBarriers[i].srcStageMask; result.dst |= dep_info.pImageMemoryBarriers[i].dstStageMask; } return result; } // Helpers to try to print the shortest string description of masks. // If the bitmask doesn't use a synchronization2 specific flag, we'll // print the old strings. There are common code paths where we need // to print masks as strings and this makes the output less confusing // for people not using synchronization2. std::string StringPipelineStageFlags(VkPipelineStageFlags2KHR mask) { if (mask <= UINT32_MAX) { return string_VkPipelineStageFlags(mask & UINT32_MAX); } return string_VkPipelineStageFlags2KHR(mask); } std::string StringAccessFlags(VkAccessFlags2KHR mask) { if (mask <= UINT32_MAX) { return string_VkAccessFlags(mask & UINT32_MAX); } return string_VkAccessFlags2KHR(mask); } } // namespace sync_utils
mechasource/mechcommander2
source/tools/editor/usertextedit.h
<gh_stars>10-100 //===========================================================================// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// #pragma once #if !defined(AFX_USERTEXTEDIT_H__5C5823FE_6B1B_469D_B5E8_223BE4A723AD__INCLUDED_) #define AFX_USERTEXTEDIT_H__5C5823FE_6B1B_469D_B5E8_223BE4A723AD__INCLUDED_ ///////////////////////////////////////////////////////////////////////////// // CUserTextEdit dialog class CUserTextEdit : public CDialog { // Construction public: CUserTextEdit(CWnd* pParent = nullptr); // standard constructor void UpdateTextDisplay(void); CString m_UnlocalizedText; bool m_UseResourceString; int32_t m_ResourceStringID; // Dialog Data //{{AFX_DATA(CUserTextEdit) enum { IDD = IDD_USER_TEXT_EDIT_DIALOG }; CString m_Edit; CString m_ResourceStringIDEdit; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CUserTextEdit) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CUserTextEdit) afx_msg void OnUserTextEditEnterTextButton(void); afx_msg void OnUserTextEditSelectResourceStringButton(void); virtual BOOL OnInitDialog(void); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before // the previous line. #endif // !defined(AFX_USERTEXTEDIT_H__5C5823FE_6B1B_469D_B5E8_223BE4A723AD__INCLUDED_)
Enterprise-Neurosystem/ai-signal-processing
aisp-core/aisp-core-main/src/main/java/org/eng/aisp/classifier/anomaly/normal/StatUtils.java
/******************************************************************************* * Copyright [2022] [IBM] * * 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.eng.aisp.classifier.anomaly.normal; import org.apache.commons.math3.distribution.RealDistribution; import org.eng.util.OnlineStats; /** * Holds some methods on OnlineStats that may be candidates for moving there. * @author DavidWood * */ public class StatUtils { /** * Find the point between the two distributions that is an equal number of standard deviations * away from each of the means. * Find d, such that * m1 + d*s1 = m2 - d*s2, where m is the mean, s is the standard deviation and m1<m2 * then * d = (m2 - m1) / (s2 + s1) * Then compute the point as m1 + d * s1; * @param normStats * @param abnormStats * @return */ public static double getEqualProbabiltyMidPoint(OnlineStats stats1, OnlineStats stats2) { double m1 = stats1.getMean(); double m2 = stats2.getMean(); double s1 = stats1.getStdDev(); double s2 = stats2.getStdDev(); double d; if (m1 < m2) { d = (m2 - m1) / (s1 + s2); d = m1 + d * s1; } else { d = (m1 - m2) / (s1 + s2); d = m2 + d * s2; } // RealDistribution dist1 = new NormalDistribution(m1, s1); // RealDistribution dist2 = new NormalDistribution(m2, s2); // AISPLogger.logger.info("d=" + d + ", cdf1=" + dist1.cumulativeProbability(d) + ", cdf2=" // + dist2.cumulativeProbability(d)); return d; } // /** // * Transform a value in one distribution to a value in a 2nd distribution using a linear transform. // * See <a href="https://proofwiki.org/wiki/Linear_Transformation_of_Gaussian_Random_Variable">https://proofwiki.org/wiki/Linear_Transformation_of_Gaussian_Random_Variable</a> // * for the basis of implementation here. // * Assuming, // * <pre> // * destValue = m * srcValue + b // * </pre> // * To determine m and b, we assume the following // * <pre> // * srcN[Us, Vs] = src distribution with mean Us and variance Vs. // * destN[Ud,Vd] = dest distribution with mean Ud and variance Vd. // * </pre> // * To map a value in srcN[] to a value in destN[], we can determine // * m and b from the following: // * with // * <pre> // * destN[Ud, Vd] = srcN[m * Us + b, m^2 * Vs] // * </pre> // * so that, // * <pre> // * m^2 * Vs = Vd, so that m = sqrt(Vd/Vs) // * m * Us + b = Ud, so that b = Ud - m * Us // * </pre> // * and finally, from above, // * <pre> // * destValue = m * srcValue + b // * </pre> // * @param value // * @param srcStats // * @param destStats // * @return a value mapped from the src distribution to the destination distribution assuming a linear transform between distributions. // */ // public static double transfer(double srcValue, OnlineStats srcStats, OnlineStats destStats) { // if (srcStats.getSampleCount() == 0) // throw new IllegalArgumentException("src stats has no samples"); // if (destStats.getSampleCount() == 0) // throw new IllegalArgumentException("dest stats has no samples"); // double Vd = destStats.getVariance(); // double Vs = srcStats.getVariance(); // double Ud = destStats.getMean(); // double Us = srcStats.getMean(); // double m = Math.sqrt(Vd/Vs); // double b = Ud - m * Us; // double destValue = m * srcValue + b; // return destValue; // } public static double getEqualProbabiltyMidPoint(RealDistribution dist1, RealDistribution dist2) { double dist1Mean = dist1.getNumericalMean(); double dist2Mean = dist2.getNumericalMean(); dist1Mean = dist1.inverseCumulativeProbability(.5); dist2Mean = dist2.inverseCumulativeProbability(.5); if (dist1Mean < dist2Mean) return searchMidPoint(dist1, dist2, dist1Mean, dist2Mean); else return searchMidPoint(dist2, dist1, dist2Mean, dist1Mean); } private static double searchMidPoint(RealDistribution dist1, RealDistribution dist2, double min, double max) { double mid = (max + min) / 2.0; double cdf1 = dist1.cumulativeProbability(mid); double cdf2 = 1.0 - dist2.cumulativeProbability(mid); double diff = cdf1 - cdf2; if (Math.abs(diff) < .0001) return mid; else if (diff < 0) return searchMidPoint(dist1,dist2, mid, max); else return searchMidPoint(dist1,dist2, min, mid); } // private boolean isDisjoint(OnlineStats stats1, OnlineStats stats2, double n) { // boolean disjoint; // double mean1 = stats1.getMean(); // double mean2 = stats2.getMean(); // double stddev1 = stats1.getStdDev(); // double stddev2 = stats2.getStdDev(); // if (mean1 < mean2) { // disjoint = (mean1 + n*stddev1) <= (mean2 - n*stddev2); // } else if (mean2 < mean1){ // disjoint = (mean2 + n*stddev2) <= (mean1 - n*stddev1); // } else { // they are equal // disjoint = false; // } // return disjoint; // //} }
huangshiyou/shiyouh.github.io
files/csce111/examples/chap3/Seasons.java
<gh_stars>0 import java.util.Scanner; /** This program translates the English names of the seasons into Spanish. */ public class Seasons { public static void main(String[] args) { String input; // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get a day from the user. System.out.print("Enter the name of a season: "); input = keyboard.nextLine(); // Translate the season to Spanish. switch (input) { case "spring": System.out.println("la primavera"); break; case "summer": System.out.println("el verano"); break; case "autumn": case "fall": System.out.println("el otono"); break; case "winter": System.out.println("el invierno"); break; default: System.out.println("Please enter one of these words:\n" + "spring, summer, autumn, fall, or winter."); } } }
morning-song/sunspot
sunspot_rails/dev_tasks/rdoc.rake
rdoc_task = begin require 'rdoc/task' RDoc::Task rescue LoadError begin require 'rake/rdoctask' Rake::RDocTask rescue nil end end if rdoc_task rdoc_task.new(:doc) do |rdoc| rdoc.main = '../README.md' rdoc.rdoc_files.include('../README.md', 'lib/sunspot/rails/**/*.rb', 'lib/sunspot/rails.rb') rdoc.rdoc_dir = 'doc' end end namespace :doc do desc 'Generate rdoc and move into pages directory' task :publish => :redoc do doc_dir = File.join(File.dirname(__FILE__), '..', 'doc') publish_dir = File.join(File.dirname(__FILE__), '..', '..', 'pages', 'rails', 'docs') FileUtils.rm_rf(publish_dir) if File.exist?(publish_dir) FileUtils.cp_r(doc_dir, publish_dir) end end
SKCraft/Plume
src/main/java/com/skcraft/plume/module/border/WorldBorderConfig.java
<filename>src/main/java/com/skcraft/plume/module/border/WorldBorderConfig.java package com.skcraft.plume.module.border; import com.skcraft.plume.util.Location3d; import ninja.leaping.configurate.objectmapping.Setting; import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; public class WorldBorderConfig { @Setting("border") public Border border = new Border(); @ConfigSerializable public static class Border { @Setting(comment = "The radius of the border, in blocks, from the spawn point") public int borderSize = 10000; @Setting(comment = "The radius of the buffer zone, in blocks, from the spawn point") public int bufferSize = 9990; @Setting(comment = "The radius of the snapback zone, in blocks, from the spawn point") public int snapBackSize = 9970; @Setting(comment = "The type of border, can currently only be CIRCLE") public BorderType borderType = BorderType.CIRCLE; public enum BorderType { CIRCLE { @Override public Threshold getThreshold(Location3d current, Location3d center, int radius, int buffer) { int distance = (int) (Math.pow(center.getX() - current.getX(), 2) + Math.pow(center.getZ() - current.getZ(), 2)); if (distance > radius * radius) { return Threshold.ESCAPED; } else if (distance > buffer * buffer) { return Threshold.BUFFER; } else { return Threshold.CLEAR; } } @Override public Location3d getSnapBackLocation(Location3d current, Location3d center, int radius) { return current.subtract(center).unit().multiply(radius).add(center); } }; public abstract Threshold getThreshold(Location3d current, Location3d centre, int radius, int buffer); public abstract Location3d getSnapBackLocation(Location3d current, Location3d center, int radius); } public enum Threshold { BUFFER, CLEAR, ESCAPED } } }
bluerelay/windyquery
windyquery/combiner/raw_stmt.py
from ._base import _rule class RawStmt: @_rule('raw_stmt : RAW') def p_raw_raw(self, p): p.lexer.append('RAW', p[1], 1) @_rule('raw_stmt : RRULE') def p_raw_rrule(self, p): p.lexer.append('RRULE', p[1]) @_rule('raw_stmt : WITH_VALUES') def p_raw_with_values(self, p): p.lexer.append('WITH_VALUES', p[1]) @_rule('''raw_stmts : raw_stmt | raw_stmt raw_stmts''') def p_raw_stmts(self, p): pass
fsxfreak/club-suite
clubsuite/suite/migrations/0022_auto_20170301_0407.py
<gh_stars>10-100 # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-01 04:07 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('suite', '0021_auto_20170227_2231'), ] operations = [ migrations.AddField( model_name='event', name='end_date', field=models.DateField(default=datetime.datetime.now), ), migrations.AddField( model_name='event', name='start_date', field=models.DateField(default=datetime.datetime.now), ), migrations.AlterField( model_name='event', name='end_time', field=models.TimeField(default='12:00:00'), ), migrations.AlterField( model_name='event', name='start_time', field=models.TimeField(default='12:00:00'), ), ]
NickG-Math/Mackey
docs/html/Graph__Policies_8hpp.js
<reponame>NickG-Math/Mackey<filename>docs/html/Graph__Policies_8hpp.js var Graph__Policies_8hpp = [ [ "bicolored_edge_with_id", "structmackey_1_1bicolored__edge__with__id.html", "structmackey_1_1bicolored__edge__with__id" ], [ "MinLength", "classmackey_1_1MinLength.html", "classmackey_1_1MinLength" ], [ "MinColorsLength", "classmackey_1_1MinColorsLength.html", "classmackey_1_1MinColorsLength" ], [ "operator<<", "Graph__Policies_8hpp.html#ace9bfedd2fd4649ba4c06ef354aa6577", null ], [ "operator<<", "Graph__Policies_8hpp.html#ad4641b2dacb76f90999a7a7322b06137", null ], [ "operator<<", "Graph__Policies_8hpp.html#a5762bcdf05cf484e2cb33ac304044748", null ] ];
xsthunder/a
old/week1/0I.cc
const bool test=0; #include<iostream> #include<cctype> #include<algorithm> #include<cstdio> #include<cstdlib> #include<vector> #include<map> #include<queue> #include<set> #include<cctype> #include<cstring> #include<utility> #include<cmath> const int inf=0x7fffffff; #define IF if(test) #define FI if(!test) #define gts(s) fgets((s),sizeof(s),stdin) #define MS(s) memset((s),0,sizeof((s))) typedef long long int ll; using namespace std; typedef pair<int,int> point; template <typename T> void pA(T *begin,int n){ for(int i=0;i<n;i++){ printf("%d " ,*(begin+i)); } printf("\n"); } const int N=300+50; ll ak[N]; ll av[N]; ll sum[N]; ll dp[N][N]; void sol(){ int TK;scanf("%d",&TK); while(TK--){ MS(ak);MS(av);MS(dp);MS(sum); int n;scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%lld",&ak[i]); } for(int i=1;i<=n;i++){ scanf("%lld",&av[i]); sum[i]=sum[i-1]+av[i]; } int j; for(int len=2;len<=n;len++){ for(int i=1;i+len-1<=n;i++){ j=i+len-1; if(__gcd(ak[i],ak[j])!=1&&dp[i+1][j-1]==sum[j-1]-sum[i]){ (dp[i][j]=sum[j]-sum[i-1]); continue; } else { for(int k=i;k<j;k++){ dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]); //(dp[i][j]=sum[j]-sum[i-1]); } } } } IF { cout<<TK<<endl; for(int i=1;i<=n;i++)cout<<i<<' '; for(int i=1;i<=n;i++){cout<<i<<':'; for(int j=1;j<n;j++)cout<<dp[i][j]; } cout<<endl; } printf("%lld\n",dp[1][n]); } } int main() { sol(); return 0; } //0I.cc //generated automatically at Fri Oct 21 05:40:49 2016 //by xsthunder
DTomoo/betting
src/main/java/com/dt/betting/db/domain/bet/ScoreGuestBetPiece.java
package com.dt.betting.db.domain.bet; public class ScoreGuestBetPiece extends BetPiece<Long> { public ScoreGuestBetPiece(long scoreGuest) { super(scoreGuest); } @Override public BetPieceType getType() { return BetPieceType.SCORE_GUEST; } public long getScoreIfOk() { return getValue().longValue() == 0 ? 5 : 5 * getValue().longValue(); } }
CoderMMK/RSPS
Server/src/server/model/items/Item.java
<reponame>CoderMMK/RSPS package server.model.items; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import server.Config; import server.Server; /** * Handles The Item Wielding Of The Server Used When Hardcoding Additional Items * Fixing Bugged Items * * @author Sanity Revised by Shawn Notes by Shawn */ public class Item { /** * Server cape IDs. */ public static int capes[] = { 2731, 2677, 2683, 2680, 2701, 2686, 2689, 2692, 2737, 2734, 2716, 2728, 2695, 2713, 2725, 2722, 2707, 2704, 2710, 2719, 2737, 2698, 14590, 2701, 8102, 8075, 8044, 8045, 8042, 8043, 8037, 8038, 8025, 8026, 8018, 7858, 7994, 7983, 7984, 7985, 7986, 7987, 7982, 7978, 3781, 3783, 3785, 3787, 3789, 3777, 3779, 3759, 3761, 3763, 3765, 6111, 6570, 6568, 1007, 1019, 1021, 1023, 1027, 1029, 1031, 1052, 2412, 2413, 2414, 4304, 4315, 4317, 4319, 4321, 4323, 4325, 4327, 4329, 4331, 4333, 4335, 4337, 4339, 4341, 4343, 4345, 4347, 4349, 4351, 4353, 4355, 4357, 4359, 4361, 4363, 4365, 4367, 4369, 4371, 4373, 4375, 4377, 4379, 4381, 4383, 4385, 4387, 4389, 4391, 4393, 4395, 4397, 4399, 4401, 4403, 4405, 4407, 4409, 4411, 4413, 4514, 4516, 6070, 6568, 6570 }; /** * Server boot IDs. */ public static int boots[] = { 11732, 7596, 8029, 6619, 8017, 7159, 7991, 6666, 6061, 6106, 88, 89, 626, 628, 630, 632, 634, 1061, 1837, 1846, 2577, 2579, 2894, 2904, 2914, 2924, 2934, 3061, 3105, 3107, 3791, 4097, 4107, 4117, 4119, 4121, 4123, 4125, 4127, 4129, 4131, 4310, 5064, 5345, 5557, 6069, 6106, 6143, 6145, 6147, 6328, 6920, 6349, 6357, 3393 }; /** * Server glove IDs. */ public static int gloves[] = { 7595, 6629, 8021, 8016, 7964, 2491, 1065, 2487, 2489, 3060, 1495, 775, 777, 778, 6708, 1059, 1063, 1065, 1580, 2487, 2489, 2491, 2902, 2912, 2922, 2932, 2942, 3060, 3799, 4095, 4105, 4115, 4308, 5556, 6068, 6110, 6149, 6151, 6153, 6922, 7454, 7455, 7456, 7457, 7458, 7459, 7460, 7461, 7462, 6330, 3391 }; /** * Server shield IDs. */ public static int shields[] = { 11283, 7676, 7342, 7348, 7354, 7360, 7334, 7340, 7347, 7352, 7358, 7356, 7350, 7344, 8087, 8058, 8059, 8060, 8061, 8062, 8063, 6633, 7977, 7976, 7972, 7959, 6591, 7332, 7338, 7336, 7360, 1171, 1173, 1175, 1177, 1179, 1181, 1183, 1185, 1187, 1189, 1191, 1193, 1195, 1197, 1199, 1201, 1540, 2589, 2597, 2603, 2611, 2621, 2629, 2659, 2667, 2675, 2890, 3122, 3488, 3758, 3839, 3840, 3841, 3842, 3843, 3844, 4072, 4156, 4224, 4225, 4226, 4227, 4228, 4229, 4230, 4231, 4232, 4233, 4234, 4302, 4507, 4512, 6215, 6217, 6219, 6221, 6223, 6225, 6227, 6229, 6231, 6233, 6235, 6237, 6239, 6241, 6243, 6245, 6247, 6249, 6251, 6253, 6255, 6257, 6259, 6261, 6263, 6265, 6267, 6269, 6271, 6273, 6275, 6277, 6279, 6524, 6889 }; /** * Server hat IDs. */ public static int hats[] = { 10548, 2679, 2685, 2682, 2703, 2688, 2691, 2691, 2733, 2736, 2718, 2730, 2697, 2715, 2727, 2724, 2709, 2706, 2712, 2721, 2739, 2700, 2518, 2524, 2526, 7319, 7321, 7323, 7325, 7327, 1167, 8077, 8076, 8074, 4168, 1169, 8034, 8035, 8036, 8030, 6623, 8024, 8023, 8022, 8013, 1169, 7594, 7995, 7996, 7997, 7998, 7999, 8000, 8001, 7992, 7990, 7975, 7973, 7971, 7967, 7963, 6665, 6665, 7321, 6886, 6547, 6548, 2645, 2647, 2649, 4856, 4857, 4858, 4859, 4880, 4881, 4882, 4883, 4904, 4905, 4906, 4907, 4928, 4929, 4930, 4931, 4952, 4953, 4954, 4955, 4976, 4977, 4978, 4979, 4732, 4753, 4611, 6188, 6182, 4511, 4056, 4071, 4724, 2639, 2641, 2643, 2665, 6109, 5525, 5527, 5529, 5531, 5533, 5535, 5537, 5539, 5541, 5543, 5545, 5547, 5549, 5551, 74, 579, 656, 658, 660, 662, 664, 740, 1017, 1037, 1040, 1042, 1044, 1046, 1038, 1048, 1050, 1053, 1055, 1057, 1137, 1139, 1141, 1143, 1145, 1147, 1149, 1151, 1153, 1155, 1157, 1159, 1161, 1163, 1165, 1506, 1949, 2422, 2581, 2587, 2595, 2605, 2613, 2619, 2627, 2631, 2633, 2635, 2637, 2651, 2657, 2673, 2900, 2910, 2920, 2930, 2940, 2978, 2979, 2980, 2981, 2982, 2983, 2984, 2985, 2986, 2987, 2988, 2989, 2990, 2991, 2992, 2993, 2994, 2995, 3057, 3385, 3486, 3748, 3749, 3751, 3753, 3797, 4041, 4042, 4071, 4089, 3755, 4099, 4109, 4164, 4302, 4506, 4511, 4513, 4515, 4551, 4567, 4708, 4716, 4724, 4745, 4753, 4857, 4858, 4859, 4880, 4881, 4882, 4883, 4904, 4905, 4906, 4907, 4952, 4953, 4954, 4955, 4976, 4977, 4978, 4979, 5013, 5014, 5554, 5574, 6109, 6128, 6131, 6137, 6182, 6188, 6335, 6337, 6339, 6345, 6355, 6365, 6375, 6382, 6392, 6400, 6918, 6656, 2581, 7539, 7394, 7396, 7534, 5574, 6885, 6858, 6860, 6862, 6856, 6326, 6128, 6137, 7400, 7323, 7325, 7327, 7003 }; /** * Server amulet IDs. */ public static int amulets[] = { 1654, 1656, 1658, 1660, 1662, 1664, 8081, 8033, 7968, 6585, 86, 87, 295, 421, 552, 589, 1478, 1692, 1694, 1696, 1698, 1700, 1702, 1704, 1706, 1708, 1710, 1712, 1725, 1727, 1729, 1731, 4021, 4081, 4250, 4677, 6040, 6041, 6208, 1718, 1722, 6859, 6863, 6857 }; /** * Server arrow IDs. */ public static int arrows[] = { 11212, 8052, 9211, 9010, 9209, 9208, 9207, 9206, 9205, 9203, 9301, 8065, 7919, 7906, 7988, 7989, 78, 598, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 942, 2532, 2533, 2534, 2535, 2536, 2537, 2538, 2539, 2540, 2541, 2866, 4160, 4172, 4173, 4174, 4175, 4740, 5616, 5617, 5618, 5619, 5620, 5621, 5622, 5623, 5624, 5625, 5626, 5627, 6061, 6062 }; /** * Server ring IDs. */ public static int rings[] = { 8082, 773, 1635, 1637, 1639, 1641, 1643, 1645, 2550, 2552, 2554, 2556, 2558, 2560, 2562, 2564, 2566, 2568, 2570, 2572, 4202, 4657, 6465, 6737, 6731, 6735, 6735, 6583, 6733 }; /** * Server body IDs. */ public static int body[] = { 7608, 2520, 430, 7362, 7364, 636, 638, 640, 642, 644, 8064, 426, 1005, 1757, 7592, 8031, 8027, 6617, 8019, 8014, 8002, 7376, 544, 7372, 7370, 577, 7974, 7970, 7965, 7961, 7960, 3793, 3775, 3773, 3771, 3769, 3767, 6139, 1135, 2499, 2501, 1035, 540, 5553, 4757, 1833, 6388, 6384, 4111, 4101, 4091, 6186, 6184, 6180, 3058, 4509, 4504, 4069, 4728, 4736, 4712, 6107, 2661, 3140, 1101, 1103, 1105, 1107, 1109, 1111, 1113, 1115, 1117, 1119, 1121, 1123, 1125, 1127, 1129, 1131, 1133, 2583, 2591, 2599, 2607, 2615, 2623, 2653, 2669, 3481, 4712, 4720, 4728, 4749, 4892, 4893, 4894, 4895, 4916, 4917, 4918, 4919, 4964, 4965, 4966, 4967, 6107, 6133, 6322, 6322, 6129, 75, 6916, 6916, 4111, 6654, 6654, 75, 7399, 7390, 7374, 5575, 2503, 6341, 6351, 3387, 5030, 5032, 5034, 5030, 5032, 5034, 7392, 546 }; /** * Server leg IDs. */ public static int legs[] = { 7609, 2522, 7378, 7380, 7382, 7368, 7366, 7388, 646, 648, 650, 652, 654, 428, 1097, 1095, 7593, 8032, 8028, 6625, 8020, 8015, 7384, 7969, 7966, 7962, 6141, 1835, 538, 1033, 5555, 4759, 6386, 6390, 2497, 2495, 2493, 1099, 4113, 4103, 4093, 6924, 6187, 6185, 6181, 3059, 4510, 4505, 4070, 6108, 538, 542, 548, 1011, 1013, 1015, 1067, 1069, 1071, 1073, 1075, 1077, 1079, 1081, 1083, 1085, 1087, 1089, 1091, 1093, 2585, 2593, 2601, 2609, 2617, 2625, 2655, 2663, 2671, 3059, 3389, 3472, 3473, 3474, 3475, 3476, 3477, 3478, 3479, 3480, 3483, 3485, 3795, 4087, 4585, 4712, 4714, 4722, 4730, 4738, 4751, 4759, 4874, 4875, 4876, 4877, 4898, 4899, 4900, 4901, 4922, 4923, 4924, 4925, 4946, 4947, 4948, 4949, 4970, 4971, 4972, 4973, 4994, 4995, 4996, 4997, 5048, 5050, 5052, 5576, 6107, 6130, 6187, 6390, 6386, 6390, 6396, 6404, 6135, 6809, 6916, 4091, 4111, 6655, 6654, 7398, 7398, 7386, 6324, 6343, 6353, 3387, 5036, 5038, 5040 }; /** * Server platebody IDs. */ public static int platebody[] = { 11020, 10551, 10338, 7608, 2520, 430, 636, 638, 640, 642, 644, 426, 8031, 8027, 6617, 8019, 8014, 8002, 544, 577, 7974, 7970, 7965, 7961, 7960, 3793, 3773, 3775, 3771, 3769, 3767, 6139, 1035, 540, 5553, 4757, 1833, 1835, 6388, 6384, 4111, 4101, 4868, 4869, 4870, 4871, 4892, 4893, 4894, 4895, 4916, 4917, 4918, 4919, 4940, 4941, 4942, 4943, 4964, 4965, 4966, 4967, 4988, 4989, 4990, 0x2f9a0eb, 6186, 6184, 6180, 3058, 4509, 4504, 4069, 4728, 4736, 4712, 6107, 2661, 3140, 1115, 1117, 1119, 1121, 1123, 1125, 1127, 2583, 2591, 2599, 2607, 2615, 6322, 2623, 2653, 2669, 3481, 4720, 4728, 4749, 2661, 6129, 6916, 4091, 6654, 6133, 75, 7399, 7390, 5575, 6341, 6351, 3387, 5030, 5032, 5034, 7392 }; /** * Full body items that cover your arms. Names go here. */ private static String[] fullbody = { "wings", "Spined body", "plate", "Monk's robe", "torso", "top", "shirt", "platebody", "Ahrims robetop", "Karils leathertop", "brassard", "Robe top", "robetop", "platebody (t)", "platebody (g)", "chestplate", "torso", "hauberk", "Dragon chainbody" }; /** * Full hat items that cover your head go here. Names go here. */ private static String[] fullhat = { "helmet", "mage hat", "med helm", "coif", "Dharok's helm", "hood", "Initiate helm", "Coif", "Helm of neitiznot", "Armadyl helmet", "Berserker helm", "Archer helm", "Farseer helm", "Warrior helm", "Void" }; /** * Full mask items that cover your face go here. Names go here. */ private static String[] fullmask = { "helm (t)", "full helm(g)", "full", "heraldic", "heraldic helm", "full helm", "mask", "Verac's helm", "Guthan's helm", "Karil's coif", "mask", "Torag's helm", "Void", "sallet" }; /** * Calls if an item is a full body item. */ public static boolean isFullBody(int itemId) { String weapon = getItemName(itemId); if (weapon == null) return false; for (int i = 0; i < fullbody.length; i++) { if (weapon.endsWith(fullbody[i])) { return true; } } return false; } /** * Calls if an item is a full helm item. */ public static boolean isFullHelm(int itemId) { String weapon = getItemName(itemId); if (weapon == null) return false; for (int i = 0; i < fullhat.length; i++) { if (weapon.endsWith(fullhat[i])) { return true; } } return false; } /** * Calls if an item is a full mask item. */ public static boolean isFullMask(int itemId) { String weapon = getItemName(itemId); if (weapon == null) return false; for (int i = 0; i < fullmask.length; i++) { if (weapon.endsWith(fullmask[i])) { return true; } } return false; } /** * Gets an item name from the itemlist. */ public static String getItemName(int id) { for (int j = 0; j < Server.itemHandler.ItemList.length; j++) { if (Server.itemHandler.ItemList[j] != null) if (Server.itemHandler.ItemList[j].itemId == id) return Server.itemHandler.ItemList[j].itemName; } return null; } /** * Checks if the item is stackable. */ public static boolean[] itemStackable = new boolean[Config.ITEM_LIMIT]; /** * Checks if the item can be made into a note. */ public static boolean[] itemIsNote = new boolean[Config.ITEM_LIMIT]; /** * Checks if the item can wield into a slot. */ public static int[] targetSlots = new int[Config.ITEM_LIMIT]; static { int counter = 0; int c; try { FileInputStream dataIn = new FileInputStream(new File( "./Data/data/stackable.dat")); while ((c = dataIn.read()) != -1) { if (c == 0) { itemStackable[counter] = false; } else { itemStackable[counter] = true; } counter++; } dataIn.close(); } catch (IOException e) { System.out .println("Critical error while loading stackabledata! Trace:"); e.printStackTrace(); } counter = 0; try { FileInputStream dataIn = new FileInputStream(new File( "./Data/data/notes.dat")); while ((c = dataIn.read()) != -1) { if (c == 0) { itemIsNote[counter] = true; } else { itemIsNote[counter] = false; } counter++; } dataIn.close(); } catch (IOException e) { System.out.println("Critical error while loading notedata! Trace:"); e.printStackTrace(); } counter = 0; try { FileInputStream dataIn = new FileInputStream(new File( "./Data/data/equipment.dat")); while ((c = dataIn.read()) != -1) { targetSlots[counter++] = c; } dataIn.close(); } catch (IOException e) { System.out.println("Critical error while loading notedata! Trace:"); e.printStackTrace(); } } }
dtk/dtk-server
application/model/module/module/dsl/adapters/v3/object_model_form/choice.rb
# # Copyright (C) 2010-2016 dtk contributors # # This file is part of the dtk project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module DTK; class ModuleDSL; class V3 class ObjectModelForm class Choice < OMFBase::Choice r8_nested_require('choice', 'dependency') r8_nested_require('choice', 'link_def_link') def initialize(raw, dep_cmp_name, base_cmp) super() @raw = raw @dep_cmp_name = dep_cmp_name @base_cmp = base_cmp end def print_form @raw || @possible_link.inject() end def base_cmp_print_form component_print_form(base_cmp()) end def dep_cmp_print_form component_print_form(dep_cmp()) end def remote_location? ret_single_possible_link_value()['type'] == 'external' end def set_to_local_location_as_default if ret_single_possible_link_value()['type'].nil? update_single_possible_link_value('type' => 'internal') end end # returns [dependencies,link_defs] def self.deps_and_link_defs(input_hash, base_cmp, opts = {}) ndx_dep_choices = Dependency.ndx_dep_choices(input_hash['dependencies'], base_cmp, opts) ndx_link_def_links = LinkDef.ndx_link_def_links(input_hash['link_defs'], base_cmp, opts) spliced_ndx_link_def_links = integrate_deps_and_link_defs!(ndx_dep_choices, ndx_link_def_links) dependencies = Dependency.dependencies?(ndx_dep_choices.values, base_cmp, opts) link_defs = LinkDef.link_defs?(spliced_ndx_link_def_links) [dependencies, link_defs] end def matches?(choice_with_single_pl) ret = nil if pl_match_hash_value = matches_on_key?(choice_with_single_pl) pl_single_hash_value = choice_with_single_pl.possible_link.values.first matches_on_type?(pl_match_hash_value, pl_single_hash_value) end end def ret_single_possible_link_key ret_single_possible_link(1).keys.first end private def set_single_possible_link!(ndx, hash_value) unless @possible_link.empty? fail Error.new('Unexpected that @possible_link is not empty when adding an element') end @possible_link.merge!(ndx => hash_value) end def update_single_possible_link_value(hash_value) ret_single_possible_link(1).values.first.merge!(hash_value) end def ret_single_possible_link_value ret_single_possible_link().values.first || {} end def ret_single_possible_link(sizes = nil) sizes = Array(sizes || [0, 1]) unless sizes.include?(@possible_link.size) fail Error.new("Unexpected that @possible_link does not have size in (#{sizes.join(',')})") end @possible_link end attr_reader :dep_cmp_name, :base_cmp def dep_cmp convert_to_internal_cmp_form(@dep_cmp_name) end def dup self.class.new(@raw, @dep_cmp_name, @base_cmp) end def matches_on_key?(choice_with_single_pl) @possible_link[choice_with_single_pl.ret_single_possible_link_key()] end def matches_on_type?(hash_val1, hash_val2) type1 = hash_val1['type'] type2 = hash_val2['type'] type1.nil? || type2.nil? || type1 == type2 end # returns spliced_ndx_link_def_links def self.integrate_deps_and_link_defs!(ndx_dep_choices, ndx_link_def_links) # first splice spliced_ndx_link_def_links = splice_link_def_and_dep_info(ndx_link_def_links, ndx_dep_choices) # throw error if there are any unmatched ndx_dep_choices that have a remote location # remove any simple dependencies that match a link def ndx_dep_choices.each do |ndx, dep_choices| if spliced_ndx_link_def_links[ndx] # the dep matches a link def; we are purposely not matching on location a ndx_dep_choices.delete(ndx) else # this relies on assumption that if in dsl there is no location given for dep, it is set to location local if remote_dep_choice = dep_choices.find(&:remote_location?) error_msg = "The following dependency on component '?base_cmp' has a remote location, but there is no matching link def: ?dep" fail ParsingError::Dependency.create(error_msg, remote_dep_choice) else dep_choices.each(&:set_to_local_location_as_default) end end end spliced_ndx_link_def_links end def self.splice_link_def_and_dep_info(ndx_link_def_links, ndx_dep_choices) ret = {} ndx_link_def_links.each do |link_def_ndx, link_def_link_choices| pruned_ndx_dep_choices = ndx_dep_choices dep_name_match = false if dep_choices = ndx_dep_choices[link_def_ndx] pruned_ndx_dep_choices = { link_def_ndx => dep_choices } dep_name_match = true end link_def_link_choices.each do |ldl_choice| ndx = nil dep_name = ldl_choice.dependency_name if dep_name && !dep_name_match if ldl_choice.explicit_dependency_ref base_cmp_name = ldl_choice.base_cmp_print_form() dep_cmp_name = ldl_choice.dep_cmp_print_form() error_msg = "The link def segment on ?1: ?2\nreferences a dependency name (?3) that does not exist.\n" fail ParsingError.new(error_msg, base_cmp_name, { dep_cmp_name => ldl_choice.print_form }, dep_name) end ldl_choice.required = false ndx = dep_name else unless ndx = matching_dep_index?(ldl_choice, pruned_ndx_dep_choices) ldl_choice.required = false ndx = ldl_choice.dep_cmp_ndx() end end (ret[ndx] ||= []) << ldl_choice end end ret end def self.matching_dep_index?(link_def_link_choice, ndx_dep_choices) ret = nil ndx_dep_choices.each do |dep_ndx, dep_choices| dep_choices.each do |dep_choice| if dep_choice.matches?(link_def_link_choice) return dep_ndx end end end ret end end end end; end; end