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
// // MIT License // // Copyright (c) Deif Lou // // 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 <opencv2/imgproc.hpp> #include <vector> #include "filter.h" #include "filterwidget.h" #include <imgproc/types.h> #include <imgproc/thresholding.h> #include <imgproc/util.h> Filter::Filter() : mThresholdMode(0), mColorMode(0) { for (int i = 0; i < 5; i++) mAffectedChannel[i] = false; } Filter::~Filter() { } ImageFilter *Filter::clone() { Filter * f = new Filter(); f->mThresholdMode = mThresholdMode; f->mColorMode = mColorMode; for (int i = 0; i < 5; i++) f->mAffectedChannel[i] = mAffectedChannel[i]; return f; } extern "C" QHash<QString, QString> getIBPPluginInfo(); QHash<QString, QString> Filter::info() { return getIBPPluginInfo(); } QImage Filter::process(const QImage &inputImage) { if (inputImage.isNull() || inputImage.format() != QImage::Format_ARGB32) return inputImage; QImage i = inputImage.copy(); cv::Mat dstMat(i.height(), i.width(), CV_8UC4, i.bits(), i.bytesPerLine()); const int radius = 10; const int windowSize = radius * 2 + 1; const double k = .05; if (mColorMode == 0) { if (!mAffectedChannel[0] && !mAffectedChannel[4]) return i; if (mAffectedChannel[0]) { register BGRA * bitsSrc = (BGRA *)inputImage.bits(); register BGRA * bitsDst = (BGRA *)i.bits(); register int totalPixels = i.width() * i.height(); while (totalPixels--) { bitsDst->b = IBP_pixelIntensity4(bitsSrc->r, bitsSrc->g, bitsSrc->b); bitsSrc++; bitsDst++; } } cv::Mat mSrcGray, mSrcAlpha; if (mAffectedChannel[0]) { mSrcGray = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 0,0 }; cv::mixChannels(&dstMat, 1, &mSrcGray, 1, from_to, 1); } if (mAffectedChannel[4]) { mSrcAlpha = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 3,0 }; cv::mixChannels(&dstMat, 1, &mSrcAlpha, 1, from_to, 1); } if (mThresholdMode == 0) { if (mAffectedChannel[0]) cv::threshold(mSrcGray, mSrcGray, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[4]) cv::threshold(mSrcAlpha, mSrcAlpha, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); } else { if (mAffectedChannel[0]) adaptiveThresholdIntegral(mSrcGray, mSrcGray, windowSize, k); if (mAffectedChannel[4]) adaptiveThresholdIntegral(mSrcAlpha, mSrcAlpha, windowSize, k); } if (mAffectedChannel[0]) { int from_to[] = { 0,0, 0,1, 0,2 }; cv::mixChannels(&mSrcGray, 1, &dstMat, 1, from_to, 3); } if (mAffectedChannel[4]) { int from_to[] = { 0,3 }; cv::mixChannels(&mSrcAlpha, 1, &dstMat, 1, from_to, 1); } } else { if (!mAffectedChannel[1] && !mAffectedChannel[2] && !mAffectedChannel[3] && !mAffectedChannel[4]) return i; cv::Mat mSrcRed, mSrcGreen, mSrcBlue, mSrcAlpha; if (mAffectedChannel[1]) { mSrcBlue = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 0,0 }; cv::mixChannels(&dstMat, 1, &mSrcBlue, 1, from_to, 1); } if (mAffectedChannel[2]) { mSrcGreen = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 1,0 }; cv::mixChannels(&dstMat, 1, &mSrcGreen, 1, from_to, 1); } if (mAffectedChannel[3]) { mSrcRed = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 2,0 }; cv::mixChannels(&dstMat, 1, &mSrcRed, 1, from_to, 1); } if (mAffectedChannel[4]) { mSrcAlpha = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 3,0 }; cv::mixChannels(&dstMat, 1, &mSrcAlpha, 1, from_to, 1); } if (mThresholdMode == 0) { if (mAffectedChannel[1]) cv::threshold(mSrcBlue, mSrcBlue, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[2]) cv::threshold(mSrcGreen, mSrcGreen, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[3]) cv::threshold(mSrcRed, mSrcRed, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[4]) cv::threshold(mSrcAlpha, mSrcAlpha, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); } else { if (mAffectedChannel[1]) adaptiveThresholdIntegral(mSrcBlue, mSrcBlue, windowSize, k); if (mAffectedChannel[2]) adaptiveThresholdIntegral(mSrcGreen, mSrcGreen, windowSize, k); if (mAffectedChannel[3]) adaptiveThresholdIntegral(mSrcRed, mSrcRed, windowSize, k); if (mAffectedChannel[4]) adaptiveThresholdIntegral(mSrcAlpha, mSrcAlpha, windowSize, k); } if (mAffectedChannel[1]) { int from_to[] = { 0,0 }; cv::mixChannels(&mSrcBlue, 1, &dstMat, 1, from_to, 1); } if (mAffectedChannel[2]) { int from_to[] = { 0,1 }; cv::mixChannels(&mSrcGreen, 1, &dstMat, 1, from_to, 1); } if (mAffectedChannel[3]) { int from_to[] = { 0,2 }; cv::mixChannels(&mSrcRed, 1, &dstMat, 1, from_to, 1); } if (mAffectedChannel[4]) { int from_to[] = { 0,3 }; cv::mixChannels(&mSrcAlpha, 1, &dstMat, 1, from_to, 1); } } return i; } bool Filter::loadParameters(QSettings &s) { QString thresholdModeStr, colorModeStr, affectedChannelStr; int thresholdMode, colorMode; QStringList affectedChannelList; bool affectedChannel[5] = { false }; thresholdModeStr = s.value("thresholdmode", "global").toString(); if (thresholdModeStr == "global") thresholdMode = 0; else if (thresholdModeStr == "local") thresholdMode = 1; else return false; colorModeStr = s.value("colormode", "luma").toString(); if (colorModeStr == "luma") colorMode = 0; else if (colorModeStr == "rgb") colorMode = 1; else return false; affectedChannelStr = s.value("affectedchannels", "").toString(); affectedChannelList = affectedChannelStr.split(" ", QString::SkipEmptyParts); for (int i = 0; i < affectedChannelList.size(); i++) { affectedChannelStr = affectedChannelList.at(i); if (affectedChannelList.at(i) == "luma") affectedChannel[0] = true; else if (affectedChannelList.at(i) == "red") affectedChannel[1] = true; else if (affectedChannelList.at(i) == "green") affectedChannel[2] = true; else if (affectedChannelList.at(i) == "blue") affectedChannel[3] = true; else if (affectedChannelList.at(i) == "alpha") affectedChannel[4] = true; else return false; } setThresholdMode(thresholdMode); setColorMode(colorMode); for (int i = 0; i < 5; i++) setAffectedChannel(i, affectedChannel[i]); return true; } bool Filter::saveParameters(QSettings &s) { s.setValue("thresholdmode", mThresholdMode == 0 ? "global" : "local"); s.setValue("colormode", mColorMode == 0 ? "luma" : "rgb"); QStringList affectedChannelList; if (mAffectedChannel[0]) affectedChannelList.append("luma"); if (mAffectedChannel[1]) affectedChannelList.append("red"); if (mAffectedChannel[2]) affectedChannelList.append("green"); if (mAffectedChannel[3]) affectedChannelList.append("blue"); if (mAffectedChannel[4]) affectedChannelList.append("alpha"); s.setValue("affectedchannels", affectedChannelList.join(" ")); return true; } QWidget *Filter::widget(QWidget *parent) { FilterWidget * fw = new FilterWidget(parent); fw->setThresholdMode(mThresholdMode); fw->setColorMode(mColorMode); for (int i = 0; i < 5; i++) fw->setAffectedChannel(i, mAffectedChannel[i]); connect(this, SIGNAL(thresholdModeChanged(int)), fw, SLOT(setThresholdMode(int))); connect(this, SIGNAL(colorModeChanged(int)), fw, SLOT(setColorMode(int))); connect(this, SIGNAL(affectedChannelChanged(int,bool)), fw, SLOT(setAffectedChannel(int,bool))); connect(fw, SIGNAL(thresholdModeChanged(int)), this, SLOT(setThresholdMode(int))); connect(fw, SIGNAL(colorModeChanged(int)), this, SLOT(setColorMode(int))); connect(fw, SIGNAL(affectedChannelChanged(int,bool)), this, SLOT(setAffectedChannel(int,bool))); return fw; } void Filter::setThresholdMode(int m) { if (m == mThresholdMode) return; mThresholdMode = m; emit thresholdModeChanged(m); emit parametersChanged(); } void Filter::setColorMode(int m) { if (m == mColorMode) return; mColorMode = m; emit colorModeChanged(m); emit parametersChanged(); } void Filter::setAffectedChannel(int c, bool a) { if (a == mAffectedChannel[c]) return; mAffectedChannel[c] = a; emit affectedChannelChanged(c, a); emit parametersChanged(); }
DeifLou/anitools
src/plugins/imagefilter_autothreshold/filter.cpp
C++
gpl-3.0
10,641
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-20 22:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('erudit', '0065_auto_20170202_1152'), ] operations = [ migrations.AddField( model_name='issue', name='force_free_access', field=models.BooleanField(default=False, verbose_name='Contraindre en libre accès'), ), ]
erudit/zenon
eruditorg/erudit/migrations/0066_issue_force_free_access.py
Python
gpl-3.0
505
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Modules.InstantAction.Views { /// <summary> /// InstantActionPage.xaml の相互作用ロジック /// </summary> public partial class InstantActionPage : UserControl { public InstantActionPage() { InitializeComponent(); } } public class InstantActionStepDataTemplateSelecter : DataTemplateSelector { public DataTemplate EmptyTemplate { get; set; } public DataTemplate FileSelectTemplate { get; set; } public DataTemplate ActionSelectTemplate { get; set; } public DataTemplate FinishingTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item == null) { return EmptyTemplate; } else if (item is ViewModels.FileSelectInstantActionStepViewModel) { return FileSelectTemplate; } else if (item is ViewModels.ActionsSelectInstantActionStepViewModel) { return ActionSelectTemplate; } else if (item is ViewModels.FinishingInstantActionStepViewModel) { return FinishingTemplate; } return base.SelectTemplate(item, container); } } }
tor4kichi/ReactiveFolder
Module/InstantAction/Views/InstantActionPage.xaml.cs
C#
gpl-3.0
1,475
package bartburg.nl.backbaseweather.provision.remote.controller; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import bartburg.nl.backbaseweather.AppConstants; import bartburg.nl.backbaseweather.provision.remote.annotation.ApiController; import bartburg.nl.backbaseweather.provision.remote.util.QueryStringUtil; import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_MAP_BASE_URL; import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_PROTOCOL; /** * Created by Bart on 6/3/2017. */ public abstract class BaseApiController { /** * Do the actual work of requesting data from the server. Note, should not run on main thread. * * @param parameters Parameters that will be added to the query string. * @param onErrorListener Listener that will get called when status code is not 200 * @return The result string or *null* when failed. */ @Nullable public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener) { return get(parameters, onErrorListener, null); } /** * Do the actual work of requesting data from the server. Note, should not run on main thread. * * @param parameters Parameters that will be added to the query string. * @param onErrorListener Listener that will get called when status code is not 200 * @param customRelativePath Use this if you want to provide a custom relative path (not the one from the annotation). * @return The result string or *null* when failed. */ @Nullable public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener, @Nullable String customRelativePath) { try { parameters.put("appid", AppConstants.OPEN_WEATHER_MAP_KEY); URL url = new URL(OPEN_WEATHER_PROTOCOL + OPEN_WEATHER_MAP_BASE_URL + getRelativePath(customRelativePath) + QueryStringUtil.mapToQueryString(parameters)); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); String responseMessage = urlConnection.getResponseMessage(); if (responseCode != 200 && onErrorListener != null) { onErrorListener.onError(responseCode, responseMessage); } else { return readInputStream(urlConnection); } } catch (IOException e) { e.printStackTrace(); } return null; } @NonNull private String readInputStream(HttpURLConnection urlConnection) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); return sb.toString(); } public interface OnErrorListener { void onError(int responseCode, String responseMessage); } private String getRelativePath(String customRelativePath) { if (customRelativePath != null) { return customRelativePath; } Class<? extends BaseApiController> aClass = getClass(); if (aClass.isAnnotationPresent(ApiController.class)) { Annotation annotation = aClass.getAnnotation(ApiController.class); ApiController apiController = (ApiController) annotation; return apiController.relativePath(); } return ""; } }
bartburg/backbaseweatherapp
app/src/main/java/bartburg/nl/backbaseweather/provision/remote/controller/BaseApiController.java
Java
gpl-3.0
3,934
/***************************************************************** * This file is part of CCAFS Planning and Reporting Platform. * CCAFS P&R 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. * CCAFS P&R 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 CCAFS P&R. If not, see <http://www.gnu.org/licenses/>. * *************************************************************** */ package org.cgiar.ccafs.ap.data.dao.mysql; import org.cgiar.ccafs.ap.data.dao.ProjectOtherContributionDAO; import org.cgiar.ccafs.utils.db.DAOManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Javier Andrés Gallego B. */ public class MySQLProjectOtherContributionDAO implements ProjectOtherContributionDAO { // Logger private static Logger LOG = LoggerFactory.getLogger(MySQLProjectOtherContributionDAO.class); private DAOManager databaseManager; @Inject public MySQLProjectOtherContributionDAO(DAOManager databaseManager) { this.databaseManager = databaseManager; } @Override public Map<String, String> getIPOtherContributionById(int ipOtherContributionId) { Map<String, String> ipOtherContributionData = new HashMap<String, String>(); LOG.debug(">> getIPOtherContributionById( ipOtherContributionId = {} )", ipOtherContributionId); StringBuilder query = new StringBuilder(); query.append("SELECT ipo.* "); query.append("FROM project_other_contributions as ipo "); query.append("WHERE ipo.id= "); query.append(ipOtherContributionId); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { ipOtherContributionData.put("id", rs.getString("id")); ipOtherContributionData.put("project_id", rs.getString("project_id")); ipOtherContributionData.put("contribution", rs.getString("contribution")); ipOtherContributionData.put("additional_contribution", rs.getString("additional_contribution")); ipOtherContributionData.put("crp_contributions_nature", rs.getString("crp_contributions_nature")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the IP Other Contribution {}.", ipOtherContributionId, e); } LOG.debug("-- getIPOtherContributionById() > Calling method executeQuery to get the results"); return ipOtherContributionData; } @Override public Map<String, String> getIPOtherContributionByProjectId(int projectID) { LOG.debug(">> getIPOtherContributionByProjectId (projectID = {} )", projectID); Map<String, String> ipOtherContributionData = new HashMap<String, String>(); StringBuilder query = new StringBuilder(); query.append("SELECT ipo.* "); query.append("FROM project_other_contributions as ipo "); query.append("INNER JOIN projects p ON ipo.project_id = p.id "); query.append("WHERE ipo.project_id= "); query.append(projectID); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { ipOtherContributionData.put("id", rs.getString("id")); ipOtherContributionData.put("project_id", rs.getString("project_id")); ipOtherContributionData.put("contribution", rs.getString("contribution")); ipOtherContributionData.put("additional_contribution", rs.getString("additional_contribution")); ipOtherContributionData.put("crp_contributions_nature", rs.getString("crp_contributions_nature")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the IP Other Contribution by the projectID {}.", projectID, e); } LOG.debug("-- getIPOtherContributionByProjectId() : {}", ipOtherContributionData); return ipOtherContributionData; } @Override public int saveIPOtherContribution(int projectID, Map<String, Object> ipOtherContributionData) { LOG.debug(">> saveIPOtherContribution(ipOtherContributionDataData={})", ipOtherContributionData); StringBuilder query = new StringBuilder(); int result = -1; Object[] values; if (ipOtherContributionData.get("id") == null) { // Insert new IP Other Contribution record query.append("INSERT INTO project_other_contributions (project_id, contribution, additional_contribution, "); query.append("crp_contributions_nature, created_by, modified_by, modification_justification) "); query.append("VALUES (?,?,?,?,?,?,?) "); values = new Object[7]; values[0] = projectID; values[1] = ipOtherContributionData.get("contribution"); values[2] = ipOtherContributionData.get("additional_contribution"); values[3] = ipOtherContributionData.get("crp_contributions_nature"); values[4] = ipOtherContributionData.get("user_id"); values[5] = ipOtherContributionData.get("user_id"); values[6] = ipOtherContributionData.get("justification"); result = databaseManager.saveData(query.toString(), values); if (result <= 0) { LOG.error("A problem happened trying to add a new IP Other Contribution with project id={}", projectID); return -1; } } else { // update IP Other Contribution record query.append("UPDATE project_other_contributions SET project_id = ?, contribution = ?, "); query.append("additional_contribution = ?, crp_contributions_nature = ?, modified_by = ?, "); query.append("modification_justification = ? WHERE id = ? "); values = new Object[7]; values[0] = projectID; values[1] = ipOtherContributionData.get("contribution"); values[2] = ipOtherContributionData.get("additional_contribution"); values[3] = ipOtherContributionData.get("crp_contributions_nature"); values[4] = ipOtherContributionData.get("user_id"); values[5] = ipOtherContributionData.get("justification"); values[6] = ipOtherContributionData.get("id"); result = databaseManager.saveData(query.toString(), values); if (result == -1) { LOG.error("A problem happened trying to update the IP Other Contribution identified with the id = {}", ipOtherContributionData.get("id")); return -1; } } LOG.debug("<< saveIPOtherContribution():{}", result); return result; } }
CCAFS/ccafs-ap
impactPathways/src/main/java/org/cgiar/ccafs/ap/data/dao/mysql/MySQLProjectOtherContributionDAO.java
Java
gpl-3.0
6,952
// ReSharper disable CheckNamespace using System; using System.Collections.Generic; public class Program { public static void Main() { var people = new Dictionary<string, Person>(); string input; while ((input = Console.ReadLine()) != "End") { var split = input.Split(); string name = split[0]; if (!people.ContainsKey(name)) { people.Add(name, new Person()); } Person person = people[name]; string infoType = split[1]; if (infoType == "company") { person.Company = new Company(split[2], split[3], double.Parse(split[4])); } else if (infoType == "pokemon") { person.Pokemon.Add(new Pokemon(split[2], split[3])); } else if (infoType == "parents") { person.Parents.Add(new Parent(split[2], split[3])); } else if (infoType == "children") { person.Children.Add(new Child(split[2], split[3])); } else if (infoType == "car") { person.Car = new Car(split[2], int.Parse(split[3])); } } string nameToPrint = Console.ReadLine(); Console.WriteLine(nameToPrint); people[nameToPrint].PrintInformation(); } }
martinmladenov/SoftUni-Solutions
CSharp OOP Basics/Exercises/01. Defining Classes - Exercise/Google/Program.cs
C#
gpl-3.0
1,441
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Form * @subpackage Element * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @version $Id: Exception.php 24594 2012-01-05 21:27:01Z matthew $ * @license http://framework.zend.com/license/new-bsd New BSD License */ /** Zend_Form_Exception */ require_once 'Zend/Form/Exception.php'; /** * Exception for Zend_Form component. * * @category Zend * @package Zend_Form * @subpackage Element * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Form_Element_Exception extends Zend_Form_Exception { }
basdog22/Qool
lib/Zend/Form/Element/Exception.php
PHP
gpl-3.0
1,225
// +build linux package subsystem import ( "bufio" "errors" "fmt" "io" "os" "os/exec" "runtime" "strconv" "strings" ) type PlatformHeader LinuxHeader func NewPlatformHeader() *LinuxHeader { header := new(LinuxHeader) header.Devices = make(map[string]LinuxDevice) header.getDevsParts() return header } func (header *LinuxHeader) getDevsParts() { f, err := os.Open("/proc/diskstats") if err != nil { panic(err) } defer f.Close() scan := bufio.NewScanner(f) for scan.Scan() { var major, minor int var name string c, err := fmt.Sscanf(scan.Text(), "%d %d %s", &major, &minor, &name) if err != nil { panic(err) } if c != 3 { continue } header.DevsParts = append(header.DevsParts, name) if isDevice(name) { header.Devices[name] = LinuxDevice{ name, getPartitions(name), } } } } func isDevice(name string) bool { stat, err := os.Stat(fmt.Sprintf("/sys/block/%s", name)) if err == nil && stat.IsDir() { return true } return false } func getPartitions(name string) []string { var dir *os.File var fis []os.FileInfo var err error var parts = []string{} dir, err = os.Open(fmt.Sprintf("/sys/block/%s", name)) if err != nil { panic(err) } fis, err = dir.Readdir(0) if err != nil { panic(err) } for _, fi := range fis { _, err := os.Stat(fmt.Sprintf("/sys/block/%s/%s/stat", name, fi.Name())) if err == nil { // partition exists parts = append(parts, fi.Name()) } } return parts } func ReadCpuStat(record *StatRecord) error { f, ferr := os.Open("/proc/stat") if ferr != nil { return ferr } defer f.Close() if record.Cpu == nil { num_core := 0 out, err := exec.Command("nproc", "--all").Output() out_str := strings.TrimSpace(string(out)) if err == nil { num_core, err = strconv.Atoi(out_str) if err != nil { num_core = 0 } } if num_core == 0 { num_core = runtime.NumCPU() } record.Cpu = NewCpuStat(num_core) } else { record.Cpu.Clear() } if record.Proc == nil { record.Proc = NewProcStat() } else { record.Proc.Clear() } scan := bufio.NewScanner(f) for scan.Scan() { var err error var cpu string line := scan.Text() if line[0:4] == "cpu " { // Linux 2.6.33 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d", &cpu, &record.Cpu.All.User, &record.Cpu.All.Nice, &record.Cpu.All.Sys, &record.Cpu.All.Idle, &record.Cpu.All.Iowait, &record.Cpu.All.Hardirq, &record.Cpu.All.Softirq, &record.Cpu.All.Steal, &record.Cpu.All.Guest, &record.Cpu.All.GuestNice) if err == io.EOF { // Linux 2.6.24 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d", &cpu, &record.Cpu.All.User, &record.Cpu.All.Nice, &record.Cpu.All.Sys, &record.Cpu.All.Idle, &record.Cpu.All.Iowait, &record.Cpu.All.Hardirq, &record.Cpu.All.Softirq, &record.Cpu.All.Steal, &record.Cpu.All.Guest) record.Cpu.All.GuestNice = 0 } if err != nil { panic(err) } } else if line[0:3] == "cpu" { var n_core int var core_stat *CpuCoreStat // assume n_core < 10000 _, err = fmt.Sscanf(line[3:7], "%d", &n_core) if err != nil { panic(err) } core_stat = &record.Cpu.CoreStats[n_core] // Linux 2.6.33 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d", &cpu, &core_stat.User, &core_stat.Nice, &core_stat.Sys, &core_stat.Idle, &core_stat.Iowait, &core_stat.Hardirq, &core_stat.Softirq, &core_stat.Steal, &core_stat.Guest, &core_stat.GuestNice) if err == io.EOF { // Linux 2.6.24 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d", &cpu, &core_stat.User, &core_stat.Nice, &core_stat.Sys, &core_stat.Idle, &core_stat.Iowait, &core_stat.Hardirq, &core_stat.Softirq, &core_stat.Steal, &core_stat.Guest) } if err != nil { panic(err) } } else if line[0:5] == "ctxt " { _, err = fmt.Sscanf(line[4:], "%d", &record.Proc.ContextSwitch) if err != nil { panic(err) } } else if line[0:10] == "processes " { _, err = fmt.Sscanf(line[10:], "%d", &record.Proc.Fork) if err != nil { panic(err) } } } return nil } func parseInterruptStatEntry(line string, num_core int) (*InterruptStatEntry, error) { entry := new(InterruptStatEntry) entry.NumCore = num_core entry.IntrCounts = make([]int, num_core) tokens := strings.Fields(line) idx := 0 tok := tokens[0] tok = strings.TrimRight(tok, ":") if irqno, err := strconv.Atoi(tok); err == nil { entry.IrqNo = irqno entry.IrqType = "" } else { entry.IrqNo = -1 entry.IrqType = tok } for idx := 1; idx < num_core+1; idx += 1 { var c int var err error if idx >= len(tokens) { break } tok = tokens[idx] if c, err = strconv.Atoi(tok); err != nil { return nil, errors.New("Invalid string for IntrCounts element: " + tok) } entry.IntrCounts[idx-1] = c } idx = num_core + 1 if idx < len(tokens) { entry.Descr = strings.Join(tokens[idx:], " ") } else { entry.Descr = "" } return entry, nil } func ReadInterruptStat(record *StatRecord) error { intr_stat := NewInterruptStat() if record == nil { return errors.New("Valid *StatRecord is required.") } f, err := os.Open("/proc/interrupts") if err != nil { panic(err) } defer f.Close() scan := bufio.NewScanner(f) if !scan.Scan() { return errors.New("/proc/interrupts seems to be empty") } cores := strings.Fields(scan.Text()) num_core := len(cores) for scan.Scan() { entry, err := parseInterruptStatEntry(scan.Text(), num_core) if err != nil { return err } intr_stat.Entries = append(intr_stat.Entries, entry) intr_stat.NumEntries += 1 } record.Interrupt = intr_stat return nil } func ReadDiskStats(record *StatRecord, targets *map[string]bool) error { if record == nil { return errors.New("Valid *StatRecord is required.") } f, ferr := os.Open("/proc/diskstats") if ferr != nil { panic(ferr) } defer f.Close() if record.Disk == nil { record.Disk = NewDiskStat() } else { record.Disk.Clear() } scan := bufio.NewScanner(f) var num_items int var err error for scan.Scan() { var rdmerge_or_rdsec int64 var rdsec_or_wrios int64 var rdticks_or_wrsec int64 line := scan.Text() entry := NewDiskStatEntry() num_items, err = fmt.Sscanf(line, "%d %d %s %d %d %d %d %d %d %d %d %d %d %d", &entry.Major, &entry.Minor, &entry.Name, &entry.RdIos, &rdmerge_or_rdsec, &rdsec_or_wrios, &rdticks_or_wrsec, &entry.WrIos, &entry.WrMerges, &entry.WrSectors, &entry.WrTicks, &entry.IosPgr, &entry.TotalTicks, &entry.ReqTicks) if err != nil { return err } if num_items == 14 { entry.RdMerges = rdmerge_or_rdsec entry.RdSectors = rdsec_or_wrios entry.RdTicks = rdticks_or_wrsec } else if num_items == 7 { entry.RdSectors = rdmerge_or_rdsec entry.WrIos = rdsec_or_wrios entry.WrSectors = rdticks_or_wrsec } else { continue } if entry.RdIos == 0 && entry.WrIos == 0 { continue } if targets != nil { if _, ok := (*targets)[entry.Name]; !ok { // device not in targets continue } } else { if !isDevice(entry.Name) { continue } } record.Disk.Entries = append(record.Disk.Entries, entry) } return nil } func ReadNetStat(record *StatRecord) error { if record == nil { return errors.New("Valid *StatRecord is required.") } net_stat := NewNetStat() f, err := os.Open("/proc/net/dev") if err != nil { return err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() switch { case line[0:7] == "Inter-|": continue case line[0:7] == " face |": continue } line = strings.Replace(line, ":", " ", -1) e := NewNetStatEntry() var devname string n, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &devname, &e.RxBytes, &e.RxPackets, &e.RxErrors, &e.RxDrops, &e.RxFifo, &e.RxFrame, &e.RxCompressed, &e.RxMulticast, &e.TxBytes, &e.TxPackets, &e.TxErrors, &e.TxDrops, &e.TxFifo, &e.TxFrame, &e.TxCompressed, &e.TxMulticast) if err == io.EOF { break } else if err != nil { return err } if n != 17 { continue } // trim trailing ":" from devname if devname[len(devname)-1] == ':' { devname = devname[0 : len(devname)-1] } e.Name = devname net_stat.Entries = append(net_stat.Entries, e) } record.Net = net_stat return nil } func ReadMemStat(record *StatRecord) error { if record == nil { return errors.New("Valid *StatRecord is required.") } mem_stat := NewMemStat() f, err := os.Open("/proc/meminfo") if err != nil { return err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { var key string var val int64 line := scanner.Text() n, err := fmt.Sscanf(line, "%s %d", &key, &val) if err == io.EOF { break } else if err != nil { return err } if n != 2 { continue } switch key { case "HugePages_Surp:": mem_stat.HugePages_Surp = val case "HugePages_Rsvd:": mem_stat.HugePages_Rsvd = val case "HugePages_Free:": mem_stat.HugePages_Free = val case "HugePages_Total:": mem_stat.HugePages_Total = val case "Hugepagesize:": mem_stat.Hugepagesize = val case "AnonHugePages:": mem_stat.AnonHugePages = val case "Committed_AS:": mem_stat.Committed_AS = val case "CommitLimit:": mem_stat.CommitLimit = val case "Bounce:": mem_stat.Bounce = val case "NFS_Unstable:": mem_stat.NFS_Unstable = val case "Shmem:": mem_stat.Shmem = val case "Slab:": mem_stat.Slab = val case "SReclaimable:": mem_stat.SReclaimable = val case "SUnreclaim:": mem_stat.SUnreclaim = val case "KernelStack:": mem_stat.KernelStack = val case "PageTables:": mem_stat.PageTables = val case "Mapped:": mem_stat.Mapped = val case "AnonPages:": mem_stat.AnonPages = val case "Writeback:": mem_stat.Writeback = val case "Dirty:": mem_stat.Dirty = val case "SwapFree:": mem_stat.SwapFree = val case "SwapTotal:": mem_stat.SwapTotal = val case "Inactive:": mem_stat.Inactive = val case "Active:": mem_stat.Active = val case "SwapCached:": mem_stat.SwapCached = val case "Cached:": mem_stat.Cached = val case "Buffers:": mem_stat.Buffers = val case "MemFree:": mem_stat.MemFree = val case "MemTotal:": mem_stat.MemTotal = val } } record.Mem = mem_stat return nil }
hayamiz/perfmonger
core/subsystem/perfmonger_linux.go
GO
gpl-3.0
10,563
////////// // item // ////////// datablock ItemData(YoyoItem) { category = "Weapon"; // Mission editor category className = "Weapon"; // For inventory system // Basic Item Properties shapeFile = "./Yoyo.dts"; rotate = false; mass = 1; density = 0.2; elasticity = 0.2; friction = 0.6; emap = true; //gui stuff uiName = "Yo-yo"; iconName = "./icon_Yoyo"; doColorShift = true; colorShiftColor = "0 1 1 1.000"; // Dynamic properties defined by the scripts image = YoyoImage; canDrop = true; }; //////////////// //weapon image// //////////////// datablock ShapeBaseImageData(YoyoImage) { // Basic Item properties shapeFile = "./Yoyo.dts"; emap = true; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; offset = "0 0 0"; eyeOffset = 0; //"0.7 1.2 -0.5"; rotation = eulerToMatrix( "0 0 0" ); // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. correctMuzzleVector = true; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. className = "WeaponImage"; // Projectile && Ammo. item = YoyoItem; projectile = emptyProjectile; projectileType = Projectile; ammo = " "; //melee particles shoot from eye node for consistancy melee = false; //raise your arm up or not armReady = true; doColorShift = true; colorShiftColor = YoyoItem.colorShiftColor;//"0.400 0.196 0 1.000"; //casing = " "; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // Initial start up state stateName[0] = "Activate"; stateTimeoutValue[0] = 0.15; stateTransitionOnTimeout[0] = "Ready"; stateSound[0] = weaponSwitchSound; stateName[1] = "Ready"; stateTransitionOnTriggerDown[1] = "Fire"; stateAllowImageChange[1] = true; stateSequence[1] = "Ready"; stateName[2] = "Fire"; stateTimeoutValue[2] = 1.1; stateTransitionOnTimeout[2] = "Reload"; stateSequence[2] = "fire"; stateScript[2] = "OnFire"; stateName[3] = "Reload"; stateSequence[3] = "Reload"; stateTransitionOnTriggerUp[3] = "Ready"; stateSequence[3] = "Ready"; };
piber20/BL-FK-GameMode
GameMode_FASTKarts/addons/novelty/Yoyo.cs
C#
gpl-3.0
2,759
// Copyright 2016 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 "services/video_capture/device_mojo_mock_to_media_adapter.h" #include "services/video_capture/device_client_media_to_mojo_mock_adapter.h" namespace video_capture { DeviceMojoMockToMediaAdapter::DeviceMojoMockToMediaAdapter( mojom::MockMediaDevicePtr* device) : device_(device) {} DeviceMojoMockToMediaAdapter::~DeviceMojoMockToMediaAdapter() = default; void DeviceMojoMockToMediaAdapter::AllocateAndStart( const media::VideoCaptureParams& params, std::unique_ptr<Client> client) { mojom::MockDeviceClientPtr client_proxy; auto client_request = mojo::GetProxy(&client_proxy); mojo::MakeStrongBinding( base::MakeUnique<DeviceClientMediaToMojoMockAdapter>(std::move(client)), std::move(client_request)); (*device_)->AllocateAndStart(std::move(client_proxy)); } void DeviceMojoMockToMediaAdapter::RequestRefreshFrame() {} void DeviceMojoMockToMediaAdapter::StopAndDeAllocate() { (*device_)->StopAndDeAllocate(); } void DeviceMojoMockToMediaAdapter::GetPhotoCapabilities( GetPhotoCapabilitiesCallback callback) {} void DeviceMojoMockToMediaAdapter::SetPhotoOptions( media::mojom::PhotoSettingsPtr settings, SetPhotoOptionsCallback callback) {} void DeviceMojoMockToMediaAdapter::TakePhoto(TakePhotoCallback callback) {} } // namespace video_capture
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/services/video_capture/device_mojo_mock_to_media_adapter.cc
C++
gpl-3.0
1,483
package com.ocams.andre; import javax.swing.table.DefaultTableModel; public class MasterJurnal extends javax.swing.JFrame { public MasterJurnal() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jTextField4 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Kode:"); jLabel2.setText("Perkiraan:"); jLabel3.setText("Nomor Referensi:"); jLabel4.setText("Posisi:"); jLabel5.setText("Harga:"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); buttonGroup1.add(jRadioButton1); jRadioButton1.setText("Debit"); buttonGroup1.add(jRadioButton2); jRadioButton2.setText("Kredit"); jLabel6.setText("User:"); jLabel7.setText("NamaUser"); jButton1.setText("Logout"); jButton2.setText("Insert"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); jButton3.setText("Update"); jButton3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton3MouseClicked(evt); } }); jButton4.setText("Delete"); jButton4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton4MouseClicked(evt); } }); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Kode", "Perkiraan", "No. Ref.", "Posisi", "Harga" } )); jTable2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable2MouseClicked(evt); } }); jScrollPane2.setViewportView(jTable2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel2) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7)) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4)) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton2)) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jRadioButton1) .addComponent(jRadioButton2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked String kode = jTextField1.getText(); String perkiraan = jTextField2.getText(); String noref = jTextField3.getText(); String posisi = ""; if (jRadioButton1.isSelected() == true){ posisi = "Debit"; }else if (jRadioButton2.isSelected() == true){ posisi = "Kredit"; } String harga = jTextField4.getText(); Object[] row = {kode,perkiraan,noref,posisi,harga}; DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.addRow(row); }//GEN-LAST:event_jButton2MouseClicked private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked int baris = jTable2.rowAtPoint(evt.getPoint()); String kode = jTextField1.getText(); String perkiraan = jTextField2.getText(); String noref = jTextField3.getText(); String posisi = ""; if (jRadioButton1.isSelected() == true){ posisi = "Debit"; }else if (jRadioButton2.isSelected() == true){ posisi = "Kredit"; } String harga = jTextField4.getText(); DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.setValueAt(kode, baris, 0); model.setValueAt(perkiraan, baris, 1); model.setValueAt(noref, baris, 2); model.setValueAt(posisi, baris, 3); model.setValueAt(harga, baris, 4); }//GEN-LAST:event_jButton3MouseClicked private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.removeRow(jTable2.rowAtPoint(evt.getPoint())); }//GEN-LAST:event_jButton4MouseClicked private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked int baris = jTable2.rowAtPoint(evt.getPoint()); jTextField1.setText(String.valueOf(jTable2.getValueAt(baris, 0))); jTextField2.setText(String.valueOf(jTable2.getValueAt(baris, 1))); jTextField3.setText(String.valueOf(jTable2.getValueAt(baris,2))); String posisi = String.valueOf(jTable2.getValueAt(baris, 3)); if ("debit".equalsIgnoreCase(posisi)){ jRadioButton1.setSelected(true); }else if ("kredit".equalsIgnoreCase(posisi)){ jRadioButton2.setSelected(true); } jTextField4.setText(String.valueOf(jTable2.getValueAt(baris, 4))); }//GEN-LAST:event_jTable2MouseClicked private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MasterJurnal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; // End of variables declaration//GEN-END:variables }
benyaminl/OCAMS
src/com/ocams/andre/MasterJurnal.java
Java
gpl-3.0
15,559
/* * generated by Xtext */ package org.eclectic.frontend.parser.antlr; import com.google.inject.Inject; import org.eclipse.xtext.parser.antlr.XtextTokenStream; import org.eclectic.frontend.services.TaoGrammarAccess; public class TaoParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser { @Inject private TaoGrammarAccess grammarAccess; @Override protected void setInitialHiddenTokens(XtextTokenStream tokenStream) { tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT"); } @Override protected org.eclectic.frontend.parser.antlr.internal.InternalTaoParser createParser(XtextTokenStream stream) { return new org.eclectic.frontend.parser.antlr.internal.InternalTaoParser(stream, getGrammarAccess()); } @Override protected String getDefaultRuleName() { return "TaoTransformation"; } public TaoGrammarAccess getGrammarAccess() { return this.grammarAccess; } public void setGrammarAccess(TaoGrammarAccess grammarAccess) { this.grammarAccess = grammarAccess; } }
jesusc/eclectic
plugins/org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/TaoParser.java
Java
gpl-3.0
1,041
<?php require "common.inc.php"; verifica_seguranca($_SESSION[PAP_RESP_MUTIRAO]); top(); ?> <?php $action = request_get("action",-1); if($action==-1) $action=ACAO_EXIBIR_LEITURA; $est_cha=request_get("est_cha",-1); if($est_cha==-1) { if(isset($_SESSION['cha_id_pref'])) { $est_cha=$_SESSION['cha_id_pref']; } } $_SESSION['cha_id_pref']=$est_cha; if ($est_cha<>-1) { $sql = "SELECT prodt_nome, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega, cha_taxa_percentual, ((cha_dt_prazo_contabil is null) OR (cha_dt_prazo_contabil > now() ) ) as cha_dentro_prazo, date_format(cha_dt_prazo_contabil,'%d/%m/%Y %H:%i') cha_dt_prazo_contabil "; $sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt "; $sql.= "WHERE cha_id = " . prep_para_bd($est_cha); $res = executa_sql($sql); if ($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) { $prodt_nome = $row["prodt_nome"]; $cha_dt_entrega = $row["cha_dt_entrega"]; $cha_taxa_percentual = $row["cha_taxa_percentual"]; $cha_dt_prazo_contabil = $row["cha_dt_prazo_contabil"]; $cha_dentro_prazo = $row["cha_dentro_prazo"]; } } if ($action == ACAO_SALVAR) // salvar formulário preenchido { // salva disponibilidade de produtos $n = isset($_REQUEST['est_prod']) ? sizeof($_REQUEST['est_prod']) : 0; for($i=0;$i<$n;$i++) { $est_cha_bd = prep_para_bd($est_cha); $qtde_antes_bd = $_REQUEST['est_prod_qtde_antes'][$i] <>"" ? prep_para_bd(formata_numero_para_mysql($_REQUEST['est_prod_qtde_antes'][$i])) : 'NULL'; $obs_antes_bd = $_REQUEST['est_obs_antes'][$i] <>"" ? prep_para_bd($_REQUEST['est_obs_antes'][$i]) : 'NULL'; $sql = "INSERT INTO estoque (est_cha, est_prod, est_prod_qtde_antes, est_obs_antes ) "; $sql.= "VALUES ( " . $est_cha_bd . " ," . prep_para_bd($_REQUEST['est_prod'][$i]) . ", "; $sql.= $qtde_antes_bd . ", " . $obs_antes_bd . ") "; $sql.= "ON DUPLICATE KEY UPDATE "; $sql.= " est_prod_qtde_antes = " . $qtde_antes_bd . ", "; $sql.= " est_obs_antes = " . $obs_antes_bd . " "; $res = executa_sql($sql); } if($res) { $action=ACAO_EXIBIR_LEITURA; //volta para modo visualização somente leitura adiciona_mensagem_status(MSG_TIPO_SUCESSO,"As informações de estoque relacionado à chamada " . $cha_dt_entrega . " foram salvas com sucesso."); } else { adiciona_mensagem_status(MSG_TIPO_ERRO,"Erro ao tentar salvar informações de estoque da chamada para o dia " . $cha_dt_entrega . "."); } escreve_mensagem_status(); } if ($action == ACAO_EXIBIR_LEITURA || $action == ACAO_EXIBIR_EDICAO ) // exibir para visualização, ou exibir para edição { } ?> <ul class="nav nav-tabs"> <li><a href="mutirao.php">Mutirão</a></li> <li class="active"><a href="#"><i class="glyphicon glyphicon-bed"></i> Estoque Pré-Mutirão</a></li> <li><a href="recebimento.php"><i class="glyphicon glyphicon-road"></i> Recebimento</a></li> <li><a href="distribuicao_consolidado_por_produtor.php"><i class="glyphicon glyphicon-fullscreen"></i> Distribuição</a></li> <li><a href="estoque_pos.php"><i class="glyphicon glyphicon-bed"></i> Estoque Pós-Mutirão</a></li> <li><a href="mutirao_divergencias.php"><i class="glyphicon glyphicon-eye-open"></i> Divergências</a></li> </ul> <br> <div class="panel panel-default"> <div class="panel-heading"> <strong>Estoque Pré-Mutirão</strong> </div> <?php if($action==ACAO_EXIBIR_LEITURA) //visualização somente leitura { ?> <div class="panel-body"> <form class="form-inline" method="get" name="frm_filtro" id="frm_filtro"> <?php ?> <fieldset> <div class="form-group"> <label for="est_cha">Chamada: </label> <select name="est_cha" id="est_cha" onchange="javascript:frm_filtro.submit();" class="form-control"> <option value="-1">SELECIONE</option> <?php $sql = "SELECT cha_id, prodt_nome, cha_dt_entrega cha_dt_entrega_original, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega "; $sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt "; $sql.= "WHERE prodt_mutirao = '1' "; $sql.= "ORDER BY cha_dt_entrega_original DESC LIMIT 10"; $res = executa_sql($sql); if($res) { $achou=false; while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) { echo("<option value='" . $row['cha_id'] . "'"); if($row['cha_id']==$est_cha) { echo(" selected"); $achou=true; } echo (">" . $row['prodt_nome'] . " - " . $row['cha_dt_entrega'] . "</option>"); } if($est_cha!=-1 && !$achou) { $sql = "SELECT cha_id, prodt_nome, cha_dt_entrega cha_dt_entrega_original, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega "; $sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt "; $sql.= "WHERE cha_id = " . prep_para_bd($est_cha); $res2 = executa_sql($sql); $row = mysqli_fetch_array($res2,MYSQLI_ASSOC); if($row) { echo("<option value='" . $row['cha_id'] . "' selected>"); echo ($row['prodt_nome'] . " - " . $row['cha_dt_entrega'] . "</option>"); } } } ?> </select> <?php if($est_cha!=-1) { ?> &nbsp;&nbsp; <label for="cha_dt_prazo_contabil">Prazo para Edição: </label> <?php echo($cha_dt_prazo_contabil?$cha_dt_prazo_contabil:"ainda não configurado"); ?> <?php if(!$cha_dentro_prazo) { echo("<span class='alert alert-danger'>(encerrado)</span>"); } } ?> </div> </fieldset> </form> </div> <?php if($est_cha!=-1) { $sql = "SELECT prod_id, prod_nome, estoque.est_prod_qtde_antes est_atual_prod_qtde_antes, "; $sql.= "estoque.est_obs_antes est_atual_obs_antes, "; $sql.= "estoque_anterior.est_prod_qtde_depois est_anterior_prod_qtde_depois, prod_unidade, "; $sql.= "chaprod_prod, forn_nome_curto, forn_nome_completo, forn_id FROM chamadaprodutos "; $sql.= "LEFT JOIN produtos on chaprod_prod = prod_id "; $sql.= "LEFT JOIN chamadas on chaprod_cha = cha_id "; $sql.= "LEFT JOIN fornecedores on prod_forn = forn_id "; $sql.= "LEFT JOIN estoque on est_cha = cha_id AND est_prod = chaprod_prod "; $sql.="LEFT JOIN estoque estoque_anterior ON estoque_anterior.est_prod = chaprod_prod AND estoque_anterior.est_cha = " . prep_para_bd(get_chamada_anterior($est_cha)) . " "; $sql.= "WHERE prod_ini_validade<=NOW() AND prod_fim_validade>=NOW() "; $sql.= "AND chaprod_cha = " . prep_para_bd($est_cha) . " AND chaprod_disponibilidade > 0 "; $sql.= " AND (estoque.est_prod_qtde_antes >0 OR estoque_anterior.est_prod_qtde_depois > 0 OR estoque.est_obs_antes IS NOT NULL ) "; $sql.= "ORDER BY forn_nome_curto, prod_nome, prod_unidade "; $res = executa_sql($sql); if($res && mysqli_num_rows($res)==0) { ?> <div class="panel-body"> <!-- <button type="button" class="btn btn-default btn-enviando" data-loading-text="importando..." onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA);?>&est_cha=<?php echo($est_cha); ?>&importar=sim'"> <i class="icon glyphicon glyphicon-resize-small"></i> importar estoque do último mutirão </button> --> <br /><div class='well'> Sem produtos em estoque. Se de fato houver, clique em editar para registrar. </div><br /> </div> <?php } else if($res) { ?> <table class="table table-striped table-bordered table-condensed table-hover"> <thead> <tr> <th colspan="3">Informações de Estoque Pré-Mutirão da Entrega de <?php echo($prodt_nome . " - " . $cha_dt_entrega); ?></th> <th colspan="2"> <?php if($cha_dentro_prazo) { ?> <a class="btn btn-primary" href="estoque_pre.php?action=<?php echo(ACAO_EXIBIR_EDICAO); ?>&cha_id=<?php echo($est_cha); ?>"><i class="glyphicon glyphicon-edit"></i> editar</a> <?php } else { echo("&nbsp;"); } ?> </th> </tr> </thead> <tbody> <?php $ultimo_forn = ""; while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) { if($row["forn_nome_curto"]!=$ultimo_forn) { $ultimo_forn = $row["forn_nome_curto"]; ?> <tr> <th> <?php echo($row["forn_nome_curto"]); adiciona_popover_descricao("",$row["forn_nome_completo"]); ?> </th> <th>Unidade</th> <th>Estoque Pré-Mutirão Esperado<?php adiciona_popover_descricao("Descrição", " = Estoque final informado pelo Mutirão anterior"); ?></th> <th>Estoque Pré-Mutirão Real</th> <th>Observação</th> </tr> <?php } ?> <tr> <td><?php echo($row["prod_nome"]);?></td> <td><?php echo($row["prod_unidade"]); ?></td> <td> <?php if($row["est_anterior_prod_qtde_depois"]) echo_digitos_significativos($row["est_anterior_prod_qtde_depois"]); else echo("&nbsp;"); ?> </td> <td <?php if($row["est_anterior_prod_qtde_depois"] != $row["est_atual_prod_qtde_antes"]) echo(" class='" . (($row["est_atual_obs_antes"]) ? "info" : "danger") . "'");?>> <?php if($row["est_atual_prod_qtde_antes"]) echo_digitos_significativos($row["est_atual_prod_qtde_antes"]); else echo("&nbsp;"); ?> </td> <td> <?php echo( ($row["est_atual_obs_antes"]) ? $row["est_atual_obs_antes"] : "&nbsp;") ; ?> </td> </tr> <?php } echo("</tbody></table>"); } ?> </div> <?php if($est_cha!=-1 && $cha_dentro_prazo) { ?> <div align="right"> <a class="btn btn-primary" href="estoque_pre.php?action=<?php echo(ACAO_EXIBIR_EDICAO); ?>&est_cha=<?php echo($est_cha); ?>"><i class="glyphicon glyphicon-edit glyphicon-white"></i> editar</a> </div> <?php } } // fim if est_cha !=-1 ?> <?php } else //visualização para edição { ?> <form class="form-horizontal" method="post"> <div class="panel-body"> <div align="right"> <button type="submit" class="btn btn-primary btn-enviando" data-loading-text="salvando estoque..."> <i class="glyphicon glyphicon-ok glyphicon-white"></i> salvar alterações</button> &nbsp;&nbsp; <button class="btn btn-default" type="button" onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA); ?>&est_cha=<?php echo($est_cha); ?>';"><i class="glyphicon glyphicon-off"></i> descartar alterações</button> </div> </div> <fieldset> <input type="hidden" name="est_cha" value="<?php echo($est_cha); ?>" /> <input type="hidden" name="action" value="<?php echo(ACAO_SALVAR); ?>" /> <div class="form-group"> <div class="container"> <?php $sql = "SELECT prod_id, prod_nome, estoque.est_prod_qtde_antes est_atual_prod_qtde_antes, "; $sql.= "estoque.est_obs_antes est_atual_obs_antes, "; $sql.= "estoque_anterior.est_prod_qtde_depois est_anterior_prod_qtde_depois, prod_unidade, "; $sql.= "chaprod_prod, forn_nome_curto, forn_nome_completo, forn_id FROM chamadaprodutos "; $sql.= "LEFT JOIN produtos on chaprod_prod = prod_id "; $sql.= "LEFT JOIN chamadas on chaprod_cha = cha_id "; $sql.= "LEFT JOIN fornecedores on prod_forn = forn_id "; $sql.= "LEFT JOIN estoque on est_cha = cha_id AND est_prod = chaprod_prod "; $sql.="LEFT JOIN estoque estoque_anterior ON estoque_anterior.est_prod = chaprod_prod AND estoque_anterior.est_cha = " . prep_para_bd(get_chamada_anterior($est_cha)) . " "; $sql.= "WHERE prod_ini_validade<=NOW() AND prod_fim_validade>=NOW() "; $sql.= "AND chaprod_cha = " . prep_para_bd($est_cha) . " AND chaprod_disponibilidade > 0 "; $sql.= "ORDER BY forn_nome_curto, prod_nome, prod_unidade "; $res = executa_sql($sql); if($res) { ?> <table class='table table-striped table-bordered table-condensed table-hover'> <thead> <tr> <th colspan="5"> Informações de Estoque Pré-Mutirão relacionado à chamada de <?php echo($prodt_nome . " - " . $cha_dt_entrega); ?> </th> </tr> </thead> <tbody> <tr> <td>&nbsp;</td><td>&nbsp;</td> <td colspan="2"> <button type="button" class="btn btn-info" name="copia_produtos_pedido" id="copia_produtos_pedido" onclick="javascript:replicaDados('replica-origem','replica-destino');"> <i class="glyphicon glyphicon-paste"></i> replicar do estoque esperado </button> </td> <td>&nbsp;</td> </tr> <?php $ultimo_forn = ""; while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) { if($row["forn_nome_curto"]!=$ultimo_forn) { $ultimo_forn = $row["forn_nome_curto"]; ?> <tr> <th> <?php echo($row["forn_nome_curto"]); adiciona_popover_descricao("",$row["forn_nome_completo"]); ?> </th> <th>Unidade</th> <th>Estoque Pré-Mutirão Esperado<?php adiciona_popover_descricao("Descrição", " = Estoque final informado pelo Mutirão anterior"); ?></th> <th>Estoque Pré-Mutirão Real</th> <th>Observação</th> </tr> <?php } ?> <tr> <input type="hidden" name="est_prod[]" value="<?php echo($row["prod_id"]); ?>"/> <td><?php echo($row["prod_nome"]);?></td> <td><?php echo($row["prod_unidade"]); ?></td> <td style="text-align:center"> <input type="hidden" name="est_anterior_prod_qtde_depois[]" class="replica-origem" value="<?php if($row["est_anterior_prod_qtde_depois"]) echo_digitos_significativos($row["est_anterior_prod_qtde_depois"]); ?>"> <?php if($row["est_anterior_prod_qtde_depois"]) echo_digitos_significativos($row["est_anterior_prod_qtde_depois"],"0"); ?> </td> <td> <input type="text" class="replica-destino form-control propaga-colar numero-positivo" style="font-size:18px; text-align:center;" value="<?php if($row["est_atual_prod_qtde_antes"]) echo_digitos_significativos($row["est_atual_prod_qtde_antes"],"0"); ?>" name="est_prod_qtde_antes[]" id="est_prod_qtde_antes_<?php echo($row["prod_id"]); ?>"/> </td> <td> <input type="text" class="form-control" value="<?php if($row["est_atual_obs_antes"]) echo($row["est_atual_obs_antes"]); ?>" name="est_obs_antes[]" id="est_obs_antes_<?php echo($row["prod_id"]); ?>"/> </td> </tr> <?php } echo("</tbody></table>"); } ?> </div> </div> <div align="right"> <button type="submit" class="btn btn-primary btn-enviando" data-loading-text="salvando estoque..."> <i class="glyphicon glyphicon-ok glyphicon-white"></i> salvar alterações</button> &nbsp;&nbsp; <button class="btn btn-default" type="button" onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA); ?>&est_cha=<?php echo($est_cha); ?>';"><i class="glyphicon glyphicon-off"></i> descartar alterações</button> </div> </fieldset> </form> <?php } footer(); ?>
redeecologica/pedidos
estoque_pre.php
PHP
gpl-3.0
19,108
jQuery(document).ready(function($) { $('#slide-left').flexslider({ animation: "slide", controlNav: "thumbnails", start: function(slider) { $('ol.flex-control-thumbs li img.flex-active').parent('li').addClass('active'); } }); }); jQuery(document).ready(function($) { $('#slide').flexslider({ animation: "slide", controlNav: false, directionNav: true }); });
vietnamframework/vietnamframework
app/view/newstreecolumn/js/jquery.flexslider.init.js
JavaScript
gpl-3.0
414
/* * This file is part of the command-line tool sosicon. * Copyright (C) 2014 Espen Andersen, Norwegian Broadcast Corporation (NRK) * * This 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 "converter_sosi2tsv.h" void sosicon::ConverterSosi2tsv:: run( bool* ) { }
espena/sosicon
src/converter_sosi2tsv.cpp
C++
gpl-3.0
877
using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace DrakSolz.Projectiles { public class ChickenEgg : ModProjectile { public override string Texture { get { return "Terraria/Projectile_318"; } } public override void SetStaticDefaults() { DisplayName.SetDefault("Chicken Egg"); } public override void SetDefaults() { projectile.CloneDefaults(ProjectileID.RottenEgg); projectile.aiStyle = 2; projectile.friendly = false; projectile.hostile = true; projectile.penetrate = -1; projectile.timeLeft = 600; } public override bool TileCollideStyle(ref int width, ref int height, ref bool fallThrough) { width = 5; height = 5; return true; } public override void Kill(int timeLeft) { Utils.PoofOfSmoke(projectile.Center); NPC.NewNPC((int) projectile.Center.X, (int) projectile.Center.Y, ModContent.NPCType<NPCs.Enemy.PreHardMode.EvilChicken>()); } } }
Xahlicem/DrakSolz
Projectiles/ChickenEgg.cs
C#
gpl-3.0
1,089
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2011 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Society / Edition # # / # # # # modified by webspell|k3rmit (Stefan Giesecke) in 2009 # # # # - Modifications are released under the GNU GENERAL PUBLIC LICENSE # # - It is NOT allowed to remove this copyright-tag # # - http://www.fsf.org/licensing/licenses/gpl.html # # # ########################################################################## */ $_language->read_module('gallery'); if(!isgalleryadmin($userID) OR mb_substr(basename($_SERVER['REQUEST_URI']),0,15) != "admincenter.php") die($_language->module['access_denied']); $galclass = new Gallery; if(isset($_GET['part'])) $part = $_GET['part']; else $part = ''; if(isset($_GET['action'])) $action = $_GET['action']; else $action = ''; if($part=="groups") { if(isset($_POST['save'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) safe_query("INSERT INTO ".PREFIX."gallery_groups ( name, sort ) values( '".$_POST['name']."', '1' ) "); else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveedit'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) safe_query("UPDATE ".PREFIX."gallery_groups SET name='".$_POST['name']."' WHERE groupID='".$_POST['groupID']."'"); else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['sort'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(isset($_POST['sortlist'])){ if(is_array($_POST['sortlist'])) { foreach($_POST['sortlist'] as $sortstring) { $sorter=explode("-", $sortstring); safe_query("UPDATE ".PREFIX."gallery_groups SET sort='$sorter[1]' WHERE groupID='$sorter[0]' "); } } } } else echo $_language->module['transaction_invalid']; } elseif(isset($_GET['delete'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_GET['captcha_hash'])) { $db_result=safe_query("SELECT * FROM ".PREFIX."gallery WHERE groupID='".$_GET['groupID']."'"); $any=mysql_num_rows($db_result); if($any){ echo $_language->module['galleries_available'].'<br /><br />'; } else{ safe_query("DELETE FROM ".PREFIX."gallery_groups WHERE groupID='".$_GET['groupID']."'"); } } else echo $_language->module['transaction_invalid']; } if($action=="add") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=groups" class="white">'.$_language->module['groups'].'</a> &raquo; '.$_language->module['add_group'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=groups"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['group_name'].'</b></td> <td width="85%"><input type="text" name="name" size="60" /></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /></td> <td><input type="submit" name="save" value="'.$_language->module['add_group'].'" /></td> </tr> </table> </form>'; } elseif($action=="edit") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups WHERE groupID='".$_GET['groupID']."'"); $ds=mysql_fetch_array($ergebnis); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=groups" class="white">'.$_language->module['groups'].'</a> &raquo; '.$_language->module['edit_group'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=groups"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['group_name'].'</b></td> <td><input type="text" name="name" size="60" value="'.getinput($ds['name']).'" /></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="groupID" value="'.$ds['groupID'].'" /></td> <td><input type="submit" name="saveedit" value="'.$_language->module['edit_group'].'" /></td> </tr> </table> </form>'; } else { echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; '.$_language->module['groups'].'</h1>'; echo'<input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=groups&amp;action=add\');return document.MM_returnValue" value="'.$_language->module['new_group'].'" /><br /><br />'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups ORDER BY sort"); echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&amp;part=groups"> <table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD"> <tr> <td width="70%" class="title"><b>'.$_language->module['group_name'].'</b></td> <td width="20%" class="title"><b>'.$_language->module['actions'].'</b></td> <td width="10%" class="title"><b>'.$_language->module['sort'].'</b></td> </tr>'; $n=1; $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); while($ds=mysql_fetch_array($ergebnis)) { if($n%2) { $td='td1'; } else { $td='td2'; } $list = '<select name="sortlist[]">'; for($i=1;$i<=mysql_num_rows($ergebnis);$i++) { $list.='<option value="'.$ds['groupID'].'-'.$i.'">'.$i.'</option>'; } $list .= '</select>'; $list = str_replace('value="'.$ds['groupID'].'-'.$ds['sort'].'"','value="'.$ds['groupID'].'-'.$ds['sort'].'" selected="selected"',$list); echo'<tr> <td class="'.$td.'">'.$ds['name'].'</td> <td class="'.$td.'" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=groups&amp;action=edit&amp;groupID='.$ds['groupID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" /> <input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_group'].'\', \'admincenter.php?site=gallery&amp;part=groups&amp;delete=true&amp;groupID='.$ds['groupID'].'&amp;captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td> <td class="'.$td.'" align="center">'.$list.'</td> </tr>'; $n++; } echo'<tr> <td class="td_head" colspan="3" align="right"><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="submit" name="sort" value="'.$_language->module['to_sort'].'" /></td> </tr> </table> </form>'; } } //part: gallerys elseif($part=="gallerys") { if(isset($_POST['save'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) { safe_query("INSERT INTO ".PREFIX."gallery ( name, date, groupID ) values( '".$_POST['name']."', '".time()."', '".$_POST['group']."' ) "); $id = mysql_insert_id(); } else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveedit'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) { if(!isset($_POST['group'])) { $_POST['group'] = 0; } safe_query("UPDATE ".PREFIX."gallery SET name='".$_POST['name']."', groupID='".$_POST['group']."' WHERE galleryID='".$_POST['galleryID']."'"); } else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveftp'])) { $dir = '../images/gallery/'; $pictures = array(); if(isset($_POST['comment'])) $comment = $_POST['comment']; if(isset($_POST['name'])) $name = $_POST['name']; if(isset($_POST['pictures'])) $pictures = $_POST['pictures']; $i=0; $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { foreach($pictures as $picture) { $typ = getimagesize($dir.$picture); switch ($typ[2]) { case 1: $typ = '.gif'; break; case 2: $typ = '.jpg'; break; case 3: $typ = '.png'; break; } if($name[$i]) $insertname = $name[$i]; else $insertname = $picture; safe_query("INSERT INTO ".PREFIX."gallery_pictures ( galleryID, name, comment, comments) VALUES ('".$_POST['galleryID']."', '".$insertname."', '".$comment[$i]."', '".$_POST['comments']."' )"); $insertid = mysql_insert_id(); copy($dir.$picture, $dir.'large/'.$insertid.$typ); $galclass->savethumb($dir.'large/'.$insertid.$typ, $dir.'thumb/'.$insertid.'.jpg'); @unlink($dir.$picture); $i++; } } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveform'])) { $dir = '../images/gallery/'; $picture = $_FILES['picture']; $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if($picture['name'] != "") { if($_POST['name']) $insertname = $_POST['name']; else $insertname = $picture['name']; safe_query("INSERT INTO ".PREFIX."gallery_pictures ( galleryID, name, comment, comments) VALUES ('".$_POST['galleryID']."', '".$insertname."', '".$_POST['comment']."', '".$_POST['comments']."' )"); $insertid = mysql_insert_id(); $typ = getimagesize($picture['tmp_name']); switch ($typ[2]) { case 1: $typ = '.gif'; break; case 2: $typ = '.jpg'; break; case 3: $typ = '.png'; break; } move_uploaded_file($picture['tmp_name'], $dir.'large/'.$insertid.$typ); $galclass->savethumb($dir.'large/'.$insertid.$typ, $dir.'thumb/'.$insertid.'.jpg'); } } else echo $_language->module['transaction_invalid']; } elseif(isset($_GET['delete'])) { //SQL $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_GET['captcha_hash'])) { if(safe_query("DELETE FROM ".PREFIX."gallery WHERE galleryID='".$_GET['galleryID']."'")) { //FILES $ergebnis=safe_query("SELECT picID FROM ".PREFIX."gallery_pictures WHERE galleryID='".$_GET['galleryID']."'"); while($ds=mysql_fetch_array($ergebnis)) { @unlink('../images/gallery/thumb/'.$ds['picID'].'.jpg'); //thumbnails $path = '../images/gallery/large/'; if(file_exists($path.$ds['picID'].'.jpg')) $path = $path.$ds['picID'].'.jpg'; elseif(file_exists($path.$ds['picID'].'.png')) $path = $path.$ds['picID'].'.png'; else $path = $path.$ds['picID'].'.gif'; @unlink($path); //large safe_query("DELETE FROM ".PREFIX."comments WHERE parentID='".$ds['picID']."' AND type='ga'"); } safe_query("DELETE FROM ".PREFIX."gallery_pictures WHERE galleryID='".$_GET['galleryID']."'"); } } else echo $_language->module['transaction_invalid']; } if($action=="add") { $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups"); $any=mysql_num_rows($ergebnis); if($any){ $groups = '<select name="group">'; while($ds=mysql_fetch_array($ergebnis)) { $groups.='<option value="'.$ds['groupID'].'">'.getinput($ds['name']).'</option>'; } $groups.='</select>'; $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=gallerys" class="white">'.$_language->module['galleries'].'</a> &raquo; '.$_language->module['add_gallery'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=gallerys&amp;action=upload"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['gallery_name'].'</b></td> <td width="85%"><input type="text" name="name" size="60" /></td> </tr> <tr> <td><b>'.$_language->module['group'].'</b></td> <td>'.$groups.'</td> </tr> <tr> <td><b>'.$_language->module['pic_upload'].'</b></td> <td><select name="upload"> <option value="ftp">'.$_language->module['ftp'].'</option> <option value="form">'.$_language->module['formular'].'</option> </select></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /></td> <td><input type="submit" name="save" value="'.$_language->module['add_gallery'].'" /></td> </tr> </table> </form> <br /><small>'.$_language->module['ftp_info'].' "http://'.$hp_url.'/images/gallery"</small>'; } else{ echo '<br>'.$_language->module['need_group']; } } elseif($action=="edit") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups"); $groups = '<select name="group">'; while($ds=mysql_fetch_array($ergebnis)) { $groups.='<option value="'.$ds['groupID'].'">'.getinput($ds['name']).'</option>'; } $groups.='</select>'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery WHERE galleryID='".$_GET['galleryID']."'"); $ds=mysql_fetch_array($ergebnis); $groups = str_replace('value="'.$ds['groupID'].'"','value="'.$ds['groupID'].'" selected="selected"',$groups); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=gallerys" class="white">'.$_language->module['galleries'].'</a> &raquo; '.$_language->module['edit_gallery'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['gallery_name'].'</b></td> <td width="85%"><input type="text" name="name" value="'.getinput($ds['name']).'" /></td> </tr>'; if($ds['userID'] != 0) echo ' <tr> <td><b>'.$_language->module['usergallery_of'].'</b></td> <td><a href="../index.php?site=profile&amp;id='.$userID.'" target="_blank">'.getnickname($ds['userID']).'</a></td> </tr>'; else echo '<tr> <td><b>'.$_language->module['group'].'</b></td> <td>'.$groups.'</td> </tr>'; echo'<tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$ds['galleryID'].'" /></td> <td><input type="submit" name="saveedit" value="'.$_language->module['edit_gallery'].'" /></td> </tr> </table> </form>'; } elseif($action=="upload") { echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=gallerys" class="white">'.$_language->module['galleries'].'</a> &raquo; '.$_language->module['upload'].'</h1>'; $dir = '../images/gallery/'; if(isset($_POST['upload'])) $upload_type = $_POST['upload']; elseif(isset($_GET['upload'])) $upload_type = $_GET['upload']; else $upload_type = null; if(isset($_GET['galleryID'])) $id=$_GET['galleryID']; if($upload_type == "ftp") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); echo'<form method="post" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td>'; $pics = Array(); $picdir = opendir($dir); while (false !== ($file = readdir($picdir))) { if ($file != "." && $file != "..") { if(is_file($dir.$file)) { if($info = getimagesize($dir.$file)) { if($info[2]==1 OR $info[2]==2 || $info[2]==3) $pics[] = $file; } } } } closedir($picdir); natcasesort ($pics); reset ($pics); echo '<script language="JavaScript" type="text/javascript"> function fillcomments(){ document.getElementById(\'comments\').value=getselection(\'access\'); } </script> <table border="0" width="100%" cellspacing="1" cellpadding="1"> <tr> <td></td> <td><b>'.$_language->module['filename'].'</b></td> <td><b>'.$_language->module['name'].'</b></td> <td><b>'.$_language->module['comment'].'</b></td> </tr>'; foreach($pics as $val) { if(is_file($dir.$val)) { echo '<tr> <td><input type="checkbox" value="'.$val.'" name="pictures[]" checked="checked" /></td> <td><a href="'.$dir.$val.'" target="_blank">'.$val.'</a></td> <td><input type="text" name="name[]" size="40" /></td> <td><input type="text" name="comment[]" size="40" /></td> </tr>'; } } $accesses=generateaccessdropdown('access', 'access', '', 'fillcomments();'); echo '</table></td> </tr> <tr> <td><br /><b>'.$_language->module['visitor_comments'].'</b> &nbsp; '.$accesses.' <input type="hidden" value="" name="comments" id="comments" /></td> </tr> <tr> <td><br /><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$id.'" /> <input type="submit" name="saveftp" value="'.$_language->module['upload'].'" /></td> </tr> </table> </form>'; } elseif($upload_type == "form") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $accesses=generateaccessdropdown('access', 'access', '', 'fillcomments();'); echo '<script language="JavaScript" type="text/javascript"> function fillcomments(){ document.getElementById(\'comments\').value=getselection(\'access\'); } </script> <form method="post" action="admincenter.php?site=gallery&amp;part=gallerys" enctype="multipart/form-data"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="20%"><b>'.$_language->module['name'].'</b></td> <td width="80%"><input type="text" name="name" size="60" /></td> </tr> <tr> <td><b>'.$_language->module['comment'].'</b></td> <td><input type="text" name="comment" size="60" maxlength="255" /></td> </tr> <tr> <td valign="top"><b>'.$_language->module['visitor_comments'].'</b></td> <td> '.$accesses.' <input type="hidden" value="" name="comments" id="comments" /> </td> </tr> <tr> <td><b>'.$_language->module['picture'].'</b></td> <td><input name="picture" type="file" size="40" /></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$id.'" /></td> <td><input type="submit" name="saveform" value="'.$_language->module['upload'].'" /></td> </tr> </table> </form>'; } } else { echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; '.$_language->module['galleries'].'</h1>'; echo'<input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=add\');return document.MM_returnValue" value="'.$_language->module['new_gallery'].'" /><br /><br />'; echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD"> <tr> <td width="50%" class="title"><b>'.$_language->module['gallery_name'].'</b></td> <td width="50%" class="title" colspan="2"><b>'.$_language->module['actions'].'</b></td> </tr>'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups ORDER BY sort"); while($ds=mysql_fetch_array($ergebnis)) { echo'<tr> <td class="td_head" colspan="3"><b>'.getinput($ds['name']).'</b></td> </tr>'; $galleries=safe_query("SELECT * FROM ".PREFIX."gallery WHERE groupID='$ds[groupID]' AND userID='0' ORDER BY date"); $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $i=1; while($db=mysql_fetch_array($galleries)) { if($i%2) { $td='td1'; } else { $td='td2'; } echo'<tr> <td class="'.$td.'" width="50%"><a href="../index.php?site=gallery&amp;galleryID='.$db['galleryID'].'" target="_blank">'.getinput($db['name']).'</a></td> <td class="'.$td.'" width="30%" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=upload&amp;upload=form&amp;galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['add_img'].' ('.$_language->module['per_form'].')" style="margin:1px;" /> <input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=upload&amp;upload=ftp&amp;galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['add_img'].' ('.$_language->module['per_ftp'].')" style="margin:1px;" /></td> <td class="'.$td.'" width="20%" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=edit&amp;galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" /> <input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_gallery'].'\', \'admincenter.php?site=gallery&amp;part=gallerys&amp;delete=true&amp;galleryID='.$db['galleryID'].'&amp;captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td> </tr>'; $i++; } } echo'</table></form><br /><br />'; echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; '.$_language->module['usergalleries'].'</h1>'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery WHERE userID!='0'"); echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD"> <tr> <td width="50%" class="title"><b>'.$_language->module['gallery_name'].'</b></td> <td width="30%" class="title"><b>'.$_language->module['usergallery_of'].'</b></td> <td width="20%" class="title"><b>'.$_language->module['actions'].'</b></td> </tr>'; $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $i=1; while($ds=mysql_fetch_array($ergebnis)) { if($i%2) { $td='td1'; } else { $td='td2'; } echo'<tr> <td class="'.$td.'"><a href="../index.php?site=gallery&amp;galleryID='.$ds['galleryID'].'" target="_blank">'.getinput($ds['name']).'</a></td> <td class="'.$td.'"><a href="../index.php?site=profile&amp;id='.$userID.'" target="_blank">'.getnickname($ds['userID']).'</a></td> <td class="'.$td.'" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=edit&amp;galleryID='.$ds['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" /> <input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_gallery'].'\', \'admincenter.php?site=gallery&amp;part=gallerys&amp;delete=true&amp;galleryID='.$ds['galleryID'].'&amp;captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td> </tr>'; $i++; } echo'</table></form>'; } } ?>
webSPELL/webSPELL-4.2.3SE
admin/gallery.php
PHP
gpl-3.0
27,665
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * 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.github.mdsimmo.pixeldungeon.levels.painters; import com.github.mdsimmo.pixeldungeon.items.Gold; import com.github.mdsimmo.pixeldungeon.items.Heap; import com.github.mdsimmo.pixeldungeon.items.keys.IronKey; import com.github.mdsimmo.pixeldungeon.levels.Level; import com.github.mdsimmo.pixeldungeon.levels.Room; import com.github.mdsimmo.pixeldungeon.levels.Terrain; import com.github.mdsimmo.utils.Random; public class TreasuryPainter extends Painter { public static void paint( Level level, Room room ) { fill( level, room, Terrain.WALL ); fill( level, room, 1, Terrain.EMPTY ); set( level, room.center(), Terrain.STATUE ); Heap.Type heapType = Random.Int( 2 ) == 0 ? Heap.Type.CHEST : Heap.Type.HEAP; int n = Random.IntRange( 2, 3 ); for ( int i = 0; i < n; i++ ) { int pos; do { pos = room.random(); } while ( level.map[pos] != Terrain.EMPTY || level.heaps.get( pos ) != null ); level.drop( new Gold().random(), pos ).type = (i == 0 && heapType == Heap.Type.CHEST ? Heap.Type.MIMIC : heapType); } if ( heapType == Heap.Type.HEAP ) { for ( int i = 0; i < 6; i++ ) { int pos; do { pos = room.random(); } while ( level.map[pos] != Terrain.EMPTY ); level.drop( new Gold( Random.IntRange( 1, 3 ) ), pos ); } } room.entrance().set( Room.Door.Type.LOCKED ); level.addItemToSpawn( new IronKey() ); } }
mdsimmo/cake-dungeon
java/com/github/mdsimmo/pixeldungeon/levels/painters/TreasuryPainter.java
Java
gpl-3.0
2,296
// Copyright 2014 The go-krypton Authors // This file is part of the go-krypton library. // // The go-krypton 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 3 of the License, or // (at your option) any later version. // // The go-krypton 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 the go-krypton library. If not, see <http://www.gnu.org/licenses/>. // Package trie implements Merkle Patricia Tries. package trie import ( "bytes" "errors" "fmt" "hash" "github.com/krypton/go-krypton/common" "github.com/krypton/go-krypton/crypto" "github.com/krypton/go-krypton/crypto/sha3" "github.com/krypton/go-krypton/logger" "github.com/krypton/go-krypton/logger/glog" "github.com/krypton/go-krypton/rlp" ) const defaultCacheCapacity = 800 var ( // The global cache stores decoded trie nodes by hash as they get loaded. globalCache = newARC(defaultCacheCapacity) // This is the known root hash of an empty trie. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") // This is the known hash of an empty state trie entry. emptyState = crypto.Sha3Hash(nil) ) var ErrMissingRoot = errors.New("missing root node") // Database must be implemented by backing stores for the trie. type Database interface { DatabaseWriter // Get returns the value for key from the database. Get(key []byte) (value []byte, err error) } // DatabaseWriter wraps the Put method of a backing store for the trie. type DatabaseWriter interface { // Put stores the mapping key->value in the database. // Implementations must not hold onto the value bytes, the trie // will reuse the slice across calls to Put. Put(key, value []byte) error } // Trie is a Merkle Patricia Trie. // The zero value is an empty trie with no database. // Use New to create a trie that sits on top of a database. // // Trie is not safe for concurrent use. type Trie struct { root node db Database *hasher } // New creates a trie with an existing root node from db. // // If root is the zero hash or the sha3 hash of an empty string, the // trie is initially empty and does not require a database. Otherwise, // New will panics if db is nil or root does not exist in the // database. Accessing the trie loads nodes from db on demand. func New(root common.Hash, db Database) (*Trie, error) { trie := &Trie{db: db} if (root != common.Hash{}) && root != emptyRoot { if db == nil { panic("trie.New: cannot use existing root without a database") } if v, _ := trie.db.Get(root[:]); len(v) == 0 { return nil, ErrMissingRoot } trie.root = hashNode(root.Bytes()) } return trie, nil } // Iterator returns an iterator over all mappings in the trie. func (t *Trie) Iterator() *Iterator { return NewIterator(t) } // Get returns the value for key stored in the trie. // The value bytes must not be modified by the caller. func (t *Trie) Get(key []byte) []byte { key = compactHexDecode(key) tn := t.root for len(key) > 0 { switch n := tn.(type) { case shortNode: if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) { return nil } tn = n.Val key = key[len(n.Key):] case fullNode: tn = n[key[0]] key = key[1:] case nil: return nil case hashNode: tn = t.resolveHash(n) default: panic(fmt.Sprintf("%T: invalid node: %v", tn, tn)) } } return tn.(valueNode) } // Update associates key with value in the trie. Subsequent calls to // Get will return value. If value has length zero, any existing value // is deleted from the trie and calls to Get will return nil. // // The value bytes must not be modified by the caller while they are // stored in the trie. func (t *Trie) Update(key, value []byte) { k := compactHexDecode(key) if len(value) != 0 { t.root = t.insert(t.root, k, valueNode(value)) } else { t.root = t.delete(t.root, k) } } func (t *Trie) insert(n node, key []byte, value node) node { if len(key) == 0 { return value } switch n := n.(type) { case shortNode: matchlen := prefixLen(key, n.Key) // If the whole key matches, keep this short node as is // and only update the value. if matchlen == len(n.Key) { return shortNode{n.Key, t.insert(n.Val, key[matchlen:], value)} } // Otherwise branch out at the index where they differ. var branch fullNode branch[n.Key[matchlen]] = t.insert(nil, n.Key[matchlen+1:], n.Val) branch[key[matchlen]] = t.insert(nil, key[matchlen+1:], value) // Replace this shortNode with the branch if it occurs at index 0. if matchlen == 0 { return branch } // Otherwise, replace it with a short node leading up to the branch. return shortNode{key[:matchlen], branch} case fullNode: n[key[0]] = t.insert(n[key[0]], key[1:], value) return n case nil: return shortNode{key, value} case hashNode: // We've hit a part of the trie that isn't loaded yet. Load // the node and insert into it. This leaves all child nodes on // the path to the value in the trie. // // TODO: track whkrypton insertion changed the value and keep // n as a hash node if it didn't. return t.insert(t.resolveHash(n), key, value) default: panic(fmt.Sprintf("%T: invalid node: %v", n, n)) } } // Delete removes any existing value for key from the trie. func (t *Trie) Delete(key []byte) { k := compactHexDecode(key) t.root = t.delete(t.root, k) } // delete returns the new root of the trie with key deleted. // It reduces the trie to minimal form by simplifying // nodes on the way up after deleting recursively. func (t *Trie) delete(n node, key []byte) node { switch n := n.(type) { case shortNode: matchlen := prefixLen(key, n.Key) if matchlen < len(n.Key) { return n // don't replace n on mismatch } if matchlen == len(key) { return nil // remove n entirely for whole matches } // The key is longer than n.Key. Remove the remaining suffix // from the subtrie. Child can never be nil here since the // subtrie must contain at least two other values with keys // longer than n.Key. child := t.delete(n.Val, key[len(n.Key):]) switch child := child.(type) { case shortNode: // Deleting from the subtrie reduced it to another // short node. Merge the nodes to avoid creating a // shortNode{..., shortNode{...}}. Use concat (which // always creates a new slice) instead of append to // avoid modifying n.Key since it might be shared with // other nodes. return shortNode{concat(n.Key, child.Key...), child.Val} default: return shortNode{n.Key, child} } case fullNode: n[key[0]] = t.delete(n[key[0]], key[1:]) // Check how many non-nil entries are left after deleting and // reduce the full node to a short node if only one entry is // left. Since n must've contained at least two children // before deletion (otherwise it would not be a full node) n // can never be reduced to nil. // // When the loop is done, pos contains the index of the single // value that is left in n or -2 if n contains at least two // values. pos := -1 for i, cld := range n { if cld != nil { if pos == -1 { pos = i } else { pos = -2 break } } } if pos >= 0 { if pos != 16 { // If the remaining entry is a short node, it replaces // n and its key gets the missing nibble tacked to the // front. This avoids creating an invalid // shortNode{..., shortNode{...}}. Since the entry // might not be loaded yet, resolve it just for this // check. cnode := t.resolve(n[pos]) if cnode, ok := cnode.(shortNode); ok { k := append([]byte{byte(pos)}, cnode.Key...) return shortNode{k, cnode.Val} } } // Otherwise, n is replaced by a one-nibble short node // containing the child. return shortNode{[]byte{byte(pos)}, n[pos]} } // n still contains at least two values and cannot be reduced. return n case nil: return nil case hashNode: // We've hit a part of the trie that isn't loaded yet. Load // the node and delete from it. This leaves all child nodes on // the path to the value in the trie. // // TODO: track whkrypton deletion actually hit a key and keep // n as a hash node if it didn't. return t.delete(t.resolveHash(n), key) default: panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key)) } } func concat(s1 []byte, s2 ...byte) []byte { r := make([]byte, len(s1)+len(s2)) copy(r, s1) copy(r[len(s1):], s2) return r } func (t *Trie) resolve(n node) node { if n, ok := n.(hashNode); ok { return t.resolveHash(n) } return n } func (t *Trie) resolveHash(n hashNode) node { if v, ok := globalCache.Get(n); ok { return v } enc, err := t.db.Get(n) if err != nil || enc == nil { // TODO: This needs to be improved to properly distinguish errors. // Disk I/O errors shouldn't produce nil (and cause a // consensus failure or weird crash), but it is unclear how // they could be handled because the entire stack above the trie isn't // prepared to cope with missing state nodes. if glog.V(logger.Error) { glog.Errorf("Dangling hash node ref %x: %v", n, err) } return nil } dec := mustDecodeNode(n, enc) if dec != nil { globalCache.Put(n, dec) } return dec } // Root returns the root hash of the trie. // Deprecated: use Hash instead. func (t *Trie) Root() []byte { return t.Hash().Bytes() } // Hash returns the root hash of the trie. It does not write to the // database and can be used even if the trie doesn't have one. func (t *Trie) Hash() common.Hash { root, _ := t.hashRoot(nil) return common.BytesToHash(root.(hashNode)) } // Commit writes all nodes to the trie's database. // Nodes are stored with their sha3 hash as the key. // // Committing flushes nodes from memory. // Subsequent Get calls will load nodes from the database. func (t *Trie) Commit() (root common.Hash, err error) { if t.db == nil { panic("Commit called on trie with nil database") } return t.CommitTo(t.db) } // CommitTo writes all nodes to the given database. // Nodes are stored with their sha3 hash as the key. // // Committing flushes nodes from memory. Subsequent Get calls will // load nodes from the trie's database. Calling code must ensure that // the changes made to db are written back to the trie's attached // database before using the trie. func (t *Trie) CommitTo(db DatabaseWriter) (root common.Hash, err error) { n, err := t.hashRoot(db) if err != nil { return (common.Hash{}), err } t.root = n return common.BytesToHash(n.(hashNode)), nil } func (t *Trie) hashRoot(db DatabaseWriter) (node, error) { if t.root == nil { return hashNode(emptyRoot.Bytes()), nil } if t.hasher == nil { t.hasher = newHasher() } return t.hasher.hash(t.root, db, true) } type hasher struct { tmp *bytes.Buffer sha hash.Hash } func newHasher() *hasher { return &hasher{tmp: new(bytes.Buffer), sha: sha3.NewKeccak256()} } func (h *hasher) hash(n node, db DatabaseWriter, force bool) (node, error) { hashed, err := h.replaceChildren(n, db) if err != nil { return hashNode{}, err } if n, err = h.store(hashed, db, force); err != nil { return hashNode{}, err } return n, nil } // hashChildren replaces child nodes of n with their hashes if the encoded // size of the child is larger than a hash. func (h *hasher) replaceChildren(n node, db DatabaseWriter) (node, error) { var err error switch n := n.(type) { case shortNode: n.Key = compactEncode(n.Key) if _, ok := n.Val.(valueNode); !ok { if n.Val, err = h.hash(n.Val, db, false); err != nil { return n, err } } if n.Val == nil { // Ensure that nil children are encoded as empty strings. n.Val = valueNode(nil) } return n, nil case fullNode: for i := 0; i < 16; i++ { if n[i] != nil { if n[i], err = h.hash(n[i], db, false); err != nil { return n, err } } else { // Ensure that nil children are encoded as empty strings. n[i] = valueNode(nil) } } if n[16] == nil { n[16] = valueNode(nil) } return n, nil default: return n, nil } } func (h *hasher) store(n node, db DatabaseWriter, force bool) (node, error) { // Don't store hashes or empty nodes. if _, isHash := n.(hashNode); n == nil || isHash { return n, nil } h.tmp.Reset() if err := rlp.Encode(h.tmp, n); err != nil { panic("encode error: " + err.Error()) } if h.tmp.Len() < 32 && !force { // Nodes smaller than 32 bytes are stored inside their parent. return n, nil } // Larger nodes are replaced by their hash and stored in the database. h.sha.Reset() h.sha.Write(h.tmp.Bytes()) key := hashNode(h.sha.Sum(nil)) if db != nil { err := db.Put(key, h.tmp.Bytes()) return key, err } return key, nil }
covertress/go-krypton
trie/trie.go
GO
gpl-3.0
13,056
class Solution { public: string addBinary(string a, string b) { string sum = ""; int carry = 0; for (int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; i--, j--) { int m = (i >= 0 && a[i] == '1'); int n = (j >= 0 && b[j] == '1'); sum += to_string((m + n + carry) & 0x1); // &0x1 only get the last binary digit //It's better to avoid pattern string = char + string in loop. Use s[i] to alter string. //just directly writing the output string and reversing it at last. carry = (m + n + carry) >> 1; // >>1 is /2 } reverse(sum.begin(), sum.end()); if(carry) sum = '1' + sum; else sum = '0' + sum; //in case of two null input string size_t i=0; while(sum[i] == '0' && i < sum.length()-1) i++; sum = sum.substr(i); return sum; } };
zemli/Cpp-Tutorial
algorithm/string/Add Binary-optimized.cpp
C++
gpl-3.0
1,206
#include "stdafx.h" #include <gtest/gtest.h> #include "MonsterHeadingCalculator.h" namespace PacMan { namespace Logic { namespace Tests { using namespace Logic; void test_calculate_sets_heading ( Row monster_row, Column monster_column, Row pacman_row, Column pacman_column, Heading expected ) { // Arrange MonsterHeadingCalculator sut{}; sut.monster_row = monster_row; sut.monster_column = monster_column; sut.pacman_row = pacman_row; sut.pacman_column = pacman_column; // Act sut.calculate(); // Assert Heading actual = sut.get_heading(); EXPECT_EQ(expected, actual); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_0_0_and_pac_man_1_1) { test_calculate_sets_heading( Row{0}, Column{0}, Row{1}, Column{1}, Heading_Down); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_0_1_and_pac_man_1_1) { test_calculate_sets_heading( Row{0}, Column{1}, Row{1}, Column{1}, Heading_Down); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_0_2_and_pac_man_1_1) { test_calculate_sets_heading( Row{0}, Column{2}, Row{1}, Column{1}, Heading_Down); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_1_0_and_pac_man_1_1) { test_calculate_sets_heading( Row{1}, Column{0}, Row{1}, Column{1}, Heading_Right); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_1_1_and_pac_man_1_1) { test_calculate_sets_heading( Row{1}, Column{1}, Row{1}, Column{1}, Heading_Unknown); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_1_2_and_pac_man_1_1) { test_calculate_sets_heading( Row{1}, Column{2}, Row{1}, Column{1}, Heading_Left); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_2_0_and_pac_man_1_1) { using namespace Logic; test_calculate_sets_heading( Row{2}, Column{0}, Row{1}, Column{1}, Heading_Up); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_2_1_and_pac_man_1_1) { test_calculate_sets_heading( Row{2}, Column{1}, Row{1}, Column{1}, Heading_Up); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_2_2_and_pac_man_1_1) { test_calculate_sets_heading( Row{2}, Column{2}, Row{1}, Column{1}, Heading_Up); } }; }; };
tschroedter/cpp_examples
vs2015/Katas/KataPacMan/PacMan.Logic.Tests/MonsterHeadingCalculator.Tests.cpp
C++
gpl-3.0
4,978
/** Author: Sharmin Akter **/ /** Created at: 4/30/2012 12:07:26 AM **/ #include<stdio.h> int main() { int i,j,k,p,m,n,t; while(scanf("%d",&t)==1) { for(i=1;i<=t;i++) { scanf("%d",&p); if(p==2||p==3||p==5||p==7||p==13||p==17) printf("Yes\n"); else printf("No\n"); getchar(); } } return 0; }
sajinia/UVa-Online-Judge
Volume-11/1180-(2 numbery).cpp
C++
gpl-3.0
437
/** * This file is part of JsonFL. * * JsonFL is free software: you can redistribute it and/or modify it under the * terms of the Lesser GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * JsonFL 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 Lesser GNU General Public License for more * details. * * You should have received a copy of the Lesser GNU General Public License * along with JsonFL. If not, see <http://www.gnu.org/licenses/>. */ package au.com.houliston.jsonfl; /** * Is thrown when the creation string for the JsonFL is invalid * * @author Trent Houliston * @version 1.0 */ public class InvalidJsonFLException extends Exception { /** * Creates a new InvalidJsonFLException with the passed message * * @param message The message to set */ public InvalidJsonFLException(String message) { super(message); } /** * Creates a new InvalidJsonFLException along with a message and a cause * * @param message The message to set * @param cause The root cause which made this exception */ public InvalidJsonFLException(String message, Throwable cause) { super(message, cause); } }
TrentHouliston/JsonFL
src/main/java/au/com/houliston/jsonfl/InvalidJsonFLException.java
Java
gpl-3.0
1,371
package edu.kit.iti.formal.mandatsverteilung.generierer; import edu.kit.iti.formal.mandatsverteilung.datenhaltung.Bundestagswahl; /** * Modelliert eine Einschränkung an das Ergebnis des Generierers, dass der * Bundestag eine bestimmte Größe haben soll. * * @author Jan * */ public class SitzzahlEinschraenkung extends Einschraenkung { public SitzzahlEinschraenkung(int wert, int abweichung) { assert wert > 0; assert abweichung > 0; this.wert = wert; this.abweichung = abweichung; gewichtung = 1.0; } @Override int ueberpruefeErgebnis(Bundestagswahl b) { int tatsaechlicheSitzzahl = b.getSitzzahl(); int genauigkeit = RandomisierterGenerierer.getGenauigkeit(); double minD = (minDistance(genauigkeit * tatsaechlicheSitzzahl, genauigkeit * wert, genauigkeit * abweichung)); return (int) (gewichtung * minD); } }
Bundeswahlrechner/Bundeswahlrechner
mandatsverteilung/src/main/java/edu/kit/iti/formal/mandatsverteilung/generierer/SitzzahlEinschraenkung.java
Java
gpl-3.0
934
#include "definitions.h" CustomWeakForm::CustomWeakForm(std::vector<std::string> newton_boundaries, double heatcap, double rho, double tau, double lambda, double alpha, double temp_ext, MeshFunctionSharedPtr<double> sln_prev_time, bool JFNK) : WeakForm<double>(1, JFNK) { this->set_ext(sln_prev_time); // Jacobian forms - volumetric. add_matrix_form(new JacobianFormVol(0, 0, heatcap, rho, lambda, tau)); // Jacobian forms - surface. add_matrix_form_surf(new JacobianFormSurf(0, 0, newton_boundaries, alpha, lambda)); // Residual forms - volumetric. ResidualFormVol* res_form = new ResidualFormVol(0, heatcap, rho, lambda, tau); add_vector_form(res_form); // Residual forms - surface. add_vector_form_surf(new ResidualFormSurf(0, newton_boundaries, alpha, lambda, temp_ext)); } double CustomWeakForm::JacobianFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double> **ext) const { double result = 0; for (int i = 0; i < n; i++) result += wt[i] * (heatcap * rho * u->val[i] * v->val[i] / tau + lambda * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])); return result; } Ord CustomWeakForm::JacobianFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord> **ext) const { // Returning the sum of the degrees of the basis and test function plus two. return Ord(10); } MatrixFormVol<double>* CustomWeakForm::JacobianFormVol::clone() const { return new CustomWeakForm::JacobianFormVol(*this); } double CustomWeakForm::JacobianFormSurf::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomSurf<double> *e, Func<double> **ext) const { double result = 0; for (int i = 0; i < n; i++) result += wt[i] * alpha * lambda * u->val[i] * v->val[i]; return result; } Ord CustomWeakForm::JacobianFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord> **ext) const { // Returning the sum of the degrees of the basis and test function plus two. return Ord(10); } MatrixFormSurf<double>* CustomWeakForm::JacobianFormSurf::clone() const { return new CustomWeakForm::JacobianFormSurf(*this); } double CustomWeakForm::ResidualFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e, Func<double> **ext) const { double result = 0; for (int i = 0; i < n; i++) result += wt[i] * (heatcap * rho * (u_ext[0]->val[i] - ext[0]->val[i]) * v->val[i] / tau + lambda * (u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i])); return result; } Ord CustomWeakForm::ResidualFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord> **ext) const { // Returning the sum of the degrees of the test function and solution plus two. return Ord(10); } VectorFormVol<double>* CustomWeakForm::ResidualFormVol::clone() const { return new CustomWeakForm::ResidualFormVol(*this); } double CustomWeakForm::ResidualFormSurf::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomSurf<double> *e, Func<double> **ext) const { double result = 0; for (int i = 0; i < n; i++) result += wt[i] * alpha * lambda * (u_ext[0]->val[i] - temp_ext) * v->val[i]; return result; } Ord CustomWeakForm::ResidualFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord> **ext) const { // Returning the sum of the degrees of the test function and solution plus two. return Ord(10); } VectorFormSurf<double>* CustomWeakForm::ResidualFormSurf::clone() const { return new CustomWeakForm::ResidualFormSurf(*this); }
hpfem/hermes-tutorial
F-trilinos/03-trilinos-timedep/definitions.cpp
C++
gpl-3.0
3,694
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding unique constraint on 'Vendeur', fields ['code_permanent'] db.create_unique(u'encefal_vendeur', ['code_permanent']) def backwards(self, orm): # Removing unique constraint on 'Vendeur', fields ['code_permanent'] db.delete_unique(u'encefal_vendeur', ['code_permanent']) models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'encefal.exemplaire': { 'Meta': {'object_name': 'Exemplaire'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'etat': ('django.db.models.fields.CharField', [], {'default': "'VENT'", 'max_length': '4'}), 'facture': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'exemplaires'", 'null': 'True', 'db_column': "'facture'", 'to': u"orm['encefal.Facture']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'livre': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exemplaires'", 'db_column': "'livre'", 'to': u"orm['encefal.Livre']"}), 'prix': ('django.db.models.fields.IntegerField', [], {}), 'vendeur': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exemplaires'", 'db_column': "'vendeur'", 'to': u"orm['encefal.Vendeur']"}) }, u'encefal.facture': { 'Meta': {'object_name': 'Facture'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'employe': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'factures'", 'blank': 'True', 'db_column': "'employe'", 'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'factures'", 'blank': 'True', 'db_column': "'session'", 'to': u"orm['encefal.Session']"}) }, u'encefal.livre': { 'Meta': {'object_name': 'Livre'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'auteur': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'edition': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'isbn': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '13', 'blank': 'True'}), 'titre': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'vendeur': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'livres'", 'symmetrical': 'False', 'through': u"orm['encefal.Exemplaire']", 'db_column': "'vendeur'", 'to': u"orm['encefal.Vendeur']"}) }, u'encefal.session': { 'Meta': {'object_name': 'Session'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_debut': ('django.db.models.fields.DateField', [], {}), 'date_fin': ('django.db.models.fields.DateField', [], {}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, u'encefal.vendeur': { 'Meta': {'object_name': 'Vendeur'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'code_permanent': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'prenom': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'telephone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['encefal']
nilovna/EnceFAL
project/encefal/migrations/0003_auto__add_unique_vendeur_code_permanent.py
Python
gpl-3.0
8,651
# $Id$ # Copyright 2013 Matthew Wall # See the file LICENSE.txt for your full rights. # # Thanks to Eddie De Pieri for the first Python implementation for WS-28xx. # Eddie did the difficult work of decompiling HeavyWeather then converting # and reverse engineering into a functional Python implementation. Eddie's # work was based on reverse engineering of HeavyWeather 2800 v 1.54 # # Thanks to Lucas Heijst for enumerating the console message types and for # debugging the transceiver/console communication timing issues. """Classes and functions for interfacing with WS-28xx weather stations. LaCrosse makes a number of stations in the 28xx series, including: WS-2810, WS-2810U-IT WS-2811, WS-2811SAL-IT, WS-2811BRN-IT, WS-2811OAK-IT WS-2812, WS-2812U-IT WS-2813 WS-2814, WS-2814U-IT WS-2815, WS-2815U-IT C86234 The station is also sold as the TFA Primus, TFA Opus, and TechnoLine. HeavyWeather is the software provided by LaCrosse. There are two versions of HeavyWeather for the WS-28xx series: 1.5.4 and 1.5.4b Apparently there is a difference between TX59UN-1-IT and TX59U-IT models (this identifier is printed on the thermo-hygro sensor). HeavyWeather Version Firmware Version Thermo-Hygro Model 1.54 333 or 332 TX59UN-1-IT 1.54b 288, 262, 222 TX59U-IT HeavyWeather provides the following weather station settings: time display: 12|24 hour temperature display: C|F air pressure display: inhg|hpa wind speed display: m/s|knots|bft|km/h|mph rain display: mm|inch recording interval: 1m keep weather station in hi-speed communication mode: true/false According to the HeavyWeatherPro User Manual (1.54, rev2), "Hi speed mode wears down batteries on your display much faster, and similarly consumes more power on the PC. We do not believe most users need to enable this setting. It was provided at the request of users who prefer ultra-frequent uploads." The HeavyWeatherPro 'CurrentWeather' view is updated as data arrive from the console. The console sends current weather data approximately every 13 seconds. Historical data are updated less frequently - every 2 hours in the default HeavyWeatherPro configuration. According to the User Manual, "The 2800 series weather station uses the 'original' wind chill calculation rather than the 2001 'North American' formula because the original formula is international." Apparently the station console determines when data will be sent, and, once paired, the transceiver is always listening. The station console sends a broadcast on the hour. If the transceiver responds, the station console may continue to broadcast data, depending on the transceiver response and the timing of the transceiver response. According to the C86234 Operations Manual (Revision 7): - Temperature and humidity data are sent to the console every 13 seconds. - Wind data are sent to the temperature/humidity sensor every 17 seconds. - Rain data are sent to the temperature/humidity sensor every 19 seconds. - Air pressure is measured every 15 seconds. Each tip of the rain bucket is 0.26 mm of rain. The following information was obtained by logging messages from the ws28xx.py driver in weewx and by capturing USB messages between Heavy Weather Pro for ws2800 and the TFA Primus Weather Station via windows program USB sniffer busdog64_v0.2.1. Pairing The transceiver must be paired with a console before it can receive data. Each frame sent by the console includes the device identifier of the transceiver with which it is paired. Synchronizing When the console and transceiver stop communicating, they can be synchronized by one of the following methods: - Push the SET button on the console - Wait till the next full hour when the console sends a clock message In each case a Request Time message is received by the transceiver from the console. The 'Send Time to WS' message should be sent within ms (10 ms typical). The transceiver should handle the 'Time SET' message then send a 'Time/Config written' message about 85 ms after the 'Send Time to WS' message. When complete, the console and transceiver will have been synchronized. Timing Current Weather messages, History messages, getConfig/setConfig messages, and setTime messages each have their own timing. Missed History messages - as a result of bad timing - result in console and transceiver becoming out of synch. Current Weather The console periodically sends Current Weather messages, each with the latest values from the sensors. The CommModeInterval determines how often the console will send Current Weather messages. History The console records data periodically at an interval defined by the HistoryInterval parameter. The factory default setting is 2 hours. Each history record contains a timestamp. Timestamps use the time from the console clock. The console can record up to 1797 history records. Reading 1795 history records took about 110 minutes on a raspberry pi, for an average of 3.6 seconds per history record. Reading 1795 history records took 65 minutes on a synology ds209+ii, for an average of 2.2 seconds per history record. Reading 1750 history records took 19 minutes using HeavyWeatherPro on a Windows 7 64-bit laptop. Message Types The first byte of a message determines the message type. ID Type Length 01 ? 0x0f (15) d0 SetRX 0x15 (21) d1 SetTX 0x15 (21) d5 SetFrame 0x111 (273) d6 GetFrame 0x111 (273) d7 SetState 0x15 (21) d8 SetPreamblePattern 0x15 (21) d9 Execute 0x0f (15) dc ReadConfigFlash< 0x15 (21) dd ReadConfigFlash> 0x15 (21) de GetState 0x0a (10) f0 WriteReg 0x05 (5) In the following sections, some messages are decomposed using the following structure: start position in message buffer hi-lo data starts on first (hi) or second (lo) nibble chars data length in characters (nibbles) rem remark name variable ------------------------------------------------------------------------------- 1. 01 message (15 bytes) 000: 01 15 00 0b 08 58 3f 53 00 00 00 00 ff 15 0b (detected via USB sniffer) 000: 01 15 00 57 01 92 3f 53 00 00 00 00 ff 15 0a (detected via USB sniffer) 00: messageID 02-15: ?? ------------------------------------------------------------------------------- 2. SetRX message (21 bytes) 000: d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 020: 00 00: messageID 01-20: 00 ------------------------------------------------------------------------------- 3. SetTX message (21 bytes) 000: d1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 020: 00 00: messageID 01-20: 00 ------------------------------------------------------------------------------- 4. SetFrame message (273 bytes) Action: 00: rtGetHistory - Ask for History message 01: rtSetTime - Ask for Send Time to weather station message 02: rtSetConfig - Ask for Send Config to weather station message 03: rtGetConfig - Ask for Config message 05: rtGetCurrent - Ask for Current Weather message c0: Send Time - Send Time to WS 40: Send Config - Send Config to WS 000: d5 00 09 DevID 00 CfgCS cIntThisAdr xx xx xx rtGetHistory 000: d5 00 09 DevID 01 CfgCS cIntThisAdr xx xx xx rtReqSetTime 000: d5 00 09 f0 f0 02 CfgCS cIntThisAdr xx xx xx rtReqFirstConfig 000: d5 00 09 DevID 02 CfgCS cIntThisAdr xx xx xx rtReqSetConfig 000: d5 00 09 DevID 03 CfgCS cIntThisAdr xx xx xx rtGetConfig 000: d5 00 09 DevID 05 CfgCS cIntThisAdr xx xx xx rtGetCurrent 000: d5 00 0c DevID c0 CfgCS [TimeData . .. .. .. Send Time 000: d5 00 30 DevID 40 CfgCS [ConfigData .. .. .. Send Config All SetFrame messages: 00: messageID 01: 00 02: Message Length (starting with next byte) 03-04: DeviceID [DevID] 05: Action 06-07: Config checksum [CfgCS] Additional bytes rtGetCurrent, rtGetHistory, rtSetTime messages: 08-09hi: ComInt [cINT] 1.5 bytes (high byte first) 09lo-11: ThisHistoryAddress [ThisAdr] 2.5 bytes (high byte first) Additional bytes Send Time message: 08: seconds 09: minutes 10: hours 11hi: DayOfWeek 11lo: day_lo (low byte) 12hi: month_lo (low byte) 12lo: day_hi (high byte) 13hi: (year-2000)_lo (low byte) 13lo: month_hi (high byte) 14lo: (year-2000)_hi (high byte) ------------------------------------------------------------------------------- 5. GetFrame message Response type: 20: WS SetTime / SetConfig - Data written 40: GetConfig 60: Current Weather 80: Actual / Outstanding History a1: Request First-Time Config a2: Request SetConfig a3: Request SetTime 000: 00 00 06 DevID 20 64 CfgCS xx xx xx xx xx xx xx xx xx Time/Config written 000: 00 00 30 DevID 40 64 [ConfigData .. .. .. .. .. .. .. GetConfig 000: 00 00 d7 DevID 60 64 CfgCS [CurData .. .. .. .. .. .. Current Weather 000: 00 00 1e DevID 80 64 CfgCS 0LateAdr 0ThisAdr [HisData Outstanding History 000: 00 00 1e DevID 80 64 CfgCS 0LateAdr 0ThisAdr [HisData Actual History 000: 00 00 06 DevID a1 64 CfgCS xx xx xx xx xx xx xx xx xx Request FirstConfig 000: 00 00 06 DevID a2 64 CfgCS xx xx xx xx xx xx xx xx xx Request SetConfig 000: 00 00 06 DevID a3 64 CfgCS xx xx xx xx xx xx xx xx xx Request SetTime ReadConfig example: 000: 01 2e 40 5f 36 53 02 00 00 00 00 81 00 04 10 00 82 00 04 20 020: 00 71 41 72 42 00 05 00 00 00 27 10 00 02 83 60 96 01 03 07 040: 21 04 01 00 00 00 CfgCS WriteConfig example: 000: 01 2e 40 64 36 53 02 00 00 00 00 00 10 04 00 81 00 20 04 00 020: 82 41 71 42 72 00 00 05 00 00 00 10 27 01 96 60 83 02 01 04 040: 21 07 03 10 00 00 CfgCS 00: messageID 01: 00 02: Message Length (starting with next byte) 03-04: DeviceID [devID] 05hi: responseType 06: Quality (in steps of 5) Additional byte GetFrame messages except Request SetConfig and Request SetTime: 05lo: BatteryStat 8=WS bat low; 4=TMP bat low; 2=RAIN bat low; 1=WIND bat low Additional byte Request SetConfig and Request SetTime: 05lo: RequestID Additional bytes all GetFrame messages except ReadConfig and WriteConfig 07-08: Config checksum [CfgCS] Additional bytes Outstanding History: 09lo-11: LatestHistoryAddress [LateAdr] 2.5 bytes (Latest to sent) 12lo-14: ThisHistoryAddress [ThisAdr] 2.5 bytes (Outstanding) Additional bytes Actual History: 09lo-11: LatestHistoryAddress [ThisAdr] 2.5 bytes (LatestHistoryAddress is the) 12lo-14: ThisHistoryAddress [ThisAdr] 2.5 bytes (same as ThisHistoryAddress) Additional bytes ReadConfig and WriteConfig 43-45: ResetMinMaxFlags (Output only; not included in checksum calculation) 46-47: Config checksum [CfgCS] (CheckSum = sum of bytes (00-42) + 7) ------------------------------------------------------------------------------- 6. SetState message 000: d7 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00: messageID 01-14: 00 ------------------------------------------------------------------------------- 7. SetPreamblePattern message 000: d8 aa 00 00 00 00 00 00 00 00 00 00 00 00 00 00: messageID 01: ?? 02-14: 00 ------------------------------------------------------------------------------- 8. Execute message 000: d9 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00: messageID 01: ?? 02-14: 00 ------------------------------------------------------------------------------- 9. ReadConfigFlash in - receive data 000: dc 0a 01 f5 00 01 78 a0 01 02 0a 0c 0c 01 2e ff ff ff ff ff - freq correction 000: dc 0a 01 f9 01 02 0a 0c 0c 01 2e ff ff ff ff ff ff ff ff ff - transceiver data 00: messageID 01: length 02-03: address Additional bytes frequency correction 05lo-07hi: frequency correction Additional bytes transceiver data 05-10: serial number 09-10: DeviceID [devID] ------------------------------------------------------------------------------- 10. ReadConfigFlash out - ask for data 000: dd 0a 01 f5 cc cc cc cc cc cc cc cc cc cc cc - Ask for freq correction 000: dd 0a 01 f9 cc cc cc cc cc cc cc cc cc cc cc - Ask for transceiver data 00: messageID 01: length 02-03: address 04-14: cc ------------------------------------------------------------------------------- 11. GetState message 000: de 14 00 00 00 00 (between SetPreamblePattern and first de16 message) 000: de 15 00 00 00 00 Idle message 000: de 16 00 00 00 00 Normal message 000: de 0b 00 00 00 00 (detected via USB sniffer) 00: messageID 01: stateID 02-05: 00 ------------------------------------------------------------------------------- 12. Writereg message 000: f0 08 01 00 00 - AX5051RegisterNames.IFMODE 000: f0 10 01 41 00 - AX5051RegisterNames.MODULATION 000: f0 11 01 07 00 - AX5051RegisterNames.ENCODING ... 000: f0 7b 01 88 00 - AX5051RegisterNames.TXRATEMID 000: f0 7c 01 23 00 - AX5051RegisterNames.TXRATELO 000: f0 7d 01 35 00 - AX5051RegisterNames.TXDRIVER 00: messageID 01: register address 02: 01 03: AX5051RegisterName 04: 00 ------------------------------------------------------------------------------- 13. Current Weather message start hi-lo chars rem name 0 hi 4 DevID 2 hi 2 Action 3 hi 2 Quality 4 hi 4 DeviceCS 6 hi 4 6 _AlarmRingingFlags 8 hi 1 _WeatherTendency 8 lo 1 _WeatherState 9 hi 1 not used 9 lo 10 _TempIndoorMinMax._Max._Time 14 lo 10 _TempIndoorMinMax._Min._Time 19 lo 5 _TempIndoorMinMax._Max._Value 22 hi 5 _TempIndoorMinMax._Min._Value 24 lo 5 _TempIndoor (C) 27 lo 10 _TempOutdoorMinMax._Max._Time 32 lo 10 _TempOutdoorMinMax._Min._Time 37 lo 5 _TempOutdoorMinMax._Max._Value 40 hi 5 _TempOutdoorMinMax._Min._Value 42 lo 5 _TempOutdoor (C) 45 hi 1 not used 45 lo 10 1 _WindchillMinMax._Max._Time 50 lo 10 2 _WindchillMinMax._Min._Time 55 lo 5 1 _WindchillMinMax._Max._Value 57 hi 5 1 _WindchillMinMax._Min._Value 60 lo 6 _Windchill (C) 63 hi 1 not used 63 lo 10 _DewpointMinMax._Max._Time 68 lo 10 _DewpointMinMax._Min._Time 73 lo 5 _DewpointMinMax._Max._Value 76 hi 5 _DewpointMinMax._Min._Value 78 lo 5 _Dewpoint (C) 81 hi 10 _HumidityIndoorMinMax._Max._Time 86 hi 10 _HumidityIndoorMinMax._Min._Time 91 hi 2 _HumidityIndoorMinMax._Max._Value 92 hi 2 _HumidityIndoorMinMax._Min._Value 93 hi 2 _HumidityIndoor (%) 94 hi 10 _HumidityOutdoorMinMax._Max._Time 99 hi 10 _HumidityOutdoorMinMax._Min._Time 104 hi 2 _HumidityOutdoorMinMax._Max._Value 105 hi 2 _HumidityOutdoorMinMax._Min._Value 106 hi 2 _HumidityOutdoor (%) 107 hi 10 3 _RainLastMonthMax._Time 112 hi 6 3 _RainLastMonthMax._Max._Value 115 hi 6 _RainLastMonth (mm) 118 hi 10 3 _RainLastWeekMax._Time 123 hi 6 3 _RainLastWeekMax._Max._Value 126 hi 6 _RainLastWeek (mm) 129 hi 10 _Rain24HMax._Time 134 hi 6 _Rain24HMax._Max._Value 137 hi 6 _Rain24H (mm) 140 hi 10 _Rain24HMax._Time 145 hi 6 _Rain24HMax._Max._Value 148 hi 6 _Rain24H (mm) 151 hi 1 not used 152 lo 10 _LastRainReset 158 lo 7 _RainTotal (mm) 160 hi 1 _WindDirection5 160 lo 1 _WindDirection4 161 hi 1 _WindDirection3 161 lo 1 _WindDirection2 162 hi 1 _WindDirection1 162 lo 1 _WindDirection (0-15) 163 hi 18 unknown data 172 hi 6 _WindSpeed (km/h) 175 hi 1 _GustDirection5 175 lo 1 _GustDirection4 176 hi 1 _GustDirection3 176 lo 1 _GustDirection2 177 hi 1 _GustDirection1 177 lo 1 _GustDirection (0-15) 178 hi 2 not used 179 hi 10 _GustMax._Max._Time 184 hi 6 _GustMax._Max._Value 187 hi 6 _Gust (km/h) 190 hi 10 4 _PressureRelative_MinMax._Max/Min._Time 195 hi 5 5 _PressureRelative_inHgMinMax._Max._Value 197 lo 5 5 _PressureRelative_hPaMinMax._Max._Value 200 hi 5 _PressureRelative_inHgMinMax._Max._Value 202 lo 5 _PressureRelative_hPaMinMax._Max._Value 205 hi 5 _PressureRelative_inHgMinMax._Min._Value 207 lo 5 _PressureRelative_hPaMinMax._Min._Value 210 hi 5 _PressureRelative_inHg 212 lo 5 _PressureRelative_hPa 214 lo 430 end Remarks 1 since factory reset 2 since software reset 3 not used? 4 should be: _PressureRelative_MinMax._Max._Time 5 should be: _PressureRelative_MinMax._Min._Time 6 _AlarmRingingFlags (values in hex) 80 00 = Hi Al Gust 40 00 = Al WindDir 20 00 = One or more WindDirs set 10 00 = Hi Al Rain24H 08 00 = Hi Al Outdoor Humidity 04 00 = Lo Al Outdoor Humidity 02 00 = Hi Al Indoor Humidity 01 00 = Lo Al Indoor Humidity 00 80 = Hi Al Outdoor Temp 00 40 = Lo Al Outdoor Temp 00 20 = Hi Al Indoor Temp 00 10 = Lo Al Indoor Temp 00 08 = Hi Al Pressure 00 04 = Lo Al Pressure 00 02 = not used 00 01 = not used ------------------------------------------------------------------------------- 14. History Message start hi-lo chars rem name 0 hi 4 DevID 2 hi 2 Action 3 hi 2 Quality (%) 4 hi 4 DeviceCS 6 hi 6 LatestAddress 9 hi 6 ThisAddress 12 hi 1 not used 12 lo 3 Gust (m/s) 14 hi 1 WindDirection (0-15, also GustDirection) 14 lo 3 WindSpeed (m/s) 16 hi 3 RainCounterRaw (total in period in 0.1 inch) 17 lo 2 HumidityOutdoor (%) 18 lo 2 HumidityIndoor (%) 19 lo 5 PressureRelative (hPa) 22 hi 3 TempOutdoor (C) 23 lo 3 TempIndoor (C) 25 hi 10 Time 29 lo 60 end ------------------------------------------------------------------------------- 15. Set Config Message start hi-lo chars rem name 0 hi 4 DevID 2 hi 2 Action 3 hi 2 Quality 4 hi 1 1 _WindspeedFormat 4 lo 0,25 2 _RainFormat 4 lo 0,25 3 _PressureFormat 4 lo 0,25 4 _TemperatureFormat 4 lo 0,25 5 _ClockMode 5 hi 1 _WeatherThreshold 5 lo 1 _StormThreshold 6 hi 1 _LowBatFlags 6 lo 1 6 _LCDContrast 7 hi 4 7 _WindDirAlarmFlags (reverse group 1) 9 hi 4 8 _OtherAlarmFlags (reverse group 1) 11 hi 10 _TempIndoorMinMax._Min._Value (reverse group 2) _TempIndoorMinMax._Max._Value (reverse group 2) 16 hi 10 _TempOutdoorMinMax._Min._Value (reverse group 3) _TempOutdoorMinMax._Max._Value (reverse group 3) 21 hi 2 _HumidityIndoorMinMax._Min._Value 22 hi 2 _HumidityIndoorMinMax._Max._Value 23 hi 2 _HumidityOutdoorMinMax._Min._Value 24 hi 2 _HumidityOutdoorMinMax._Max._Value 25 hi 1 not used 25 lo 7 _Rain24HMax._Max._Value (reverse bytes) 29 hi 2 _HistoryInterval 30 hi 1 not used 30 lo 5 _GustMax._Max._Value (reverse bytes) 33 hi 10 _PressureRelative_hPaMinMax._Min._Value (rev grp4) _PressureRelative_inHgMinMax._Min._Value(rev grp4) 38 hi 10 _PressureRelative_hPaMinMax._Max._Value (rev grp5) _PressureRelative_inHgMinMax._Max._Value(rev grp5) 43 hi 6 9 _ResetMinMaxFlags 46 hi 4 10 _InBufCS 47 lo 96 end Remarks 1 0=m/s 1=knots 2=bft 3=km/h 4=mph 2 0=mm 1=inch 3 0=inHg 2=hPa 4 0=F 1=C 5 0=24h 1=12h 6 values 0-7 => LCD contrast 1-8 7 WindDir Alarms (not-reversed values in hex) 80 00 = NNW 40 00 = NW 20 00 = WNW 10 00 = W 08 00 = WSW 04 00 = SW 02 00 = SSW 01 00 = S 00 80 = SSE 00 40 = SE 00 20 = ESE 00 10 = E 00 08 = ENE 00 04 = NE 00 02 = NNE 00 01 = N 8 Other Alarms (not-reversed values in hex) 80 00 = Hi Al Gust 40 00 = Al WindDir 20 00 = One or more WindDirs set 10 00 = Hi Al Rain24H 08 00 = Hi Al Outdoor Humidity 04 00 = Lo Al Outdoor Humidity 02 00 = Hi Al Indoor Humidity 01 00 = Lo Al Indoor Humidity 00 80 = Hi Al Outdoor Temp 00 40 = Lo Al Outdoor Temp 00 20 = Hi Al Indoor Temp 00 10 = Lo Al Indoor Temp 00 08 = Hi Al Pressure 00 04 = Lo Al Pressure 00 02 = not used 00 01 = not used 9 ResetMinMaxFlags (not-reversed values in hex) "Output only; not included in checksum calc" 80 00 00 = Reset DewpointMax 40 00 00 = Reset DewpointMin 20 00 00 = not used 10 00 00 = Reset WindchillMin* "*Reset dateTime only; Min._Value is preserved" 08 00 00 = Reset TempOutMax 04 00 00 = Reset TempOutMin 02 00 00 = Reset TempInMax 01 00 00 = Reset TempInMin 00 80 00 = Reset Gust 00 40 00 = not used 00 20 00 = not used 00 10 00 = not used 00 08 00 = Reset HumOutMax 00 04 00 = Reset HumOutMin 00 02 00 = Reset HumInMax 00 01 00 = Reset HumInMin 00 00 80 = not used 00 00 40 = Reset Rain Total 00 00 20 = Reset last month? 00 00 10 = Reset lastweek? 00 00 08 = Reset Rain24H 00 00 04 = Reset Rain1H 00 00 02 = Reset PresRelMax 00 00 01 = Reset PresRelMin 10 Checksum = sum bytes (0-42) + 7 ------------------------------------------------------------------------------- 16. Get Config Message start hi-lo chars rem name 0 hi 4 DevID 2 hi 2 Action 3 hi 2 Quality 4 hi 1 1 _WindspeedFormat 4 lo 0,25 2 _RainFormat 4 lo 0,25 3 _PressureFormat 4 lo 0,25 4 _TemperatureFormat 4 lo 0,25 5 _ClockMode 5 hi 1 _WeatherThreshold 5 lo 1 _StormThreshold 6 hi 1 _LowBatFlags 6 lo 1 6 _LCDContrast 7 hi 4 7 _WindDirAlarmFlags 9 hi 4 8 _OtherAlarmFlags 11 hi 5 _TempIndoorMinMax._Min._Value 13 lo 5 _TempIndoorMinMax._Max._Value 16 hi 5 _TempOutdoorMinMax._Min._Value 18 lo 5 _TempOutdoorMinMax._Max._Value 21 hi 2 _HumidityIndoorMinMax._Max._Value 22 hi 2 _HumidityIndoorMinMax._Min._Value 23 hi 2 _HumidityOutdoorMinMax._Max._Value 24 hi 2 _HumidityOutdoorMinMax._Min._Value 25 hi 1 not used 25 lo 7 _Rain24HMax._Max._Value 29 hi 2 _HistoryInterval 30 hi 5 _GustMax._Max._Value 32 lo 1 not used 33 hi 5 _PressureRelative_hPaMinMax._Min._Value 35 lo 5 _PressureRelative_inHgMinMax._Min._Value 38 hi 5 _PressureRelative_hPaMinMax._Max._Value 40 lo 5 _PressureRelative_inHgMinMax._Max._Value 43 hi 6 9 _ResetMinMaxFlags 46 hi 4 10 _InBufCS 47 lo 96 end Remarks 1 0=m/s 1=knots 2=bft 3=km/h 4=mph 2 0=mm 1=inch 3 0=inHg 2=hPa 4 0=F 1=C 5 0=24h 1=12h 6 values 0-7 => LCD contrast 1-8 7 WindDir Alarms (values in hex) 80 00 = NNW 40 00 = NW 20 00 = WNW 10 00 = W 08 00 = WSW 04 00 = SW 02 00 = SSW 01 00 = S 00 80 = SSE 00 40 = SE 00 20 = ESE 00 10 = E 00 08 = ENE 00 04 = NE 00 02 = NNE 00 01 = N 8 Other Alarms (values in hex) 80 00 = Hi Al Gust 40 00 = Al WindDir 20 00 = One or more WindDirs set 10 00 = Hi Al Rain24H 08 00 = Hi Al Outdoor Humidity 04 00 = Lo Al Outdoor Humidity 02 00 = Hi Al Indoor Humidity 01 00 = Lo Al Indoor Humidity 00 80 = Hi Al Outdoor Temp 00 40 = Lo Al Outdoor Temp 00 20 = Hi Al Indoor Temp 00 10 = Lo Al Indoor Temp 00 08 = Hi Al Pressure 00 04 = Lo Al Pressure 00 02 = not used 00 01 = not used 9 ResetMinMaxFlags (values in hex) "Output only; input = 00 00 00" 10 Checksum = sum bytes (0-42) + 7 ------------------------------------------------------------------------------- Examples of messages readCurrentWeather Cur 000: 01 2e 60 5f 05 1b 00 00 12 01 30 62 21 54 41 30 62 40 75 36 Cur 020: 59 00 60 70 06 35 00 01 30 62 31 61 21 30 62 30 55 95 92 00 Cur 040: 53 10 05 37 00 01 30 62 01 90 81 30 62 40 90 66 38 00 49 00 Cur 060: 05 37 00 01 30 62 21 53 01 30 62 22 31 75 51 11 50 40 05 13 Cur 080: 80 13 06 22 21 40 13 06 23 19 37 67 52 59 13 06 23 06 09 13 Cur 100: 06 23 16 19 91 65 86 00 00 00 00 00 00 00 00 00 00 00 00 00 Cur 120: 00 00 00 00 00 00 00 00 00 13 06 23 09 59 00 06 19 00 00 51 Cur 140: 13 06 22 20 43 00 01 54 00 00 00 01 30 62 21 51 00 00 38 70 Cur 160: a7 cc 7b 50 09 01 01 00 00 00 00 00 00 fc 00 a7 cc 7b 14 13 Cur 180: 06 23 14 06 0e a0 00 01 b0 00 13 06 23 06 34 03 00 91 01 92 Cur 200: 03 00 91 01 92 02 97 41 00 74 03 00 91 01 92 WeatherState: Sunny(Good) WeatherTendency: Rising(Up) AlarmRingingFlags: 0000 TempIndoor 23.500 Min:20.700 2013-06-24 07:53 Max:25.900 2013-06-22 15:44 HumidityIndoor 59.000 Min:52.000 2013-06-23 19:37 Max:67.000 2013-06-22 21:40 TempOutdoor 13.700 Min:13.100 2013-06-23 05:59 Max:19.200 2013-06-23 16:12 HumidityOutdoor 86.000 Min:65.000 2013-06-23 16:19 Max:91.000 2013-06-23 06:09 Windchill 13.700 Min: 9.000 2013-06-24 09:06 Max:23.800 2013-06-20 19:08 Dewpoint 11.380 Min:10.400 2013-06-22 23:17 Max:15.111 2013-06-22 15:30 WindSpeed 2.520 Gust 4.320 Max:37.440 2013-06-23 14:06 WindDirection WSW GustDirection WSW WindDirection1 SSE GustDirection1 SSE WindDirection2 W GustDirection2 W WindDirection3 W GustDirection3 W WindDirection4 SSE GustDirection4 SSE WindDirection5 SW GustDirection5 SW RainLastMonth 0.000 Max: 0.000 1900-01-01 00:00 RainLastWeek 0.000 Max: 0.000 1900-01-01 00:00 Rain24H 0.510 Max: 6.190 2013-06-23 09:59 Rain1H 0.000 Max: 1.540 2013-06-22 20:43 RainTotal 3.870 LastRainReset 2013-06-22 15:10 PresRelhPa 1019.200 Min:1007.400 2013-06-23 06:34 Max:1019.200 2013-06-23 06:34 PresRel_inHg 30.090 Min: 29.740 2013-06-23 06:34 Max: 30.090 2013-06-23 06:34 Bytes with unknown meaning at 157-165: 50 09 01 01 00 00 00 00 00 ------------------------------------------------------------------------------- readHistory His 000: 01 2e 80 5f 05 1b 00 7b 32 00 7b 32 00 0c 70 0a 00 08 65 91 His 020: 01 92 53 76 35 13 06 24 09 10 Time 2013-06-24 09:10:00 TempIndoor= 23.5 HumidityIndoor= 59 TempOutdoor= 13.7 HumidityOutdoor= 86 PressureRelative= 1019.2 RainCounterRaw= 0.0 WindDirection= SSE WindSpeed= 1.0 Gust= 1.2 ------------------------------------------------------------------------------- readConfig In 000: 01 2e 40 5f 36 53 02 00 00 00 00 81 00 04 10 00 82 00 04 20 In 020: 00 71 41 72 42 00 05 00 00 00 27 10 00 02 83 60 96 01 03 07 In 040: 21 04 01 00 00 00 05 1b ------------------------------------------------------------------------------- writeConfig Out 000: 01 2e 40 64 36 53 02 00 00 00 00 00 10 04 00 81 00 20 04 00 Out 020: 82 41 71 42 72 00 00 05 00 00 00 10 27 01 96 60 83 02 01 04 Out 040: 21 07 03 10 00 00 05 1b OutBufCS= 051b ClockMode= 0 TemperatureFormat= 1 PressureFormat= 1 RainFormat= 0 WindspeedFormat= 3 WeatherThreshold= 3 StormThreshold= 5 LCDContrast= 2 LowBatFlags= 0 WindDirAlarmFlags= 0000 OtherAlarmFlags= 0000 HistoryInterval= 0 TempIndoor_Min= 1.0 TempIndoor_Max= 41.0 TempOutdoor_Min= 2.0 TempOutdoor_Max= 42.0 HumidityIndoor_Min= 41 HumidityIndoor_Max= 71 HumidityOutdoor_Min= 42 HumidityOutdoor_Max= 72 Rain24HMax= 50.0 GustMax= 100.0 PressureRel_hPa_Min= 960.1 PressureRel_inHg_Min= 28.36 PressureRel_hPa_Max= 1040.1 PressureRel_inHg_Max= 30.72 ResetMinMaxFlags= 100000 (Output only; Input always 00 00 00) ------------------------------------------------------------------------------- class EHistoryInterval: Constant Value Message received at hi01Min = 0 00:00, 00:01, 00:02, 00:03 ... 23:59 hi05Min = 1 00:00, 00:05, 00:10, 00:15 ... 23:55 hi10Min = 2 00:00, 00:10, 00:20, 00:30 ... 23:50 hi15Min = 3 00:00, 00:15, 00:30, 00:45 ... 23:45 hi20Min = 4 00:00, 00:20, 00:40, 01:00 ... 23:40 hi30Min = 5 00:00, 00:30, 01:00, 01:30 ... 23:30 hi60Min = 6 00:00, 01:00, 02:00, 03:00 ... 23:00 hi02Std = 7 00:00, 02:00, 04:00, 06:00 ... 22:00 hi04Std = 8 00:00, 04:00, 08:00, 12:00 ... 20:00 hi06Std = 9 00:00, 06:00, 12:00, 18:00 hi08Std = 0xA 00:00, 08:00, 16:00 hi12Std = 0xB 00:00, 12:00 hi24Std = 0xC 00:00 ------------------------------------------------------------------------------- WS SetTime - Send time to WS Time 000: 01 2e c0 05 1b 19 14 12 40 62 30 01 time sent: 2013-06-24 12:14:19 ------------------------------------------------------------------------------- ReadConfigFlash data Ask for frequency correction rcfo 000: dd 0a 01 f5 cc cc cc cc cc cc cc cc cc cc cc readConfigFlash frequency correction rcfi 000: dc 0a 01 f5 00 01 78 a0 01 02 0a 0c 0c 01 2e ff ff ff ff ff frequency correction: 96416 (0x178a0) adjusted frequency: 910574957 (3646456d) Ask for transceiver data rcfo 000: dd 0a 01 f9 cc cc cc cc cc cc cc cc cc cc cc readConfigFlash serial number and DevID rcfi 000: dc 0a 01 f9 01 02 0a 0c 0c 01 2e ff ff ff ff ff ff ff ff ff transceiver ID: 302 (0x012e) transceiver serial: 01021012120146 Program Logic The RF communication thread uses the following logic to communicate with the weather station console: Step 1. Perform in a while loop getState commands until state 0xde16 is received. Step 2. Perform a getFrame command to read the message data. Step 3. Handle the contents of the message. The type of message depends on the response type: Response type (hex): 20: WS SetTime / SetConfig - Data written confirmation the setTime/setConfig setFrame message has been received by the console 40: GetConfig save the contents of the configuration for later use (i.e. a setConfig message with one ore more parameters changed) 60: Current Weather handle the weather data of the current weather message 80: Actual / Outstanding History ignore the data of the actual history record when there is no data gap; handle the data of a (one) requested history record (note: in step 4 we can decide to request another history record). a1: Request First-Time Config prepare a setFrame first time message a2: Request SetConfig prepare a setFrame setConfig message a3: Request SetTime prepare a setFrame setTime message Step 4. When you didn't receive the message in step 3 you asked for (see step 5 how to request a certain type of message), decide if you want to ignore or handle the received message. Then go to step 5 to request for a certain type of message unless the received message has response type a1, a2 or a3, then prepare first the setFrame message the wireless console asked for. Step 5. Decide what kind of message you want to receive next time. The request is done via a setFrame message (see step 6). It is not guaranteed that you will receive that kind of message the next time but setting the proper timing parameters of firstSleep and nextSleep increase the chance you will get the requested type of message. Step 6. The action parameter in the setFrame message sets the type of the next to receive message. Action (hex): 00: rtGetHistory - Ask for History message setSleep(0.300,0.010) 01: rtSetTime - Ask for Send Time to weather station message setSleep(0.085,0.005) 02: rtSetConfig - Ask for Send Config to weather station message setSleep(0.300,0.010) 03: rtGetConfig - Ask for Config message setSleep(0.400,0.400) 05: rtGetCurrent - Ask for Current Weather message setSleep(0.300,0.010) c0: Send Time - Send Time to WS setSleep(0.085,0.005) 40: Send Config - Send Config to WS setSleep(0.085,0.005) Note: after the Request First-Time Config message (response type = 0xa1) perform a rtGetConfig with setSleep(0.085,0.005) Step 7. Perform a setTX command Step 8. Go to step 1 to wait for state 0xde16 again. """ # TODO: how often is currdat.lst modified with/without hi-speed mode? # TODO: thread locking around observation data # TODO: eliminate polling, make MainThread get data as soon as RFThread updates # TODO: get rid of Length/Buffer construct, replace with a Buffer class or obj # FIXME: the history retrieval assumes a constant archive interval across all # history records. this means anything that modifies the archive # interval should clear the history. from datetime import datetime import StringIO import sys import syslog import threading import time import traceback import usb import weewx.drivers import weewx.wxformulas import weeutil.weeutil DRIVER_NAME = 'WS28xx' DRIVER_VERSION = '0.33' def loader(config_dict, engine): return WS28xxDriver(**config_dict[DRIVER_NAME]) def configurator_loader(config_dict): return WS28xxConfigurator() def confeditor_loader(): return WS28xxConfEditor() # flags for enabling/disabling debug verbosity DEBUG_COMM = 0 DEBUG_CONFIG_DATA = 0 DEBUG_WEATHER_DATA = 0 DEBUG_HISTORY_DATA = 0 DEBUG_DUMP_FORMAT = 'auto' def logmsg(dst, msg): syslog.syslog(dst, 'ws28xx: %s: %s' % (threading.currentThread().getName(), msg)) def logdbg(msg): logmsg(syslog.LOG_DEBUG, msg) def loginf(msg): logmsg(syslog.LOG_INFO, msg) def logcrt(msg): logmsg(syslog.LOG_CRIT, msg) def logerr(msg): logmsg(syslog.LOG_ERR, msg) def log_traceback(dst=syslog.LOG_INFO, prefix='**** '): sfd = StringIO.StringIO() traceback.print_exc(file=sfd) sfd.seek(0) for line in sfd: logmsg(dst, prefix + line) del sfd def log_frame(n, buf): logdbg('frame length is %d' % n) strbuf = '' for i in xrange(0,n): strbuf += str('%02x ' % buf[i]) if (i + 1) % 16 == 0: logdbg(strbuf) strbuf = '' if strbuf: logdbg(strbuf) def get_datum_diff(v, np, ofl): if abs(np - v) < 0.001 or abs(ofl - v) < 0.001: return None return v def get_datum_match(v, np, ofl): if np == v or ofl == v: return None return v def calc_checksum(buf, start, end=None): if end is None: end = len(buf[0]) - start cs = 0 for i in xrange(0, end): cs += buf[0][i+start] return cs def get_next_index(idx): return get_index(idx + 1) def get_index(idx): if idx < 0: return idx + WS28xxDriver.max_records elif idx >= WS28xxDriver.max_records: return idx - WS28xxDriver.max_records return idx def tstr_to_ts(tstr): try: return int(time.mktime(time.strptime(tstr, "%Y-%m-%d %H:%M:%S"))) except (OverflowError, ValueError, TypeError): pass return None def bytes_to_addr(a, b, c): return ((((a & 0xF) << 8) | b) << 8) | c def addr_to_index(addr): return (addr - 416) / 18 def index_to_addr(idx): return 18 * idx + 416 def print_dict(data): for x in sorted(data.keys()): if x == 'dateTime': print '%s: %s' % (x, weeutil.weeutil.timestamp_to_string(data[x])) else: print '%s: %s' % (x, data[x]) class WS28xxConfEditor(weewx.drivers.AbstractConfEditor): @property def default_stanza(self): return """ [WS28xx] # This section is for the La Crosse WS-2800 series of weather stations. # Radio frequency to use between USB transceiver and console: US or EU # US uses 915 MHz, EU uses 868.3 MHz. Default is US. transceiver_frequency = US # The station model, e.g., 'LaCrosse C86234' or 'TFA Primus' model = LaCrosse WS28xx # The driver to use: driver = weewx.drivers.ws28xx """ def prompt_for_settings(self): print "Specify the frequency used between the station and the" print "transceiver, either 'US' (915 MHz) or 'EU' (868.3 MHz)." freq = self._prompt('frequency', 'US', ['US', 'EU']) return {'transceiver_frequency': freq} class WS28xxConfigurator(weewx.drivers.AbstractConfigurator): def add_options(self, parser): super(WS28xxConfigurator, self).add_options(parser) parser.add_option("--check-transceiver", dest="check", action="store_true", help="check USB transceiver") parser.add_option("--pair", dest="pair", action="store_true", help="pair the USB transceiver with station console") parser.add_option("--info", dest="info", action="store_true", help="display weather station configuration") parser.add_option("--set-interval", dest="interval", type=int, metavar="N", help="set logging interval to N minutes") parser.add_option("--current", dest="current", action="store_true", help="get the current weather conditions") parser.add_option("--history", dest="nrecords", type=int, metavar="N", help="display N history records") parser.add_option("--history-since", dest="recmin", type=int, metavar="N", help="display history records since N minutes ago") parser.add_option("--maxtries", dest="maxtries", type=int, help="maximum number of retries, 0 indicates no max") def do_options(self, options, parser, config_dict, prompt): maxtries = 3 if options.maxtries is None else int(options.maxtries) self.station = WS28xxDriver(**config_dict[DRIVER_NAME]) if options.check: self.check_transceiver(maxtries) elif options.pair: self.pair(maxtries) elif options.interval is not None: self.set_interval(maxtries, options.interval, prompt) elif options.current: self.show_current(maxtries) elif options.nrecords is not None: self.show_history(maxtries, count=options.nrecords) elif options.recmin is not None: ts = int(time.time()) - options.recmin * 60 self.show_history(maxtries, ts=ts) else: self.show_info(maxtries) self.station.closePort() def check_transceiver(self, maxtries): """See if the transceiver is installed and operational.""" print 'Checking for transceiver...' ntries = 0 while ntries < maxtries: ntries += 1 if self.station.transceiver_is_present(): print 'Transceiver is present' sn = self.station.get_transceiver_serial() print 'serial: %s' % sn tid = self.station.get_transceiver_id() print 'id: %d (0x%04x)' % (tid, tid) break print 'Not found (attempt %d of %d) ...' % (ntries, maxtries) time.sleep(5) else: print 'Transceiver not responding.' def pair(self, maxtries): """Pair the transceiver with the station console.""" print 'Pairing transceiver with console...' maxwait = 90 # how long to wait between button presses, in seconds ntries = 0 while ntries < maxtries or maxtries == 0: if self.station.transceiver_is_paired(): print 'Transceiver is paired to console' break ntries += 1 msg = 'Press and hold the [v] key until "PC" appears' if maxtries > 0: msg += ' (attempt %d of %d)' % (ntries, maxtries) else: msg += ' (attempt %d)' % ntries print msg now = start_ts = int(time.time()) while (now - start_ts < maxwait and not self.station.transceiver_is_paired()): time.sleep(5) now = int(time.time()) else: print 'Transceiver not paired to console.' def get_interval(self, maxtries): cfg = self.get_config(maxtries) if cfg is None: return None return getHistoryInterval(cfg['history_interval']) def get_config(self, maxtries): start_ts = None ntries = 0 while ntries < maxtries or maxtries == 0: cfg = self.station.get_config() if cfg is not None: return cfg ntries += 1 if start_ts is None: start_ts = int(time.time()) else: dur = int(time.time()) - start_ts print 'No data after %d seconds (press SET to sync)' % dur time.sleep(30) return None def set_interval(self, maxtries, interval, prompt): """Set the station archive interval""" print "This feature is not yet implemented" def show_info(self, maxtries): """Query the station then display the settings.""" print 'Querying the station for the configuration...' cfg = self.get_config(maxtries) if cfg is not None: print_dict(cfg) def show_current(self, maxtries): """Get current weather observation.""" print 'Querying the station for current weather data...' start_ts = None ntries = 0 while ntries < maxtries or maxtries == 0: packet = self.station.get_observation() if packet is not None: print_dict(packet) break ntries += 1 if start_ts is None: start_ts = int(time.time()) else: dur = int(time.time()) - start_ts print 'No data after %d seconds (press SET to sync)' % dur time.sleep(30) def show_history(self, maxtries, ts=0, count=0): """Display the indicated number of records or the records since the specified timestamp (local time, in seconds)""" print "Querying the station for historical records..." ntries = 0 last_n = nrem = None last_ts = int(time.time()) self.station.start_caching_history(since_ts=ts, num_rec=count) while nrem is None or nrem > 0: if ntries >= maxtries: print 'Giving up after %d tries' % ntries break time.sleep(30) ntries += 1 now = int(time.time()) n = self.station.get_num_history_scanned() if n == last_n: dur = now - last_ts print 'No data after %d seconds (press SET to sync)' % dur else: ntries = 0 last_ts = now last_n = n nrem = self.station.get_uncached_history_count() ni = self.station.get_next_history_index() li = self.station.get_latest_history_index() msg = " scanned %s records: current=%s latest=%s remaining=%s\r" % (n, ni, li, nrem) sys.stdout.write(msg) sys.stdout.flush() self.station.stop_caching_history() records = self.station.get_history_cache_records() self.station.clear_history_cache() print print 'Found %d records' % len(records) for r in records: print r class WS28xxDriver(weewx.drivers.AbstractDevice): """Driver for LaCrosse WS28xx stations.""" max_records = 1797 def __init__(self, **stn_dict) : """Initialize the station object. model: Which station model is this? [Optional. Default is 'LaCrosse WS28xx'] transceiver_frequency: Frequency for transceiver-to-console. Specify either US or EU. [Required. Default is US] polling_interval: How often to sample the USB interface for data. [Optional. Default is 30 seconds] comm_interval: Communications mode interval [Optional. Default is 3] device_id: The USB device ID for the transceiver. If there are multiple devices with the same vendor and product IDs on the bus, each will have a unique device identifier. Use this identifier to indicate which device should be used. [Optional. Default is None] serial: The transceiver serial number. If there are multiple devices with the same vendor and product IDs on the bus, each will have a unique serial number. Use the serial number to indicate which transceiver should be used. [Optional. Default is None] """ self.model = stn_dict.get('model', 'LaCrosse WS28xx') self.polling_interval = int(stn_dict.get('polling_interval', 30)) self.comm_interval = int(stn_dict.get('comm_interval', 3)) self.frequency = stn_dict.get('transceiver_frequency', 'US') self.device_id = stn_dict.get('device_id', None) self.serial = stn_dict.get('serial', None) self.vendor_id = 0x6666 self.product_id = 0x5555 now = int(time.time()) self._service = None self._last_rain = None self._last_obs_ts = None self._last_nodata_log_ts = now self._nodata_interval = 300 # how often to check for no data self._last_contact_log_ts = now self._nocontact_interval = 300 # how often to check for no contact self._log_interval = 600 # how often to log global DEBUG_COMM DEBUG_COMM = int(stn_dict.get('debug_comm', 0)) global DEBUG_CONFIG_DATA DEBUG_CONFIG_DATA = int(stn_dict.get('debug_config_data', 0)) global DEBUG_WEATHER_DATA DEBUG_WEATHER_DATA = int(stn_dict.get('debug_weather_data', 0)) global DEBUG_HISTORY_DATA DEBUG_HISTORY_DATA = int(stn_dict.get('debug_history_data', 0)) global DEBUG_DUMP_FORMAT DEBUG_DUMP_FORMAT = stn_dict.get('debug_dump_format', 'auto') loginf('driver version is %s' % DRIVER_VERSION) loginf('frequency is %s' % self.frequency) self.startUp() @property def hardware_name(self): return self.model # this is invoked by StdEngine as it shuts down def closePort(self): self.shutDown() def genLoopPackets(self): """Generator function that continuously returns decoded packets.""" while True: now = int(time.time()+0.5) packet = self.get_observation() if packet is not None: ts = packet['dateTime'] if self._last_obs_ts is None or self._last_obs_ts != ts: self._last_obs_ts = ts self._last_nodata_log_ts = now self._last_contact_log_ts = now else: packet = None # if no new weather data, return an empty packet if packet is None: packet = {'usUnits': weewx.METRIC, 'dateTime': now} # if no new weather data for awhile, log it if self._last_obs_ts is None or \ now - self._last_obs_ts > self._nodata_interval: if now - self._last_nodata_log_ts > self._log_interval: msg = 'no new weather data' if self._last_obs_ts is not None: msg += ' after %d seconds' % ( now - self._last_obs_ts) loginf(msg) self._last_nodata_log_ts = now # if no contact with console for awhile, log it ts = self.get_last_contact() if ts is None or now - ts > self._nocontact_interval: if now - self._last_contact_log_ts > self._log_interval: msg = 'no contact with console' if ts is not None: msg += ' after %d seconds' % (now - ts) msg += ': press [SET] to sync' loginf(msg) self._last_contact_log_ts = now yield packet time.sleep(self.polling_interval) def genStartupRecords(self, ts): loginf('Scanning historical records') maxtries = 65 ntries = 0 last_n = n = nrem = None last_ts = now = int(time.time()) self.start_caching_history(since_ts=ts) while nrem is None or nrem > 0: if ntries >= maxtries: logerr('No historical data after %d tries' % ntries) return time.sleep(60) ntries += 1 now = int(time.time()) n = self.get_num_history_scanned() if n == last_n: dur = now - last_ts loginf('No data after %d seconds (press SET to sync)' % dur) else: ntries = 0 last_ts = now last_n = n nrem = self.get_uncached_history_count() ni = self.get_next_history_index() li = self.get_latest_history_index() loginf("Scanned %s records: current=%s latest=%s remaining=%s" % (n, ni, li, nrem)) self.stop_caching_history() records = self.get_history_cache_records() self.clear_history_cache() loginf('Found %d historical records' % len(records)) last_ts = None for r in records: if last_ts is not None and r['dateTime'] is not None: r['usUnits'] = weewx.METRIC r['interval'] = (r['dateTime'] - last_ts) / 60 yield r last_ts = r['dateTime'] # FIXME: do not implement hardware record generation until we figure # out how to query the historical records faster. # def genArchiveRecords(self, since_ts): # pass # FIXME: implement retries for this so that rf thread has time to get # configuration data from the station # @property # def archive_interval(self): # cfg = self.get_config() # return getHistoryInterval(cfg['history_interval']) * 60 # FIXME: implement set/get time # def setTime(self): # pass # def getTime(self): # pass def startUp(self): if self._service is not None: return self._service = CCommunicationService() self._service.setup(self.frequency, self.vendor_id, self.product_id, self.device_id, self.serial, comm_interval=self.comm_interval) self._service.startRFThread() def shutDown(self): self._service.stopRFThread() self._service.teardown() self._service = None def transceiver_is_present(self): return self._service.DataStore.getTransceiverPresent() def transceiver_is_paired(self): return self._service.DataStore.getDeviceRegistered() def get_transceiver_serial(self): return self._service.DataStore.getTransceiverSerNo() def get_transceiver_id(self): return self._service.DataStore.getDeviceID() def get_last_contact(self): return self._service.getLastStat().last_seen_ts def get_observation(self): data = self._service.getWeatherData() ts = data._timestamp if ts is None: return None # add elements required for weewx LOOP packets packet = {} packet['usUnits'] = weewx.METRIC packet['dateTime'] = ts # data from the station sensors packet['inTemp'] = get_datum_diff(data._TempIndoor, CWeatherTraits.TemperatureNP(), CWeatherTraits.TemperatureOFL()) packet['inHumidity'] = get_datum_diff(data._HumidityIndoor, CWeatherTraits.HumidityNP(), CWeatherTraits.HumidityOFL()) packet['outTemp'] = get_datum_diff(data._TempOutdoor, CWeatherTraits.TemperatureNP(), CWeatherTraits.TemperatureOFL()) packet['outHumidity'] = get_datum_diff(data._HumidityOutdoor, CWeatherTraits.HumidityNP(), CWeatherTraits.HumidityOFL()) packet['pressure'] = get_datum_diff(data._PressureRelative_hPa, CWeatherTraits.PressureNP(), CWeatherTraits.PressureOFL()) packet['windSpeed'] = get_datum_diff(data._WindSpeed, CWeatherTraits.WindNP(), CWeatherTraits.WindOFL()) packet['windGust'] = get_datum_diff(data._Gust, CWeatherTraits.WindNP(), CWeatherTraits.WindOFL()) packet['windDir'] = getWindDir(data._WindDirection, packet['windSpeed']) packet['windGustDir'] = getWindDir(data._GustDirection, packet['windGust']) # calculated elements not directly reported by station packet['rainRate'] = get_datum_match(data._Rain1H, CWeatherTraits.RainNP(), CWeatherTraits.RainOFL()) if packet['rainRate'] is not None: packet['rainRate'] /= 10 # weewx wants cm/hr rain_total = get_datum_match(data._RainTotal, CWeatherTraits.RainNP(), CWeatherTraits.RainOFL()) delta = weewx.wxformulas.calculate_rain(rain_total, self._last_rain) self._last_rain = rain_total packet['rain'] = delta if packet['rain'] is not None: packet['rain'] /= 10 # weewx wants cm # track the signal strength and battery levels laststat = self._service.getLastStat() packet['rxCheckPercent'] = laststat.LastLinkQuality packet['windBatteryStatus'] = getBatteryStatus( laststat.LastBatteryStatus, 'wind') packet['rainBatteryStatus'] = getBatteryStatus( laststat.LastBatteryStatus, 'rain') packet['outTempBatteryStatus'] = getBatteryStatus( laststat.LastBatteryStatus, 'th') packet['inTempBatteryStatus'] = getBatteryStatus( laststat.LastBatteryStatus, 'console') return packet def get_config(self): logdbg('get station configuration') cfg = self._service.getConfigData().asDict() cs = cfg.get('checksum_out') if cs is None or cs == 0: return None return cfg def start_caching_history(self, since_ts=0, num_rec=0): self._service.startCachingHistory(since_ts, num_rec) def stop_caching_history(self): self._service.stopCachingHistory() def get_uncached_history_count(self): return self._service.getUncachedHistoryCount() def get_next_history_index(self): return self._service.getNextHistoryIndex() def get_latest_history_index(self): return self._service.getLatestHistoryIndex() def get_num_history_scanned(self): return self._service.getNumHistoryScanned() def get_history_cache_records(self): return self._service.getHistoryCacheRecords() def clear_history_cache(self): self._service.clearHistoryCache() def set_interval(self, interval): # FIXME: set the archive interval pass # The following classes and methods are adapted from the implementation by # eddie de pieri, which is in turn based on the HeavyWeather implementation. class BadResponse(Exception): """raised when unexpected data found in frame buffer""" pass class DataWritten(Exception): """raised when message 'data written' in frame buffer""" pass class BitHandling: # return a nonzero result, 2**offset, if the bit at 'offset' is one. @staticmethod def testBit(int_type, offset): mask = 1 << offset return int_type & mask # return an integer with the bit at 'offset' set to 1. @staticmethod def setBit(int_type, offset): mask = 1 << offset return int_type | mask # return an integer with the bit at 'offset' set to 1. @staticmethod def setBitVal(int_type, offset, val): mask = val << offset return int_type | mask # return an integer with the bit at 'offset' cleared. @staticmethod def clearBit(int_type, offset): mask = ~(1 << offset) return int_type & mask # return an integer with the bit at 'offset' inverted, 0->1 and 1->0. @staticmethod def toggleBit(int_type, offset): mask = 1 << offset return int_type ^ mask class EHistoryInterval: hi01Min = 0 hi05Min = 1 hi10Min = 2 hi15Min = 3 hi20Min = 4 hi30Min = 5 hi60Min = 6 hi02Std = 7 hi04Std = 8 hi06Std = 9 hi08Std = 0xA hi12Std = 0xB hi24Std = 0xC class EWindspeedFormat: wfMs = 0 wfKnots = 1 wfBFT = 2 wfKmh = 3 wfMph = 4 class ERainFormat: rfMm = 0 rfInch = 1 class EPressureFormat: pfinHg = 0 pfHPa = 1 class ETemperatureFormat: tfFahrenheit = 0 tfCelsius = 1 class EClockMode: ct24H = 0 ctAmPm = 1 class EWeatherTendency: TREND_NEUTRAL = 0 TREND_UP = 1 TREND_DOWN = 2 TREND_ERR = 3 class EWeatherState: WEATHER_BAD = 0 WEATHER_NEUTRAL = 1 WEATHER_GOOD = 2 WEATHER_ERR = 3 class EWindDirection: wdN = 0 wdNNE = 1 wdNE = 2 wdENE = 3 wdE = 4 wdESE = 5 wdSE = 6 wdSSE = 7 wdS = 8 wdSSW = 9 wdSW = 0x0A wdWSW = 0x0B wdW = 0x0C wdWNW = 0x0D wdNW = 0x0E wdNNW = 0x0F wdERR = 0x10 wdInvalid = 0x11 wdNone = 0x12 def getWindDir(wdir, wspeed): if wspeed is None or wspeed == 0: return None if wdir < 0 or wdir >= 16: return None return wdir * 360 / 16 class EResetMinMaxFlags: rmTempIndoorHi = 0 rmTempIndoorLo = 1 rmTempOutdoorHi = 2 rmTempOutdoorLo = 3 rmWindchillHi = 4 rmWindchillLo = 5 rmDewpointHi = 6 rmDewpointLo = 7 rmHumidityIndoorLo = 8 rmHumidityIndoorHi = 9 rmHumidityOutdoorLo = 0x0A rmHumidityOutdoorHi = 0x0B rmWindspeedHi = 0x0C rmWindspeedLo = 0x0D rmGustHi = 0x0E rmGustLo = 0x0F rmPressureLo = 0x10 rmPressureHi = 0x11 rmRain1hHi = 0x12 rmRain24hHi = 0x13 rmRainLastWeekHi = 0x14 rmRainLastMonthHi = 0x15 rmRainTotal = 0x16 rmInvalid = 0x17 class ERequestType: rtGetCurrent = 0 rtGetHistory = 1 rtGetConfig = 2 rtSetConfig = 3 rtSetTime = 4 rtFirstConfig = 5 rtINVALID = 6 class EAction: aGetHistory = 0 aReqSetTime = 1 aReqSetConfig = 2 aGetConfig = 3 aGetCurrent = 5 aSendTime = 0xc0 aSendConfig = 0x40 class ERequestState: rsQueued = 0 rsRunning = 1 rsFinished = 2 rsPreamble = 3 rsWaitDevice = 4 rsWaitConfig = 5 rsError = 6 rsChanged = 7 rsINVALID = 8 class EResponseType: rtDataWritten = 0x20 rtGetConfig = 0x40 rtGetCurrentWeather = 0x60 rtGetHistory = 0x80 rtRequest = 0xa0 rtReqFirstConfig = 0xa1 rtReqSetConfig = 0xa2 rtReqSetTime = 0xa3 # frequency standards and their associated transmission frequencies class EFrequency: fsUS = 'US' tfUS = 905000000 fsEU = 'EU' tfEU = 868300000 def getFrequency(standard): if standard == EFrequency.fsUS: return EFrequency.tfUS elif standard == EFrequency.fsEU: return EFrequency.tfEU logerr("unknown frequency standard '%s', using US" % standard) return EFrequency.tfUS def getFrequencyStandard(frequency): if frequency == EFrequency.tfUS: return EFrequency.fsUS elif frequency == EFrequency.tfEU: return EFrequency.fsEU logerr("unknown frequency '%s', using US" % frequency) return EFrequency.fsUS # HWPro presents battery flags as WS/TH/RAIN/WIND # 0 - wind # 1 - rain # 2 - thermo-hygro # 3 - console batterybits = {'wind':0, 'rain':1, 'th':2, 'console':3} def getBatteryStatus(status, flag): """Return 1 if bit is set, 0 otherwise""" bit = batterybits.get(flag) if bit is None: return None if BitHandling.testBit(status, bit): return 1 return 0 history_intervals = { EHistoryInterval.hi01Min: 1, EHistoryInterval.hi05Min: 5, EHistoryInterval.hi10Min: 10, EHistoryInterval.hi20Min: 20, EHistoryInterval.hi30Min: 30, EHistoryInterval.hi60Min: 60, EHistoryInterval.hi02Std: 120, EHistoryInterval.hi04Std: 240, EHistoryInterval.hi06Std: 360, EHistoryInterval.hi08Std: 480, EHistoryInterval.hi12Std: 720, EHistoryInterval.hi24Std: 1440, } def getHistoryInterval(i): return history_intervals.get(i) # NP - not present # OFL - outside factory limits class CWeatherTraits(object): windDirMap = { 0: "N", 1: "NNE", 2: "NE", 3: "ENE", 4: "E", 5: "ESE", 6: "SE", 7: "SSE", 8: "S", 9: "SSW", 10: "SW", 11: "WSW", 12: "W", 13: "WNW", 14: "NW", 15: "NWN", 16: "err", 17: "inv", 18: "None" } forecastMap = { 0: "Rainy(Bad)", 1: "Cloudy(Neutral)", 2: "Sunny(Good)", 3: "Error" } trendMap = { 0: "Stable(Neutral)", 1: "Rising(Up)", 2: "Falling(Down)", 3: "Error" } @staticmethod def TemperatureNP(): return 81.099998 @staticmethod def TemperatureOFL(): return 136.0 @staticmethod def PressureNP(): return 10101010.0 @staticmethod def PressureOFL(): return 16666.5 @staticmethod def HumidityNP(): return 110.0 @staticmethod def HumidityOFL(): return 121.0 @staticmethod def RainNP(): return -0.2 @staticmethod def RainOFL(): return 16666.664 @staticmethod def WindNP(): return 183.6 # km/h = 51.0 m/s @staticmethod def WindOFL(): return 183.96 # km/h = 51.099998 m/s @staticmethod def TemperatureOffset(): return 40.0 class CMeasurement: _Value = 0.0 _ResetFlag = 23 _IsError = 1 _IsOverflow = 1 _Time = None def Reset(self): self._Value = 0.0 self._ResetFlag = 23 self._IsError = 1 self._IsOverflow = 1 class CMinMaxMeasurement(object): def __init__(self): self._Min = CMeasurement() self._Max = CMeasurement() # firmware XXX has bogus date values for these fields _bad_labels = ['RainLastMonthMax','RainLastWeekMax','PressureRelativeMin'] class USBHardware(object): @staticmethod def isOFL2(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) == 15 \ or (buf[0][start+0] & 0xF) == 15 else: result = (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 return result @staticmethod def isOFL3(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) == 15 \ or (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 else: result = (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 \ or (buf[0][start+1] & 0xF) == 15 return result @staticmethod def isOFL5(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) == 15 \ or (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 \ or (buf[0][start+1] & 0xF) == 15 \ or (buf[0][start+2] >> 4) == 15 else: result = (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 \ or (buf[0][start+1] & 0xF) == 15 \ or (buf[0][start+2] >> 4) == 15 \ or (buf[0][start+2] & 0xF) == 15 return result @staticmethod def isErr2(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) >= 10 \ and (buf[0][start+0] >> 4) != 15 \ or (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 else: result = (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 return result @staticmethod def isErr3(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) >= 10 \ and (buf[0][start+0] >> 4) != 15 \ or (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 else: result = (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 \ or (buf[0][start+1] & 0xF) >= 10 \ and (buf[0][start+1] & 0xF) != 15 return result @staticmethod def isErr5(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) >= 10 \ and (buf[0][start+0] >> 4) != 15 \ or (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 \ or (buf[0][start+1] & 0xF) >= 10 \ and (buf[0][start+1] & 0xF) != 15 \ or (buf[0][start+2] >> 4) >= 10 \ and (buf[0][start+2] >> 4) != 15 else: result = (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 \ or (buf[0][start+1] & 0xF) >= 10 \ and (buf[0][start+1] & 0xF) != 15 \ or (buf[0][start+2] >> 4) >= 10 \ and (buf[0][start+2] >> 4) != 15 \ or (buf[0][start+2] & 0xF) >= 10 \ and (buf[0][start+2] & 0xF) != 15 return result @staticmethod def reverseByteOrder(buf, start, Count): nbuf=buf[0] for i in xrange(0, Count >> 1): tmp = nbuf[start + i] nbuf[start + i] = nbuf[start + Count - i - 1] nbuf[start + Count - i - 1 ] = tmp buf[0]=nbuf @staticmethod def readWindDirectionShared(buf, start): return (buf[0][0+start] & 0xF, buf[0][start] >> 4) @staticmethod def toInt_2(buf, start, StartOnHiNibble): """read 2 nibbles""" if StartOnHiNibble: rawpre = (buf[0][start+0] >> 4)* 10 \ + (buf[0][start+0] & 0xF)* 1 else: rawpre = (buf[0][start+0] & 0xF)* 10 \ + (buf[0][start+1] >> 4)* 1 return rawpre @staticmethod def toRain_7_3(buf, start, StartOnHiNibble): """read 7 nibbles, presentation with 3 decimals; units of mm""" if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or USBHardware.isErr5(buf, start+1, StartOnHiNibble)): result = CWeatherTraits.RainNP() elif (USBHardware.isOFL2(buf, start+0, StartOnHiNibble) or USBHardware.isOFL5(buf, start+1, StartOnHiNibble)): result = CWeatherTraits.RainOFL() elif StartOnHiNibble: result = (buf[0][start+0] >> 4)* 1000 \ + (buf[0][start+0] & 0xF)* 100 \ + (buf[0][start+1] >> 4)* 10 \ + (buf[0][start+1] & 0xF)* 1 \ + (buf[0][start+2] >> 4)* 0.1 \ + (buf[0][start+2] & 0xF)* 0.01 \ + (buf[0][start+3] >> 4)* 0.001 else: result = (buf[0][start+0] & 0xF)* 1000 \ + (buf[0][start+1] >> 4)* 100 \ + (buf[0][start+1] & 0xF)* 10 \ + (buf[0][start+2] >> 4)* 1 \ + (buf[0][start+2] & 0xF)* 0.1 \ + (buf[0][start+3] >> 4)* 0.01 \ + (buf[0][start+3] & 0xF)* 0.001 return result @staticmethod def toRain_6_2(buf, start, StartOnHiNibble): '''read 6 nibbles, presentation with 2 decimals; units of mm''' if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or USBHardware.isErr2(buf, start+1, StartOnHiNibble) or USBHardware.isErr2(buf, start+2, StartOnHiNibble) ): result = CWeatherTraits.RainNP() elif (USBHardware.isOFL2(buf, start+0, StartOnHiNibble) or USBHardware.isOFL2(buf, start+1, StartOnHiNibble) or USBHardware.isOFL2(buf, start+2, StartOnHiNibble)): result = CWeatherTraits.RainOFL() elif StartOnHiNibble: result = (buf[0][start+0] >> 4)* 1000 \ + (buf[0][start+0] & 0xF)* 100 \ + (buf[0][start+1] >> 4)* 10 \ + (buf[0][start+1] & 0xF)* 1 \ + (buf[0][start+2] >> 4)* 0.1 \ + (buf[0][start+2] & 0xF)* 0.01 else: result = (buf[0][start+0] & 0xF)* 1000 \ + (buf[0][start+1] >> 4)* 100 \ + (buf[0][start+1] & 0xF)* 10 \ + (buf[0][start+2] >> 4)* 1 \ + (buf[0][start+2] & 0xF)* 0.1 \ + (buf[0][start+3] >> 4)* 0.01 return result @staticmethod def toRain_3_1(buf, start, StartOnHiNibble): """read 3 nibbles, presentation with 1 decimal; units of 0.1 inch""" if StartOnHiNibble: hibyte = buf[0][start+0] lobyte = (buf[0][start+1] >> 4) & 0xF else: hibyte = 16*(buf[0][start+0] & 0xF) + ((buf[0][start+1] >> 4) & 0xF) lobyte = buf[0][start+1] & 0xF if hibyte == 0xFF and lobyte == 0xE : result = CWeatherTraits.RainNP() elif hibyte == 0xFF and lobyte == 0xF : result = CWeatherTraits.RainOFL() else: val = USBHardware.toFloat_3_1(buf, start, StartOnHiNibble) # 0.1 inch result = val * 2.54 # mm return result @staticmethod def toFloat_3_1(buf, start, StartOnHiNibble): """read 3 nibbles, presentation with 1 decimal""" if StartOnHiNibble: result = (buf[0][start+0] >> 4)*16**2 \ + (buf[0][start+0] & 0xF)* 16**1 \ + (buf[0][start+1] >> 4)* 16**0 else: result = (buf[0][start+0] & 0xF)*16**2 \ + (buf[0][start+1] >> 4)* 16**1 \ + (buf[0][start+1] & 0xF)* 16**0 result = result / 10.0 return result @staticmethod def toDateTime(buf, start, StartOnHiNibble, label): """read 10 nibbles, presentation as DateTime""" result = None if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or USBHardware.isErr2(buf, start+1, StartOnHiNibble) or USBHardware.isErr2(buf, start+2, StartOnHiNibble) or USBHardware.isErr2(buf, start+3, StartOnHiNibble) or USBHardware.isErr2(buf, start+4, StartOnHiNibble)): logerr('ToDateTime: bogus date for %s: error status in buffer' % label) else: year = USBHardware.toInt_2(buf, start+0, StartOnHiNibble) + 2000 month = USBHardware.toInt_2(buf, start+1, StartOnHiNibble) days = USBHardware.toInt_2(buf, start+2, StartOnHiNibble) hours = USBHardware.toInt_2(buf, start+3, StartOnHiNibble) minutes = USBHardware.toInt_2(buf, start+4, StartOnHiNibble) try: result = datetime(year, month, days, hours, minutes) except ValueError: if label not in _bad_labels: logerr(('ToDateTime: bogus date for %s:' ' bad date conversion from' ' %s %s %s %s %s') % (label, minutes, hours, days, month, year)) if result is None: # FIXME: use None instead of a really old date to indicate invalid result = datetime(1900, 01, 01, 00, 00) return result @staticmethod def toHumidity_2_0(buf, start, StartOnHiNibble): """read 2 nibbles, presentation with 0 decimal""" if USBHardware.isErr2(buf, start+0, StartOnHiNibble): result = CWeatherTraits.HumidityNP() elif USBHardware.isOFL2(buf, start+0, StartOnHiNibble): result = CWeatherTraits.HumidityOFL() else: result = USBHardware.toInt_2(buf, start, StartOnHiNibble) return result @staticmethod def toTemperature_5_3(buf, start, StartOnHiNibble): """read 5 nibbles, presentation with 3 decimals; units of degree C""" if USBHardware.isErr5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.TemperatureNP() elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.TemperatureOFL() else: if StartOnHiNibble: rawtemp = (buf[0][start+0] >> 4)* 10 \ + (buf[0][start+0] & 0xF)* 1 \ + (buf[0][start+1] >> 4)* 0.1 \ + (buf[0][start+1] & 0xF)* 0.01 \ + (buf[0][start+2] >> 4)* 0.001 else: rawtemp = (buf[0][start+0] & 0xF)* 10 \ + (buf[0][start+1] >> 4)* 1 \ + (buf[0][start+1] & 0xF)* 0.1 \ + (buf[0][start+2] >> 4)* 0.01 \ + (buf[0][start+2] & 0xF)* 0.001 result = rawtemp - CWeatherTraits.TemperatureOffset() return result @staticmethod def toTemperature_3_1(buf, start, StartOnHiNibble): """read 3 nibbles, presentation with 1 decimal; units of degree C""" if USBHardware.isErr3(buf, start+0, StartOnHiNibble): result = CWeatherTraits.TemperatureNP() elif USBHardware.isOFL3(buf, start+0, StartOnHiNibble): result = CWeatherTraits.TemperatureOFL() else: if StartOnHiNibble : rawtemp = (buf[0][start+0] >> 4)* 10 \ + (buf[0][start+0] & 0xF)* 1 \ + (buf[0][start+1] >> 4)* 0.1 else: rawtemp = (buf[0][start+0] & 0xF)* 10 \ + (buf[0][start+1] >> 4)* 1 \ + (buf[0][start+1] & 0xF)* 0.1 result = rawtemp - CWeatherTraits.TemperatureOffset() return result @staticmethod def toWindspeed_6_2(buf, start): """read 6 nibbles, presentation with 2 decimals; units of km/h""" result = (buf[0][start+0] >> 4)* 16**5 \ + (buf[0][start+0] & 0xF)* 16**4 \ + (buf[0][start+1] >> 4)* 16**3 \ + (buf[0][start+1] & 0xF)* 16**2 \ + (buf[0][start+2] >> 4)* 16**1 \ + (buf[0][start+2] & 0xF) result /= 256.0 result /= 100.0 # km/h return result @staticmethod def toWindspeed_3_1(buf, start, StartOnHiNibble): """read 3 nibbles, presentation with 1 decimal; units of m/s""" if StartOnHiNibble : hibyte = buf[0][start+0] lobyte = (buf[0][start+1] >> 4) & 0xF else: hibyte = 16*(buf[0][start+0] & 0xF) + ((buf[0][start+1] >> 4) & 0xF) lobyte = buf[0][start+1] & 0xF if hibyte == 0xFF and lobyte == 0xE: result = CWeatherTraits.WindNP() elif hibyte == 0xFF and lobyte == 0xF: result = CWeatherTraits.WindOFL() else: result = USBHardware.toFloat_3_1(buf, start, StartOnHiNibble) # m/s result *= 3.6 # km/h return result @staticmethod def readPressureShared(buf, start, StartOnHiNibble): return (USBHardware.toPressure_hPa_5_1(buf,start+2,1-StartOnHiNibble), USBHardware.toPressure_inHg_5_2(buf,start,StartOnHiNibble)) @staticmethod def toPressure_hPa_5_1(buf, start, StartOnHiNibble): """read 5 nibbles, presentation with 1 decimal; units of hPa (mbar)""" if USBHardware.isErr5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.PressureNP() elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.PressureOFL() elif StartOnHiNibble : result = (buf[0][start+0] >> 4)* 1000 \ + (buf[0][start+0] & 0xF)* 100 \ + (buf[0][start+1] >> 4)* 10 \ + (buf[0][start+1] & 0xF)* 1 \ + (buf[0][start+2] >> 4)* 0.1 else: result = (buf[0][start+0] & 0xF)* 1000 \ + (buf[0][start+1] >> 4)* 100 \ + (buf[0][start+1] & 0xF)* 10 \ + (buf[0][start+2] >> 4)* 1 \ + (buf[0][start+2] & 0xF)* 0.1 return result @staticmethod def toPressure_inHg_5_2(buf, start, StartOnHiNibble): """read 5 nibbles, presentation with 2 decimals; units of inHg""" if USBHardware.isErr5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.PressureNP() elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.PressureOFL() elif StartOnHiNibble : result = (buf[0][start+0] >> 4)* 100 \ + (buf[0][start+0] & 0xF)* 10 \ + (buf[0][start+1] >> 4)* 1 \ + (buf[0][start+1] & 0xF)* 0.1 \ + (buf[0][start+2] >> 4)* 0.01 else: result = (buf[0][start+0] & 0xF)* 100 \ + (buf[0][start+1] >> 4)* 10 \ + (buf[0][start+1] & 0xF)* 1 \ + (buf[0][start+2] >> 4)* 0.1 \ + (buf[0][start+2] & 0xF)* 0.01 return result class CCurrentWeatherData(object): def __init__(self): self._timestamp = None self._checksum = None self._PressureRelative_hPa = CWeatherTraits.PressureNP() self._PressureRelative_hPaMinMax = CMinMaxMeasurement() self._PressureRelative_inHg = CWeatherTraits.PressureNP() self._PressureRelative_inHgMinMax = CMinMaxMeasurement() self._WindSpeed = CWeatherTraits.WindNP() self._WindDirection = EWindDirection.wdNone self._WindDirection1 = EWindDirection.wdNone self._WindDirection2 = EWindDirection.wdNone self._WindDirection3 = EWindDirection.wdNone self._WindDirection4 = EWindDirection.wdNone self._WindDirection5 = EWindDirection.wdNone self._Gust = CWeatherTraits.WindNP() self._GustMax = CMinMaxMeasurement() self._GustDirection = EWindDirection.wdNone self._GustDirection1 = EWindDirection.wdNone self._GustDirection2 = EWindDirection.wdNone self._GustDirection3 = EWindDirection.wdNone self._GustDirection4 = EWindDirection.wdNone self._GustDirection5 = EWindDirection.wdNone self._Rain1H = CWeatherTraits.RainNP() self._Rain1HMax = CMinMaxMeasurement() self._Rain24H = CWeatherTraits.RainNP() self._Rain24HMax = CMinMaxMeasurement() self._RainLastWeek = CWeatherTraits.RainNP() self._RainLastWeekMax = CMinMaxMeasurement() self._RainLastMonth = CWeatherTraits.RainNP() self._RainLastMonthMax = CMinMaxMeasurement() self._RainTotal = CWeatherTraits.RainNP() self._LastRainReset = None self._TempIndoor = CWeatherTraits.TemperatureNP() self._TempIndoorMinMax = CMinMaxMeasurement() self._TempOutdoor = CWeatherTraits.TemperatureNP() self._TempOutdoorMinMax = CMinMaxMeasurement() self._HumidityIndoor = CWeatherTraits.HumidityNP() self._HumidityIndoorMinMax = CMinMaxMeasurement() self._HumidityOutdoor = CWeatherTraits.HumidityNP() self._HumidityOutdoorMinMax = CMinMaxMeasurement() self._Dewpoint = CWeatherTraits.TemperatureNP() self._DewpointMinMax = CMinMaxMeasurement() self._Windchill = CWeatherTraits.TemperatureNP() self._WindchillMinMax = CMinMaxMeasurement() self._WeatherState = EWeatherState.WEATHER_ERR self._WeatherTendency = EWeatherTendency.TREND_ERR self._AlarmRingingFlags = 0 self._AlarmMarkedFlags = 0 self._PresRel_hPa_Max = 0.0 self._PresRel_inHg_Max = 0.0 @staticmethod def calcChecksum(buf): return calc_checksum(buf, 6) def checksum(self): return self._checksum def read(self, buf): self._timestamp = int(time.time() + 0.5) self._checksum = CCurrentWeatherData.calcChecksum(buf) nbuf = [0] nbuf[0] = buf[0] self._StartBytes = nbuf[0][6]*0xF + nbuf[0][7] # FIXME: what is this? self._WeatherTendency = (nbuf[0][8] >> 4) & 0xF if self._WeatherTendency > 3: self._WeatherTendency = 3 self._WeatherState = nbuf[0][8] & 0xF if self._WeatherState > 3: self._WeatherState = 3 self._TempIndoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 19, 0) self._TempIndoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 22, 1) self._TempIndoor = USBHardware.toTemperature_5_3(nbuf, 24, 0) self._TempIndoorMinMax._Min._IsError = (self._TempIndoorMinMax._Min._Value == CWeatherTraits.TemperatureNP()) self._TempIndoorMinMax._Min._IsOverflow = (self._TempIndoorMinMax._Min._Value == CWeatherTraits.TemperatureOFL()) self._TempIndoorMinMax._Max._IsError = (self._TempIndoorMinMax._Max._Value == CWeatherTraits.TemperatureNP()) self._TempIndoorMinMax._Max._IsOverflow = (self._TempIndoorMinMax._Max._Value == CWeatherTraits.TemperatureOFL()) self._TempIndoorMinMax._Max._Time = None if self._TempIndoorMinMax._Max._IsError or self._TempIndoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 9, 0, 'TempIndoorMax') self._TempIndoorMinMax._Min._Time = None if self._TempIndoorMinMax._Min._IsError or self._TempIndoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 14, 0, 'TempIndoorMin') self._TempOutdoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 37, 0) self._TempOutdoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 40, 1) self._TempOutdoor = USBHardware.toTemperature_5_3(nbuf, 42, 0) self._TempOutdoorMinMax._Min._IsError = (self._TempOutdoorMinMax._Min._Value == CWeatherTraits.TemperatureNP()) self._TempOutdoorMinMax._Min._IsOverflow = (self._TempOutdoorMinMax._Min._Value == CWeatherTraits.TemperatureOFL()) self._TempOutdoorMinMax._Max._IsError = (self._TempOutdoorMinMax._Max._Value == CWeatherTraits.TemperatureNP()) self._TempOutdoorMinMax._Max._IsOverflow = (self._TempOutdoorMinMax._Max._Value == CWeatherTraits.TemperatureOFL()) self._TempOutdoorMinMax._Max._Time = None if self._TempOutdoorMinMax._Max._IsError or self._TempOutdoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 27, 0, 'TempOutdoorMax') self._TempOutdoorMinMax._Min._Time = None if self._TempOutdoorMinMax._Min._IsError or self._TempOutdoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 32, 0, 'TempOutdoorMin') self._WindchillMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 55, 0) self._WindchillMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 58, 1) self._Windchill = USBHardware.toTemperature_5_3(nbuf, 60, 0) self._WindchillMinMax._Min._IsError = (self._WindchillMinMax._Min._Value == CWeatherTraits.TemperatureNP()) self._WindchillMinMax._Min._IsOverflow = (self._WindchillMinMax._Min._Value == CWeatherTraits.TemperatureOFL()) self._WindchillMinMax._Max._IsError = (self._WindchillMinMax._Max._Value == CWeatherTraits.TemperatureNP()) self._WindchillMinMax._Max._IsOverflow = (self._WindchillMinMax._Max._Value == CWeatherTraits.TemperatureOFL()) self._WindchillMinMax._Max._Time = None if self._WindchillMinMax._Max._IsError or self._WindchillMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 45, 0, 'WindchillMax') self._WindchillMinMax._Min._Time = None if self._WindchillMinMax._Min._IsError or self._WindchillMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 50, 0, 'WindchillMin') self._DewpointMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 73, 0) self._DewpointMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 76, 1) self._Dewpoint = USBHardware.toTemperature_5_3(nbuf, 78, 0) self._DewpointMinMax._Min._IsError = (self._DewpointMinMax._Min._Value == CWeatherTraits.TemperatureNP()) self._DewpointMinMax._Min._IsOverflow = (self._DewpointMinMax._Min._Value == CWeatherTraits.TemperatureOFL()) self._DewpointMinMax._Max._IsError = (self._DewpointMinMax._Max._Value == CWeatherTraits.TemperatureNP()) self._DewpointMinMax._Max._IsOverflow = (self._DewpointMinMax._Max._Value == CWeatherTraits.TemperatureOFL()) self._DewpointMinMax._Min._Time = None if self._DewpointMinMax._Min._IsError or self._DewpointMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 68, 0, 'DewpointMin') self._DewpointMinMax._Max._Time = None if self._DewpointMinMax._Max._IsError or self._DewpointMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 63, 0, 'DewpointMax') self._HumidityIndoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 91, 1) self._HumidityIndoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 92, 1) self._HumidityIndoor = USBHardware.toHumidity_2_0(nbuf, 93, 1) self._HumidityIndoorMinMax._Min._IsError = (self._HumidityIndoorMinMax._Min._Value == CWeatherTraits.HumidityNP()) self._HumidityIndoorMinMax._Min._IsOverflow = (self._HumidityIndoorMinMax._Min._Value == CWeatherTraits.HumidityOFL()) self._HumidityIndoorMinMax._Max._IsError = (self._HumidityIndoorMinMax._Max._Value == CWeatherTraits.HumidityNP()) self._HumidityIndoorMinMax._Max._IsOverflow = (self._HumidityIndoorMinMax._Max._Value == CWeatherTraits.HumidityOFL()) self._HumidityIndoorMinMax._Max._Time = None if self._HumidityIndoorMinMax._Max._IsError or self._HumidityIndoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 81, 1, 'HumidityIndoorMax') self._HumidityIndoorMinMax._Min._Time = None if self._HumidityIndoorMinMax._Min._IsError or self._HumidityIndoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 86, 1, 'HumidityIndoorMin') self._HumidityOutdoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 104, 1) self._HumidityOutdoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 105, 1) self._HumidityOutdoor = USBHardware.toHumidity_2_0(nbuf, 106, 1) self._HumidityOutdoorMinMax._Min._IsError = (self._HumidityOutdoorMinMax._Min._Value == CWeatherTraits.HumidityNP()) self._HumidityOutdoorMinMax._Min._IsOverflow = (self._HumidityOutdoorMinMax._Min._Value == CWeatherTraits.HumidityOFL()) self._HumidityOutdoorMinMax._Max._IsError = (self._HumidityOutdoorMinMax._Max._Value == CWeatherTraits.HumidityNP()) self._HumidityOutdoorMinMax._Max._IsOverflow = (self._HumidityOutdoorMinMax._Max._Value == CWeatherTraits.HumidityOFL()) self._HumidityOutdoorMinMax._Max._Time = None if self._HumidityOutdoorMinMax._Max._IsError or self._HumidityOutdoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 94, 1, 'HumidityOutdoorMax') self._HumidityOutdoorMinMax._Min._Time = None if self._HumidityOutdoorMinMax._Min._IsError or self._HumidityOutdoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 99, 1, 'HumidityOutdoorMin') self._RainLastMonthMax._Max._Time = USBHardware.toDateTime(nbuf, 107, 1, 'RainLastMonthMax') self._RainLastMonthMax._Max._Value = USBHardware.toRain_6_2(nbuf, 112, 1) self._RainLastMonth = USBHardware.toRain_6_2(nbuf, 115, 1) self._RainLastWeekMax._Max._Time = USBHardware.toDateTime(nbuf, 118, 1, 'RainLastWeekMax') self._RainLastWeekMax._Max._Value = USBHardware.toRain_6_2(nbuf, 123, 1) self._RainLastWeek = USBHardware.toRain_6_2(nbuf, 126, 1) self._Rain24HMax._Max._Time = USBHardware.toDateTime(nbuf, 129, 1, 'Rain24HMax') self._Rain24HMax._Max._Value = USBHardware.toRain_6_2(nbuf, 134, 1) self._Rain24H = USBHardware.toRain_6_2(nbuf, 137, 1) self._Rain1HMax._Max._Time = USBHardware.toDateTime(nbuf, 140, 1, 'Rain1HMax') self._Rain1HMax._Max._Value = USBHardware.toRain_6_2(nbuf, 145, 1) self._Rain1H = USBHardware.toRain_6_2(nbuf, 148, 1) self._LastRainReset = USBHardware.toDateTime(nbuf, 151, 0, 'LastRainReset') self._RainTotal = USBHardware.toRain_7_3(nbuf, 156, 0) (w ,w1) = USBHardware.readWindDirectionShared(nbuf, 162) (w2,w3) = USBHardware.readWindDirectionShared(nbuf, 161) (w4,w5) = USBHardware.readWindDirectionShared(nbuf, 160) self._WindDirection = w self._WindDirection1 = w1 self._WindDirection2 = w2 self._WindDirection3 = w3 self._WindDirection4 = w4 self._WindDirection5 = w5 if DEBUG_WEATHER_DATA > 2: unknownbuf = [0]*9 for i in xrange(0,9): unknownbuf[i] = nbuf[163+i] strbuf = "" for i in unknownbuf: strbuf += str("%.2x " % i) logdbg('Bytes with unknown meaning at 157-165: %s' % strbuf) self._WindSpeed = USBHardware.toWindspeed_6_2(nbuf, 172) # FIXME: read the WindErrFlags (g ,g1) = USBHardware.readWindDirectionShared(nbuf, 177) (g2,g3) = USBHardware.readWindDirectionShared(nbuf, 176) (g4,g5) = USBHardware.readWindDirectionShared(nbuf, 175) self._GustDirection = g self._GustDirection1 = g1 self._GustDirection2 = g2 self._GustDirection3 = g3 self._GustDirection4 = g4 self._GustDirection5 = g5 self._GustMax._Max._Value = USBHardware.toWindspeed_6_2(nbuf, 184) self._GustMax._Max._IsError = (self._GustMax._Max._Value == CWeatherTraits.WindNP()) self._GustMax._Max._IsOverflow = (self._GustMax._Max._Value == CWeatherTraits.WindOFL()) self._GustMax._Max._Time = None if self._GustMax._Max._IsError or self._GustMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 179, 1, 'GustMax') self._Gust = USBHardware.toWindspeed_6_2(nbuf, 187) # Apparently the station returns only ONE date time for both hPa/inHg # Min Time Reset and Max Time Reset self._PressureRelative_hPaMinMax._Max._Time = USBHardware.toDateTime(nbuf, 190, 1, 'PressureRelative_hPaMax') self._PressureRelative_inHgMinMax._Max._Time = self._PressureRelative_hPaMinMax._Max._Time self._PressureRelative_hPaMinMax._Min._Time = self._PressureRelative_hPaMinMax._Max._Time # firmware bug, should be: USBHardware.toDateTime(nbuf, 195, 1) self._PressureRelative_inHgMinMax._Min._Time = self._PressureRelative_hPaMinMax._Min._Time (self._PresRel_hPa_Max, self._PresRel_inHg_Max) = USBHardware.readPressureShared(nbuf, 195, 1) # firmware bug, should be: self._PressureRelative_hPaMinMax._Min._Time (self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Value) = USBHardware.readPressureShared(nbuf, 200, 1) (self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Value) = USBHardware.readPressureShared(nbuf, 205, 1) (self._PressureRelative_hPa, self._PressureRelative_inHg) = USBHardware.readPressureShared(nbuf, 210, 1) def toLog(self): logdbg("_WeatherState=%s _WeatherTendency=%s _AlarmRingingFlags %04x" % (CWeatherTraits.forecastMap[self._WeatherState], CWeatherTraits.trendMap[self._WeatherTendency], self._AlarmRingingFlags)) logdbg("_TempIndoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._TempIndoor, self._TempIndoorMinMax._Min._Value, self._TempIndoorMinMax._Min._Time, self._TempIndoorMinMax._Max._Value, self._TempIndoorMinMax._Max._Time)) logdbg("_HumidityIndoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._HumidityIndoor, self._HumidityIndoorMinMax._Min._Value, self._HumidityIndoorMinMax._Min._Time, self._HumidityIndoorMinMax._Max._Value, self._HumidityIndoorMinMax._Max._Time)) logdbg("_TempOutdoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._TempOutdoor, self._TempOutdoorMinMax._Min._Value, self._TempOutdoorMinMax._Min._Time, self._TempOutdoorMinMax._Max._Value, self._TempOutdoorMinMax._Max._Time)) logdbg("_HumidityOutdoor=%8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._HumidityOutdoor, self._HumidityOutdoorMinMax._Min._Value, self._HumidityOutdoorMinMax._Min._Time, self._HumidityOutdoorMinMax._Max._Value, self._HumidityOutdoorMinMax._Max._Time)) logdbg("_Windchill= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._Windchill, self._WindchillMinMax._Min._Value, self._WindchillMinMax._Min._Time, self._WindchillMinMax._Max._Value, self._WindchillMinMax._Max._Time)) logdbg("_Dewpoint= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._Dewpoint, self._DewpointMinMax._Min._Value, self._DewpointMinMax._Min._Time, self._DewpointMinMax._Max._Value, self._DewpointMinMax._Max._Time)) logdbg("_WindSpeed= %8.3f" % self._WindSpeed) logdbg("_Gust= %8.3f _Max=%8.3f (%s)" % (self._Gust, self._GustMax._Max._Value, self._GustMax._Max._Time)) logdbg('_WindDirection= %3s _GustDirection= %3s' % (CWeatherTraits.windDirMap[self._WindDirection], CWeatherTraits.windDirMap[self._GustDirection])) logdbg('_WindDirection1= %3s _GustDirection1= %3s' % (CWeatherTraits.windDirMap[self._WindDirection1], CWeatherTraits.windDirMap[self._GustDirection1])) logdbg('_WindDirection2= %3s _GustDirection2= %3s' % (CWeatherTraits.windDirMap[self._WindDirection2], CWeatherTraits.windDirMap[self._GustDirection2])) logdbg('_WindDirection3= %3s _GustDirection3= %3s' % (CWeatherTraits.windDirMap[self._WindDirection3], CWeatherTraits.windDirMap[self._GustDirection3])) logdbg('_WindDirection4= %3s _GustDirection4= %3s' % (CWeatherTraits.windDirMap[self._WindDirection4], CWeatherTraits.windDirMap[self._GustDirection4])) logdbg('_WindDirection5= %3s _GustDirection5= %3s' % (CWeatherTraits.windDirMap[self._WindDirection5], CWeatherTraits.windDirMap[self._GustDirection5])) if (self._RainLastMonth > 0) or (self._RainLastWeek > 0): logdbg("_RainLastMonth= %8.3f _Max=%8.3f (%s)" % (self._RainLastMonth, self._RainLastMonthMax._Max._Value, self._RainLastMonthMax._Max._Time)) logdbg("_RainLastWeek= %8.3f _Max=%8.3f (%s)" % (self._RainLastWeek, self._RainLastWeekMax._Max._Value, self._RainLastWeekMax._Max._Time)) logdbg("_Rain24H= %8.3f _Max=%8.3f (%s)" % (self._Rain24H, self._Rain24HMax._Max._Value, self._Rain24HMax._Max._Time)) logdbg("_Rain1H= %8.3f _Max=%8.3f (%s)" % (self._Rain1H, self._Rain1HMax._Max._Value, self._Rain1HMax._Max._Time)) logdbg("_RainTotal= %8.3f _LastRainReset= (%s)" % (self._RainTotal, self._LastRainReset)) logdbg("PressureRel_hPa= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s) " % (self._PressureRelative_hPa, self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_hPaMinMax._Min._Time, self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_hPaMinMax._Max._Time)) logdbg("PressureRel_inHg=%8.3f _Min=%8.3f (%s) _Max=%8.3f (%s) " % (self._PressureRelative_inHg, self._PressureRelative_inHgMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Time, self._PressureRelative_inHgMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Time)) ###logdbg('(* Bug in Weather Station: PressureRelative._Min._Time is written to location of _PressureRelative._Max._Time') ###logdbg('Instead of PressureRelative._Min._Time we get: _PresRel_hPa_Max= %8.3f, _PresRel_inHg_max =%8.3f;' % (self._PresRel_hPa_Max, self._PresRel_inHg_Max)) class CWeatherStationConfig(object): def __init__(self): self._InBufCS = 0 # checksum of received config self._OutBufCS = 0 # calculated config checksum from outbuf config self._ClockMode = 0 self._TemperatureFormat = 0 self._PressureFormat = 0 self._RainFormat = 0 self._WindspeedFormat = 0 self._WeatherThreshold = 0 self._StormThreshold = 0 self._LCDContrast = 0 self._LowBatFlags = 0 self._WindDirAlarmFlags = 0 self._OtherAlarmFlags = 0 self._ResetMinMaxFlags = 0 # output only self._HistoryInterval = 0 self._TempIndoorMinMax = CMinMaxMeasurement() self._TempOutdoorMinMax = CMinMaxMeasurement() self._HumidityIndoorMinMax = CMinMaxMeasurement() self._HumidityOutdoorMinMax = CMinMaxMeasurement() self._Rain24HMax = CMinMaxMeasurement() self._GustMax = CMinMaxMeasurement() self._PressureRelative_hPaMinMax = CMinMaxMeasurement() self._PressureRelative_inHgMinMax = CMinMaxMeasurement() def setTemps(self,TempFormat,InTempLo,InTempHi,OutTempLo,OutTempHi): f1 = TempFormat t1 = InTempLo t2 = InTempHi t3 = OutTempLo t4 = OutTempHi if f1 not in [ETemperatureFormat.tfFahrenheit, ETemperatureFormat.tfCelsius]: logerr('setTemps: unknown temperature format %s' % TempFormat) return 0 if t1 < -40.0 or t1 > 59.9 or t2 < -40.0 or t2 > 59.9 or \ t3 < -40.0 or t3 > 59.9 or t4 < -40.0 or t4 > 59.9: logerr('setTemps: one or more values out of range') return 0 self._TemperatureFormat = f1 self._TempIndoorMinMax._Min._Value = t1 self._TempIndoorMinMax._Max._Value = t2 self._TempOutdoorMinMax._Min._Value = t3 self._TempOutdoorMinMax._Max._Value = t4 return 1 def setHums(self,InHumLo,InHumHi,OutHumLo,OutHumHi): h1 = InHumLo h2 = InHumHi h3 = OutHumLo h4 = OutHumHi if h1 < 1 or h1 > 99 or h2 < 1 or h2 > 99 or \ h3 < 1 or h3 > 99 or h4 < 1 or h4 > 99: logerr('setHums: one or more values out of range') return 0 self._HumidityIndoorMinMax._Min._Value = h1 self._HumidityIndoorMinMax._Max._Value = h2 self._HumidityOutdoorMinMax._Min._Value = h3 self._HumidityOutdoorMinMax._Max._Value = h4 return 1 def setRain24H(self,RainFormat,Rain24hHi): f1 = RainFormat r1 = Rain24hHi if f1 not in [ERainFormat.rfMm, ERainFormat.rfInch]: logerr('setRain24: unknown format %s' % RainFormat) return 0 if r1 < 0.0 or r1 > 9999.9: logerr('setRain24: value outside range') return 0 self._RainFormat = f1 self._Rain24HMax._Max._Value = r1 return 1 def setGust(self,WindSpeedFormat,GustHi): # When the units of a max gust alarm are changed in the weather # station itself, automatically the value is converted to the new # unit and rounded to a whole number. Weewx receives a value # converted to km/h. # # It is too much trouble to sort out what exactly the internal # conversion algoritms are for the other wind units. # # Setting a value in km/h units is tested and works, so this will # be the only option available. f1 = WindSpeedFormat g1 = GustHi if f1 < EWindspeedFormat.wfMs or f1 > EWindspeedFormat.wfMph: logerr('setGust: unknown format %s' % WindSpeedFormat) return 0 if f1 != EWindspeedFormat.wfKmh: logerr('setGust: only units of km/h are supported') return 0 if g1 < 0.0 or g1 > 180.0: logerr('setGust: value outside range') return 0 self._WindSpeedFormat = f1 self._GustMax._Max._Value = int(g1) # apparently gust value is always an integer return 1 def setPresRels(self,PressureFormat,PresRelhPaLo,PresRelhPaHi,PresRelinHgLo,PresRelinHgHi): f1 = PressureFormat p1 = PresRelhPaLo p2 = PresRelhPaHi p3 = PresRelinHgLo p4 = PresRelinHgHi if f1 not in [EPressureFormat.pfinHg, EPressureFormat.pfHPa]: logerr('setPresRel: unknown format %s' % PressureFormat) return 0 if p1 < 920.0 or p1 > 1080.0 or p2 < 920.0 or p2 > 1080.0 or \ p3 < 27.10 or p3 > 31.90 or p4 < 27.10 or p4 > 31.90: logerr('setPresRel: value outside range') return 0 self._RainFormat = f1 self._PressureRelative_hPaMinMax._Min._Value = p1 self._PressureRelative_hPaMinMax._Max._Value = p2 self._PressureRelative_inHgMinMax._Min._Value = p3 self._PressureRelative_inHgMinMax._Max._Value = p4 return 1 def getOutBufCS(self): return self._OutBufCS def getInBufCS(self): return self._InBufCS def setResetMinMaxFlags(self, resetMinMaxFlags): logdbg('setResetMinMaxFlags: %s' % resetMinMaxFlags) self._ResetMinMaxFlags = resetMinMaxFlags def parseRain_3(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 7-digit number with 3 decimals''' num = int(number*1000) parsebuf=[0]*7 for i in xrange(7-numbytes,7): parsebuf[i] = num%10 num = num//10 if StartOnHiNibble: buf[0][0+start] = parsebuf[6]*16 + parsebuf[5] buf[0][1+start] = parsebuf[4]*16 + parsebuf[3] buf[0][2+start] = parsebuf[2]*16 + parsebuf[1] buf[0][3+start] = parsebuf[0]*16 + (buf[0][3+start] & 0xF) else: buf[0][0+start] = (buf[0][0+start] & 0xF0) + parsebuf[6] buf[0][1+start] = parsebuf[5]*16 + parsebuf[4] buf[0][2+start] = parsebuf[3]*16 + parsebuf[2] buf[0][3+start] = parsebuf[1]*16 + parsebuf[0] def parseWind_6(self, number, buf, start): '''Parse float number to 6 bytes''' num = int(number*100*256) parsebuf=[0]*6 for i in xrange(0,6): parsebuf[i] = num%16 num = num//16 buf[0][0+start] = parsebuf[5]*16 + parsebuf[4] buf[0][1+start] = parsebuf[3]*16 + parsebuf[2] buf[0][2+start] = parsebuf[1]*16 + parsebuf[0] def parse_0(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 5-digit number with 0 decimals''' num = int(number) nbuf=[0]*5 for i in xrange(5-numbytes,5): nbuf[i] = num%10 num = num//10 if StartOnHiNibble: buf[0][0+start] = nbuf[4]*16 + nbuf[3] buf[0][1+start] = nbuf[2]*16 + nbuf[1] buf[0][2+start] = nbuf[0]*16 + (buf[0][2+start] & 0x0F) else: buf[0][0+start] = (buf[0][0+start] & 0xF0) + nbuf[4] buf[0][1+start] = nbuf[3]*16 + nbuf[2] buf[0][2+start] = nbuf[1]*16 + nbuf[0] def parse_1(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 5 digit number with 1 decimal''' self.parse_0(number*10.0, buf, start, StartOnHiNibble, numbytes) def parse_2(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 5 digit number with 2 decimals''' self.parse_0(number*100.0, buf, start, StartOnHiNibble, numbytes) def parse_3(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 5 digit number with 3 decimals''' self.parse_0(number*1000.0, buf, start, StartOnHiNibble, numbytes) def read(self,buf): nbuf=[0] nbuf[0]=buf[0] self._WindspeedFormat = (nbuf[0][4] >> 4) & 0xF self._RainFormat = (nbuf[0][4] >> 3) & 1 self._PressureFormat = (nbuf[0][4] >> 2) & 1 self._TemperatureFormat = (nbuf[0][4] >> 1) & 1 self._ClockMode = nbuf[0][4] & 1 self._StormThreshold = (nbuf[0][5] >> 4) & 0xF self._WeatherThreshold = nbuf[0][5] & 0xF self._LowBatFlags = (nbuf[0][6] >> 4) & 0xF self._LCDContrast = nbuf[0][6] & 0xF self._WindDirAlarmFlags = (nbuf[0][7] << 8) | nbuf[0][8] self._OtherAlarmFlags = (nbuf[0][9] << 8) | nbuf[0][10] self._TempIndoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 11, 1) self._TempIndoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 13, 0) self._TempOutdoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 16, 1) self._TempOutdoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 18, 0) self._HumidityIndoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 21, 1) self._HumidityIndoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 22, 1) self._HumidityOutdoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 23, 1) self._HumidityOutdoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 24, 1) self._Rain24HMax._Max._Value = USBHardware.toRain_7_3(nbuf, 25, 0) self._HistoryInterval = nbuf[0][29] self._GustMax._Max._Value = USBHardware.toWindspeed_6_2(nbuf, 30) (self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Value) = USBHardware.readPressureShared(nbuf, 33, 1) (self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Value) = USBHardware.readPressureShared(nbuf, 38, 1) self._ResetMinMaxFlags = (nbuf[0][43]) <<16 | (nbuf[0][44] << 8) | (nbuf[0][45]) self._InBufCS = (nbuf[0][46] << 8) | nbuf[0][47] self._OutBufCS = calc_checksum(buf, 4, end=39) + 7 """ Reset DewpointMax 80 00 00 Reset DewpointMin 40 00 00 not used 20 00 00 Reset WindchillMin* 10 00 00 *dateTime only; Min._Value is preserved Reset TempOutMax 08 00 00 Reset TempOutMin 04 00 00 Reset TempInMax 02 00 00 Reset TempInMin 01 00 00 Reset Gust 00 80 00 not used 00 40 00 not used 00 20 00 not used 00 10 00 Reset HumOutMax 00 08 00 Reset HumOutMin 00 04 00 Reset HumInMax 00 02 00 Reset HumInMin 00 01 00 not used 00 00 80 Reset Rain Total 00 00 40 Reset last month? 00 00 20 Reset last week? 00 00 10 Reset Rain24H 00 00 08 Reset Rain1H 00 00 04 Reset PresRelMax 00 00 02 Reset PresRelMin 00 00 01 """ #self._ResetMinMaxFlags = 0x000000 #logdbg('set _ResetMinMaxFlags to %06x' % self._ResetMinMaxFlags) """ setTemps(self,TempFormat,InTempLo,InTempHi,OutTempLo,OutTempHi) setHums(self,InHumLo,InHumHi,OutHumLo,OutHumHi) setPresRels(self,PressureFormat,PresRelhPaLo,PresRelhPaHi,PresRelinHgLo,PresRelinHgHi) setGust(self,WindSpeedFormat,GustHi) setRain24H(self,RainFormat,Rain24hHi) """ # Examples: #self.setTemps(ETemperatureFormat.tfCelsius,1.0,41.0,2.0,42.0) #self.setHums(41,71,42,72) #self.setPresRels(EPressureFormat.pfHPa,960.1,1040.1,28.36,30.72) #self.setGust(EWindspeedFormat.wfKmh,040.0) #self.setRain24H(ERainFormat.rfMm,50.0) # Set historyInterval to 5 minutes (default: 2 hours) self._HistoryInterval = EHistoryInterval.hi05Min # Clear all alarm flags, otherwise the datastream from the weather # station will pause during an alarm and connection will be lost. self._WindDirAlarmFlags = 0x0000 self._OtherAlarmFlags = 0x0000 def testConfigChanged(self,buf): nbuf = [0] nbuf[0] = buf[0] nbuf[0][0] = 16*(self._WindspeedFormat & 0xF) + 8*(self._RainFormat & 1) + 4*(self._PressureFormat & 1) + 2*(self._TemperatureFormat & 1) + (self._ClockMode & 1) nbuf[0][1] = self._WeatherThreshold & 0xF | 16 * self._StormThreshold & 0xF0 nbuf[0][2] = self._LCDContrast & 0xF | 16 * self._LowBatFlags & 0xF0 nbuf[0][3] = (self._OtherAlarmFlags >> 0) & 0xFF nbuf[0][4] = (self._OtherAlarmFlags >> 8) & 0xFF nbuf[0][5] = (self._WindDirAlarmFlags >> 0) & 0xFF nbuf[0][6] = (self._WindDirAlarmFlags >> 8) & 0xFF # reverse buf from here self.parse_2(self._PressureRelative_inHgMinMax._Max._Value, nbuf, 7, 1, 5) self.parse_1(self._PressureRelative_hPaMinMax._Max._Value, nbuf, 9, 0, 5) self.parse_2(self._PressureRelative_inHgMinMax._Min._Value, nbuf, 12, 1, 5) self.parse_1(self._PressureRelative_hPaMinMax._Min._Value, nbuf, 14, 0, 5) self.parseWind_6(self._GustMax._Max._Value, nbuf, 17) nbuf[0][20] = self._HistoryInterval & 0xF self.parseRain_3(self._Rain24HMax._Max._Value, nbuf, 21, 0, 7) self.parse_0(self._HumidityOutdoorMinMax._Max._Value, nbuf, 25, 1, 2) self.parse_0(self._HumidityOutdoorMinMax._Min._Value, nbuf, 26, 1, 2) self.parse_0(self._HumidityIndoorMinMax._Max._Value, nbuf, 27, 1, 2) self.parse_0(self._HumidityIndoorMinMax._Min._Value, nbuf, 28, 1, 2) self.parse_3(self._TempOutdoorMinMax._Max._Value + CWeatherTraits.TemperatureOffset(), nbuf, 29, 1, 5) self.parse_3(self._TempOutdoorMinMax._Min._Value + CWeatherTraits.TemperatureOffset(), nbuf, 31, 0, 5) self.parse_3(self._TempIndoorMinMax._Max._Value + CWeatherTraits.TemperatureOffset(), nbuf, 34, 1, 5) self.parse_3(self._TempIndoorMinMax._Min._Value + CWeatherTraits.TemperatureOffset(), nbuf, 36, 0, 5) # reverse buf to here USBHardware.reverseByteOrder(nbuf, 7, 32) # do not include the ResetMinMaxFlags bytes when calculating checksum nbuf[0][39] = (self._ResetMinMaxFlags >> 16) & 0xFF nbuf[0][40] = (self._ResetMinMaxFlags >> 8) & 0xFF nbuf[0][41] = (self._ResetMinMaxFlags >> 0) & 0xFF self._OutBufCS = calc_checksum(nbuf, 0, end=39) + 7 nbuf[0][42] = (self._OutBufCS >> 8) & 0xFF nbuf[0][43] = (self._OutBufCS >> 0) & 0xFF buf[0] = nbuf[0] if self._OutBufCS == self._InBufCS and self._ResetMinMaxFlags == 0: if DEBUG_CONFIG_DATA > 2: logdbg('testConfigChanged: checksum not changed: OutBufCS=%04x' % self._OutBufCS) changed = 0 else: if DEBUG_CONFIG_DATA > 0: logdbg('testConfigChanged: checksum or resetMinMaxFlags changed: OutBufCS=%04x InBufCS=%04x _ResetMinMaxFlags=%06x' % (self._OutBufCS, self._InBufCS, self._ResetMinMaxFlags)) if DEBUG_CONFIG_DATA > 1: self.toLog() changed = 1 return changed def toLog(self): logdbg('OutBufCS= %04x' % self._OutBufCS) logdbg('InBufCS= %04x' % self._InBufCS) logdbg('ClockMode= %s' % self._ClockMode) logdbg('TemperatureFormat= %s' % self._TemperatureFormat) logdbg('PressureFormat= %s' % self._PressureFormat) logdbg('RainFormat= %s' % self._RainFormat) logdbg('WindspeedFormat= %s' % self._WindspeedFormat) logdbg('WeatherThreshold= %s' % self._WeatherThreshold) logdbg('StormThreshold= %s' % self._StormThreshold) logdbg('LCDContrast= %s' % self._LCDContrast) logdbg('LowBatFlags= %01x' % self._LowBatFlags) logdbg('WindDirAlarmFlags= %04x' % self._WindDirAlarmFlags) logdbg('OtherAlarmFlags= %04x' % self._OtherAlarmFlags) logdbg('HistoryInterval= %s' % self._HistoryInterval) logdbg('TempIndoor_Min= %s' % self._TempIndoorMinMax._Min._Value) logdbg('TempIndoor_Max= %s' % self._TempIndoorMinMax._Max._Value) logdbg('TempOutdoor_Min= %s' % self._TempOutdoorMinMax._Min._Value) logdbg('TempOutdoor_Max= %s' % self._TempOutdoorMinMax._Max._Value) logdbg('HumidityIndoor_Min= %s' % self._HumidityIndoorMinMax._Min._Value) logdbg('HumidityIndoor_Max= %s' % self._HumidityIndoorMinMax._Max._Value) logdbg('HumidityOutdoor_Min= %s' % self._HumidityOutdoorMinMax._Min._Value) logdbg('HumidityOutdoor_Max= %s' % self._HumidityOutdoorMinMax._Max._Value) logdbg('Rain24HMax= %s' % self._Rain24HMax._Max._Value) logdbg('GustMax= %s' % self._GustMax._Max._Value) logdbg('PressureRel_hPa_Min= %s' % self._PressureRelative_hPaMinMax._Min._Value) logdbg('PressureRel_inHg_Min= %s' % self._PressureRelative_inHgMinMax._Min._Value) logdbg('PressureRel_hPa_Max= %s' % self._PressureRelative_hPaMinMax._Max._Value) logdbg('PressureRel_inHg_Max= %s' % self._PressureRelative_inHgMinMax._Max._Value) logdbg('ResetMinMaxFlags= %06x (Output only)' % self._ResetMinMaxFlags) def asDict(self): return { 'checksum_in': self._InBufCS, 'checksum_out': self._OutBufCS, 'format_clock': self._ClockMode, 'format_temperature': self._TemperatureFormat, 'format_pressure': self._PressureFormat, 'format_rain': self._RainFormat, 'format_windspeed': self._WindspeedFormat, 'threshold_weather': self._WeatherThreshold, 'threshold_storm': self._StormThreshold, 'lcd_contrast': self._LCDContrast, 'low_battery_flags': self._LowBatFlags, 'alarm_flags_wind_dir': self._WindDirAlarmFlags, 'alarm_flags_other': self._OtherAlarmFlags, # 'reset_minmax_flags': self._ResetMinMaxFlags, 'history_interval': self._HistoryInterval, 'indoor_temp_min': self._TempIndoorMinMax._Min._Value, 'indoor_temp_min_time': self._TempIndoorMinMax._Min._Time, 'indoor_temp_max': self._TempIndoorMinMax._Max._Value, 'indoor_temp_max_time': self._TempIndoorMinMax._Max._Time, 'indoor_humidity_min': self._HumidityIndoorMinMax._Min._Value, 'indoor_humidity_min_time': self._HumidityIndoorMinMax._Min._Time, 'indoor_humidity_max': self._HumidityIndoorMinMax._Max._Value, 'indoor_humidity_max_time': self._HumidityIndoorMinMax._Max._Time, 'outdoor_temp_min': self._TempOutdoorMinMax._Min._Value, 'outdoor_temp_min_time': self._TempOutdoorMinMax._Min._Time, 'outdoor_temp_max': self._TempOutdoorMinMax._Max._Value, 'outdoor_temp_max_time': self._TempOutdoorMinMax._Max._Time, 'outdoor_humidity_min': self._HumidityOutdoorMinMax._Min._Value, 'outdoor_humidity_min_time':self._HumidityOutdoorMinMax._Min._Time, 'outdoor_humidity_max': self._HumidityOutdoorMinMax._Max._Value, 'outdoor_humidity_max_time':self._HumidityOutdoorMinMax._Max._Time, 'rain_24h_max': self._Rain24HMax._Max._Value, 'rain_24h_max_time': self._Rain24HMax._Max._Time, 'wind_gust_max': self._GustMax._Max._Value, 'wind_gust_max_time': self._GustMax._Max._Time, 'pressure_min': self._PressureRelative_hPaMinMax._Min._Value, 'pressure_min_time': self._PressureRelative_hPaMinMax._Min._Time, 'pressure_max': self._PressureRelative_hPaMinMax._Max._Value, 'pressure_max_time': self._PressureRelative_hPaMinMax._Max._Time # do not bother with pressure inHg } class CHistoryData(object): def __init__(self): self.Time = None self.TempIndoor = CWeatherTraits.TemperatureNP() self.HumidityIndoor = CWeatherTraits.HumidityNP() self.TempOutdoor = CWeatherTraits.TemperatureNP() self.HumidityOutdoor = CWeatherTraits.HumidityNP() self.PressureRelative = None self.RainCounterRaw = 0 self.WindSpeed = CWeatherTraits.WindNP() self.WindDirection = EWindDirection.wdNone self.Gust = CWeatherTraits.WindNP() self.GustDirection = EWindDirection.wdNone def read(self, buf): nbuf = [0] nbuf[0] = buf[0] self.Gust = USBHardware.toWindspeed_3_1(nbuf, 12, 0) self.GustDirection = (nbuf[0][14] >> 4) & 0xF self.WindSpeed = USBHardware.toWindspeed_3_1(nbuf, 14, 0) self.WindDirection = (nbuf[0][14] >> 4) & 0xF self.RainCounterRaw = USBHardware.toRain_3_1(nbuf, 16, 1) self.HumidityOutdoor = USBHardware.toHumidity_2_0(nbuf, 17, 0) self.HumidityIndoor = USBHardware.toHumidity_2_0(nbuf, 18, 0) self.PressureRelative = USBHardware.toPressure_hPa_5_1(nbuf, 19, 0) self.TempIndoor = USBHardware.toTemperature_3_1(nbuf, 23, 0) self.TempOutdoor = USBHardware.toTemperature_3_1(nbuf, 22, 1) self.Time = USBHardware.toDateTime(nbuf, 25, 1, 'HistoryData') def toLog(self): """emit raw historical data""" logdbg("Time %s" % self.Time) logdbg("TempIndoor= %7.1f" % self.TempIndoor) logdbg("HumidityIndoor= %7.0f" % self.HumidityIndoor) logdbg("TempOutdoor= %7.1f" % self.TempOutdoor) logdbg("HumidityOutdoor= %7.0f" % self.HumidityOutdoor) logdbg("PressureRelative= %7.1f" % self.PressureRelative) logdbg("RainCounterRaw= %7.3f" % self.RainCounterRaw) logdbg("WindSpeed= %7.3f" % self.WindSpeed) logdbg("WindDirection= % 3s" % CWeatherTraits.windDirMap[self.WindDirection]) logdbg("Gust= %7.3f" % self.Gust) logdbg("GustDirection= % 3s" % CWeatherTraits.windDirMap[self.GustDirection]) def asDict(self): """emit historical data as a dict with weewx conventions""" return { 'dateTime': tstr_to_ts(str(self.Time)), 'inTemp': self.TempIndoor, 'inHumidity': self.HumidityIndoor, 'outTemp': self.TempOutdoor, 'outHumidity': self.HumidityOutdoor, 'pressure': self.PressureRelative, 'rain': self.RainCounterRaw / 10, # weewx wants cm 'windSpeed': self.WindSpeed, 'windDir': getWindDir(self.WindDirection, self.WindSpeed), 'windGust': self.Gust, 'windGustDir': getWindDir(self.GustDirection, self.Gust), } class HistoryCache: def __init__(self): self.clear_records() def clear_records(self): self.since_ts = 0 self.num_rec = 0 self.start_index = None self.next_index = None self.records = [] self.num_outstanding_records = None self.num_scanned = 0 self.last_ts = 0 class CDataStore(object): class TTransceiverSettings(object): def __init__(self): self.VendorId = 0x6666 self.ProductId = 0x5555 self.VersionNo = 1 self.manufacturer = "LA CROSSE TECHNOLOGY" self.product = "Weather Direct Light Wireless Device" self.FrequencyStandard = EFrequency.fsUS self.Frequency = getFrequency(self.FrequencyStandard) self.SerialNumber = None self.DeviceID = None class TLastStat(object): def __init__(self): self.LastBatteryStatus = None self.LastLinkQuality = None self.LastHistoryIndex = None self.LatestHistoryIndex = None self.last_seen_ts = None self.last_weather_ts = 0 self.last_history_ts = 0 self.last_config_ts = 0 def __init__(self): self.transceiverPresent = False self.commModeInterval = 3 self.registeredDeviceID = None self.LastStat = CDataStore.TLastStat() self.TransceiverSettings = CDataStore.TTransceiverSettings() self.StationConfig = CWeatherStationConfig() self.CurrentWeather = CCurrentWeatherData() def getFrequencyStandard(self): return self.TransceiverSettings.FrequencyStandard def setFrequencyStandard(self, val): logdbg('setFrequency: %s' % val) self.TransceiverSettings.FrequencyStandard = val self.TransceiverSettings.Frequency = getFrequency(val) def getDeviceID(self): return self.TransceiverSettings.DeviceID def setDeviceID(self,val): logdbg("setDeviceID: %04x" % val) self.TransceiverSettings.DeviceID = val def getRegisteredDeviceID(self): return self.registeredDeviceID def setRegisteredDeviceID(self, val): if val != self.registeredDeviceID: loginf("console is paired to device with ID %04x" % val) self.registeredDeviceID = val def getTransceiverPresent(self): return self.transceiverPresent def setTransceiverPresent(self, val): self.transceiverPresent = val def setLastStatCache(self, seen_ts=None, quality=None, battery=None, weather_ts=None, history_ts=None, config_ts=None): if DEBUG_COMM > 1: logdbg('setLastStatCache: seen=%s quality=%s battery=%s weather=%s history=%s config=%s' % (seen_ts, quality, battery, weather_ts, history_ts, config_ts)) if seen_ts is not None: self.LastStat.last_seen_ts = seen_ts if quality is not None: self.LastStat.LastLinkQuality = quality if battery is not None: self.LastStat.LastBatteryStatus = battery if weather_ts is not None: self.LastStat.last_weather_ts = weather_ts if history_ts is not None: self.LastStat.last_history_ts = history_ts if config_ts is not None: self.LastStat.last_config_ts = config_ts def setLastHistoryIndex(self,val): self.LastStat.LastHistoryIndex = val def getLastHistoryIndex(self): return self.LastStat.LastHistoryIndex def setLatestHistoryIndex(self,val): self.LastStat.LatestHistoryIndex = val def getLatestHistoryIndex(self): return self.LastStat.LatestHistoryIndex def setCurrentWeather(self, data): self.CurrentWeather = data def getDeviceRegistered(self): if ( self.registeredDeviceID is None or self.TransceiverSettings.DeviceID is None or self.registeredDeviceID != self.TransceiverSettings.DeviceID ): return False return True def getCommModeInterval(self): return self.commModeInterval def setCommModeInterval(self,val): logdbg("setCommModeInterval to %x" % val) self.commModeInterval = val def setTransceiverSerNo(self,val): logdbg("setTransceiverSerialNumber to %s" % val) self.TransceiverSettings.SerialNumber = val def getTransceiverSerNo(self): return self.TransceiverSettings.SerialNumber class sHID(object): """USB driver abstraction""" def __init__(self): self.devh = None self.timeout = 1000 self.last_dump = None def open(self, vid, pid, did, serial): device = self._find_device(vid, pid, did, serial) if device is None: logcrt('Cannot find USB device with Vendor=0x%04x ProdID=0x%04x Device=%s Serial=%s' % (vid, pid, did, serial)) raise weewx.WeeWxIOError('Unable to find transceiver on USB') self._open_device(device) def close(self): self._close_device() def _find_device(self, vid, pid, did, serial): for bus in usb.busses(): for dev in bus.devices: if dev.idVendor == vid and dev.idProduct == pid: if did is None or dev.filename == did: if serial is None: loginf('found transceiver at bus=%s device=%s' % (bus.dirname, dev.filename)) return dev else: handle = dev.open() try: buf = self.readCfg(handle, 0x1F9, 7) sn = str("%02d" % (buf[0])) sn += str("%02d" % (buf[1])) sn += str("%02d" % (buf[2])) sn += str("%02d" % (buf[3])) sn += str("%02d" % (buf[4])) sn += str("%02d" % (buf[5])) sn += str("%02d" % (buf[6])) if str(serial) == sn: loginf('found transceiver at bus=%s device=%s serial=%s' % (bus.dirname, dev.filename, sn)) return dev else: loginf('skipping transceiver with serial %s (looking for %s)' % (sn, serial)) finally: del handle return None def _open_device(self, dev, interface=0): self.devh = dev.open() if not self.devh: raise weewx.WeeWxIOError('Open USB device failed') loginf('manufacturer: %s' % self.devh.getString(dev.iManufacturer,30)) loginf('product: %s' % self.devh.getString(dev.iProduct,30)) loginf('interface: %d' % interface) # be sure kernel does not claim the interface try: self.devh.detachKernelDriver(interface) except Exception: pass # attempt to claim the interface try: logdbg('claiming USB interface %d' % interface) self.devh.claimInterface(interface) self.devh.setAltInterface(interface) except usb.USBError, e: self._close_device() logcrt('Unable to claim USB interface %s: %s' % (interface, e)) raise weewx.WeeWxIOError(e) # FIXME: this seems to be specific to ws28xx? # FIXME: check return values usbWait = 0.05 self.devh.getDescriptor(0x1, 0, 0x12) time.sleep(usbWait) self.devh.getDescriptor(0x2, 0, 0x9) time.sleep(usbWait) self.devh.getDescriptor(0x2, 0, 0x22) time.sleep(usbWait) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, 0xa, [], 0x0, 0x0, 1000) time.sleep(usbWait) self.devh.getDescriptor(0x22, 0, 0x2a9) time.sleep(usbWait) def _close_device(self): try: logdbg('releasing USB interface') self.devh.releaseInterface() except Exception: pass self.devh = None def setTX(self): buf = [0]*0x15 buf[0] = 0xD1 if DEBUG_COMM > 1: self.dump('setTX', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d1, index=0x0000000, timeout=self.timeout) def setRX(self): buf = [0]*0x15 buf[0] = 0xD0 if DEBUG_COMM > 1: self.dump('setRX', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d0, index=0x0000000, timeout=self.timeout) def getState(self,StateBuffer): buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS | usb.RECIP_INTERFACE | usb.ENDPOINT_IN, request=usb.REQ_CLEAR_FEATURE, buffer=0x0a, value=0x00003de, index=0x0000000, timeout=self.timeout) if DEBUG_COMM > 1: self.dump('getState', buf, fmt=DEBUG_DUMP_FORMAT) StateBuffer[0]=[0]*0x2 StateBuffer[0][0]=buf[1] StateBuffer[0][1]=buf[2] def readConfigFlash(self, addr, numBytes, data): if numBytes > 512: raise Exception('bad number of bytes') while numBytes: buf=[0xcc]*0x0f #0x15 buf[0] = 0xdd buf[1] = 0x0a buf[2] = (addr >>8) & 0xFF buf[3] = (addr >>0) & 0xFF if DEBUG_COMM > 1: self.dump('readCfgFlash>', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003dd, index=0x0000000, timeout=self.timeout) buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS | usb.RECIP_INTERFACE | usb.ENDPOINT_IN, request=usb.REQ_CLEAR_FEATURE, buffer=0x15, value=0x00003dc, index=0x0000000, timeout=self.timeout) new_data=[0]*0x15 if numBytes < 16: for i in xrange(0, numBytes): new_data[i] = buf[i+4] numBytes = 0 else: for i in xrange(0, 16): new_data[i] = buf[i+4] numBytes -= 16 addr += 16 if DEBUG_COMM > 1: self.dump('readCfgFlash<', buf, fmt=DEBUG_DUMP_FORMAT) data[0] = new_data # FIXME: new_data might be unset def setState(self,state): buf = [0]*0x15 buf[0] = 0xd7 buf[1] = state if DEBUG_COMM > 1: self.dump('setState', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d7, index=0x0000000, timeout=self.timeout) def setFrame(self,data,numBytes): buf = [0]*0x111 buf[0] = 0xd5 buf[1] = numBytes >> 8 buf[2] = numBytes for i in xrange(0, numBytes): buf[i+3] = data[i] if DEBUG_COMM == 1: self.dump('setFrame', buf, 'short') elif DEBUG_COMM > 1: self.dump('setFrame', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d5, index=0x0000000, timeout=self.timeout) def getFrame(self,data,numBytes): buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS | usb.RECIP_INTERFACE | usb.ENDPOINT_IN, request=usb.REQ_CLEAR_FEATURE, buffer=0x111, value=0x00003d6, index=0x0000000, timeout=self.timeout) new_data=[0]*0x131 new_numBytes=(buf[1] << 8 | buf[2])& 0x1ff for i in xrange(0, new_numBytes): new_data[i] = buf[i+3] if DEBUG_COMM == 1: self.dump('getFrame', buf, 'short') elif DEBUG_COMM > 1: self.dump('getFrame', buf, fmt=DEBUG_DUMP_FORMAT) data[0] = new_data numBytes[0] = new_numBytes def writeReg(self,regAddr,data): buf = [0]*0x05 buf[0] = 0xf0 buf[1] = regAddr & 0x7F buf[2] = 0x01 buf[3] = data buf[4] = 0x00 if DEBUG_COMM > 1: self.dump('writeReg', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003f0, index=0x0000000, timeout=self.timeout) def execute(self, command): buf = [0]*0x0f #*0x15 buf[0] = 0xd9 buf[1] = command if DEBUG_COMM > 1: self.dump('execute', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d9, index=0x0000000, timeout=self.timeout) def setPreamblePattern(self,pattern): buf = [0]*0x15 buf[0] = 0xd8 buf[1] = pattern if DEBUG_COMM > 1: self.dump('setPreamble', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d8, index=0x0000000, timeout=self.timeout) # three formats, long, short, auto. short shows only the first 16 bytes. # long shows the full length of the buffer. auto shows the message length # as indicated by the length in the message itself for setFrame and # getFrame, or the first 16 bytes for any other message. def dump(self, cmd, buf, fmt='auto'): strbuf = '' msglen = None if fmt == 'auto': if buf[0] in [0xd5, 0x00]: msglen = buf[2] + 3 # use msg length for set/get frame else: msglen = 16 # otherwise do same as short format elif fmt == 'short': msglen = 16 for i,x in enumerate(buf): strbuf += str('%02x ' % x) if (i+1) % 16 == 0: self.dumpstr(cmd, strbuf) strbuf = '' if msglen is not None and i+1 >= msglen: break if strbuf: self.dumpstr(cmd, strbuf) # filter output that we do not care about, pad the command string. def dumpstr(self, cmd, strbuf): pad = ' ' * (15-len(cmd)) # de15 is idle, de14 is intermediate if strbuf in ['de 15 00 00 00 00 ','de 14 00 00 00 00 ']: if strbuf != self.last_dump or DEBUG_COMM > 2: logdbg('%s: %s%s' % (cmd, pad, strbuf)) self.last_dump = strbuf else: logdbg('%s: %s%s' % (cmd, pad, strbuf)) self.last_dump = None def readCfg(self, handle, addr, numBytes): while numBytes: buf=[0xcc]*0x0f #0x15 buf[0] = 0xdd buf[1] = 0x0a buf[2] = (addr >>8) & 0xFF buf[3] = (addr >>0) & 0xFF handle.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003dd, index=0x0000000, timeout=1000) buf = handle.controlMsg(requestType=usb.TYPE_CLASS | usb.RECIP_INTERFACE | usb.ENDPOINT_IN, request=usb.REQ_CLEAR_FEATURE, buffer=0x15, value=0x00003dc, index=0x0000000, timeout=1000) new_data=[0]*0x15 if numBytes < 16: for i in xrange(0, numBytes): new_data[i] = buf[i+4] numBytes = 0 else: for i in xrange(0, 16): new_data[i] = buf[i+4] numBytes -= 16 addr += 16 return new_data class CCommunicationService(object): reg_names = dict() class AX5051RegisterNames: REVISION = 0x0 SCRATCH = 0x1 POWERMODE = 0x2 XTALOSC = 0x3 FIFOCTRL = 0x4 FIFODATA = 0x5 IRQMASK = 0x6 IFMODE = 0x8 PINCFG1 = 0x0C PINCFG2 = 0x0D MODULATION = 0x10 ENCODING = 0x11 FRAMING = 0x12 CRCINIT3 = 0x14 CRCINIT2 = 0x15 CRCINIT1 = 0x16 CRCINIT0 = 0x17 FREQ3 = 0x20 FREQ2 = 0x21 FREQ1 = 0x22 FREQ0 = 0x23 FSKDEV2 = 0x25 FSKDEV1 = 0x26 FSKDEV0 = 0x27 IFFREQHI = 0x28 IFFREQLO = 0x29 PLLLOOP = 0x2C PLLRANGING = 0x2D PLLRNGCLK = 0x2E TXPWR = 0x30 TXRATEHI = 0x31 TXRATEMID = 0x32 TXRATELO = 0x33 MODMISC = 0x34 FIFOCONTROL2 = 0x37 ADCMISC = 0x38 AGCTARGET = 0x39 AGCATTACK = 0x3A AGCDECAY = 0x3B AGCCOUNTER = 0x3C CICDEC = 0x3F DATARATEHI = 0x40 DATARATELO = 0x41 TMGGAINHI = 0x42 TMGGAINLO = 0x43 PHASEGAIN = 0x44 FREQGAIN = 0x45 FREQGAIN2 = 0x46 AMPLGAIN = 0x47 TRKFREQHI = 0x4C TRKFREQLO = 0x4D XTALCAP = 0x4F SPAREOUT = 0x60 TESTOBS = 0x68 APEOVER = 0x70 TMMUX = 0x71 PLLVCOI = 0x72 PLLCPEN = 0x73 PLLRNGMISC = 0x74 AGCMANUAL = 0x78 ADCDCLEVEL = 0x79 RFMISC = 0x7A TXDRIVER = 0x7B REF = 0x7C RXMISC = 0x7D def __init__(self): logdbg('CCommunicationService.init') self.shid = sHID() self.DataStore = CDataStore() self.firstSleep = 1 self.nextSleep = 1 self.pollCount = 0 self.running = False self.child = None self.thread_wait = 60.0 # seconds self.command = None self.history_cache = HistoryCache() # do not set time when offset to whole hour is <= _a3_offset self._a3_offset = 3 def buildFirstConfigFrame(self, Buffer, cs): logdbg('buildFirstConfigFrame: cs=%04x' % cs) newBuffer = [0] newBuffer[0] = [0]*9 comInt = self.DataStore.getCommModeInterval() historyAddress = 0xFFFFFF newBuffer[0][0] = 0xf0 newBuffer[0][1] = 0xf0 newBuffer[0][2] = EAction.aGetConfig newBuffer[0][3] = (cs >> 8) & 0xff newBuffer[0][4] = (cs >> 0) & 0xff newBuffer[0][5] = (comInt >> 4) & 0xff newBuffer[0][6] = (historyAddress >> 16) & 0x0f | 16 * (comInt & 0xf) newBuffer[0][7] = (historyAddress >> 8 ) & 0xff newBuffer[0][8] = (historyAddress >> 0 ) & 0xff Buffer[0] = newBuffer[0] Length = 0x09 return Length def buildConfigFrame(self, Buffer): logdbg("buildConfigFrame") newBuffer = [0] newBuffer[0] = [0]*48 cfgBuffer = [0] cfgBuffer[0] = [0]*44 changed = self.DataStore.StationConfig.testConfigChanged(cfgBuffer) if changed: self.shid.dump('OutBuf', cfgBuffer[0], fmt='long') newBuffer[0][0] = Buffer[0][0] newBuffer[0][1] = Buffer[0][1] newBuffer[0][2] = EAction.aSendConfig # 0x40 # change this value if we won't store config newBuffer[0][3] = Buffer[0][3] for i in xrange(0,44): newBuffer[0][i+4] = cfgBuffer[0][i] Buffer[0] = newBuffer[0] Length = 48 # 0x30 else: # current config not up to date; do not write yet Length = 0 return Length def buildTimeFrame(self, Buffer, cs): logdbg("buildTimeFrame: cs=%04x" % cs) now = time.time() tm = time.localtime(now) newBuffer=[0] newBuffer[0]=Buffer[0] #00000000: d5 00 0c 00 32 c0 00 8f 45 25 15 91 31 20 01 00 #00000000: d5 00 0c 00 32 c0 06 c1 47 25 15 91 31 20 01 00 # 3 4 5 6 7 8 9 10 11 newBuffer[0][2] = EAction.aSendTime # 0xc0 newBuffer[0][3] = (cs >> 8) & 0xFF newBuffer[0][4] = (cs >> 0) & 0xFF newBuffer[0][5] = (tm[5] % 10) + 0x10 * (tm[5] // 10) #sec newBuffer[0][6] = (tm[4] % 10) + 0x10 * (tm[4] // 10) #min newBuffer[0][7] = (tm[3] % 10) + 0x10 * (tm[3] // 10) #hour #DayOfWeek = tm[6] - 1; #ole from 1 - 7 - 1=Sun... 0-6 0=Sun DayOfWeek = tm[6] #py from 0 - 6 - 0=Mon newBuffer[0][8] = DayOfWeek % 10 + 0x10 * (tm[2] % 10) #DoW + Day newBuffer[0][9] = (tm[2] // 10) + 0x10 * (tm[1] % 10) #day + month newBuffer[0][10] = (tm[1] // 10) + 0x10 * ((tm[0] - 2000) % 10) #month + year newBuffer[0][11] = (tm[0] - 2000) // 10 #year Buffer[0]=newBuffer[0] Length = 0x0c return Length def buildACKFrame(self, Buffer, action, cs, hidx=None): if DEBUG_COMM > 1: logdbg("buildACKFrame: action=%x cs=%04x historyIndex=%s" % (action, cs, hidx)) newBuffer = [0] newBuffer[0] = [0]*9 for i in xrange(0,2): newBuffer[0][i] = Buffer[0][i] comInt = self.DataStore.getCommModeInterval() # When last weather is stale, change action to get current weather # This is only needed during long periods of history data catchup if self.command == EAction.aGetHistory: now = int(time.time()) age = now - self.DataStore.LastStat.last_weather_ts # Morphing action only with GetHistory requests, # and stale data after a period of twice the CommModeInterval, # but not with init GetHistory requests (0xF0) if action == EAction.aGetHistory and age >= (comInt +1) * 2 and newBuffer[0][1] != 0xF0: if DEBUG_COMM > 0: logdbg('buildACKFrame: morphing action from %d to 5 (age=%s)' % (action, age)) action = EAction.aGetCurrent if hidx is None: if self.command == EAction.aGetHistory: hidx = self.history_cache.next_index elif self.DataStore.getLastHistoryIndex() is not None: hidx = self.DataStore.getLastHistoryIndex() if hidx is None or hidx < 0 or hidx >= WS28xxDriver.max_records: haddr = 0xffffff else: haddr = index_to_addr(hidx) if DEBUG_COMM > 1: logdbg('buildACKFrame: idx: %s addr: 0x%04x' % (hidx, haddr)) newBuffer[0][2] = action & 0xF newBuffer[0][3] = (cs >> 8) & 0xFF newBuffer[0][4] = (cs >> 0) & 0xFF newBuffer[0][5] = (comInt >> 4) & 0xFF newBuffer[0][6] = (haddr >> 16) & 0x0F | 16 * (comInt & 0xF) newBuffer[0][7] = (haddr >> 8 ) & 0xFF newBuffer[0][8] = (haddr >> 0 ) & 0xFF #d5 00 09 f0 f0 03 00 32 00 3f ff ff Buffer[0]=newBuffer[0] return 9 def handleWsAck(self,Buffer,Length): logdbg('handleWsAck') self.DataStore.setLastStatCache(seen_ts=int(time.time()), quality=(Buffer[0][3] & 0x7f), battery=(Buffer[0][2] & 0xf)) def handleConfig(self,Buffer,Length): logdbg('handleConfig: %s' % self.timing()) if DEBUG_CONFIG_DATA > 2: self.shid.dump('InBuf', Buffer[0], fmt='long') newBuffer=[0] newBuffer[0] = Buffer[0] newLength = [0] now = int(time.time()) self.DataStore.StationConfig.read(newBuffer) if DEBUG_CONFIG_DATA > 1: self.DataStore.StationConfig.toLog() self.DataStore.setLastStatCache(seen_ts=now, quality=(Buffer[0][3] & 0x7f), battery=(Buffer[0][2] & 0xf), config_ts=now) cs = newBuffer[0][47] | (newBuffer[0][46] << 8) self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs) Buffer[0] = newBuffer[0] Length[0] = newLength[0] def handleCurrentData(self,Buffer,Length): if DEBUG_WEATHER_DATA > 0: logdbg('handleCurrentData: %s' % self.timing()) now = int(time.time()) # update the weather data cache if changed or stale chksum = CCurrentWeatherData.calcChecksum(Buffer) age = now - self.DataStore.LastStat.last_weather_ts if age >= 10 or chksum != self.DataStore.CurrentWeather.checksum(): if DEBUG_WEATHER_DATA > 2: self.shid.dump('CurWea', Buffer[0], fmt='long') data = CCurrentWeatherData() data.read(Buffer) self.DataStore.setCurrentWeather(data) if DEBUG_WEATHER_DATA > 1: data.toLog() # update the connection cache self.DataStore.setLastStatCache(seen_ts=now, quality=(Buffer[0][3] & 0x7f), battery=(Buffer[0][2] & 0xf), weather_ts=now) newBuffer = [0] newBuffer[0] = Buffer[0] newLength = [0] cs = newBuffer[0][5] | (newBuffer[0][4] << 8) cfgBuffer = [0] cfgBuffer[0] = [0]*44 changed = self.DataStore.StationConfig.testConfigChanged(cfgBuffer) inBufCS = self.DataStore.StationConfig.getInBufCS() if inBufCS == 0 or inBufCS != cs: # request for a get config logdbg('handleCurrentData: inBufCS of station does not match') self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetConfig, cs) elif changed: # Request for a set config logdbg('handleCurrentData: outBufCS of station changed') self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aReqSetConfig, cs) else: # Request for either a history message or a current weather message # In general we don't use EAction.aGetCurrent to ask for a current # weather message; they also come when requested for # EAction.aGetHistory. This we learned from the Heavy Weather Pro # messages (via USB sniffer). self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs) Length[0] = newLength[0] Buffer[0] = newBuffer[0] def handleHistoryData(self, buf, buflen): if DEBUG_HISTORY_DATA > 0: logdbg('handleHistoryData: %s' % self.timing()) now = int(time.time()) self.DataStore.setLastStatCache(seen_ts=now, quality=(buf[0][3] & 0x7f), battery=(buf[0][2] & 0xf), history_ts=now) newbuf = [0] newbuf[0] = buf[0] newlen = [0] data = CHistoryData() data.read(newbuf) if DEBUG_HISTORY_DATA > 1: data.toLog() cs = newbuf[0][5] | (newbuf[0][4] << 8) latestAddr = bytes_to_addr(buf[0][6], buf[0][7], buf[0][8]) thisAddr = bytes_to_addr(buf[0][9], buf[0][10], buf[0][11]) latestIndex = addr_to_index(latestAddr) thisIndex = addr_to_index(thisAddr) ts = tstr_to_ts(str(data.Time)) nrec = get_index(latestIndex - thisIndex) logdbg('handleHistoryData: time=%s' ' this=%d (0x%04x) latest=%d (0x%04x) nrec=%d' % (data.Time, thisIndex, thisAddr, latestIndex, latestAddr, nrec)) # track the latest history index self.DataStore.setLastHistoryIndex(thisIndex) self.DataStore.setLatestHistoryIndex(latestIndex) nextIndex = None if self.command == EAction.aGetHistory: if self.history_cache.start_index is None: nreq = 0 if self.history_cache.num_rec > 0: loginf('handleHistoryData: request for %s records' % self.history_cache.num_rec) nreq = self.history_cache.num_rec else: loginf('handleHistoryData: request records since %s' % weeutil.weeutil.timestamp_to_string(self.history_cache.since_ts)) span = int(time.time()) - self.history_cache.since_ts # FIXME: what if we do not have config data yet? cfg = self.getConfigData().asDict() arcint = 60 * getHistoryInterval(cfg['history_interval']) # FIXME: this assumes a constant archive interval for all # records in the station history nreq = int(span / arcint) + 5 # FIXME: punt 5 if nreq > nrec: loginf('handleHistoryData: too many records requested (%d)' ', clipping to number stored (%d)' % (nreq, nrec)) nreq = nrec idx = get_index(latestIndex - nreq) self.history_cache.start_index = idx self.history_cache.next_index = idx self.DataStore.setLastHistoryIndex(idx) self.history_cache.num_outstanding_records = nreq logdbg('handleHistoryData: start_index=%s' ' num_outstanding_records=%s' % (idx, nreq)) nextIndex = idx elif self.history_cache.next_index is not None: # thisIndex should be the next record after next_index thisIndexTst = get_next_index(self.history_cache.next_index) if thisIndexTst == thisIndex: self.history_cache.num_scanned += 1 # get the next history record if ts is not None and self.history_cache.since_ts <= ts: # Check if two records in a row with the same ts if self.history_cache.last_ts == ts: logdbg('handleHistoryData: remove previous record' ' with duplicate timestamp: %s' % weeutil.weeutil.timestamp_to_string(ts)) self.history_cache.records.pop() self.history_cache.last_ts = ts # append to the history logdbg('handleHistoryData: appending history record' ' %s: %s' % (thisIndex, data.asDict())) self.history_cache.records.append(data.asDict()) self.history_cache.num_outstanding_records = nrec elif ts is None: logerr('handleHistoryData: skip record: this_ts=None') else: logdbg('handleHistoryData: skip record: since_ts=%s this_ts=%s' % (weeutil.weeutil.timestamp_to_string(self.history_cache.since_ts), weeutil.weeutil.timestamp_to_string(ts))) self.history_cache.next_index = thisIndex else: loginf('handleHistoryData: index mismatch: %s != %s' % (thisIndexTst, thisIndex)) nextIndex = self.history_cache.next_index logdbg('handleHistoryData: next=%s' % nextIndex) self.setSleep(0.300,0.010) newlen[0] = self.buildACKFrame(newbuf, EAction.aGetHistory, cs, nextIndex) buflen[0] = newlen[0] buf[0] = newbuf[0] def handleNextAction(self,Buffer,Length): newBuffer = [0] newBuffer[0] = Buffer[0] newLength = [0] newLength[0] = Length[0] self.DataStore.setLastStatCache(seen_ts=int(time.time()), quality=(Buffer[0][3] & 0x7f)) cs = newBuffer[0][5] | (newBuffer[0][4] << 8) if (Buffer[0][2] & 0xEF) == EResponseType.rtReqFirstConfig: logdbg('handleNextAction: a1 (first-time config)') self.setSleep(0.085,0.005) newLength[0] = self.buildFirstConfigFrame(newBuffer, cs) elif (Buffer[0][2] & 0xEF) == EResponseType.rtReqSetConfig: logdbg('handleNextAction: a2 (set config data)') self.setSleep(0.085,0.005) newLength[0] = self.buildConfigFrame(newBuffer) elif (Buffer[0][2] & 0xEF) == EResponseType.rtReqSetTime: logdbg('handleNextAction: a3 (set time data)') now = int(time.time()) age = now - self.DataStore.LastStat.last_weather_ts if age >= (self.DataStore.getCommModeInterval() +1) * 2: # always set time if init or stale communication self.setSleep(0.085,0.005) newLength[0] = self.buildTimeFrame(newBuffer, cs) else: # When time is set at the whole hour we may get an extra # historical record with time stamp a history period ahead # We will skip settime if offset to whole hour is too small # (time difference between WS and server < self._a3_offset) m, s = divmod(now, 60) h, m = divmod(m, 60) logdbg('Time: hh:%02d:%02d' % (m,s)) if (m == 59 and s >= (60 - self._a3_offset)) or (m == 0 and s <= self._a3_offset): logdbg('Skip settime; time difference <= %s s' % int(self._a3_offset)) self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs) else: # set time self.setSleep(0.085,0.005) newLength[0] = self.buildTimeFrame(newBuffer, cs) else: logdbg('handleNextAction: %02x' % (Buffer[0][2] & 0xEF)) self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs) Length[0] = newLength[0] Buffer[0] = newBuffer[0] def generateResponse(self, Buffer, Length): if DEBUG_COMM > 1: logdbg('generateResponse: %s' % self.timing()) newBuffer = [0] newBuffer[0] = Buffer[0] newLength = [0] newLength[0] = Length[0] if Length[0] == 0: raise BadResponse('zero length buffer') bufferID = (Buffer[0][0] <<8) | Buffer[0][1] respType = (Buffer[0][2] & 0xE0) if DEBUG_COMM > 1: logdbg("generateResponse: id=%04x resp=%x length=%x" % (bufferID, respType, Length[0])) deviceID = self.DataStore.getDeviceID() if bufferID != 0xF0F0: self.DataStore.setRegisteredDeviceID(bufferID) if bufferID == 0xF0F0: loginf('generateResponse: console not paired, attempting to pair to 0x%04x' % deviceID) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetConfig, deviceID, 0xFFFF) elif bufferID == deviceID: if respType == EResponseType.rtDataWritten: # 00000000: 00 00 06 00 32 20 if Length[0] == 0x06: self.DataStore.StationConfig.setResetMinMaxFlags(0) self.shid.setRX() raise DataWritten() else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) elif respType == EResponseType.rtGetConfig: # 00000000: 00 00 30 00 32 40 if Length[0] == 0x30: self.handleConfig(newBuffer, newLength) else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) elif respType == EResponseType.rtGetCurrentWeather: # 00000000: 00 00 d7 00 32 60 if Length[0] == 0xd7: #215 self.handleCurrentData(newBuffer, newLength) else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) elif respType == EResponseType.rtGetHistory: # 00000000: 00 00 1e 00 32 80 if Length[0] == 0x1e: self.handleHistoryData(newBuffer, newLength) else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) elif respType == EResponseType.rtRequest: # 00000000: 00 00 06 f0 f0 a1 # 00000000: 00 00 06 00 32 a3 # 00000000: 00 00 06 00 32 a2 if Length[0] == 0x06: self.handleNextAction(newBuffer, newLength) else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) else: raise BadResponse('unexpected response type %x' % respType) elif respType not in [0x20,0x40,0x60,0x80,0xa1,0xa2,0xa3]: # message is probably corrupt raise BadResponse('unknown response type %x' % respType) else: msg = 'message from console contains unknown device ID (id=%04x resp=%x)' % (bufferID, respType) logdbg(msg) log_frame(Length[0],Buffer[0]) raise BadResponse(msg) Buffer[0] = newBuffer[0] Length[0] = newLength[0] def configureRegisterNames(self): self.reg_names[self.AX5051RegisterNames.IFMODE] =0x00 self.reg_names[self.AX5051RegisterNames.MODULATION]=0x41 #fsk self.reg_names[self.AX5051RegisterNames.ENCODING] =0x07 self.reg_names[self.AX5051RegisterNames.FRAMING] =0x84 #1000:0100 ##?hdlc? |1000 010 0 self.reg_names[self.AX5051RegisterNames.CRCINIT3] =0xff self.reg_names[self.AX5051RegisterNames.CRCINIT2] =0xff self.reg_names[self.AX5051RegisterNames.CRCINIT1] =0xff self.reg_names[self.AX5051RegisterNames.CRCINIT0] =0xff self.reg_names[self.AX5051RegisterNames.FREQ3] =0x38 self.reg_names[self.AX5051RegisterNames.FREQ2] =0x90 self.reg_names[self.AX5051RegisterNames.FREQ1] =0x00 self.reg_names[self.AX5051RegisterNames.FREQ0] =0x01 self.reg_names[self.AX5051RegisterNames.PLLLOOP] =0x1d self.reg_names[self.AX5051RegisterNames.PLLRANGING]=0x08 self.reg_names[self.AX5051RegisterNames.PLLRNGCLK] =0x03 self.reg_names[self.AX5051RegisterNames.MODMISC] =0x03 self.reg_names[self.AX5051RegisterNames.SPAREOUT] =0x00 self.reg_names[self.AX5051RegisterNames.TESTOBS] =0x00 self.reg_names[self.AX5051RegisterNames.APEOVER] =0x00 self.reg_names[self.AX5051RegisterNames.TMMUX] =0x00 self.reg_names[self.AX5051RegisterNames.PLLVCOI] =0x01 self.reg_names[self.AX5051RegisterNames.PLLCPEN] =0x01 self.reg_names[self.AX5051RegisterNames.RFMISC] =0xb0 self.reg_names[self.AX5051RegisterNames.REF] =0x23 self.reg_names[self.AX5051RegisterNames.IFFREQHI] =0x20 self.reg_names[self.AX5051RegisterNames.IFFREQLO] =0x00 self.reg_names[self.AX5051RegisterNames.ADCMISC] =0x01 self.reg_names[self.AX5051RegisterNames.AGCTARGET] =0x0e self.reg_names[self.AX5051RegisterNames.AGCATTACK] =0x11 self.reg_names[self.AX5051RegisterNames.AGCDECAY] =0x0e self.reg_names[self.AX5051RegisterNames.CICDEC] =0x3f self.reg_names[self.AX5051RegisterNames.DATARATEHI]=0x19 self.reg_names[self.AX5051RegisterNames.DATARATELO]=0x66 self.reg_names[self.AX5051RegisterNames.TMGGAINHI] =0x01 self.reg_names[self.AX5051RegisterNames.TMGGAINLO] =0x96 self.reg_names[self.AX5051RegisterNames.PHASEGAIN] =0x03 self.reg_names[self.AX5051RegisterNames.FREQGAIN] =0x04 self.reg_names[self.AX5051RegisterNames.FREQGAIN2] =0x0a self.reg_names[self.AX5051RegisterNames.AMPLGAIN] =0x06 self.reg_names[self.AX5051RegisterNames.AGCMANUAL] =0x00 self.reg_names[self.AX5051RegisterNames.ADCDCLEVEL]=0x10 self.reg_names[self.AX5051RegisterNames.RXMISC] =0x35 self.reg_names[self.AX5051RegisterNames.FSKDEV2] =0x00 self.reg_names[self.AX5051RegisterNames.FSKDEV1] =0x31 self.reg_names[self.AX5051RegisterNames.FSKDEV0] =0x27 self.reg_names[self.AX5051RegisterNames.TXPWR] =0x03 self.reg_names[self.AX5051RegisterNames.TXRATEHI] =0x00 self.reg_names[self.AX5051RegisterNames.TXRATEMID] =0x51 self.reg_names[self.AX5051RegisterNames.TXRATELO] =0xec self.reg_names[self.AX5051RegisterNames.TXDRIVER] =0x88 def initTransceiver(self, frequency_standard): logdbg('initTransceiver: frequency_standard=%s' % frequency_standard) self.DataStore.setFrequencyStandard(frequency_standard) self.configureRegisterNames() # calculate the frequency then set frequency registers freq = self.DataStore.TransceiverSettings.Frequency loginf('base frequency: %d' % freq) freqVal = long(freq / 16000000.0 * 16777216.0) corVec = [None] self.shid.readConfigFlash(0x1F5, 4, corVec) corVal = corVec[0][0] << 8 corVal |= corVec[0][1] corVal <<= 8 corVal |= corVec[0][2] corVal <<= 8 corVal |= corVec[0][3] loginf('frequency correction: %d (0x%x)' % (corVal,corVal)) freqVal += corVal if not (freqVal % 2): freqVal += 1 loginf('adjusted frequency: %d (0x%x)' % (freqVal,freqVal)) self.reg_names[self.AX5051RegisterNames.FREQ3] = (freqVal >>24) & 0xFF self.reg_names[self.AX5051RegisterNames.FREQ2] = (freqVal >>16) & 0xFF self.reg_names[self.AX5051RegisterNames.FREQ1] = (freqVal >>8) & 0xFF self.reg_names[self.AX5051RegisterNames.FREQ0] = (freqVal >>0) & 0xFF logdbg('frequency registers: %x %x %x %x' % ( self.reg_names[self.AX5051RegisterNames.FREQ3], self.reg_names[self.AX5051RegisterNames.FREQ2], self.reg_names[self.AX5051RegisterNames.FREQ1], self.reg_names[self.AX5051RegisterNames.FREQ0])) # figure out the transceiver id buf = [None] self.shid.readConfigFlash(0x1F9, 7, buf) tid = buf[0][5] << 8 tid += buf[0][6] loginf('transceiver identifier: %d (0x%04x)' % (tid,tid)) self.DataStore.setDeviceID(tid) # figure out the transceiver serial number sn = str("%02d"%(buf[0][0])) sn += str("%02d"%(buf[0][1])) sn += str("%02d"%(buf[0][2])) sn += str("%02d"%(buf[0][3])) sn += str("%02d"%(buf[0][4])) sn += str("%02d"%(buf[0][5])) sn += str("%02d"%(buf[0][6])) loginf('transceiver serial: %s' % sn) self.DataStore.setTransceiverSerNo(sn) for r in self.reg_names: self.shid.writeReg(r, self.reg_names[r]) def setup(self, frequency_standard, vendor_id, product_id, device_id, serial, comm_interval=3): self.DataStore.setCommModeInterval(comm_interval) self.shid.open(vendor_id, product_id, device_id, serial) self.initTransceiver(frequency_standard) self.DataStore.setTransceiverPresent(True) def teardown(self): self.shid.close() # FIXME: make this thread-safe def getWeatherData(self): return self.DataStore.CurrentWeather # FIXME: make this thread-safe def getLastStat(self): return self.DataStore.LastStat # FIXME: make this thread-safe def getConfigData(self): return self.DataStore.StationConfig def startCachingHistory(self, since_ts=0, num_rec=0): self.history_cache.clear_records() if since_ts is None: since_ts = 0 self.history_cache.since_ts = since_ts if num_rec > WS28xxDriver.max_records - 2: num_rec = WS28xxDriver.max_records - 2 self.history_cache.num_rec = num_rec self.command = EAction.aGetHistory def stopCachingHistory(self): self.command = None def getUncachedHistoryCount(self): return self.history_cache.num_outstanding_records def getNextHistoryIndex(self): return self.history_cache.next_index def getNumHistoryScanned(self): return self.history_cache.num_scanned def getLatestHistoryIndex(self): return self.DataStore.LastStat.LatestHistoryIndex def getHistoryCacheRecords(self): return self.history_cache.records def clearHistoryCache(self): self.history_cache.clear_records() def startRFThread(self): if self.child is not None: return logdbg('startRFThread: spawning RF thread') self.running = True self.child = threading.Thread(target=self.doRF) self.child.setName('RFComm') self.child.setDaemon(True) self.child.start() def stopRFThread(self): self.running = False logdbg('stopRFThread: waiting for RF thread to terminate') self.child.join(self.thread_wait) if self.child.isAlive(): logerr('unable to terminate RF thread after %d seconds' % self.thread_wait) else: self.child = None def isRunning(self): return self.running def doRF(self): try: logdbg('setting up rf communication') self.doRFSetup() logdbg('starting rf communication') while self.running: self.doRFCommunication() except Exception, e: logerr('exception in doRF: %s' % e) if weewx.debug: log_traceback(dst=syslog.LOG_DEBUG) self.running = False raise finally: logdbg('stopping rf communication') # it is probably not necessary to have two setPreamblePattern invocations. # however, HeavyWeatherPro seems to do it this way on a first time config. # doing it this way makes configuration easier during a factory reset and # when re-establishing communication with the station sensors. def doRFSetup(self): self.shid.execute(5) self.shid.setPreamblePattern(0xaa) self.shid.setState(0) time.sleep(1) self.shid.setRX() self.shid.setPreamblePattern(0xaa) self.shid.setState(0x1e) time.sleep(1) self.shid.setRX() self.setSleep(0.085,0.005) def doRFCommunication(self): time.sleep(self.firstSleep) self.pollCount = 0 while self.running: StateBuffer = [None] self.shid.getState(StateBuffer) self.pollCount += 1 if StateBuffer[0][0] == 0x16: break time.sleep(self.nextSleep) else: return DataLength = [0] DataLength[0] = 0 FrameBuffer=[0] FrameBuffer[0]=[0]*0x03 self.shid.getFrame(FrameBuffer, DataLength) try: self.generateResponse(FrameBuffer, DataLength) self.shid.setFrame(FrameBuffer[0], DataLength[0]) except BadResponse, e: logerr('generateResponse failed: %s' % e) except DataWritten, e: logdbg('SetTime/SetConfig data written') self.shid.setTX() # these are for diagnostics and debugging def setSleep(self, firstsleep, nextsleep): self.firstSleep = firstsleep self.nextSleep = nextsleep def timing(self): s = self.firstSleep + self.nextSleep * (self.pollCount - 1) return 'sleep=%s first=%s next=%s count=%s' % ( s, self.firstSleep, self.nextSleep, self.pollCount)
sai9/weewx-gitsvn
bin/weewx/drivers/ws28xx.py
Python
gpl-3.0
174,398
# frozen_string_literal: true RSpec.shared_examples 'vcs: having remote' do describe '#remote' do it 'sets @remote' do object.remote = 'some-value' expect(object.instance_variable_get(:@remote)).to eq 'some-value' end end describe '#remote' do subject(:remote) { object.remote } let(:remote_class) { object.send(:remote_class) } before do allow(object).to receive(:remote_file_id).and_return 'remote-id' allow(remote_class).to receive(:new).and_return 'new-instance' hook if defined?(hook) object.remote end it 'returns an instance of remote class' do expect(remote_class).to have_received(:new).with('remote-id') end it 'sets @remote to new instance' do expect(object.instance_variable_get(:@remote)).to eq 'new-instance' end context 'when @remote is already set' do let(:hook) { object.instance_variable_set(:@remote, 'existing-value') } it { is_expected.to eq 'existing-value' } end end describe '#reload' do before do allow(object).to receive(:reset_remote) allow(object.class).to receive(:find) object.reload end it { expect(object).to have_received(:reset_remote) } it 'reloads the object from database' do expect(object.class).to have_received(:find) end end describe '#reset_remote' do subject(:reset_remote) { object.send(:reset_remote) } before do object.instance_variable_set(:@remote, 'some-value') end it 'resets @remote to nil' do reset_remote expect(object.instance_variable_get(:@remote)).to eq nil end end describe '#remote_class' do subject { object.send(:remote_class) } it { is_expected.to eq Providers::GoogleDrive::FileSync } end end
UpshiftOne/upshift
spec/models/shared_examples/vcs/having_remote.rb
Ruby
gpl-3.0
1,792
// NOTE: nbApp is defined in app.js nbApp.directive("languageContainerDirective", function() { return { restrict : 'E', templateUrl : 'js/templates/language-container.html', scope: { color: "@", language: "@", reading: "@", writing: "@", listening: "@", speaking: "@", flag: "@", }, link: function(scope, element, attrs) { scope.color = attrs.color; scope.language = attrs.language; scope.reading = attrs.reading; scope.writing = attrs.writing; scope.listening = attrs.listening; scope.speaking = attrs.speaking; scope.flag = attrs.flag; scope.$watch('language', function(nV, oV) { if(nV){ RadarChart.defaultConfig.color = function() {}; RadarChart.defaultConfig.radius = 3; RadarChart.defaultConfig.w = 250; RadarChart.defaultConfig.h = 250; /* * 0 - No Practical Proficiency * 1 - Elementary Proficiency * 2 - Limited Working Proficiency * 3 - Minimum Professional Proficiency * 4 - Full Professional Proficiency * 5 - Native or Bilingual Proficiency Read: the ability to read and understand texts written in the language Write: the ability to formulate written texts in the language Listen: the ability to follow and understand speech in the language Speak: the ability to produce speech in the language and be understood by its speakers. */ var data = [ { className: attrs.language, // optional can be used for styling axes: [ {axis: "Reading", value: attrs.reading}, {axis: "Writing", value: attrs.writing}, {axis: "Listening", value: attrs.listening}, {axis: "Speaking", value: attrs.speaking}, ] }, ]; function mapData() { return data.map(function(d) { return { className: d.className, axes: d.axes.map(function(axis) { return {axis: axis.axis, value: axis.value}; }) }; }); } // chart.config.w; // chart.config.h; // chart.config.axisText = true; // chart.config.levels = 5; // chart.config.maxValue = 5; // chart.config.circles = true; // chart.config.actorLegend = 1; var chart = RadarChart.chart(); var cfg = chart.config(); // retrieve default config cfg = chart.config({axisText: true, levels: 5, maxValue: 5, circles: true}); // retrieve default config var svg = d3.select('.' + attrs.language).append('svg') .attr('width', 250) .attr('height', 270); svg.append('g').classed('single', 1).datum(mapData()).call(chart); console.log('Rendering new language Radar Viz! --> ' + attrs.language); } }) } }; });
nbuechler/nb.com-v8
js/directives/language-container-directive.js
JavaScript
gpl-3.0
3,501
//============================================================================= /*! return transposed _dsymatrix */ inline _dsymatrix t(const _dsymatrix& mat) {CPPL_VERBOSE_REPORT; #ifdef CPPL_DEBUG WARNING_REPORT; std::cerr << "This function call has no effect since the matrix is symmetric." << std::endl; #endif//CPPL_DEBUG return mat; } //============================================================================= /*! return its inverse matrix */ inline _dsymatrix i(const _dsymatrix& mat) {CPPL_VERBOSE_REPORT; dsymatrix mat_cp(mat); dsymatrix mat_inv(mat_cp.n); mat_inv.identity(); char UPLO('l'); CPPL_INT NRHS(mat.n), LDA(mat.n), *IPIV(new CPPL_INT[mat.n]), LDB(mat.n), LWORK(-1), INFO(1); double *WORK( new double[1] ); dsysv_(&UPLO, &mat_cp.n, &NRHS, mat_cp.array, &LDA, IPIV, mat_inv.array, &LDB, WORK, &LWORK, &INFO); LWORK = CPPL_INT(WORK[0]); delete [] WORK; WORK = new double[LWORK]; dsysv_(&UPLO, &mat_cp.n, &NRHS, mat_cp.array, &LDA, IPIV, mat_inv.array, &LDB, WORK, &LWORK, &INFO); delete [] WORK; delete [] IPIV; if(INFO!=0){ WARNING_REPORT; std::cerr << "Serious trouble happend. INFO = " << INFO << "." << std::endl; } return _(mat_inv); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //============================================================================= /*! search the index of element having the largest absolute value in 0-based numbering system */ inline void idamax(CPPL_INT& i, CPPL_INT& j, const _dsymatrix& mat) {CPPL_VERBOSE_REPORT; dsymatrix newmat =mat; idamax(i, j, newmat); } //============================================================================= /*! return its largest absolute value */ inline double damax(const _dsymatrix& mat) {CPPL_VERBOSE_REPORT; dsymatrix newmat =mat; return damax(newmat); }
j-otsuki/SpM
thirdparty/cpplapack/include/_dsymatrix-/_dsymatrix-calc.hpp
C++
gpl-3.0
2,027
package name.parsak.controller; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import name.parsak.api.Tcpip; import name.parsak.dto.UsrDptRole; import name.parsak.model.Department; import name.parsak.model.Menu; import name.parsak.model.Role; import name.parsak.model.User; import name.parsak.service.UserDBService; @Controller public class WebController { final private String project_name = "JWC"; final private String user_cookie_name = "user"; final private String blank = ""; final private int max_login_time = 7200; private UserDBService userDBService; @Autowired(required=true) @Qualifier(value="UserDBService") public void setUserDBService(UserDBService us){ this.userDBService = us; } // Create Admin User, if it doesn't exist @RequestMapping(value="setup") public String setup() { this.userDBService.setup(); return "redirect:/"; } // Default page @RequestMapping({"/", "index"}) public String index( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @ModelAttribute(project_name)Menu menu) { if (! userid.equals(blank)) { int id = Integer.parseInt(userid); User user = this.userDBService.getUserById(id); if (user != null) { model.addAttribute("id", userid); model.addAttribute("name", user.getName()); model.addAttribute("lastname", user.getLastname()); model.addAttribute("email", user.getEmail()); if (this.userDBService.isUserAdmin(user)) { model.addAttribute("admin", "true"); } try { String name = menu.getName(); if (name != null) { this.userDBService.AddMenu(menu); } } catch (NullPointerException e) {} // menu.id is used to browse long menuid = menu.getId(); model.addAttribute("menu", this.userDBService.getMenuDtoById(menuid)); model.addAttribute("parent", menuid); model.addAttribute("menulist", this.userDBService.getMenuByParent(menuid)); } } return "index"; } // Login User @RequestMapping(value="login") public String login( Model model, @ModelAttribute(project_name)User u, HttpServletResponse response) { Long userid = u.getId(); // In case user enters /login without submitting a login form if (userid != 0) { User user = this.userDBService.getUser(u.getId(), u.getPassword()); if (user != null) { Cookie cookie = new Cookie(user_cookie_name, String.valueOf(user.getId())); cookie.setMaxAge(max_login_time); response.addCookie(cookie); } } return "redirect:/"; } // Logout User @RequestMapping(value="logout") public String logout( HttpServletResponse response) { Cookie cookie = new Cookie(user_cookie_name,blank); cookie.setMaxAge(0); response.addCookie(cookie); return "redirect:/"; } // Display All Users @RequestMapping(value="users") public String users( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); model.addAttribute("userslist", this.userDBService.listUsers()); return "users"; } } } return "redirect:/"; } // Display All Departments @RequestMapping(value="departments") public String departments( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); model.addAttribute("deptlist", this.userDBService.listDepartments()); model.addAttribute("rolelist", this.userDBService.listRoles()); return "departments"; } } } return "redirect:/"; } @RequestMapping(value="department") public String department( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @ModelAttribute(project_name)UsrDptRole usrdptrole){ if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); String DeptName = usrdptrole.getDeptname(); System.out.println(">> Displaying "+DeptName); Department department = this.userDBService.getDepartmentByName(DeptName); model.addAttribute("department", department.getDepartment_name()); // model.addAttribute("deptrolelist", this.userDBService.getDepartmentUsers(department)); return "department"; } } } return "redirect:/"; } @RequestMapping(value="add_user") public String add_user( Model model, @ModelAttribute(project_name)User user, HttpServletResponse response) { String user_name = null; String user_lastname = null; String user_email = null; String user_password = null; try { user_name = user.getName(); user_lastname = user.getLastname(); user_email = user.getEmail(); user_password = user.getPassword(); } catch (NullPointerException e) {} if (user_name != null && user_lastname != null && user_email != null && user_password != null) { this.userDBService.addUser(user); } return "redirect:/users"; } @RequestMapping(value="update_user") public String update_user( Model model, @ModelAttribute(project_name)User user, HttpServletResponse response) { String user_name = null; String user_lastname = null; String user_email = null; String user_password = null; try { user_name = user.getName(); user_lastname = user.getLastname(); user_email = user.getEmail(); user_password = user.getPassword(); } catch (NullPointerException e) {} if (user_name != null && user_lastname != null && user_email != null && user_password != null) { this.userDBService.updateUser(user); } return "redirect:/user"+user.getId(); } // Assign UserRole to a user @RequestMapping(value="add_user_role") public String AddUserRole(@ModelAttribute(project_name)UsrDptRole usrdptrole) { String deptname = usrdptrole.getDeptname(); String rolename = usrdptrole.getRolename(); long userid = usrdptrole.getUserid(); if (userid != 0 && !deptname.equals(blank) && !rolename.equals(blank)) { User user = this.userDBService.getUserById((int) userid); Department department = this.userDBService.getDepartmentByName(deptname); Role role = this.userDBService.getRoleByName(rolename); this.userDBService.AddUserRole(user, department, role); } return "redirect:/user"+userid; } @RequestMapping(value="remove_userrole") public String RemoveUserRole(@ModelAttribute(project_name) UsrDptRole deptrole) { this.userDBService.removeUserRoleById(deptrole.getId()); return "redirect:/user"+deptrole.getUserid(); } // Display User{id} @RequestMapping(value="/user{id}") public String user( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @PathVariable("id") int id) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); User user = this.userDBService.getUserById(id); model.addAttribute("userid",user.getId()); model.addAttribute("name",user.getName()); model.addAttribute("lastname",user.getLastname()); model.addAttribute("email",user.getEmail()); model.addAttribute("User", user); // To populate Edit Form model.addAttribute("deptrolelist",this.userDBService.getUsrDptRoles(user)); model.addAttribute("deptlist", this.userDBService.listDepartments()); model.addAttribute("rolelist", this.userDBService.listRoles()); return "user"; } } } return "redirect:/"; } // Remove User{id} @RequestMapping(value="/removeuser{id}") public String removeuser( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @PathVariable("id") int id) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); User user = this.userDBService.getUserById(id); this.userDBService.RemoveUserRoleByUser(user); this.userDBService.removeUser(user); return "redirect:/users"; } } } return "redirect:/"; } @RequestMapping(value="/add_department") public String addNewDepartment(@ModelAttribute(project_name) UsrDptRole deptrole) { this.userDBService.AddDepartment(deptrole.getDeptname()); return "redirect:/departments"; } @RequestMapping(value="/add_role") public String addNewRole(@ModelAttribute(project_name) UsrDptRole deptrole) { this.userDBService.AddRole(deptrole.getRolename()); return "redirect:/departments"; } @RequestMapping(value="/api_test") public String test_api(Model model) { Tcpip tcpip = new Tcpip(); String response = tcpip.get("http://www.google.com"); model.addAttribute("response", response); return "api_test"; } }
yparsak/JWC
src/main/java/name/parsak/controller/WebController.java
Java
gpl-3.0
10,545
#pragma once // // njhseq - A library for analyzing sequence data // Copyright (C) 2012-2018 Nicholas Hathaway <nicholas.hathaway@umassmed.edu>, // // This file is part of njhseq. // // njhseq 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. // // njhseq 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 njhseq. If not, see <http://www.gnu.org/licenses/>. // // // alnInfoHolder.hpp // // Created by Nicholas Hathaway on 1/13/14. // #include "njhseq/alignment/alnCache/alnInfoHolderBase.hpp" #if __APPLE__ == 1 && __cpp_lib_shared_timed_mutex < 201402L && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 101106 #include <sharedMutex.h> #else #include <shared_mutex> #endif namespace njhseq { class alnInfoMasterHolder { public: // constructors alnInfoMasterHolder(); alnInfoMasterHolder(const gapScoringParameters & gapPars, const substituteMatrix & scoringArray); alnInfoMasterHolder(const std::string &masterDirName, const gapScoringParameters & gapPars, const substituteMatrix & scoringArray, bool verbose = false); // members std::unordered_map<std::string, alnInfoHolderBase<alnInfoLocal>> localHolder_; std::unordered_map<std::string, alnInfoHolderBase<alnInfoGlobal>> globalHolder_; std::hash<std::string> strH_; void clearHolders(); void addHolder(const gapScoringParameters & gapPars, const substituteMatrix & scoringArray); // reading void read(const std::string &masterDirName, bool verbose = false); // writing void write(const std::string &masterDirName, bool verbose = false); void mergeOtherHolder(const alnInfoMasterHolder & otherHolder); }; namespace alignment { static std::mutex alnCacheDirSearchLock; static std::unordered_map<std::string, std::unique_ptr<std::shared_timed_mutex>> alnCacheDirLocks; } // namespace alignment } // namespace njhseq
bailey-lab/bibseq
src/njhseq/alignment/alnCache/alnInfoHolder.hpp
C++
gpl-3.0
2,293
module XmlResolution # Most named exceptions in the XmlResolution service we subclass here # to one of the HTTP classes. Libraries are designed specifically # to be unaware of this mapping: they only use their specific low level # exceptions classes. # # In general, if we catch an HttpError at our top level app, we can # blindly return the error message to the client as a diagnostic, # and log it. The fact that we're naming these exceptions means # we're being careful not to leak information, and still be helpful # to the Client. They are very specific messages; tracebacks will # not be required. # # When we get an un-named exception, however, the appropriate thing # to do is to just supply a very terse message to the client (e.g., # we wouldn't like to expose errors from an ORM that said something # like "password 'topsecret' failed in mysql open"). We *will* want # to log the full error message, and probably a backtrace to boot. class HttpError < StandardError; def client_message "#{status_code} #{status_text} - #{message.chomp('.')}." end end # Most of the following comments are pretty darn obvious - they # are included for easy navigation in the generated rdoc html files. # Http400Error's group named exceptions as something the client did # wrong. It is subclassed from the HttpError exception. class Http400Error < HttpError; end # Http400 exception: 400 Bad Request - it is subclassed from Http400Error. class Http400 < Http400Error def status_code; 400; end def status_text; "Bad Request"; end end # Http401 exception: 401 Unauthorized - it is subclassed from Http400Error. class Http401 < Http400Error def status_code; 401; end def status_text; "Unauthorized"; end end # Http403 exception: 403 Forbidden - it is subclassed from Http400Error. class Http403 < Http400Error def status_code; 403; end def status_text; "Forbidden"; end end # Http404 exception: 404 Not Found - it is subclassed from Http400Error. class Http404 < Http400Error def status_code; 404; end def status_text; "Not Found"; end end # Http405 exception: 405 Method Not Allowed - it is subclassed from Http400Error. class Http405 < Http400Error def status_code; 405; end def status_text; "Method Not Allowed"; end end # Http406 exception: 406 Not Acceptable - it is subclassed from Http400Error. class Http406 < Http400Error def status_code; 406; end def status_text; "Not Acceptable"; end end # Http408 exception: 408 Request Timeout - it is subclassed from Http400Error. class Http408 < Http400Error def status_code; 408; end def status_text; "Request Timeout"; end end # Http409 exception: 409 Conflict - it is subclassed from Http400Error. class Http409 < Http400Error def status_code; 409; end def status_text; "Conflict"; end end # Http410 exception: 410 Gone - it is subclassed from Http400Error. class Http410 < Http400Error def status_code; 410; end def status_text; "Gone"; end end # Http411 exception: 411 Length Required - it is subclassed from Http400Error. class Http411 < Http400Error def status_code; 411; end def status_text; "Length Required"; end end # Http412 exception: 412 Precondition Failed - it is subclassed from Http400Error. class Http412 < Http400Error def status_code; 412; end def status_text; "Precondition Failed"; end end # Http413 exception: 413 Request Entity Too Large - it is subclassed from Http400Error. class Http413 < Http400Error def status_code; 413; end def status_text; "Request Entity Too Large"; end end # Http414 exception: 414 Request-URI Too Long - it is subclassed from Http400Error. class Http414 < Http400Error def status_code; 414; end def status_text; "Request-URI Too Long"; end end # Http415 exception: 415 Unsupported Media Type - it is subclassed from Http400Error. class Http415 < Http400Error def status_code; 415; end def status_text; "Unsupported Media Type"; end end # Http500Error's group errors that are the server's fault. # It is subclassed from the HttpError exception. class Http500Error < HttpError; end # Http500 exception: 500 Internal Service Error - it is subclassed from Http500Error. class Http500 < Http500Error def status_code; 500; end def status_text; "Internal Service Error"; end end # Http501 exception: 501 Not Implemented - it is subclassed from Http500Error. class Http501 < Http500Error def status_code; 501; end def status_text; "Not Implemented"; end end # Http503 exception: 503 Service Unavailable - it is subclassed from Http500Error. class Http503 < Http500Error def status_code; 503; end def status_text; "Service Unavailable"; end end # Http505 exception: 505 HTTP Version Not Supported - it is subclassed from Http500Error. class Http505 < Http500Error def status_code; 505; end def status_text; "HTTP Version Not Supported"; end end # BadXmlDocument exception, client's fault (subclasses Http400): Instance document could not be parsed.. class BadXmlDocument < Http415; end # BadBadXmlDocument exception, client's fault (subclasses BadXmlDocument): ..it *really* could not be parsed class BadBadXmlDocument < BadXmlDocument; end # InadequateDataError exception, client's fault (subclasses Http400): Problem with uploaded data (e.g. length 0) class InadequateDataError < Http400; end # BadCollectionID exception, client's fault (subclasses Http400): PUT of a Collection ID wasn't suitable class BadCollectionID < Http400; end # BadXmlVersion exception, client's fault (subclasses Http415): Unsupported XML version (only 1.0) class BadXmlVersion < Http415; end # TooManyDarnSchemas exception, client's fault (subclasses Http400): Possible denial of service - infinite train of schemas class TooManyDarnSchemas < Http400; end # LockError exception, server's fault (subclasses Http500): Timed out trying to get a locked file class LockError < Http500; end # ConfigurationError exception, server's fault (subclasses Http500): Something wasn't set up correctly class ConfigurationError < Http500; end # ResolverError exception, server's fault (subclasses Http500): Result of a programming error class ResolverError < Http500; end # The LocationError is caught internally, and is used to indicate that # the fetch of a Schema could not be performed because the location # URL scheme was not supported. This results in reporting broken # link, and is normally not very important: there are many other # schemas to report on. # # However, if this exception was raised to the top level, we do # not want to pass the information to the user. That's why it is not # assigned to an HttpError subclass - we *want* a logged backtrace in # that case. class LocationError < StandardError; end end # of module
fcla/xmlresolution
lib/xmlresolution/exceptions.rb
Ruby
gpl-3.0
7,177
/*************************************************************************** * Copyright © 2010-2011 Jonathan Thomas <echidnaman@kubuntu.org> * * Heavily inspired by Synaptic library code ;-) * * * * 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) version 3 or any later version * * accepted by the membership of KDE e.V. (or its successor approved * * by the membership of KDE e.V.), which shall act as a proxy * * defined in Section 14 of version 3 of the license. * * * * 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/>. * ***************************************************************************/ //krazy:excludeall=qclasses // Qt-only library, so things like QUrl *should* be used #include "package.h" // Qt includes #include <QtCore/QFile> #include <QtCore/QStringBuilder> #include <QtCore/QStringList> #include <QtCore/QTemporaryFile> #include <QtCore/QTextStream> #include <QDebug> // Apt includes #include <apt-pkg/algorithms.h> #include <apt-pkg/debversion.h> #include <apt-pkg/depcache.h> #include <apt-pkg/indexfile.h> #include <apt-pkg/init.h> #include <apt-pkg/pkgrecords.h> #include <apt-pkg/sourcelist.h> #include <apt-pkg/strutl.h> #include <apt-pkg/tagfile.h> #include <apt-pkg/versionmatch.h> #include <algorithm> // Own includes #include "backend.h" #include "cache.h" #include "config.h" // krazy:exclude=includes #include "markingerrorinfo.h" namespace QApt { class PackagePrivate { public: PackagePrivate(pkgCache::PkgIterator iter, Backend *back) : packageIter(iter) , backend(back) , state(0) , staticStateCalculated(false) , foreignArchCalculated(false) { } ~PackagePrivate() { } pkgCache::PkgIterator packageIter; QApt::Backend *backend; int state; bool staticStateCalculated; bool isForeignArch; bool foreignArchCalculated; pkgCache::PkgFileIterator searchPkgFileIter(QLatin1String label, const QString &release) const; QString getReleaseFileForOrigin(QLatin1String label, const QString &release) const; // Calculate state flags that cannot change void initStaticState(const pkgCache::VerIterator &ver, pkgDepCache::StateCache &stateCache); }; pkgCache::PkgFileIterator PackagePrivate::searchPkgFileIter(QLatin1String label, const QString &release) const { pkgCache::VerIterator verIter = packageIter.VersionList(); pkgCache::VerFileIterator verFileIter; pkgCache::PkgFileIterator found; while (!verIter.end()) { for (verFileIter = verIter.FileList(); !verFileIter.end(); ++verFileIter) { for(found = verFileIter.File(); !found.end(); ++found) { const char *verLabel = found.Label(); const char *verOrigin = found.Origin(); const char *verArchive = found.Archive(); if (verLabel && verOrigin && verArchive) { if(verLabel == label && verOrigin == label && QLatin1String(verArchive) == release) { return found; } } } } ++verIter; } found = pkgCache::PkgFileIterator(*packageIter.Cache()); return found; } QString PackagePrivate::getReleaseFileForOrigin(QLatin1String label, const QString &release) const { pkgCache::PkgFileIterator pkg = searchPkgFileIter(label, release); // Return empty if no package matches the given label and release if (pkg.end()) return QString(); // Search for the matching meta-index pkgSourceList *list = backend->packageSourceList(); pkgIndexFile *index; // Return empty if the source list doesn't contain an index for the package if (!list->FindIndex(pkg, index)) return QString(); for (auto I = list->begin(); I != list->end(); ++I) { vector<pkgIndexFile *> *ifv = (*I)->GetIndexFiles(); if (find(ifv->begin(), ifv->end(), index) == ifv->end()) continue; // Construct release file path QString uri = backend->config()->findDirectory("Dir::State::lists") % QString::fromStdString(URItoFileName((*I)->GetURI())) % QLatin1String("dists_") % QString::fromStdString((*I)->GetDist()) % QLatin1String("_Release"); return uri; } return QString(); } void PackagePrivate::initStaticState(const pkgCache::VerIterator &ver, pkgDepCache::StateCache &stateCache) { int packageState = 0; if (!ver.end()) { // Set flags exclusive to installed packages packageState |= QApt::Package::Installed; if (stateCache.CandidateVer && stateCache.Upgradable()) { packageState |= QApt::Package::Upgradeable; if (stateCache.Keep()) packageState |= QApt::Package::Held; } } else packageState |= QApt::Package::NotInstalled; // Broken/garbage statuses are constant until a cache reload if (stateCache.NowBroken()) { packageState |= QApt::Package::NowBroken; } if (stateCache.InstBroken()) { packageState |= QApt::Package::InstallBroken; } if (stateCache.Garbage) { packageState |= QApt::Package::IsGarbage; } if (stateCache.NowPolicyBroken()) { packageState |= QApt::Package::NowPolicyBroken; } if (stateCache.InstPolicyBroken()) { packageState |= QApt::Package::InstallPolicyBroken; } // Essential/important status can only be changed by cache reload if (packageIter->Flags & (pkgCache::Flag::Important | pkgCache::Flag::Essential)) { packageState |= QApt::Package::IsImportant; } if (packageIter->CurrentState == pkgCache::State::ConfigFiles) { packageState |= QApt::Package::ResidualConfig; } // Packages will stay undownloadable until a sources file is refreshed // and the cache is reloaded. bool downloadable = true; if (!stateCache.CandidateVer || stateCache.CandidateVerIter(*backend->cache()->depCache()).Downloadable()) downloadable = false; if (!downloadable) packageState |= QApt::Package::NotDownloadable; state |= packageState; staticStateCalculated = true; } Package::Package(QApt::Backend* backend, pkgCache::PkgIterator &packageIter) : d(new PackagePrivate(packageIter, backend)) { } Package::~Package() { delete d; } const pkgCache::PkgIterator &Package::packageIterator() const { return d->packageIter; } QLatin1String Package::name() const { return QLatin1String(d->packageIter.Name()); } int Package::id() const { return d->packageIter->ID; } QLatin1String Package::section() const { return QLatin1String(d->packageIter.Section()); } QString Package::sourcePackage() const { QString sourcePackage; // In the APT package record format, the only time when a "Source:" field // is present is when the binary package name doesn't match the source // name const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList()); sourcePackage = QString::fromStdString(rec.SourcePkg()); } // If the package record didn't have a "Source:" field, then this package's // name must be the source package's name. (Or there isn't a record for this package) if (sourcePackage.isEmpty()) { sourcePackage = name(); } return sourcePackage; } QString Package::shortDescription() const { QString shortDescription; const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { pkgCache::DescIterator Desc = ver.TranslatedDescription(); pkgRecords::Parser & parser = d->backend->records()->Lookup(Desc.FileList()); shortDescription = QString::fromUtf8(parser.ShortDesc().data()); return shortDescription; } return shortDescription; } QString Package::longDescription() const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { QString rawDescription; pkgCache::DescIterator Desc = ver.TranslatedDescription(); pkgRecords::Parser & parser = d->backend->records()->Lookup(Desc.FileList()); rawDescription = QString::fromUtf8(parser.LongDesc().data()); // Apt acutally returns the whole description, we just want the // extended part. rawDescription.remove(shortDescription() % '\n'); // *Now* we're really raw. Sort of. ;) QString parsedDescription; // Split at double newline, by "section" QStringList sections = rawDescription.split(QLatin1String("\n .")); for (int i = 0; i < sections.count(); ++i) { sections[i].replace(QRegExp(QLatin1String("\n( |\t)+(-|\\*)")), QLatin1Literal("\n\r ") % QString::fromUtf8("\xE2\x80\xA2")); // There should be no new lines within a section. sections[i].remove(QLatin1Char('\n')); // Hack to get the lists working again. sections[i].replace(QLatin1Char('\r'), QLatin1Char('\n')); // Merge multiple whitespace chars into one sections[i].replace(QRegExp(QLatin1String("\\ \\ +")), QChar::fromLatin1(' ')); // Remove the initial whitespace sections[i].remove(0, 1); // Append to parsedDescription if (sections[i].startsWith(QLatin1String("\n ") % QString::fromUtf8("\xE2\x80\xA2 ")) || !i) { parsedDescription += sections[i]; } else { parsedDescription += QLatin1Literal("\n\n") % sections[i]; } } return parsedDescription; } return QString(); } QString Package::maintainer() const { QString maintainer; const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { pkgRecords::Parser &parser = d->backend->records()->Lookup(ver.FileList()); maintainer = QString::fromUtf8(parser.Maintainer().data()); // This replacement prevents frontends from interpreting '<' as // an HTML tag opening maintainer.replace(QLatin1Char('<'), QLatin1String("&lt;")); } return maintainer; } QString Package::homepage() const { QString homepage; const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { pkgRecords::Parser &parser = d->backend->records()->Lookup(ver.FileList()); homepage = QString::fromUtf8(parser.Homepage().data()); } return homepage; } QString Package::version() const { if (!d->packageIter->CurrentVer) { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return QString(); } else { return QLatin1String(State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr()); } } else { return QLatin1String(d->packageIter.CurrentVer().VerStr()); } } QString Package::upstreamVersion() const { const char *ver; if (!d->packageIter->CurrentVer) { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return QString(); } else { ver = State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr(); } } else { ver = d->packageIter.CurrentVer().VerStr(); } return QString::fromStdString(_system->VS->UpstreamVersion(ver)); } QString Package::upstreamVersion(const QString &version) { QByteArray ver = version.toLatin1(); return QString::fromStdString(_system->VS->UpstreamVersion(ver.constData())); } QString Package::architecture() const { pkgDepCache *depCache = d->backend->cache()->depCache(); pkgCache::VerIterator ver = (*depCache)[d->packageIter].InstVerIter(*depCache); // the arch:all property is part of the version if (ver && ver.Arch()) return QLatin1String(ver.Arch()); return QLatin1String(d->packageIter.Arch()); } QStringList Package::availableVersions() const { QStringList versions; // Get available Versions. for (auto Ver = d->packageIter.VersionList(); !Ver.end(); ++Ver) { // We always take the first available version. pkgCache::VerFileIterator VF = Ver.FileList(); if (VF.end()) continue; pkgCache::PkgFileIterator File = VF.File(); // Files without an archive will have a site QString archive = (File->Archive) ? QLatin1String(File.Archive()) : QLatin1String(File.Site()); versions.append(QLatin1String(Ver.VerStr()) % QLatin1String(" (") % archive % ')'); } return versions; } QString Package::installedVersion() const { if (!d->packageIter->CurrentVer) { return QString(); } return QLatin1String(d->packageIter.CurrentVer().VerStr()); } QString Package::availableVersion() const { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return QString(); } return QLatin1String(State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr()); } QString Package::priority() const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (ver.end()) return QString(); return QLatin1String(ver.PriorityType()); } QStringList Package::installedFilesList() const { QStringList installedFilesList; QString path = QLatin1String("/var/lib/dpkg/info/") % name() % QLatin1String(".list"); // Fallback for multiarch packages if (!QFile::exists(path)) { path = QLatin1String("/var/lib/dpkg/info/") % name() % ':' % architecture() % QLatin1String(".list"); } QFile infoFile(path); if (infoFile.open(QFile::ReadOnly)) { QTextStream stream(&infoFile); QString line; do { line = stream.readLine(); installedFilesList << line; } while (!line.isNull()); // The first item won't be a file installedFilesList.removeFirst(); // Remove non-file directory listings for (int i = 0; i < installedFilesList.size() - 1; ++i) { if (installedFilesList.at(i+1).contains(installedFilesList.at(i) + '/')) { installedFilesList[i] = QString(QLatin1Char(' ')); } } installedFilesList.removeAll(QChar::fromLatin1(' ')); // Last line is empty for some reason... if (!installedFilesList.isEmpty()) { installedFilesList.removeLast(); } } return installedFilesList; } QString Package::origin() const { const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if(Ver.end()) return QString(); pkgCache::VerFileIterator VF = Ver.FileList(); return QLatin1String(VF.File().Origin()); } QStringList Package::archives() const { const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if(Ver.end()) return QStringList(); QStringList archiveList; for (auto VF = Ver.FileList(); !VF.end(); ++VF) archiveList << QLatin1String(VF.File().Archive()); return archiveList; } QString Package::component() const { QString sect = section(); if(sect.isEmpty()) return QString(); QStringList split = sect.split('/'); if (split.count() > 1) return split.first(); return QString("main"); } QByteArray Package::md5Sum() const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if(ver.end()) return QByteArray(); pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList()); return rec.MD5Hash().c_str(); } QUrl Package::changelogUrl() const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (ver.end()) return QUrl(); pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList()); // Find the latest version for the latest changelog QString versionString; if (!availableVersion().isEmpty()) versionString = availableVersion(); // Epochs in versions are ignored on changelog servers if (versionString.contains(QLatin1Char(':'))) { QStringList epochVersion = versionString.split(QLatin1Char(':')); // If the version has an epoch, take the stuff after the epoch versionString = epochVersion.at(1); } // Create URL in form using the correct server, file path, and file suffix Config *config = d->backend->config(); QString server = config->readEntry(QLatin1String("Apt::Changelogs::Server"), QLatin1String("http://packages.debian.org/changelogs")); QString path = QLatin1String(rec.FileName().c_str()); path = path.left(path.lastIndexOf(QLatin1Char('/')) + 1); path += sourcePackage() % '_' % versionString % '/'; bool fromDebian = server.contains(QLatin1String("debian")); QString suffix = fromDebian ? QLatin1String("changelog.txt") : QLatin1String("changelog"); return QUrl(server % '/' % path % suffix); } QUrl Package::screenshotUrl(QApt::ScreenshotType type) const { QUrl url; switch (type) { case QApt::Thumbnail: url = QUrl(controlField(QLatin1String("Thumbnail-Url"))); if(url.isEmpty()) url = QUrl("http://screenshots.debian.net/thumbnail/" % name()); break; case QApt::Screenshot: url = QUrl(controlField(QLatin1String("Screenshot-Url"))); if(url.isEmpty()) url = QUrl("http://screenshots.debian.net/screenshot/" % name()); break; default: qDebug() << "I do not know how to handle the screenshot type given to me: " << QString::number(type); } return url; } QDateTime Package::supportedUntil() const { if (!isSupported()) { return QDateTime(); } QFile lsb_release(QLatin1String("/etc/lsb-release")); if (!lsb_release.open(QFile::ReadOnly)) { // Though really, your system is screwed if this happens... return QDateTime(); } pkgTagSection sec; time_t releaseDate = -1; QString release; QTextStream stream(&lsb_release); QString line; do { line = stream.readLine(); QStringList split = line.split(QLatin1Char('=')); if (split.size() != 2) { continue; } if (split.at(0) == QLatin1String("DISTRIB_CODENAME")) { release = split.at(1); } } while (!line.isNull()); // Canonical only provides support for Ubuntu, but we don't have to worry // about Debian systems as long as we assume that this function can fail. QString releaseFile = d->getReleaseFileForOrigin(QLatin1String("Ubuntu"), release); if(!FileExists(releaseFile.toStdString())) { // happens e.g. when there is no release file and is harmless return QDateTime(); } // read the relase file FileFd fd(releaseFile.toStdString(), FileFd::ReadOnly); pkgTagFile tag(&fd); tag.Step(sec); if(!RFC1123StrToTime(sec.FindS("Date").data(), releaseDate)) { return QDateTime(); } // Default to 18m in case the package has no "supported" field QString supportTimeString = QLatin1String("18m"); QString supportTimeField = controlField(QLatin1String("Supported")); if (!supportTimeField.isEmpty()) { supportTimeString = supportTimeField; } QChar unit = supportTimeString.at(supportTimeString.length() - 1); supportTimeString.chop(1); // Remove the letter signifying months/years const int supportTime = supportTimeString.toInt(); QDateTime supportEnd; if (unit == QLatin1Char('m')) { supportEnd = QDateTime::fromTime_t(releaseDate).addMonths(supportTime); } else if (unit == QLatin1Char('y')) { supportEnd = QDateTime::fromTime_t(releaseDate).addYears(supportTime); } return supportEnd; } QString Package::controlField(QLatin1String name) const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (ver.end()) { return QString(); } pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList()); return QString::fromStdString(rec.RecordField(name.latin1())); } QString Package::controlField(const QString &name) const { return controlField(QLatin1String(name.toLatin1())); } qint64 Package::currentInstalledSize() const { const pkgCache::VerIterator &ver = d->packageIter.CurrentVer(); if (!ver.end()) { return qint64(ver->InstalledSize); } else { return qint64(-1); } } qint64 Package::availableInstalledSize() const { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return qint64(-1); } return qint64(State.CandidateVerIter(*d->backend->cache()->depCache())->InstalledSize); } qint64 Package::downloadSize() const { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return qint64(-1); } return qint64(State.CandidateVerIter(*d->backend->cache()->depCache())->Size); } int Package::state() const { int packageState = 0; const pkgCache::VerIterator &ver = d->packageIter.CurrentVer(); pkgDepCache::StateCache &stateCache = (*d->backend->cache()->depCache())[d->packageIter]; if (!d->staticStateCalculated) { d->initStaticState(ver, stateCache); } if (stateCache.Install()) { packageState |= ToInstall; } if (stateCache.Flags & pkgCache::Flag::Auto) { packageState |= QApt::Package::IsAuto; } if (stateCache.iFlags & pkgDepCache::ReInstall) { packageState |= ToReInstall; } else if (stateCache.NewInstall()) { // Order matters here. packageState |= NewInstall; } else if (stateCache.Upgrade()) { packageState |= ToUpgrade; } else if (stateCache.Downgrade()) { packageState |= ToDowngrade; } else if (stateCache.Delete()) { packageState |= ToRemove; if (stateCache.iFlags & pkgDepCache::Purge) { packageState |= ToPurge; } } else if (stateCache.Keep()) { packageState |= ToKeep; } return packageState | d->state; } int Package::staticState() const { if (!d->staticStateCalculated) { const pkgCache::VerIterator &ver = d->packageIter.CurrentVer(); pkgDepCache::StateCache &stateCache = (*d->backend->cache()->depCache())[d->packageIter]; d->initStaticState(ver, stateCache); } return d->state; } int Package::compareVersion(const QString &v1, const QString &v2) { // Make deep copies of toStdString(), since otherwise they would // go out of scope when we call c_str() string s1 = v1.toStdString(); string s2 = v2.toStdString(); const char *a = s1.c_str(); const char *b = s2.c_str(); int lenA = strlen(a); int lenB = strlen(b); return _system->VS->DoCmpVersion(a, a+lenA, b, b+lenB); } bool Package::isInstalled() const { return !d->packageIter.CurrentVer().end(); } bool Package::isSupported() const { if (origin() == QLatin1String("Ubuntu")) { QString componentString = component(); if ((componentString == QLatin1String("main") || componentString == QLatin1String("restricted")) && isTrusted()) { return true; } } return false; } bool Package::isMultiArchDuplicate() const { // Excludes installed packages, which are always "interesting" if (isInstalled()) return false; // Otherwise, check if the pkgIterator is the "best" from its group return (d->packageIter.Group().FindPkg() != d->packageIter); } QString Package::multiArchTypeString() const { return controlField(QLatin1String("Multi-Arch")); } MultiArchType Package::multiArchType() const { QString typeString = multiArchTypeString(); MultiArchType archType = InvalidMultiArchType; if (typeString == QLatin1String("same")) archType = MultiArchSame; else if (typeString == QLatin1String("foreign")) archType = MultiArchForeign; else if (typeString == QLatin1String("allowed")) archType = MultiArchAllowed; return archType; } bool Package::isForeignArch() const { if (!d->foreignArchCalculated) { QString arch = architecture(); d->isForeignArch = (d->backend->nativeArchitecture() != arch) & (arch != QLatin1String("all")); d->foreignArchCalculated = true; } return d->isForeignArch; } QList<DependencyItem> Package::depends() const { return DependencyInfo::parseDepends(controlField("Depends"), Depends); } QList<DependencyItem> Package::preDepends() const { return DependencyInfo::parseDepends(controlField("Pre-Depends"), PreDepends); } QList<DependencyItem> Package::suggests() const { return DependencyInfo::parseDepends(controlField("Suggests"), Suggests); } QList<DependencyItem> Package::recommends() const { return DependencyInfo::parseDepends(controlField("Recommends"), Recommends); } QList<DependencyItem> Package::conflicts() const { return DependencyInfo::parseDepends(controlField("Conflicts"), Conflicts); } QList<DependencyItem> Package::replaces() const { return DependencyInfo::parseDepends(controlField("Replaces"), Replaces); } QList<DependencyItem> Package::obsoletes() const { return DependencyInfo::parseDepends(controlField("Obsoletes"), Obsoletes); } QList<DependencyItem> Package::breaks() const { return DependencyInfo::parseDepends(controlField("Breaks"), Breaks); } QList<DependencyItem> Package::enhances() const { return DependencyInfo::parseDepends(controlField("Enhance"), Enhances); } QStringList Package::dependencyList(bool useCandidateVersion) const { QStringList dependsList; pkgCache::VerIterator current; pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if(!useCandidateVersion) { current = State.InstVerIter(*d->backend->cache()->depCache()); } if(useCandidateVersion || current.end()) { current = State.CandidateVerIter(*d->backend->cache()->depCache()); } // no information found if(current.end()) { return dependsList; } for(pkgCache::DepIterator D = current.DependsList(); D.end() != true; ++D) { QString type; bool isOr = false; bool isVirtual = false; QString name; QString version; QString versionCompare; QString finalString; // check target and or-depends status pkgCache::PkgIterator Trg = D.TargetPkg(); if ((D->CompareOp & pkgCache::Dep::Or) == pkgCache::Dep::Or) { isOr=true; } // common information type = QString::fromUtf8(D.DepType()); name = QLatin1String(Trg.Name()); if (!Trg->VersionList) { isVirtual = true; } else { version = QLatin1String(D.TargetVer()); versionCompare = QLatin1String(D.CompType()); } finalString = QLatin1Literal("<b>") % type % QLatin1Literal(":</b> "); if (isVirtual) { finalString += QLatin1Literal("<i>") % name % QLatin1Literal("</i>"); } else { finalString += name; } // Escape the compare operator so it won't be seen as HTML if (!version.isEmpty()) { QString compMarkup(versionCompare); compMarkup.replace(QLatin1Char('<'), QLatin1String("&lt;")); finalString += QLatin1String(" (") % compMarkup % QLatin1Char(' ') % version % QLatin1Char(')'); } if (isOr) { finalString += QLatin1String(" |"); } dependsList.append(finalString); } return dependsList; } QStringList Package::requiredByList() const { QStringList reverseDependsList; for(pkgCache::DepIterator it = d->packageIter.RevDependsList(); !it.end(); ++it) { reverseDependsList << QLatin1String(it.ParentPkg().Name()); } return reverseDependsList; } QStringList Package::providesList() const { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return QStringList(); } QStringList provides; for (pkgCache::PrvIterator Prv = State.CandidateVerIter(*d->backend->cache()->depCache()).ProvidesList(); !Prv.end(); ++Prv) { provides.append(QLatin1String(Prv.Name())); } return provides; } QStringList Package::recommendsList() const { QStringList recommends; const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (Ver.end()) { return recommends; } for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) { pkgCache::PkgIterator pkg = it.TargetPkg(); // Skip purely virtual packages if (!pkg->VersionList) { continue; } pkgDepCache::StateCache &rState = (*d->backend->cache()->depCache())[pkg]; if (it->Type == pkgCache::Dep::Recommends && (rState.CandidateVer != 0 )) { recommends << QLatin1String(it.TargetPkg().Name()); } } return recommends; } QStringList Package::suggestsList() const { QStringList suggests; const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (Ver.end()) { return suggests; } for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) { pkgCache::PkgIterator pkg = it.TargetPkg(); // Skip purely virtual packages if (!pkg->VersionList) { continue; } pkgDepCache::StateCache &sState = (*d->backend->cache()->depCache())[pkg]; if (it->Type == pkgCache::Dep::Suggests && (sState.CandidateVer != 0 )) { suggests << QLatin1String(it.TargetPkg().Name()); } } return suggests; } QStringList Package::enhancesList() const { QStringList enhances; const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (Ver.end()) { return enhances; } for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) { pkgCache::PkgIterator pkg = it.TargetPkg(); // Skip purely virtual packages if (!pkg->VersionList) { continue; } pkgDepCache::StateCache &eState = (*d->backend->cache()->depCache())[pkg]; if (it->Type == pkgCache::Dep::Enhances && (eState.CandidateVer != 0 )) { enhances << QLatin1String(it.TargetPkg().Name()); } } return enhances; } QStringList Package::enhancedByList() const { QStringList enhancedByList; Q_FOREACH (QApt::Package *package, d->backend->availablePackages()) { if (package->enhancesList().contains(name())) { enhancedByList << package->name(); } } return enhancedByList; } QList<QApt::MarkingErrorInfo> Package::brokenReason() const { const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); QList<MarkingErrorInfo> reasons; // check if there is actually something to install if (!Ver) { QApt::DependencyInfo info(name(), QString(), NoOperand, InvalidType); QApt::MarkingErrorInfo error(QApt::ParentNotInstallable, info); reasons.append(error); return reasons; } for (pkgCache::DepIterator D = Ver.DependsList(); !D.end();) { // Compute a single dependency element (glob or) pkgCache::DepIterator Start; pkgCache::DepIterator End; D.GlobOr(Start, End); pkgCache::PkgIterator Targ = Start.TargetPkg(); if (!d->backend->cache()->depCache()->IsImportantDep(End)) { continue; } if (((*d->backend->cache()->depCache())[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall) { continue; } if (!Targ->ProvidesList) { // Ok, not a virtual package since no provides pkgCache::VerIterator Ver = (*d->backend->cache()->depCache())[Targ].InstVerIter(*d->backend->cache()->depCache()); QString requiredVersion; if(Start.TargetVer() != 0) { requiredVersion = '(' % QLatin1String(Start.CompType()) % QLatin1String(Start.TargetVer()) % ')'; } if (!Ver.end()) { // Happens when a package needs an upgraded dep, but the dep won't // upgrade. Example: // "apt 0.5.4 but 0.5.3 is to be installed" QString targetName = QLatin1String(Start.TargetPkg().Name()); QApt::DependencyType relation = (QApt::DependencyType)End->Type; QApt::DependencyInfo errorInfo(targetName, requiredVersion, NoOperand, relation); QApt::MarkingErrorInfo error(QApt::WrongCandidateVersion, errorInfo); reasons.append(error); } else { // We have the package, but for some reason it won't be installed // In this case, the required version does not exist at all QString targetName = QLatin1String(Start.TargetPkg().Name()); QApt::DependencyType relation = (QApt::DependencyType)End->Type; QApt::DependencyInfo errorInfo(targetName, requiredVersion, NoOperand, relation); QApt::MarkingErrorInfo error(QApt::DepNotInstallable, errorInfo); reasons.append(error); } } else { // Ok, candidate has provides. We're a virtual package QString targetName = QLatin1String(Start.TargetPkg().Name()); QApt::DependencyType relation = (QApt::DependencyType)End->Type; QApt::DependencyInfo errorInfo(targetName, QString(), NoOperand, relation); QApt::MarkingErrorInfo error(QApt::VirtualPackage, errorInfo); reasons.append(error); } } return reasons; } bool Package::isTrusted() const { const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!Ver) return false; pkgSourceList *Sources = d->backend->packageSourceList(); QHash<pkgCache::PkgFileIterator, pkgIndexFile*> *trustCache = d->backend->cache()->trustCache(); for (pkgCache::VerFileIterator i = Ver.FileList(); !i.end(); ++i) { pkgIndexFile *Index; //FIXME: Should be done in apt auto trustIter = trustCache->constBegin(); while (trustIter != trustCache->constEnd()) { if (trustIter.key() == i.File()) break; // Found it trustIter++; } // Find the index of the package file from the package sources if (trustIter == trustCache->constEnd()) { // Not found if (!Sources->FindIndex(i.File(), Index)) continue; } else Index = trustIter.value(); if (Index->IsTrusted()) return true; } return false; } bool Package::wouldBreak() const { int pkgState = state(); if ((pkgState & ToRemove) || (!(pkgState & Installed) && (pkgState & ToKeep))) { return false; } return pkgState & InstallBroken; } void Package::setAuto(bool flag) { d->backend->cache()->depCache()->MarkAuto(d->packageIter, flag); } void Package::setKeep() { d->backend->cache()->depCache()->MarkKeep(d->packageIter, false); if (d->backend->cache()->depCache()->BrokenCount() > 0) { pkgProblemResolver Fix(d->backend->cache()->depCache()); Fix.ResolveByKeep(); } d->state |= IsManuallyHeld; if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } void Package::setInstall() { d->backend->cache()->depCache()->MarkInstall(d->packageIter, true); d->state &= ~IsManuallyHeld; // FIXME: can't we get rid of it here? // if there is something wrong, try to fix it if (!state() & ToInstall || d->backend->cache()->depCache()->BrokenCount() > 0) { pkgProblemResolver Fix(d->backend->cache()->depCache()); Fix.Clear(d->packageIter); Fix.Protect(d->packageIter); Fix.Resolve(true); } if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } void Package::setReInstall() { d->backend->cache()->depCache()->SetReInstall(d->packageIter, true); d->state &= ~IsManuallyHeld; if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } void Package::setRemove() { pkgProblemResolver Fix(d->backend->cache()->depCache()); Fix.Clear(d->packageIter); Fix.Protect(d->packageIter); Fix.Remove(d->packageIter); Fix.Resolve(true); d->backend->cache()->depCache()->SetReInstall(d->packageIter, false); d->backend->cache()->depCache()->MarkDelete(d->packageIter, false); d->state &= ~IsManuallyHeld; if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } void Package::setPurge() { pkgProblemResolver Fix(d->backend->cache()->depCache()); Fix.Clear(d->packageIter); Fix.Protect(d->packageIter); Fix.Remove(d->packageIter); Fix.Resolve(true); d->backend->cache()->depCache()->SetReInstall(d->packageIter, false); d->backend->cache()->depCache()->MarkDelete(d->packageIter, true); d->state &= ~IsManuallyHeld; if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } bool Package::setVersion(const QString &version) { pkgDepCache::StateCache &state = (*d->backend->cache()->depCache())[d->packageIter]; QLatin1String defaultCandVer(state.CandVersion); bool isDefault = (version == defaultCandVer); pkgVersionMatch Match(version.toLatin1().constData(), pkgVersionMatch::Version); const pkgCache::VerIterator &Ver = Match.Find(d->packageIter); if (Ver.end()) return false; d->backend->cache()->depCache()->SetCandidateVersion(Ver); for (auto VF = Ver.FileList(); !VF.end(); ++VF) { if (!VF.File() || !VF.File().Archive()) continue; d->backend->cache()->depCache()->SetCandidateRelease(Ver, VF.File().Archive()); break; } if (isDefault) d->state &= ~OverrideVersion; else d->state |= OverrideVersion; return true; } void Package::setPinned(bool pin) { pin ? d->state |= IsPinned : d->state &= ~IsPinned; } }
manchicken/libqapt
src/package.cpp
C++
gpl-3.0
40,648
<?php namespace App; use Illuminate\Database\Eloquent\Model; final class Contact extends Model { const PHONE = 'phone'; const ADDRESS = 'address'; const ADDRESS_COMPLEMENT = 'address_complement'; const POSTAL_CODE = 'postal_code'; const CITY = 'city'; const REGION = 'region'; const COUNTRY = 'country'; const CONTACTABLE_ID = 'contactable_id'; const CONTACTABLE_TYPE = 'contactable_type'; protected $fillable = [ self::PHONE, self::ADDRESS, self::ADDRESS_COMPLEMENT, self::POSTAL_CODE, self::CITY, self::REGION, self::COUNTRY, ]; protected $hidden = [ self::CONTACTABLE_ID, self::CONTACTABLE_TYPE, ]; }
murilocosta/huitzilopochtli
app/Contact.php
PHP
gpl-3.0
744
/* -*- c++ -*- * Copyright (C) 2007-2016 Hypertable, Inc. * * This file is part of Hypertable. * * Hypertable 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 any later version. * * Hypertable 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. */ /// @file /// Definitions for UpdatePipeline. /// This file contains type definitions for UpdatePipeline, a three-staged, /// multithreaded update pipeline. #include <Common/Compat.h> #include "UpdatePipeline.h" #include <Hypertable/RangeServer/Global.h> #include <Hypertable/RangeServer/Response/Callback/Update.h> #include <Hypertable/RangeServer/UpdateContext.h> #include <Hypertable/RangeServer/UpdateRecRange.h> #include <Hypertable/RangeServer/UpdateRecTable.h> #include <Hypertable/Lib/ClusterId.h> #include <Hypertable/Lib/RangeServer/Protocol.h> #include <Common/DynamicBuffer.h> #include <Common/FailureInducer.h> #include <Common/Logger.h> #include <Common/Serialization.h> #include <chrono> #include <set> #include <thread> using namespace Hypertable; using namespace Hypertable::RangeServer; using namespace std; UpdatePipeline::UpdatePipeline(ContextPtr &context, QueryCachePtr &query_cache, TimerHandlerPtr &timer_handler, CommitLogPtr &log, Filesystem::Flags flags) : m_context(context), m_query_cache(query_cache), m_timer_handler(timer_handler), m_log(log), m_flags(flags) { m_update_coalesce_limit = m_context->props->get_i64("Hypertable.RangeServer.UpdateCoalesceLimit"); m_maintenance_pause_interval = m_context->props->get_i32("Hypertable.RangeServer.Testing.MaintenanceNeeded.PauseInterval"); m_update_delay = m_context->props->get_i32("Hypertable.RangeServer.UpdateDelay", 0); m_max_clock_skew = m_context->props->get_i32("Hypertable.RangeServer.ClockSkew.Max"); m_threads.reserve(3); m_threads.push_back( thread(&UpdatePipeline::qualify_and_transform, this) ); m_threads.push_back( thread(&UpdatePipeline::commit, this) ); m_threads.push_back( thread(&UpdatePipeline::add_and_respond, this) ); } void UpdatePipeline::add(UpdateContext *uc) { lock_guard<mutex> lock(m_qualify_queue_mutex); m_qualify_queue.push_back(uc); m_qualify_queue_cond.notify_all(); } void UpdatePipeline::shutdown() { m_shutdown = true; m_qualify_queue_cond.notify_all(); m_commit_queue_cond.notify_all(); m_response_queue_cond.notify_all(); for (std::thread &t : m_threads) t.join(); } void UpdatePipeline::qualify_and_transform() { UpdateContext *uc; SerializedKey key; const uint8_t *mod, *mod_end; const char *row; String start_row, end_row; UpdateRecRangeList *rulist; int error = Error::OK; int64_t latest_range_revision; RangeTransferInfo transfer_info; bool transfer_pending; DynamicBuffer *cur_bufp; DynamicBuffer *transfer_bufp; uint32_t go_buf_reset_offset; uint32_t root_buf_reset_offset; CommitLogPtr transfer_log; UpdateRecRange range_update; RangePtr range; std::mutex &mutex = m_qualify_queue_mutex; condition_variable &cond = m_qualify_queue_cond; std::list<UpdateContext *> &queue = m_qualify_queue; while (true) { { unique_lock<std::mutex> lock(mutex); cond.wait(lock, [this, &queue](){ return !queue.empty() || m_shutdown; }); if (m_shutdown) return; uc = queue.front(); queue.pop_front(); } rulist = 0; transfer_bufp = 0; go_buf_reset_offset = 0; root_buf_reset_offset = 0; // This probably shouldn't happen for group commit, but since // it's only for testing purposes, we'll leave it here if (m_update_delay) this_thread::sleep_for(chrono::milliseconds(m_update_delay)); // Global commit log is only available after local recovery uc->auto_revision = Hypertable::get_ts64(); // TODO: Sanity check mod data (checksum validation) // hack to workaround xen timestamp issue if (uc->auto_revision < m_last_revision) uc->auto_revision = m_last_revision; for (UpdateRecTable *table_update : uc->updates) { HT_DEBUG_OUT <<"Update: "<< table_update->id << HT_END; if (!table_update->id.is_system() && m_context->server_state->readonly()) { table_update->error = Error::RANGESERVER_SERVER_IN_READONLY_MODE; continue; } try { if (!m_context->live_map->lookup(table_update->id.id, table_update->table_info)) { table_update->error = Error::TABLE_NOT_FOUND; table_update->error_msg = table_update->id.id; continue; } } catch (Exception &e) { table_update->error = e.code(); table_update->error_msg = e.what(); continue; } // verify schema if (table_update->table_info->get_schema()->get_generation() != table_update->id.generation) { table_update->error = Error::RANGESERVER_GENERATION_MISMATCH; table_update->error_msg = format("Update schema generation mismatch for table %s (received %lld != %lld)", table_update->id.id, (Lld)table_update->id.generation, (Lld)table_update->table_info->get_schema()->get_generation()); continue; } // Pre-allocate the go_buf - each key could expand by 8 or 9 bytes, // if auto-assigned (8 for the ts or rev and maybe 1 for possible // increase in vint length) table_update->go_buf.reserve(table_update->id.encoded_length() + table_update->total_buffer_size + (table_update->total_count * 9)); table_update->id.encode(&table_update->go_buf.ptr); table_update->go_buf.set_mark(); for (UpdateRequest *request : table_update->requests) { uc->total_updates++; mod_end = request->buffer.base + request->buffer.size; mod = request->buffer.base; go_buf_reset_offset = table_update->go_buf.fill(); root_buf_reset_offset = uc->root_buf.fill(); memset(&uc->send_back, 0, sizeof(uc->send_back)); while (mod < mod_end) { key.ptr = mod; row = key.row(); // error inducer for tests/integration/fail-index-mutator if (HT_FAILURE_SIGNALLED("fail-index-mutator-0")) { if (!strcmp(row, "1,+/JzamFvB6rqPqP5yNgI5nreCtZHkT\t\t01501")) { uc->send_back.count++; uc->send_back.error = Error::INDUCED_FAILURE; uc->send_back.offset = mod - request->buffer.base; uc->send_back.len = strlen(row); request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); key.next(); // skip key key.next(); // skip value; mod = key.ptr; continue; } } // If the row key starts with '\0' then the buffer is probably // corrupt, so mark the remaing key/value pairs as bad if (*row == 0) { uc->send_back.error = Error::BAD_KEY; uc->send_back.count = request->count; // fix me !!!! uc->send_back.offset = mod - request->buffer.base; uc->send_back.len = mod_end - mod; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); mod = mod_end; continue; } // Look for containing range, add to stop mods if not found if (!table_update->table_info->find_containing_range(row, range, start_row, end_row) || range->get_relinquish()) { if (uc->send_back.error != Error::RANGESERVER_OUT_OF_RANGE && uc->send_back.count > 0) { uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); } if (uc->send_back.count == 0) { uc->send_back.error = Error::RANGESERVER_OUT_OF_RANGE; uc->send_back.offset = mod - request->buffer.base; } key.next(); // skip key key.next(); // skip value; mod = key.ptr; uc->send_back.count++; continue; } if ((rulist = table_update->range_map[range.get()]) == 0) { rulist = new UpdateRecRangeList(); rulist->range = range; table_update->range_map[range.get()] = rulist; } // See if range has some other error preventing it from receiving updates if ((error = rulist->range->get_error()) != Error::OK) { if (uc->send_back.error != error && uc->send_back.count > 0) { uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); } if (uc->send_back.count == 0) { uc->send_back.error = error; uc->send_back.offset = mod - request->buffer.base; } key.next(); // skip key key.next(); // skip value; mod = key.ptr; uc->send_back.count++; continue; } if (uc->send_back.count > 0) { uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); } /* * Increment update count on range * (block if maintenance in progress) */ if (!rulist->range_blocked) { if (!rulist->range->increment_update_counter()) { uc->send_back.error = Error::RANGESERVER_RANGE_NOT_FOUND; uc->send_back.offset = mod - request->buffer.base; uc->send_back.count++; key.next(); // skip key key.next(); // skip value; mod = key.ptr; continue; } rulist->range_blocked = true; } String range_start_row, range_end_row; rulist->range->get_boundary_rows(range_start_row, range_end_row); // Make sure range didn't just shrink if (range_start_row != start_row || range_end_row != end_row) { rulist->range->decrement_update_counter(); table_update->range_map.erase(rulist->range.get()); delete rulist; continue; } /** Fetch range transfer information **/ { bool wait_for_maintenance; transfer_pending = rulist->range->get_transfer_info(transfer_info, transfer_log, &latest_range_revision, wait_for_maintenance); } if (rulist->transfer_log.get() == 0) rulist->transfer_log = transfer_log; HT_ASSERT(rulist->transfer_log.get() == transfer_log.get()); bool in_transferring_region = false; // Check for clock skew { ByteString tmp_key; const uint8_t *tmp; int64_t difference, tmp_timestamp; tmp_key.ptr = key.ptr; tmp_key.decode_length(&tmp); if ((*tmp & Key::HAVE_REVISION) == 0) { if (latest_range_revision > TIMESTAMP_MIN && uc->auto_revision < latest_range_revision) { tmp_timestamp = Hypertable::get_ts64(); if (tmp_timestamp > uc->auto_revision) uc->auto_revision = tmp_timestamp; if (uc->auto_revision < latest_range_revision) { difference = (int32_t)((latest_range_revision - uc->auto_revision) / 1000LL); if (difference > m_max_clock_skew && !Global::ignore_clock_skew_errors) { request->error = Error::RANGESERVER_CLOCK_SKEW; HT_ERRORF("Clock skew of %lld microseconds exceeds maximum " "(%lld) range=%s", (Lld)difference, (Lld)m_max_clock_skew, rulist->range->get_name().c_str()); uc->send_back.count = 0; request->send_back_vector.clear(); break; } } } } } if (transfer_pending) { transfer_bufp = &rulist->transfer_buf; if (transfer_bufp->empty()) { transfer_bufp->reserve(table_update->id.encoded_length()); table_update->id.encode(&transfer_bufp->ptr); transfer_bufp->set_mark(); } rulist->transfer_buf_reset_offset = rulist->transfer_buf.fill(); } else { transfer_bufp = 0; rulist->transfer_buf_reset_offset = 0; } if (rulist->range->is_root()) { if (uc->root_buf.empty()) { uc->root_buf.reserve(table_update->id.encoded_length()); table_update->id.encode(&uc->root_buf.ptr); uc->root_buf.set_mark(); root_buf_reset_offset = uc->root_buf.fill(); } cur_bufp = &uc->root_buf; } else cur_bufp = &table_update->go_buf; rulist->last_request = request; range_update.bufp = cur_bufp; range_update.offset = cur_bufp->fill(); while (mod < mod_end && (end_row == "" || (strcmp(row, end_row.c_str()) <= 0))) { if (transfer_pending) { if (transfer_info.transferring(row)) { if (!in_transferring_region) { range_update.len = cur_bufp->fill() - range_update.offset; rulist->add_update(request, range_update); cur_bufp = transfer_bufp; range_update.bufp = cur_bufp; range_update.offset = cur_bufp->fill(); in_transferring_region = true; } table_update->transfer_count++; } else { if (in_transferring_region) { range_update.len = cur_bufp->fill() - range_update.offset; rulist->add_update(request, range_update); cur_bufp = &table_update->go_buf; range_update.bufp = cur_bufp; range_update.offset = cur_bufp->fill(); in_transferring_region = false; } } } try { SchemaPtr schema = table_update->table_info->get_schema(); uint8_t family=*(key.ptr+1+strlen((const char *)key.ptr+1)+1); ColumnFamilySpec *cf_spec = schema->get_column_family(family); // reset auto_revision if it's gotten behind if (uc->auto_revision < latest_range_revision) { uc->auto_revision = Hypertable::get_ts64(); if (uc->auto_revision < latest_range_revision) { HT_THROWF(Error::RANGESERVER_REVISION_ORDER_ERROR, "Auto revision (%lld) is less than latest range " "revision (%lld) for range %s", (Lld)uc->auto_revision, (Lld)latest_range_revision, rulist->range->get_name().c_str()); } } // This will transform keys that need to be assigned a // timestamp and/or revision number by re-writing the key // with the added timestamp and/or revision tacked on to the end transform_key(key, cur_bufp, ++uc->auto_revision,&m_last_revision, cf_spec ? cf_spec->get_option_time_order_desc() : false); // Validate revision number if (m_last_revision < latest_range_revision) { if (m_last_revision != uc->auto_revision) { HT_THROWF(Error::RANGESERVER_REVISION_ORDER_ERROR, "Supplied revision (%lld) is less than most recently " "seen revision (%lld) for range %s", (Lld)m_last_revision, (Lld)latest_range_revision, rulist->range->get_name().c_str()); } } } catch (Exception &e) { HT_ERRORF("%s - %s", e.what(), Error::get_text(e.code())); request->error = e.code(); break; } // Now copy the value (with sanity check) mod = key.ptr; key.next(); // skip value HT_ASSERT(key.ptr <= mod_end); cur_bufp->add(mod, key.ptr-mod); mod = key.ptr; table_update->total_added++; if (mod < mod_end) row = key.row(); } if (request->error == Error::OK) { range_update.len = cur_bufp->fill() - range_update.offset; rulist->add_update(request, range_update); // if there were transferring updates, record the latest revision if (transfer_pending && rulist->transfer_buf_reset_offset < rulist->transfer_buf.fill()) { if (rulist->latest_transfer_revision < m_last_revision) rulist->latest_transfer_revision = m_last_revision; } } else { /* * If we drop into here, this means that the request is * being aborted, so reset all of the UpdateRecRangeLists, * reset the go_buf and the root_buf */ for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) (*iter).second->reset_updates(request); table_update->go_buf.ptr = table_update->go_buf.base + go_buf_reset_offset; if (root_buf_reset_offset) uc->root_buf.ptr = uc->root_buf.base + root_buf_reset_offset; uc->send_back.count = 0; mod = mod_end; } range_update.bufp = 0; } transfer_log = 0; if (uc->send_back.count > 0) { uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); } } HT_DEBUGF("Added %d (%d transferring) updates to '%s'", table_update->total_added, table_update->transfer_count, table_update->id.id); if (!table_update->id.is_metadata()) uc->total_added += table_update->total_added; } uc->last_revision = m_last_revision; // Enqueue update { lock_guard<std::mutex> lock(m_commit_queue_mutex); m_commit_queue.push_back(uc); m_commit_queue_cond.notify_all(); m_commit_queue_count++; } } } void UpdatePipeline::commit() { UpdateContext *uc; SerializedKey key; std::list<UpdateContext *> coalesce_queue; uint64_t coalesce_amount = 0; int error = Error::OK; uint32_t committed_transfer_data; bool log_needs_syncing {}; while (true) { // Dequeue next update { unique_lock<std::mutex> lock(m_commit_queue_mutex); m_commit_queue_cond.wait(lock, [this](){ return !m_commit_queue.empty() || m_shutdown; }); if (m_shutdown) return; uc = m_commit_queue.front(); m_commit_queue.pop_front(); m_commit_queue_count--; } committed_transfer_data = 0; log_needs_syncing = false; // Commit ROOT mutations if (uc->root_buf.ptr > uc->root_buf.mark) { if ((error = Global::root_log->write(ClusterId::get(), uc->root_buf, uc->last_revision, Filesystem::Flags::SYNC)) != Error::OK) { HT_FATALF("Problem writing %d bytes to ROOT commit log - %s", (int)uc->root_buf.fill(), Error::get_text(error)); } } for (UpdateRecTable *table_update : uc->updates) { coalesce_amount += table_update->total_buffer_size; // Iterate through all of the ranges, committing any transferring updates for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) { if ((*iter).second->transfer_buf.ptr > (*iter).second->transfer_buf.mark) { committed_transfer_data += (*iter).second->transfer_buf.ptr - (*iter).second->transfer_buf.mark; if ((error = (*iter).second->transfer_log->write(ClusterId::get(), (*iter).second->transfer_buf, (*iter).second->latest_transfer_revision, m_flags)) != Error::OK) { table_update->error = error; table_update->error_msg = format("Problem writing %d bytes to transfer log", (int)(*iter).second->transfer_buf.fill()); HT_ERRORF("%s - %s", table_update->error_msg.c_str(), Error::get_text(error)); break; } } } if (table_update->error != Error::OK) continue; constexpr uint32_t NO_LOG_SYNC_FLAGS = Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG_SYNC | Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG; if ((table_update->flags & NO_LOG_SYNC_FLAGS) == 0) log_needs_syncing = true; // Commit valid (go) mutations if ((table_update->flags & Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG) == 0 && table_update->go_buf.ptr > table_update->go_buf.mark) { if ((error = m_log->write(ClusterId::get(), table_update->go_buf, uc->last_revision, Filesystem::Flags::NONE)) != Error::OK) { table_update->error_msg = format("Problem writing %d bytes to commit log (%s) - %s", (int)table_update->go_buf.fill(), m_log->get_log_dir().c_str(), Error::get_text(error)); HT_ERRORF("%s", table_update->error_msg.c_str()); table_update->error = error; continue; } } } bool do_sync = false; if (log_needs_syncing) { if (m_commit_queue_count > 0 && coalesce_amount < m_update_coalesce_limit) { coalesce_queue.push_back(uc); continue; } do_sync = true; } else if (!coalesce_queue.empty()) do_sync = true; // Now sync the commit log if needed if (do_sync) { size_t retry_count {}; uc->total_syncs++; while (true) { if (m_flags == Filesystem::Flags::FLUSH) error = m_log->flush(); else if (m_flags == Filesystem::Flags::SYNC) error = m_log->sync(); else error = Error::OK; if (error != Error::OK) { HT_ERRORF("Problem %sing log fragment (%s) - %s", (m_flags == Filesystem::Flags::FLUSH ? "flush" : "sync"), m_log->get_current_fragment_file().c_str(), Error::get_text(error)); if (++retry_count == 6) break; this_thread::sleep_for(chrono::milliseconds(10000)); } else break; } } // Enqueue update { lock_guard<std::mutex> lock(m_response_queue_mutex); coalesce_queue.push_back(uc); while (!coalesce_queue.empty()) { uc = coalesce_queue.front(); coalesce_queue.pop_front(); m_response_queue.push_back(uc); } coalesce_amount = 0; m_response_queue_cond.notify_all(); } } } void UpdatePipeline::add_and_respond() { UpdateContext *uc; SerializedKey key; int error = Error::OK; while (true) { // Dequeue next update { unique_lock<std::mutex> lock(m_response_queue_mutex); m_response_queue_cond.wait(lock, [this](){ return !m_response_queue.empty() || m_shutdown; }); if (m_shutdown) return; uc = m_response_queue.front(); m_response_queue.pop_front(); } /** * Insert updates into Ranges */ for (UpdateRecTable *table_update : uc->updates) { // Iterate through all of the ranges, inserting updates for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) { ByteString value; Key key_comps; for (UpdateRecRange &update : (*iter).second->updates) { Range *rangep = (*iter).first; lock_guard<Range> lock(*rangep); uint8_t *ptr = update.bufp->base + update.offset; uint8_t *end = ptr + update.len; if (!table_update->id.is_metadata()) uc->total_bytes_added += update.len; rangep->add_bytes_written( update.len ); std::set<uint8_t> columns; bool invalidate {}; const char *current_row {}; uint64_t count = 0; while (ptr < end) { key.ptr = ptr; key_comps.load(key); if (current_row == nullptr) current_row = key_comps.row; count++; ptr += key_comps.length; value.ptr = ptr; ptr += value.length(); if (key_comps.column_family_code == 0 && key_comps.flag != FLAG_DELETE_ROW) { HT_ERRORF("Skipping bad key - column family not specified in " "non-delete row update on %s row=%s", table_update->id.id, key_comps.row); continue; } rangep->add(key_comps, value); // invalidate if (m_query_cache) { if (strcmp(current_row, key_comps.row)) { if (invalidate) columns.clear(); m_query_cache->invalidate(table_update->id.id, current_row, columns); columns.clear(); invalidate = false; current_row = key_comps.row; } if (key_comps.flag == FLAG_DELETE_ROW) invalidate = true; else columns.insert(key_comps.column_family_code); } } if (m_query_cache && current_row) { if (invalidate) columns.clear(); m_query_cache->invalidate(table_update->id.id, current_row, columns); } rangep->add_cells_written(count); } } } // Decrement usage counters for all referenced ranges for (UpdateRecTable *table_update : uc->updates) { for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) { if ((*iter).second->range_blocked) (*iter).first->decrement_update_counter(); } } /** * wait for these ranges to complete maintenance */ bool maintenance_needed = false; for (UpdateRecTable *table_update : uc->updates) { /* * If any of the newly updated ranges needs maintenance, * schedule immediately */ for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) { if ((*iter).first->need_maintenance() && !Global::maintenance_queue->contains((*iter).first)) { maintenance_needed = true; HT_MAYBE_FAIL_X("metadata-update-and-respond", (*iter).first->is_metadata()); if (m_timer_handler) m_timer_handler->schedule_immediate_maintenance(); break; } } for (UpdateRequest *request : table_update->requests) { Response::Callback::Update cb(m_context->comm, request->event); if (table_update->error != Error::OK) { if ((error = cb.error(table_update->error, table_update->error_msg)) != Error::OK) HT_ERRORF("Problem sending error response - %s", Error::get_text(error)); continue; } if (request->error == Error::OK) { /** * Send back response */ if (!request->send_back_vector.empty()) { StaticBuffer ext(new uint8_t [request->send_back_vector.size() * 16], request->send_back_vector.size() * 16); uint8_t *ptr = ext.base; for (size_t i=0; i<request->send_back_vector.size(); i++) { Serialization::encode_i32(&ptr, request->send_back_vector[i].error); Serialization::encode_i32(&ptr, request->send_back_vector[i].count); Serialization::encode_i32(&ptr, request->send_back_vector[i].offset); Serialization::encode_i32(&ptr, request->send_back_vector[i].len); /* HT_INFOF("Sending back error %x, count %d, offset %d, len %d, table id %s", request->send_back_vector[i].error, request->send_back_vector[i].count, request->send_back_vector[i].offset, request->send_back_vector[i].len, table_update->id.id); */ } if ((error = cb.response(ext)) != Error::OK) HT_ERRORF("Problem sending OK response - %s", Error::get_text(error)); } else { if ((error = cb.response_ok()) != Error::OK) HT_ERRORF("Problem sending OK response - %s", Error::get_text(error)); } } else { if ((error = cb.error(request->error, "")) != Error::OK) HT_ERRORF("Problem sending error response - %s", Error::get_text(error)); } } } { lock_guard<LoadStatistics> lock(*Global::load_statistics); Global::load_statistics->add_update_data(uc->total_updates, uc->total_added, uc->total_bytes_added, uc->total_syncs); } delete uc; // For testing if (m_maintenance_pause_interval > 0 && maintenance_needed) this_thread::sleep_for(chrono::milliseconds(m_maintenance_pause_interval)); } } void UpdatePipeline::transform_key(ByteString &bskey, DynamicBuffer *dest_bufp, int64_t auto_revision, int64_t *revisionp, bool timeorder_desc) { size_t len; const uint8_t *ptr; len = bskey.decode_length(&ptr); HT_ASSERT(*ptr == Key::AUTO_TIMESTAMP || *ptr == Key::HAVE_TIMESTAMP); // if TIME_ORDER DESC was set for this column then we store the timestamps // NOT in 1-complements! if (timeorder_desc) { // if the timestamp was specified by the user: unpack it and pack it // again w/o 1-complement if (*ptr == Key::HAVE_TIMESTAMP) { uint8_t *p=(uint8_t *)ptr+len-8; int64_t ts=Key::decode_ts64((const uint8_t **)&p); p=(uint8_t *)ptr+len-8; Key::encode_ts64((uint8_t **)&p, ts, false); } } dest_bufp->ensure((ptr-bskey.ptr) + len + 9); Serialization::encode_vi32(&dest_bufp->ptr, len+8); memcpy(dest_bufp->ptr, ptr, len); if (*ptr == Key::AUTO_TIMESTAMP) *dest_bufp->ptr = Key::HAVE_REVISION | Key::HAVE_TIMESTAMP | Key::REV_IS_TS; else *dest_bufp->ptr = Key::HAVE_REVISION | Key::HAVE_TIMESTAMP; // if TIME_ORDER DESC then store a flag in the key if (timeorder_desc) *dest_bufp->ptr |= Key::TS_CHRONOLOGICAL; dest_bufp->ptr += len; Key::encode_ts64(&dest_bufp->ptr, auto_revision, timeorder_desc ? false : true); *revisionp = auto_revision; bskey.ptr = ptr + len; }
hypertable/hypertable
src/cc/Hypertable/RangeServer/UpdatePipeline.cc
C++
gpl-3.0
32,361
#!/usr/bin/env python ''' Purpose: This script, using default values, determines and plots the CpG islands in relation to a given feature "type" (e.g. "gene" or "mRNA") from a GFF file which corresponds to the user-provided fasta file. Note: CpG Islands are determined by ObEx = (Observed CpG) / (Expected CpG) , default threshold > 1. Where Expected CpG = (count(C) * count(G)) / WindowSize Usage: python cpg_gene.py FastaFile Gff_File OutFile.png Default optional parameters: -s, Step Size, default = 50 -w, Window Size, default = 200 -oe, Minimum Observed Expected CpG, default = 1 -gc, Minimum GC, default = .5 -r Range from ATG, or provided feature, default = 5000 -f, GFF Feature, default = "gene" -i, Gene ID from GFF, default = "" ''' import sys import os import argparse from collections import Counter from Bio import SeqIO import cpgmod import gffutils import pandas as pd import numpy as np from ggplot import * # Capture command line args, with or without defaults if __name__ == '__main__': # Parse the arguments LineArgs = cpgmod.parseArguments() # Populate vars with args FastaFile = LineArgs.FastaFile GffFile = LineArgs.GffFile OutFile = LineArgs.FileOut Step = LineArgs.s WinSize = LineArgs.w ObExthresh = LineArgs.oe GCthresh = LineArgs.gc StartRange = LineArgs.r FeatGFF = LineArgs.f ID_Feat = LineArgs.i # Gather all possible CpG islands MergedRecs = [] print "Parsing sequences...\n" for SeqRecord in SeqIO.parse(FastaFile, "fasta"): print SeqRecord.id # Determine if sequences and args are acceptable cpgmod.arg_seqcheck(SeqRecord, WinSize, Step) # Pre-determine number of islands NumOfChunks = cpgmod.chunks(SeqRecord, WinSize, Step) # Return array of SeqRec class (potential CpG island) instances SeqRecList = cpgmod.compute(SeqRecord, Step, NumOfChunks, WinSize) MergedRecs = MergedRecs + SeqRecList # Create GFF DB GffDb = gffutils.create_db(GffFile, dbfn='GFF.db', force=True, keep_order=True, merge_strategy='merge', sort_attribute_values=True, disable_infer_transcripts=True, disable_infer_genes=True) print "\nGFF Database Created...\n" # Filter out SeqRec below threshold DistArr = [] for Rec in MergedRecs: Cond1 = Rec.expect() > 0 if Cond1 == True: ObEx = (Rec.observ() / Rec.expect()) Cond2 = ObEx > ObExthresh Cond3 = Rec.gc_cont() > GCthresh if Cond2 and Cond3: # Query GFF DB for closest gene feature *or provided feature* Arr = cpgmod.get_closest(Rec, GffDb, StartRange, FeatGFF, ID_Feat) if Arr <> False: Arr.append(ObEx) DistArr.append(Arr) print "CpG Islands predicted...\n" print "Generating Figure...\n" # Releasing SeqRecs MergedRecs = None SeqRecList = None # Pre-check DistArr Results if len(DistArr) < 2: print "WARNING, "+ str(len(DistArr)) + " sites were found." print "Consider changing parameters.\n" # Generate Figure: ObExRes = pd.DataFrame({ 'gene' : [], 'xval': [], 'yval': []}) try: Cnt = 0 for Dist in DistArr: Cnt += 1 print "PROGRESS: "+str(Cnt) +" of "+ str(len(DistArr)) ObExdf = pd.DataFrame({ 'gene': [Dist[2]], 'xval': [Dist[1]], 'yval': [Dist[3]]}) ObExFram = [ObExRes, ObExdf] ObExRes = pd.concat(ObExFram, ignore_index=True) p = ggplot(aes(x='xval', y='yval'), data=ObExRes) \ + geom_point() \ + ylab("Observed/Expected CpG") \ + xlab("Position (bp) Relative to (ATG = 0)") \ + ggtitle("Predicted CpG Island Position Relative to ATG") p.save(OutFile) except IndexError as e: print 'Error: '+ str(e) sys.exit('Exiting script...') print p # Remove GFF DB os.remove('GFF.db')
juswilliams/bioscripts
CpG_by_feature/cpg_gene.py
Python
gpl-3.0
3,970
// Copyright 2020 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only import * as React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { number } from '@storybook/addon-knobs'; import { LightboxGallery, Props } from './LightboxGallery'; import { setup as setupI18n } from '../../js/modules/i18n'; import enMessages from '../../_locales/en/messages.json'; import { IMAGE_JPEG, VIDEO_MP4 } from '../types/MIME'; const i18n = setupI18n('en', enMessages); const story = storiesOf('Components/LightboxGallery', module); const createProps = (overrideProps: Partial<Props> = {}): Props => ({ close: action('close'), i18n, media: overrideProps.media || [], onSave: action('onSave'), selectedIndex: number('selectedIndex', overrideProps.selectedIndex || 0), }); story.add('Image and Video', () => { const props = createProps({ media: [ { attachment: { contentType: IMAGE_JPEG, fileName: 'tina-rolf-269345-unsplash.jpg', url: '/fixtures/tina-rolf-269345-unsplash.jpg', caption: 'Still from The Lighthouse, starring Robert Pattinson and Willem Defoe.', }, contentType: IMAGE_JPEG, index: 0, message: { attachments: [], id: 'image-msg', received_at: Date.now(), }, objectURL: '/fixtures/tina-rolf-269345-unsplash.jpg', }, { attachment: { contentType: VIDEO_MP4, fileName: 'pixabay-Soap-Bubble-7141.mp4', url: '/fixtures/pixabay-Soap-Bubble-7141.mp4', }, contentType: VIDEO_MP4, index: 1, message: { attachments: [], id: 'video-msg', received_at: Date.now(), }, objectURL: '/fixtures/pixabay-Soap-Bubble-7141.mp4', }, ], }); return <LightboxGallery {...props} />; }); story.add('Missing Media', () => { const props = createProps({ media: [ { attachment: { contentType: IMAGE_JPEG, fileName: 'tina-rolf-269345-unsplash.jpg', url: '/fixtures/tina-rolf-269345-unsplash.jpg', }, contentType: IMAGE_JPEG, index: 0, message: { attachments: [], id: 'image-msg', received_at: Date.now(), }, objectURL: undefined, }, ], }); return <LightboxGallery {...props} />; });
nrizzio/Signal-Desktop
ts/components/LightboxGallery.stories.tsx
TypeScript
gpl-3.0
2,482
// app.photoGrid var Backbone = require("backbone"); // var _ = require("underscore"); var $ = require("jquery"); var ImageGridFuncs = require("./photo_grid_functions"); var ImageCollection = require("../models/photo_grid_image_collection"); var ImageView = require("./photo_grid_image"); module.exports = Backbone.View.extend({ el: '#photo-grid', initialize: function () { "use strict"; if (this.$el.length === 1) { var gridJSON = this.$(".hid"); if (gridJSON.length === 1) { this.funcs = new ImageGridFuncs(); this.template = this.funcs.slideTemplate(); // there is only one allowed div.hid gridJSON = JSON.parse(gridJSON[0].innerHTML); if (gridJSON.spacer_URL && gridJSON.image_URL) { this.model.set({ parentModel: this.model, // pass as reference spacerURL: gridJSON.spacer_URL, imageURL: gridJSON.image_URL, spacers: gridJSON.spacers, images: gridJSON.images, // shuffle image order: imagesShuffled: this.funcs.shuffleArray(gridJSON.images), }); this.setupGrid(); } this.model.on({ 'change:currentSlide': this.modelChange }, this); app.mindbodyModel.on({ 'change:popoverVisible': this.killSlides }, this); } } }, setupGrid: function () { "use strict"; var that = this, spacers = this.model.get("spacers"), randomInt, imageCollection = new ImageCollection(), i; for (i = 0; i < this.model.get("images").length; i += 1) { randomInt = that.funcs.getRandomInt(0, spacers.length); imageCollection.add({ // push some info to individual views: parentModel: this.model, order: i, spacerURL: this.model.get("spacerURL"), spacer: spacers[randomInt], imageURL: this.model.get("imageURL"), image: this.model.get("imagesShuffled")[i], }); } imageCollection.each(this.imageView, this); }, imageView: function (imageModel) { "use strict"; var imageView = new ImageView({model: imageModel}); this.$el.append(imageView.render().el); }, modelChange: function () { "use strict"; var currSlide = this.model.get("currentSlide"), allImages = this.model.get("imageURL"), imageInfo, imageViewer, imgWidth, slideDiv; if (currSlide !== false) { if (app.mindbodyModel.get("popoverVisible") !== true) { app.mindbodyModel.set({popoverVisible : true}); } // retrieve cached DOM object: imageViewer = app.mbBackGroundShader.openPopUp("imageViewer"); // set the stage: imageViewer.html(this.template(this.model.toJSON())); // select div.slide, the ugly way: slideDiv = imageViewer[0].getElementsByClassName("slide")[0]; // pull the array of info about the image: imageInfo = this.model.get("images")[currSlide]; // calculate the size of the image when it fits the slideshow: imgWidth = this.funcs.findSlideSize(imageInfo, slideDiv.offsetWidth, slideDiv.offsetHeight); slideDiv.innerHTML = '<img src="' + allImages + imageInfo.filename + '" style="width: ' + imgWidth + 'px;" />'; } }, killSlides: function () { "use strict"; if (app.mindbodyModel.get("popoverVisible") === false) { // popover is gone. No more slideshow. this.model.set({currentSlide : false}); } }, });
alexkademan/solful-2016-wp
_assets/js/views/photo_grid.js
JavaScript
gpl-3.0
4,143
package ua.pp.shurgent.tfctech.integration.bc.blocks.pipes.transport; import net.minecraft.item.Item; import net.minecraftforge.common.util.ForgeDirection; import ua.pp.shurgent.tfctech.integration.bc.BCStuff; import ua.pp.shurgent.tfctech.integration.bc.ModPipeIconProvider; import ua.pp.shurgent.tfctech.integration.bc.blocks.pipes.handlers.PipeItemsInsertionHandler; import buildcraft.api.core.IIconProvider; import buildcraft.transport.pipes.PipeItemsQuartz; import buildcraft.transport.pipes.events.PipeEventItem; public class PipeItemsSterlingSilver extends PipeItemsQuartz { public PipeItemsSterlingSilver(Item item) { super(item); } @Override public IIconProvider getIconProvider() { return BCStuff.pipeIconProvider; } @Override public int getIconIndex(ForgeDirection direction) { return ModPipeIconProvider.TYPE.PipeItemsSterlingSilver.ordinal(); } public void eventHandler(PipeEventItem.AdjustSpeed event) { super.eventHandler(event); } public void eventHandler(PipeEventItem.Entered event) { event.item.setInsertionHandler(PipeItemsInsertionHandler.INSTANCE); } }
Shurgent/TFCTech
src/main/java/ua/pp/shurgent/tfctech/integration/bc/blocks/pipes/transport/PipeItemsSterlingSilver.java
Java
gpl-3.0
1,104
package org.crazyit.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * Description: * <br/>site: <a href="http://www.crazyit.org">crazyit.org</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class StartActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //»ñȡӦÓóÌÐòÖеÄbn°´Å¥ Button bn = (Button)findViewById(R.id.bn); //Ϊbn°´Å¥°ó¶¨Ê¼þ¼àÌýÆ÷ bn.setOnClickListener(new OnClickListener() { @Override public void onClick(View source) { //´´½¨ÐèÒªÆô¶¯µÄActivity¶ÔÓ¦µÄIntent Intent intent = new Intent(StartActivity.this , SecondActivity.class); //Æô¶¯intent¶ÔÓ¦µÄActivity startActivity(intent); } }); } }
footoflove/android
crazy_android/04/4.1/StartActivity/src/org/crazyit/activity/StartActivity.java
Java
gpl-3.0
1,081
// Remove the particular item function removeArr(arr , removeItem){ if(arr.indexOf(removeItem) > -1){ arr.splice(arr.indexOf(removeItem),1); } return arr; }
SCABER-Dev-Team/SCABER
client-service/js/user_defined_operator.js
JavaScript
gpl-3.0
177
package ru.mos.polls.ourapps.ui.adapter; import java.util.ArrayList; import java.util.List; import ru.mos.polls.base.BaseRecyclerAdapter; import ru.mos.polls.base.RecyclerBaseViewModel; import ru.mos.polls.ourapps.model.OurApplication; import ru.mos.polls.ourapps.vm.item.OurApplicationVM; public class OurAppsAdapter extends BaseRecyclerAdapter<RecyclerBaseViewModel> { public void add(List<OurApplication> list) { List<RecyclerBaseViewModel> rbvm = new ArrayList<>(); for (OurApplication ourApp : list) { rbvm.add(new OurApplicationVM(ourApp)); } addData(rbvm); } }
active-citizen/android.java
app/src/main/java/ru/mos/polls/ourapps/ui/adapter/OurAppsAdapter.java
Java
gpl-3.0
625
using System; namespace SourceCodeCounter.Core { /// <summary> /// The exception that is thrown when a command-line argument is invalid. /// </summary> internal class InvalidArgumentException : Exception { readonly string _argument; public InvalidArgumentException(string argument) : base("Invalid argument: '" + argument + "'") { _argument = argument; } public InvalidArgumentException(string argument, string message) : base(message) { _argument = argument; } public InvalidArgumentException(string argument, string message, Exception inner) : base(message, inner) { _argument = argument; } public InvalidArgumentException(string message, Exception inner) : base(message, inner) { } public string Argument { get { return _argument; } } } }
kkurapaty/SourceCodeCounter
SourceCodeCounter/Core/InvalidArgumentException.cs
C#
gpl-3.0
1,037
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('dashboard/index',['page'=>'Dashboard','breadcrumbs'=>['dashboard/'=>'/home']]); } }
wellingtonfds/cms
app/Http/Controllers/HomeController.php
PHP
gpl-3.0
524
const gal=[//731-62 '1@001/b4avsq1y2i', '1@002/50uvpeo7tb', '1@002/0ypu4wgjxm', '1@002/b61d80e9pf', '1@002/f1kb57t4ul', '1@002/swq38v49nz', '1@002/zeak367fw1', '1@003/nx1ld4j9pe', '1@003/yh0ub5rank', '1@004/j29uftobmh', '1@005/0asu1qo75n', '1@005/4c7bn1q5mx', '1@005/le3vrzbwfs', '1@006/ek0tq9wvny', '1@006/ax21m8tjos', '1@006/w2e3104dp6', '1@007/bsukxlv9j7', '1@007/w5cpl0uvy6', '1@007/l04q3wrucj', '2@007/s2hr6jv7nc', '2@009/31yrxp8waj', '2@009/8josfrbgwi', '2@009/rt4jie1fg8', '2@009/p0va85n4gf', '2@010/i9thzxn50q', '3@010/a6w84ltj02', '3@010/mfyevin3so', '3@010/wdy5qzflnv', '3@011/06wim8bjdp', '3@011/avtd46k9cx', '3@011/80915y2exz', '3@011/vkt4dalwhb', '3@011/znudscat9h', '3@012/18xg4h9s3i', '3@012/120sub86vt', '3@012/5gxj7u0om8', '3@012/95gzec2rsm', '3@012/dihoerqp40', '3@012/nif7secp8l', '3@012/q8awn1iplo', '3@012/ubzfcjte63', '3@013/b9atnq1les', '3@013/zof4tprh73', '3@013/lvdyctgefs', '4@013/c7fgqbsxkn', '4@013/ci9vg76yj5', '4@013/y3v8tjreas', '4@014/75krn9ifbp', '4@014/9tf7n5iexy', '4@014/boz3y1wauf', '4@014/ihqxma938n', '4@014/suxj4yv5w6', '4@014/o19tbsqjxe', '4@014/wy8tx24g0c', '4@015/302u7cs5nx', '4@015/4bo9c8053u', '4@015/8clxnh6eao', '4@015/hbi1d9grwz', '4@015/w8vmtnod7z', '5@016/0yeinjua6h', '5@016/rgpcwv4nym', '5@016/scxjm7ofar'];
Klanly/klanly.github.io
imh/az60.js
JavaScript
gpl-3.0
1,322
// // semaphore.cpp // // Circle - A C++ bare metal environment for Raspberry Pi // Copyright (C) 2021 R. Stange <rsta2@o2online.de> // // 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 <circle/sched/semaphore.h> #include <circle/atomic.h> #include <assert.h> CSemaphore::CSemaphore (unsigned nInitialCount) : m_nCount (nInitialCount), m_Event (TRUE) { assert (m_nCount > 0); } CSemaphore::~CSemaphore (void) { assert (m_nCount > 0); } unsigned CSemaphore::GetState (void) const { return AtomicGet (&m_nCount); } void CSemaphore::Down (void) { while (AtomicGet (&m_nCount) == 0) { m_Event.Wait (); } if (AtomicDecrement (&m_nCount) == 0) { assert (m_Event.GetState ()); m_Event.Clear (); } } void CSemaphore::Up (void) { if (AtomicIncrement (&m_nCount) == 1) { assert (!m_Event.GetState ()); m_Event.Set (); } #if NDEBUG else { assert (m_Event.GetState ()); } #endif } boolean CSemaphore::TryDown (void) { if (AtomicGet (&m_nCount) == 0) { return FALSE; } if (AtomicDecrement (&m_nCount) == 0) { assert (m_Event.GetState ()); m_Event.Clear (); } return TRUE; }
rsta2/circle
lib/sched/semaphore.cpp
C++
gpl-3.0
1,721
import numpy as np from scipy import sparse from scipy.interpolate import interp1d class calibration(object): ''' some useful tools for manual calibration ''' def normalize_zdata(self,z_data,cal_z_data): return z_data/cal_z_data def normalize_amplitude(self,z_data,cal_ampdata): return z_data/cal_ampdata def normalize_phase(self,z_data,cal_phase): return z_data*np.exp(-1j*cal_phase) def normalize_by_func(self,f_data,z_data,func): return z_data/func(f_data) def _baseline_als(self,y, lam, p, niter=10): ''' see http://zanran_storage.s3.amazonaws.com/www.science.uva.nl/ContentPages/443199618.pdf "Asymmetric Least Squares Smoothing" by P. Eilers and H. Boelens in 2005. http://stackoverflow.com/questions/29156532/python-baseline-correction-library "There are two parameters: p for asymmetry and lambda for smoothness. Both have to be tuned to the data at hand. We found that generally 0.001<=p<=0.1 is a good choice (for a trace with positive peaks) and 10e2<=lambda<=10e9, but exceptions may occur." ''' L = len(y) D = sparse.csc_matrix(np.diff(np.eye(L), 2)) w = np.ones(L) for i in range(niter): W = sparse.spdiags(w, 0, L, L) Z = W + lam * D.dot(D.transpose()) z = sparse.linalg.spsolve(Z, w*y) w = p * (y > z) + (1-p) * (y < z) return z def fit_baseline_amp(self,z_data,lam,p,niter=10): ''' for this to work, you need to analyze a large part of the baseline tune lam and p until you get the desired result ''' return self._baseline_als(np.absolute(z_data),lam,p,niter=niter) def baseline_func_amp(self,z_data,f_data,lam,p,niter=10): ''' for this to work, you need to analyze a large part of the baseline tune lam and p until you get the desired result returns the baseline as a function the points in between the datapoints are computed by cubic interpolation ''' return interp1d(f_data, self._baseline_als(np.absolute(z_data),lam,p,niter=niter), kind='cubic') def baseline_func_phase(self,z_data,f_data,lam,p,niter=10): ''' for this to work, you need to analyze a large part of the baseline tune lam and p until you get the desired result returns the baseline as a function the points in between the datapoints are computed by cubic interpolation ''' return interp1d(f_data, self._baseline_als(np.angle(z_data),lam,p,niter=niter), kind='cubic') def fit_baseline_phase(self,z_data,lam,p,niter=10): ''' for this to work, you need to analyze a large part of the baseline tune lam and p until you get the desired result ''' return self._baseline_als(np.angle(z_data),lam,p,niter=niter) def GUIbaselinefit(self): ''' A GUI to help you fit the baseline ''' self.__lam = 1e6 self.__p = 0.9 niter = 10 self.__baseline = self._baseline_als(np.absolute(self.z_data_raw),self.__lam,self.__p,niter=niter) import matplotlib.pyplot as plt from matplotlib.widgets import Slider fig, (ax0,ax1) = plt.subplots(nrows=2) plt.suptitle('Use the sliders to make the green curve match the baseline.') plt.subplots_adjust(left=0.25, bottom=0.25) l0, = ax0.plot(np.absolute(self.z_data_raw)) l0b, = ax0.plot(np.absolute(self.__baseline)) l1, = ax1.plot(np.absolute(self.z_data_raw/self.__baseline)) ax0.set_ylabel('amp, rawdata vs. baseline') ax1.set_ylabel('amp, corrected') axcolor = 'lightgoldenrodyellow' axSmooth = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axAsym = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) axbcorr = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor) sSmooth = Slider(axSmooth, 'Smoothness', 0.1, 10., valinit=np.log10(self.__lam),valfmt='1E%f') sAsym = Slider(axAsym, 'Asymmetry', 1e-4,0.99999, valinit=self.__p,valfmt='%f') sbcorr = Slider(axbcorr, 'vertical shift',0.7,1.1,valinit=1.) def update(val): self.__lam = 10**sSmooth.val self.__p = sAsym.val self.__baseline = sbcorr.val*self._baseline_als(np.absolute(self.z_data_raw),self.__lam,self.__p,niter=niter) l0.set_ydata(np.absolute(self.z_data_raw)) l0b.set_ydata(np.absolute(self.__baseline)) l1.set_ydata(np.absolute(self.z_data_raw/self.__baseline)) fig.canvas.draw_idle() sSmooth.on_changed(update) sAsym.on_changed(update) sbcorr.on_changed(update) plt.show() self.z_data_raw /= self.__baseline plt.close()
vdrhtc/Measurement-automation
resonator_tools/resonator_tools/calibration.py
Python
gpl-3.0
4,324
QUnit.test( "testGetIbanCheckDigits", function( assert ) { assert.equal(getIBANCheckDigits( 'GB00WEST12345698765432' ), '82', 'Get check digits of an IBAN' ); assert.equal(getIBANCheckDigits( '1234567890' ), '', 'If string isn\'t an IBAN, returns empty' ); assert.equal(getIBANCheckDigits( '' ), '', 'If string is empty, returns empty' ); } ); QUnit.test( "testGetGlobalIdentifier", function( assert ) { assert.equal(getGlobalIdentifier( 'G28667152', 'ES', '' ), 'ES55000G28667152', 'Obtain a global Id' ); } ); QUnit.test( "testReplaceCharactersNotInPattern", function( assert ) { assert.equal(replaceCharactersNotInPattern( 'ABC123-?:', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', '0' ), 'ABC123000', 'Remove unwanted characters' ); assert.equal(replaceCharactersNotInPattern( '12345', '0123456789', '0' ), '12345', 'If the string didn\'t have unwanted characters, returns it' ); } ); QUnit.test( "testReplaceLetterWithDigits", function( assert ) { assert.equal(replaceLetterWithDigits( '510007547061BE00' ), '510007547061111400', 'Replaces letters with digits' ); assert.equal(replaceLetterWithDigits( '1234567890' ), '1234567890', 'If we only receive digits, we return them' ); assert.equal(replaceLetterWithDigits( '' ), '', 'If we receive empty, we return empty' ); } ); QUnit.test( "testGetAccountLength", function( assert ) { assert.equal(getAccountLength( 'GB' ), 22, 'Returns tohe string th a SEPA country' ); assert.equal(getAccountLength( 'US' ), 0, 'If string isn\'t a SEPA country code, returns empty' ); assert.equal(getAccountLength( '' ), 0, 'If string is empty, returns empty' ); } ); QUnit.test( "testIsSepaCountry", function( assert ) { assert.equal(isSepaCountry( 'ES' ) , 1, 'Detects SEPA countries' ); assert.equal(isSepaCountry( 'US' ), 0, 'Rejects non SEPA countries' ); assert.equal(isSepaCountry( '' ) , 0, 'If string is empty, returns empty' ); } ); QUnit.test( "testIsValidIban", function( assert ) { assert.equal(isValidIBAN( 'GB82WEST12345698765432' ), 1, 'Accepts a good IBAN' ); assert.equal(isValidIBAN( 'GB00WEST12345698765432' ) , 0, 'Rejects a wrong IBAN' ); assert.equal(isValidIBAN( '' ), 0, 'Rejects empty strings' ); } );
amnesty/dataquality
test/javascript/iban.js
JavaScript
gpl-3.0
2,366
<?php namespace Aqua\SQL; class Search extends Select { /** * @var array */ public $whereOptions = array(); /** * @var array */ public $havingOptions = array(); /** * @param array $where * @param bool $merge * @return static */ public function whereOptions(array $where, $merge = true) { if($merge) { $this->whereOptions = array_merge($this->whereOptions, $where); } else { $this->whereOptions = $where; } return $this; } /** * @param array $having * @param bool $merge * @return static */ public function havingOptions(array $having, $merge = true) { if($merge) { $this->havingOptions = array_merge($this->havingOptions, $having); } else { $this->havingOptions = $having; } return $this; } /** * @param mixed $options * @param $values * @param string $type * @return string|null */ public function parseSearch(&$options, &$values, $type = null) { if($type === 'where') { $columns = & $this->whereOptions; } else { $columns = & $this->havingOptions; } $query = ''; $i = 0; if(!is_array($options)) { return null; } else { foreach($options as $alias => &$value) { if($i % 2) { ++$i; if(is_string($value)) { $v = strtoupper($value); if($v === 'AND' || $v === 'OR') { $query .= "$v "; continue; } } $query .= 'AND '; } if(is_int($alias)) { if(is_string($value)) { $query .= "$value "; ++$i; } else if($q = $this->parseSearch($value, $values, $type)) { $query .= "$q "; ++$i; } } else if(array_key_exists($alias, $columns)) { if(!is_array($value)) { $value = array( self::SEARCH_NATURAL, $value ); } if($this->parseSearchFlags($value, $w, $values, $columns[$alias], $alias)) { $query .= "$w "; ++$i; } } } } if($i === 0) { return null; } $query = preg_replace('/(^\s*(AND|OR)\s*)|(\s*(AND|OR)\s*$)/i', '', $query); if($i === 1) { return $query; } else { return "($query)"; } } public function parseOrder() { if(empty($this->order)) return ''; $order = array(); foreach($this->order as $column => $ord) { if($ord === 'DESC' || $ord === 'ASC') { if(array_key_exists($column, $this->columns)) { $column = $this->columns[$column]; } $order[] = "$column $ord"; } else { if(array_key_exists($ord, $this->columns)) { $ord = $this->columns[$ord]; } $order[] = $ord; } } if(empty($order)) return ''; else return 'ORDER BY ' . implode(', ', $order); } }
AquaCore/AquaCore
lib/Aqua/SQL/Search.php
PHP
gpl-3.0
2,598
/* * SPDX-License-Identifier: GPL-3.0 * * * (J)ava (M)iscellaneous (U)tilities (L)ibrary * * JMUL is a central repository for utilities which are used in my * other public and private repositories. * * Copyright (C) 2013 Kristian Kutin * * 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/>. * * e-mail: kristian.kutin@arcor.de */ /* * This section contains meta informations. * * $Id$ */ package jmul.transformation.xml.rules.xml2object; import jmul.misc.id.ID; import jmul.misc.id.IntegerID; import jmul.reflection.classes.ClassDefinition; import jmul.reflection.classes.ClassHelper; import jmul.string.TextHelper; import jmul.transformation.TransformationException; import jmul.transformation.TransformationParameters; import jmul.transformation.TransformationRuleBase; import jmul.transformation.xml.cache.Xml2ObjectCache; import static jmul.transformation.xml.rules.PersistenceMarkups.ID_ATTRIBUTE; import static jmul.transformation.xml.rules.PersistenceMarkups.OBJECT_ELEMENT; import static jmul.transformation.xml.rules.PersistenceMarkups.TYPE_ATTRIBUTE; import static jmul.transformation.xml.rules.PersistenceMarkups.VALUE_ATTRIBUTE; import static jmul.transformation.xml.rules.TransformationConstants.OBJECT_CACHE; import jmul.xml.XmlParserHelper; import org.w3c.dom.Node; /** * An implementation of a transformation rule. * * @author Kristian Kutin */ public class Xml2ClassRule extends TransformationRuleBase { /** * A class name. */ private static final String EXPECTED_TYPE_NAME = Class.class.getName(); /** * Constructs a transformation rule. * * @param anOrigin * a description of the transformation origin * @param aDestination * a description of the transformation destination * @param aPriority * a rule priority */ public Xml2ClassRule(String anOrigin, String aDestination, int aPriority) { super(anOrigin, aDestination, aPriority); } /** * The method determines if this rule can be applied to the specified * object. * * @param someParameters * some transformation parameters, including the object which is to * be transformed * * @return <code>true</code> if the rule is applicable, else * <code>false</code> */ @Override public boolean isApplicable(TransformationParameters someParameters) { return RuleHelper.isApplicable(someParameters, EXPECTED_TYPE_NAME); } /** * The method performs the actual transformation. * * @param someParameters * some transformation parameters, including the object which is to * be transformed * * @return the transformed object */ @Override public Object transform(TransformationParameters someParameters) { // Check some plausibilites first. if (!someParameters.containsPrerequisite(OBJECT_CACHE)) { String message = TextHelper.concatenateStrings("Prerequisites for the transformation are missing (", OBJECT_CACHE, ")!"); throw new TransformationException(message); } Object target = someParameters.getObject(); Node objectElement = (Node) target; XmlParserHelper.assertMatchesXmlElement(objectElement, OBJECT_ELEMENT); XmlParserHelper.assertExistsXmlAttribute(objectElement, ID_ATTRIBUTE); XmlParserHelper.assertExistsXmlAttribute(objectElement, TYPE_ATTRIBUTE); XmlParserHelper.assertExistsXmlAttribute(objectElement, VALUE_ATTRIBUTE); // Get the required informations. Xml2ObjectCache objectCache = (Xml2ObjectCache) someParameters.getPrerequisite(OBJECT_CACHE); String idString = XmlParserHelper.getXmlAttributeValue(objectElement, ID_ATTRIBUTE); String typeString = XmlParserHelper.getXmlAttributeValue(objectElement, TYPE_ATTRIBUTE); String valueString = XmlParserHelper.getXmlAttributeValue(objectElement, VALUE_ATTRIBUTE); ID id = new IntegerID(idString); ClassDefinition type = null; try { type = ClassHelper.getClass(typeString); } catch (ClassNotFoundException e) { String message = TextHelper.concatenateStrings("An unknown class was specified (", typeString, ")!"); throw new TransformationException(message, e); } Class clazz = null; try { ClassDefinition definition = ClassHelper.getClass(valueString); clazz = definition.getType(); } catch (ClassNotFoundException e) { String message = TextHelper.concatenateStrings("An unknown class was specified (", valueString, ")!"); throw new TransformationException(message, e); } // Instantiate and initialize the specified object objectCache.addObject(id, clazz, type.getType()); return clazz; } }
gammalgris/jmul
Utilities/Transformation-XML/src/jmul/transformation/xml/rules/xml2object/Xml2ClassRule.java
Java
gpl-3.0
5,570
Bitrix 16.5 Business Demo = bf14f0c5bad016e66d0ed2d224b15630
gohdan/DFC
known_files/hashes/bitrix/modules/main/install/js/main/amcharts/3.11/lang/hr.min.js
JavaScript
gpl-3.0
61
## mostly copied from: http://norvig.com/spell-correct.html import sys, random import re, collections, time TXT_FILE=''; BUF_DIR=''; NWORDS=None; def words(text): return re.findall('[a-z]+', text) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) ####################################################################################### if __name__ == '__main__': TXT_FILE = sys.argv[1] t0 = time.clock() o_words = words(file(TXT_FILE).read()) NWORDS = train(o_words) #print time.clock() - t0, " seconds build time" #print "dictionary size: %d" %len(NWORDS) et1 = time.clock() - t0 t_count = 10 rl = o_words[0:t_count] #random.sample(o_words, t_count) orl = [''.join(random.sample(word, len(word))) for word in o_words] t1 = time.clock() r_count = 10 for i in range(0, r_count): for w1, w2 in zip(rl, orl): correct(w1); correct(w2) et2 = (time.clock() - t1)/t_count/r_count/2 print '%d\t%f\t%f' %(len(NWORDS), et1, et2) ####################################################################################### print 'Done'
xulesc/spellchecker
impl1.py
Python
gpl-3.0
1,898
package com.baeldung.webflux; import static java.time.LocalDateTime.now; import static java.util.UUID.randomUUID; import java.time.Duration; import org.springframework.stereotype.Component; import org.springframework.web.reactive.socket.WebSocketHandler; import org.springframework.web.reactive.socket.WebSocketSession; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Component("EmployeeWebSocketHandler") public class EmployeeWebSocketHandler implements WebSocketHandler { ObjectMapper om = new ObjectMapper(); @Override public Mono<Void> handle(WebSocketSession webSocketSession) { Flux<String> employeeCreationEvent = Flux.generate(sink -> { EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString()); try { sink.next(om.writeValueAsString(event)); } catch (JsonProcessingException e) { sink.error(e); } }); return webSocketSession.send(employeeCreationEvent .map(webSocketSession::textMessage) .delayElements(Duration.ofSeconds(1))); } }
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java
Java
gpl-3.0
1,272
describe SearchController, type: :controller do it { is_expected.to route(:get, '/search').to(action: :basic) } it { is_expected.to route(:get, '/search/entity').to(action: :entity_search) } describe "GET #entity_search" do login_user let(:org) { build(:org) } def search_service_double instance_double('EntitySearchService').tap do |d| d.instance_variable_set(:@search, [org]) end end it 'returns http status bad_request if missing param q' do get :entity_search expect(response).to have_http_status(:bad_request) end it "returns http success" do allow(Entity).to receive(:search).with("@(name,aliases) name", any_args).and_return([org]) get :entity_search, params: { :q => 'name' } expect(response).to have_http_status(:success) end it "hash includes url by default" do allow(Entity).to receive(:search).with("@(name,aliases) name", any_args).and_return([org]) get :entity_search, params: { :q => 'name' } expect(JSON.parse(response.body)[0]['url']).to include "/org/#{org.id}" expect(JSON.parse(response.body)[0]).not_to have_key "is_parent" end it "hash can optionally include parent" do allow(Entity).to receive(:search).with("@(name,aliases) name", any_args).and_return([org]) expect(org).to receive(:parent?).once.and_return(false) get :entity_search, params: { :q => 'name', include_parent: true } expect(JSON.parse(response.body)[0]['is_parent']).to eq false end end end
public-accountability/littlesis-rails
spec/controllers/search_controller_spec.rb
Ruby
gpl-3.0
1,540
<?php namespace App\Model; use PDO; use Exception; use App\Model; use App\Config; use App\Exceptions\ServerException; use App\Exceptions\DatabaseInsertException; class Account extends Model { public $id; public $name; public $email; public $service; public $password; public $is_active; public $imap_host; public $imap_port; public $smtp_host; public $smtp_port; public $imap_flags; public $created_at; public function getData() { return [ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email, 'service' => $this->service, 'password' => $this->password, 'is_active' => $this->is_active, 'imap_host' => $this->imap_host, 'imap_port' => $this->imap_port, 'smtp_host' => $this->smtp_host, 'smtp_port' => $this->smtp_port, 'imap_flags' => $this->imap_flags, 'created_at' => $this->created_at ]; } public function getActive() { return $this->db() ->select() ->from('accounts') ->where('is_active', '=', 1) ->execute() ->fetchAll(PDO::FETCH_CLASS, get_class()); } public function getFirstActive() { $active = $this->getActive(); return $active ? current($active) : null; } public function getByEmail(string $email) { $account = $this->db() ->select() ->from('accounts') ->where('email', '=', $email) ->execute() ->fetchObject(); return $account ? new self($account) : null; } public function fromAddress() { return $this->name ? sprintf('%s <%s>', $this->name, $this->email) : $this->email; } public function hasFolders() { return (new Folder)->countByAccount($this->id) > 0; } /** * Updates the account configuration. */ public function update( string $email, string $password, string $name, string $imapHost, int $imapPort, string $smtpHost, int $smtpPort ) { if (! $this->exists()) { return false; } $updated = $this->db() ->update([ 'name' => trim($name), 'email' => trim($email), 'password' => trim($password), 'imap_host' => trim($imapHost), 'imap_port' => trim($imapPort), 'smtp_host' => trim($smtpHost), 'smtp_port' => trim($smtpPort) ]) ->table('accounts') ->where('id', '=', $this->id) ->execute(); return is_numeric($updated) ? $updated : false; } /** * Creates a new account with the class data. This is done only * after the IMAP credentials are tested to be working. * * @throws ServerException * * @return Account */ public function create() { // Exit if it already exists! if ($this->exists()) { return false; } $service = Config::getEmailService($this->email); list($imapHost, $imapPort) = Config::getImapSettings($this->email); if ($imapHost) { $this->imap_host = $imapHost; $this->imap_port = $imapPort; } $data = [ 'is_active' => 1, 'service' => $service, 'name' => trim($this->name), 'email' => trim($this->email), 'password' => trim($this->password), 'imap_host' => trim($this->imap_host), 'imap_port' => trim($this->imap_port), 'smtp_host' => trim($this->smtp_host), 'smtp_port' => trim($this->smtp_port), 'created_at' => $this->utcDate()->format(DATE_DATABASE) ]; try { // Start a transaction to prevent storing bad data $this->db()->beginTransaction(); $newAccountId = $this->db() ->insert(array_keys($data)) ->into('accounts') ->values(array_values($data)) ->execute(); if (! $newAccountId) { throw new DatabaseInsertException; } $this->db()->commit(); // Saved to the database } catch (Exception $e) { $this->db()->rollback(); throw new ServerException( 'Failed creating new account. '.$e->getMessage() ); } $this->id = $newAccountId; return $this; } }
mikegioia/libremail
webmail/src/Model/Account.php
PHP
gpl-3.0
4,773
class Global_var_WeaponGUI { idd=-1; movingenable=false; class controls { class Global_var_WeaponGUI_Frame: RscFrame { idc = -1; x = 0.365937 * safezoneW + safezoneX; y = 0.379 * safezoneH + safezoneY; w = 0.170156 * safezoneW; h = 0.143 * safezoneH; }; class Global_var_WeaponGUI_Background: Box { idc = -1; x = 0.365937 * safezoneW + safezoneX; y = 0.379 * safezoneH + safezoneY; w = 0.170156 * safezoneW; h = 0.143 * safezoneH; }; class Global_var_WeaponGUI_Text: RscText { idc = -1; text = "Waffenauswahl"; //--- ToDo: Localize; x = 0.365937 * safezoneW + safezoneX; y = 0.39 * safezoneH + safezoneY; w = 0.0773437 * safezoneW; h = 0.022 * safezoneH; }; class Global_var_WeaponGUI_Combo: RscCombo { idc = 2100; x = 0.371094 * safezoneW + safezoneX; y = 0.445 * safezoneH + safezoneY; w = 0.159844 * safezoneW; h = 0.022 * safezoneH; }; class Global_var_WeaponGUI_Button_OK: RscButton { idc = 2101; text = "OK"; //--- ToDo: Localize; x = 0.371094 * safezoneW + safezoneX; y = 0.489 * safezoneH + safezoneY; w = 0.0773437 * safezoneW; h = 0.022 * safezoneH; action = "(lbText [2100, lbCurSel 2100]) execVM ""Ammo\Dialog.sqf"";closeDialog 1;"; }; class Global_var_WeaponGUI_Button_Cancel: RscButton { idc = 2102; text = "Abbruch"; //--- ToDo: Localize; x = 0.453594 * safezoneW + safezoneX; y = 0.489 * safezoneH + safezoneY; w = 0.0773437 * safezoneW; h = 0.022 * safezoneH; action = "closeDialog 2;"; }; }; };
Rockhount/ArmA3_Event_TheOutbreak
The_Outbreak2.Altis/Ammo/dialogs.hpp
C++
gpl-3.0
1,558
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class inkMenuAccountLogicController : inkWidgetLogicController { [Ordinal(1)] [RED("playerId")] public inkTextWidgetReference PlayerId { get; set; } [Ordinal(2)] [RED("changeAccountLabelTextRef")] public inkTextWidgetReference ChangeAccountLabelTextRef { get; set; } [Ordinal(3)] [RED("inputDisplayControllerRef")] public inkWidgetReference InputDisplayControllerRef { get; set; } [Ordinal(4)] [RED("changeAccountEnabled")] public CBool ChangeAccountEnabled { get; set; } public inkMenuAccountLogicController(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/inkMenuAccountLogicController.cs
C#
gpl-3.0
733
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2018 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Application mirrorMesh Description Mirrors a mesh around a given plane. \*---------------------------------------------------------------------------*/ #include "argList.H" #include "Time.H" #include "mirrorFvMesh.H" #include "mapPolyMesh.H" #include "hexRef8Data.H" using namespace Foam; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // int main(int argc, char *argv[]) { #include "addOverwriteOption.H" #include "addDictOption.H" #include "setRootCase.H" #include "createTime.H" const bool overwrite = args.optionFound("overwrite"); const word dictName ( args.optionLookupOrDefault<word>("dict", "mirrorMeshDict") ); mirrorFvMesh mesh ( IOobject ( mirrorFvMesh::defaultRegion, runTime.constant(), runTime ), dictName ); hexRef8Data refData ( IOobject ( "dummy", mesh.facesInstance(), polyMesh::meshSubDir, mesh, IOobject::READ_IF_PRESENT, IOobject::NO_WRITE, false ) ); if (!overwrite) { runTime++; mesh.setInstance(runTime.timeName()); } // Set the precision of the points data to 10 IOstream::defaultPrecision(max(10u, IOstream::defaultPrecision())); // Generate the mirrored mesh const fvMesh& mMesh = mesh.mirrorMesh(); const_cast<fvMesh&>(mMesh).setInstance(mesh.facesInstance()); Info<< "Writing mirrored mesh" << endl; mMesh.write(); // Map the hexRef8 data mapPolyMesh map ( mesh, mesh.nPoints(), // nOldPoints, mesh.nFaces(), // nOldFaces, mesh.nCells(), // nOldCells, mesh.pointMap(), // pointMap, List<objectMap>(0), // pointsFromPoints, labelList(0), // faceMap, List<objectMap>(0), // facesFromPoints, List<objectMap>(0), // facesFromEdges, List<objectMap>(0), // facesFromFaces, mesh.cellMap(), // cellMap, List<objectMap>(0), // cellsFromPoints, List<objectMap>(0), // cellsFromEdges, List<objectMap>(0), // cellsFromFaces, List<objectMap>(0), // cellsFromCells, labelList(0), // reversePointMap, labelList(0), // reverseFaceMap, labelList(0), // reverseCellMap, labelHashSet(0), // flipFaceFlux, labelListList(0), // patchPointMap, labelListList(0), // pointZoneMap, labelListList(0), // faceZonePointMap, labelListList(0), // faceZoneFaceMap, labelListList(0), // cellZoneMap, pointField(0), // preMotionPoints, labelList(0), // oldPatchStarts, labelList(0), // oldPatchNMeshPoints, autoPtr<scalarField>() // oldCellVolumesPtr ); refData.updateMesh(map); refData.write(); Info<< "End" << endl; return 0; } // ************************************************************************* //
will-bainbridge/OpenFOAM-dev
applications/utilities/mesh/manipulation/mirrorMesh/mirrorMesh.C
C++
gpl-3.0
4,304
#include "Data/datadescriptor.h" #include <type_traits> #include <QDebug> unsigned int DataDescriptor::_uid_ctr = 0; DataDescriptor::DataDescriptor(QString name, QString unit, double factor, Type t) : _name(name), _unit(unit), _factor(factor), _type(t) { _uuid = getUUID(); } DataDescriptor::DataDescriptor(const QJsonObject &jo) { _uuid = getUUID(); _name = jo["name"].toString(); _unit = jo["unit"].toString(); _factor = jo["factor"].toDouble(); _type = static_cast<Type>(jo["type"].toInt()); } DataDescriptor::Type DataDescriptor::typeFromId(quint8 id) { switch (id) { case 0: return Type::CHAR; case 1: return Type::FLOAT; case 2: return Type::UINT16T; case 3: return Type::BIGLITTLE; default: return Type::UINT32T; } } QString DataDescriptor::str() const { QString test("%1 [%2] * %3"); return test.arg(_name,_unit,QString::number(_factor)); } unsigned int DataDescriptor::getUUID() { return _uid_ctr++; } QJsonObject DataDescriptor::json() const { QJsonObject json; json["name"] = _name; json["unit"] = _unit; json["factor"] = _factor; json["type"] = static_cast<std::underlying_type<Type>::type>(_type); return json; }
TUD-OS/OdroidReader
Data/datadescriptor.cpp
C++
gpl-3.0
1,161
/* ----------------------------------------------------------------------- Copyright: 2010-2015, iMinds-Vision Lab, University of Antwerp 2014-2015, CWI, Amsterdam Contact: astra@uantwerpen.be Website: http://sf.net/projects/astra-toolbox This file is part of the ASTRA Toolbox. The ASTRA Toolbox 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. The ASTRA Toolbox 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 the ASTRA Toolbox. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------- $Id$ */ #ifdef ASTRA_CUDA #include "astra/CudaEMAlgorithm.h" #include "../cuda/2d/em.h" using namespace std; namespace astra { // type of the algorithm, needed to register with CAlgorithmFactory std::string CCudaEMAlgorithm::type = "EM_CUDA"; //---------------------------------------------------------------------------------------- // Constructor CCudaEMAlgorithm::CCudaEMAlgorithm() { m_bIsInitialized = false; CCudaReconstructionAlgorithm2D::_clear(); } //---------------------------------------------------------------------------------------- // Destructor CCudaEMAlgorithm::~CCudaEMAlgorithm() { // The actual work is done by ~CCudaReconstructionAlgorithm2D } //--------------------------------------------------------------------------------------- // Initialize - Config bool CCudaEMAlgorithm::initialize(const Config& _cfg) { ASTRA_ASSERT(_cfg.self); ConfigStackCheck<CAlgorithm> CC("CudaEMAlgorithm", this, _cfg); m_bIsInitialized = CCudaReconstructionAlgorithm2D::initialize(_cfg); if (!m_bIsInitialized) return false; m_pAlgo = new astraCUDA::EM(); m_bAlgoInit = false; return true; } //--------------------------------------------------------------------------------------- // Initialize - C++ bool CCudaEMAlgorithm::initialize(CProjector2D* _pProjector, CFloat32ProjectionData2D* _pSinogram, CFloat32VolumeData2D* _pReconstruction) { m_bIsInitialized = CCudaReconstructionAlgorithm2D::initialize(_pProjector, _pSinogram, _pReconstruction); if (!m_bIsInitialized) return false; m_pAlgo = new astraCUDA::EM(); m_bAlgoInit = false; return true; } } // namespace astra #endif // ASTRA_CUDA
mohamedadaly/trex
src/CudaEMAlgorithm.cpp
C++
gpl-3.0
2,709
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015 Daniel Rodriguez # # 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/>. # ############################################################################### from __future__ import (absolute_import, division, print_function, unicode_literals) import collections import six from .comminfo import CommissionInfo from .position import Position from .metabase import MetaParams from .order import Order, BuyOrder, SellOrder class BrokerBack(six.with_metaclass(MetaParams, object)): params = (('cash', 10000.0), ('commission', CommissionInfo()),) def __init__(self): self.comminfo = dict() self.init() def init(self): if None not in self.comminfo.keys(): self.comminfo = dict({None: self.p.commission}) self.startingcash = self.cash = self.p.cash self.orders = list() # will only be appending self.pending = collections.deque() # popleft and append(right) self.positions = collections.defaultdict(Position) self.notifs = collections.deque() def getcash(self): return self.cash def setcash(self, cash): self.startingcash = self.cash = self.p.cash = cash def getcommissioninfo(self, data): if data._name in self.comminfo: return self.comminfo[data._name] return self.comminfo[None] def setcommission(self, commission=0.0, margin=None, mult=1.0, name=None): comm = CommissionInfo(commission=commission, margin=margin, mult=mult) self.comminfo[name] = comm def addcommissioninfo(self, comminfo, name=None): self.comminfo[name] = comminfo def start(self): self.init() def stop(self): pass def cancel(self, order): try: self.pending.remove(order) except ValueError: # If the list didn't have the element we didn't cancel anything return False order.cancel() self.notify(order) return True def getvalue(self, datas=None): pos_value = 0.0 for data in datas or self.positions.keys(): comminfo = self.getcommissioninfo(data) position = self.positions[data] pos_value += comminfo.getvalue(position, data.close[0]) return self.cash + pos_value def getposition(self, data): return self.positions[data] def submit(self, order): # FIXME: When an order is submitted, a margin check # requirement has to be done before it can be accepted. This implies # going over the entire list of pending orders for all datas and # existing positions, simulating order execution and ending up # with a "cash" figure that can be used to check the margin requirement # of the order. If not met, the order can be immediately rejected order.pannotated = None order.plen = len(order.data) order.accept() self.orders.append(order) self.pending.append(order) self.notify(order) return order def buy(self, owner, data, size, price=None, plimit=None, exectype=None, valid=None): order = BuyOrder(owner=owner, data=data, size=size, price=price, pricelimit=plimit, exectype=exectype, valid=valid) return self.submit(order) def sell(self, owner, data, size, price=None, plimit=None, exectype=None, valid=None): order = SellOrder(owner=owner, data=data, size=size, price=price, pricelimit=plimit, exectype=exectype, valid=valid) return self.submit(order) def _execute(self, order, dt, price): # Orders are fully executed, get operation size size = order.executed.remsize # Get comminfo object for the data comminfo = self.getcommissioninfo(order.data) # Adjust position with operation size position = self.positions[order.data] oldpprice = position.price psize, pprice, opened, closed = position.update(size, price) abopened, abclosed = abs(opened), abs(closed) # if part/all of a position has been closed, then there has been # a profitandloss ... record it pnl = comminfo.profitandloss(abclosed, oldpprice, price) if closed: # Adjust to returned value for closed items & acquired opened items closedvalue = comminfo.getoperationcost(abclosed, price) self.cash += closedvalue # Calculate and substract commission closedcomm = comminfo.getcomm_pricesize(abclosed, price) self.cash -= closedcomm # Re-adjust cash according to future-like movements # Restore cash which was already taken at the start of the day self.cash -= comminfo.cashadjust(abclosed, price, order.data.close[0]) # pnl = comminfo.profitandloss(oldpsize, oldpprice, price) else: closedvalue = closedcomm = 0.0 if opened: openedvalue = comminfo.getoperationcost(abopened, price) self.cash -= openedvalue openedcomm = comminfo.getcomm_pricesize(abopened, price) self.cash -= openedcomm # Remove cash for the new opened contracts self.cash += comminfo.cashadjust(abopened, price, order.data.close[0]) else: openedvalue = openedcomm = 0.0 # Execute and notify the order order.execute(dt, size, price, closed, closedvalue, closedcomm, opened, openedvalue, openedcomm, comminfo.margin, pnl, psize, pprice) self.notify(order) def notify(self, order): self.notifs.append(order.clone()) def next(self): for data, pos in self.positions.items(): # futures change cash in the broker in every bar # to ensure margin requirements are met comminfo = self.getcommissioninfo(data) self.cash += comminfo.cashadjust(pos.size, data.close[-1], data.close[0]) # Iterate once over all elements of the pending queue for i in range(len(self.pending)): order = self.pending.popleft() if order.expire(): self.notify(order) continue popen = order.data.tick_open or order.data.open[0] phigh = order.data.tick_high or order.data.high[0] plow = order.data.tick_low or order.data.low[0] pclose = order.data.tick_close or order.data.close[0] pcreated = order.created.price plimit = order.created.pricelimit if order.exectype == Order.Market: self._execute(order, order.data.datetime[0], price=popen) elif order.exectype == Order.Close: self._try_exec_close(order, pclose) elif order.exectype == Order.Limit: self._try_exec_limit(order, popen, phigh, plow, pcreated) elif order.exectype == Order.StopLimit and order.triggered: self._try_exec_limit(order, popen, phigh, plow, plimit) elif order.exectype == Order.Stop: self._try_exec_stop(order, popen, phigh, plow, pcreated) elif order.exectype == Order.StopLimit: self._try_exec_stoplimit(order, popen, phigh, plow, pclose, pcreated, plimit) if order.alive(): self.pending.append(order) def _try_exec_close(self, order, pclose): if len(order.data) > order.plen: dt0 = order.data.datetime[0] if dt0 > order.dteos: if order.pannotated: execdt = order.data.datetime[-1] execprice = pannotated else: execdt = dt0 execprice = pclose self._execute(order, execdt, price=execprice) return # If no exexcution has taken place ... annotate the closing price order.pannotated = pclose def _try_exec_limit(self, order, popen, phigh, plow, plimit): if order.isbuy(): if plimit >= popen: # open smaller/equal than requested - buy cheaper self._execute(order, order.data.datetime[0], price=popen) elif plimit >= plow: # day low below req price ... match limit price self._execute(order, order.data.datetime[0], price=plimit) else: # Sell if plimit <= popen: # open greater/equal than requested - sell more expensive self._execute(order, order.data.datetime[0], price=popen) elif plimit <= phigh: # day high above req price ... match limit price self._execute(order, order.data.datetime[0], price=plimit) def _try_exec_stop(self, order, popen, phigh, plow, pcreated): if order.isbuy(): if popen >= pcreated: # price penetrated with an open gap - use open self._execute(order, order.data.datetime[0], price=popen) elif phigh >= pcreated: # price penetrated during the session - use trigger price self._execute(order, order.data.datetime[0], price=pcreated) else: # Sell if popen <= pcreated: # price penetrated with an open gap - use open self._execute(order, order.data.datetime[0], price=popen) elif plow <= pcreated: # price penetrated during the session - use trigger price self._execute(order, order.data.datetime[0], price=pcreated) def _try_exec_stoplimit(self, order, popen, phigh, plow, pclose, pcreated, plimit): if order.isbuy(): if popen >= pcreated: order.triggered = True # price penetrated with an open gap if plimit >= popen: self._execute(order, order.data.datetime[0], price=popen) elif plimit >= plow: # execute in same bar self._execute(order, order.data.datetime[0], price=plimit) elif phigh >= pcreated: # price penetrated upwards during the session order.triggered = True # can calculate execution for a few cases - datetime is fixed dt = order.data.datetime[0] if popen > pclose: if plimit >= pcreated: self._execute(order, dt, price=pcreated) elif plimit >= pclose: self._execute(order, dt, price=plimit) else: # popen < pclose if plimit >= pcreated: self._execute(order, dt, price=pcreated) else: # Sell if popen <= pcreated: # price penetrated downwards with an open gap order.triggered = True if plimit <= open: self._execute(order, order.data.datetime[0], price=popen) elif plimit <= phigh: # execute in same bar self._execute(order, order.data.datetime[0], price=plimit) elif plow <= pcreated: # price penetrated downwards during the session order.triggered = True # can calculate execution for a few cases - datetime is fixed dt = order.data.datetime[0] if popen <= pclose: if plimit <= pcreated: self._execute(order, dt, price=pcreated) elif plimit <= pclose: self._execute(order, dt, price=plimit) else: # popen > pclose if plimit <= pcreated: self._execute(order, dt, price=pcreated)
gnagel/backtrader
backtrader/broker.py
Python
gpl-3.0
13,299
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.mariotaku.twidere.util.http; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.microedition.io.Connector; import javax.microedition.io.SecurityInfo; import javax.microedition.io.SocketConnection; import javax.microedition.io.StreamConnection; import repackaged.com.sun.midp.pki.X509Certificate; import repackaged.com.sun.midp.ssl.SSLStreamConnection; /** * * @author mariotaku */ public final class UnsafeSSLConnection implements StreamConnection { private final SSLStreamConnection sc; UnsafeSSLConnection(final String host, final int port) throws IOException { final SocketConnection tcp = (SocketConnection) Connector.open("socket://" + host + ":" + port); tcp.setSocketOption(SocketConnection.DELAY, 0); final InputStream tcpIn = tcp.openInputStream(); final OutputStream tcpOut = tcp.openOutputStream(); sc = new SSLStreamConnection(host, port, tcpIn, tcpOut); } public synchronized OutputStream openOutputStream() throws IOException { return sc.openOutputStream(); } public synchronized InputStream openInputStream() throws IOException { return sc.openInputStream(); } public DataOutputStream openDataOutputStream() throws IOException { return sc.openDataOutputStream(); } public DataInputStream openDataInputStream() throws IOException { return sc.openDataInputStream(); } public X509Certificate getServerCertificate() { return sc.getServerCertificate(); } public SecurityInfo getSecurityInfo() throws IOException { return sc.getSecurityInfo(); } public synchronized void close() throws IOException { sc.close(); } public static UnsafeSSLConnection open(final String host, final int port) throws IOException { if (host == null && port < 0) { return new UnsafeSSLConnection("127.0.0.1", 443); } else if (host != null) { return new UnsafeSSLConnection(host, 443); } return new UnsafeSSLConnection(host, port); } }
mariotaku/twidere.j2me
src/org/mariotaku/twidere/util/http/UnsafeSSLConnection.java
Java
gpl-3.0
2,116
/*************************************************************************** * Title : Find all possible paths from Source to Destination * URL : * Date : 2018-02-23 * Author: Atiq Rahman * Comp : O(V+E) * Status: Demo * Notes : comments inline, input sample at '01_BFS_SP.cs' * meta : tag-graph-dfs, tag-recursion, tag-company-gatecoin, tag-coding-test, tag-algo-core ***************************************************************************/ using System; using System.Collections.Generic; public class GraphDemo { bool[] IsVisited; // We are using Adjacency List instead of adjacency matrix to save space, // for sparse graphs which is average case List<int>[] AdjList; // Nodes in the path being visited so far int[] Path; // Number of nodes so far encountered during the visit int PathHopCount; int PathCount = 0; // Number of Vertices in the graph int nV; // Number of Edges int nE; int Source; int Destination; /* * Takes input * Build adjacency list graph representation * Does input validation */ public void TakeInput() { Console.WriteLine("Please enter number of vertices in the graph:"); nV = int.Parse(Console.ReadLine()); if (nV < 1) throw new ArgumentException(); // As number of vertices is know at this point, // Initialize (another way to do is to move this block to constructor) Path = new int[nV]; PathHopCount = 0; PathCount = 0; AdjList = new List<int>[nV]; // by default C# compiler sets values in array to false IsVisited = new bool[nV]; for (int i = 0; i < nV; i++) AdjList[i] = new List<int>(); // Build adjacency list from given points Console.WriteLine("Please enter number of edges:"); nE = int.Parse(Console.ReadLine()); if (nE < 0) throw new ArgumentException(); Console.WriteLine("Please enter {0} of edges, one edge per line \"u v\" " + "where 1 <= u <= {1} and 1 <= v <= {1}", nE, nV); string[] tokens = null; for (int i=0; i<nE; i++) { tokens = Console.ReadLine().Split(); int u = int.Parse(tokens[0]) - 1; int v = int.Parse(tokens[1]) - 1; if (u < 0 || u >= nV || v < 0 || v >= nV) throw new ArgumentException(); AdjList[u].Add(v); AdjList[v].Add(u); } Console.WriteLine("Please provide source and destination:"); // reuse tokens variable, if it were reducing readability we would a new // variable tokens = Console.ReadLine().Split(); Source = int.Parse(tokens[0]) - 1; Destination = int.Parse(tokens[1]) - 1; if (Source < 0 || Source >= nV || Destination < 0 || Destination >= nV) throw new ArgumentException(); } /* * Depth first search algorithm to find path from source to destination * for the node of the graph passed as argument * 1. We check if it's destination node (we avoid cycle) * 2. If not then if the node is not visited in the same path then we visit * its adjacent nodes * To allow visiting same node in a different path we set visited to false * for the node when we backtrack to a different path * * We store the visited paths for the node in Path variable and keep count * of nodes in the path using variable PathHopCount. Path variable is * reused for finding other paths. * * If we want to return list of all paths we can use a list of list to store * all of them from this variable */ private void DFSVisit(int u) { IsVisited[u] = true; Path[PathHopCount++] = u; if (u == Destination) PrintPath(); else foreach (int v in AdjList[u]) if (IsVisited[v] == false) DFSVisit(v); PathHopCount--; IsVisited[u] = false; } /* * Simply print nodes from array Path * PathCount increments every time a new path is found. */ private void PrintPath() { Console.WriteLine("Path {0}:", ++PathCount); for (int i = 0; i < PathHopCount; i++) if (i==0) Console.Write(" {0}", Path[i] + 1); else Console.Write(" -> {0}", Path[i]+1); Console.WriteLine(); } public void ShowResult() { Console.WriteLine("Listing paths from {0} to {1}.", Source+1, Destination+1); DFSVisit(Source); } } class Program { static void Main(string[] args) { GraphDemo graph_demo = new GraphDemo(); graph_demo.TakeInput(); graph_demo.ShowResult(); } }
atiq-cs/Problem-Solving
algo/Graph/02_DFS_AllPossiblePaths.cs
C#
gpl-3.0
4,531
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) 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 keel.Algorithms.RE_SL_Methods.LEL_TSK; import java.io.*; import org.core.*; import java.util.*; import java.lang.Math; class Simplif { public double semilla; public long cont_soluciones; public long Gen, n_genes, n_reglas, n_generaciones; public int n_soluciones; public String fich_datos_chequeo, fich_datos_tst, fich_datos_val; public String fichero_conf, ruta_salida; public String fichero_br, fichero_reglas, fich_tra_obli, fich_tst_obli; public String datos_inter = ""; public String cadenaReglas = ""; public MiDataset tabla, tabla_tst, tabla_val; public BaseR_TSK base_reglas; public BaseR_TSK base_total; public Adap_Sel fun_adap; public AG alg_gen; public Simplif(String f_e) { fichero_conf = f_e; } private String Quita_blancos(String cadena) { StringTokenizer sT = new StringTokenizer(cadena, "\t ", false); return (sT.nextToken()); } /** Reads the data of the configuration file */ public void leer_conf() { int i, j; String cadenaEntrada, valor; double cruce, mutacion, porc_radio_reglas, porc_min_reglas, alfa, tau; int tipo_fitness, long_poblacion; // we read the file in a String cadenaEntrada = Fichero.leeFichero(fichero_conf); StringTokenizer sT = new StringTokenizer(cadenaEntrada, "\n\r=", false); // we read the algorithm's name sT.nextToken(); sT.nextToken(); // we read the name of the training and test files sT.nextToken(); valor = sT.nextToken(); StringTokenizer ficheros = new StringTokenizer(valor, "\t ", false); fich_datos_chequeo = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); fich_datos_val = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); fich_datos_tst = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); // we read the name of the output files sT.nextToken(); valor = sT.nextToken(); ficheros = new StringTokenizer(valor, "\t ", false); fich_tra_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); fich_tst_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); String aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //Br inicial aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BD fichero_br = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de MAN2TSK fichero_reglas = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Select aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Tuning ruta_salida = fich_tst_obli.substring(0, fich_tst_obli.lastIndexOf('/') + 1); // we read the seed of the random generator sT.nextToken(); valor = sT.nextToken(); semilla = Double.parseDouble(valor.trim()); Randomize.setSeed( (long) semilla); ; for (i = 0; i < 19; i++) { sT.nextToken(); //variable sT.nextToken(); //valor } // we read the Number of Iterations sT.nextToken(); valor = sT.nextToken(); n_generaciones = Long.parseLong(valor.trim()); // we read the Population Size sT.nextToken(); valor = sT.nextToken(); long_poblacion = Integer.parseInt(valor.trim()); // we read the Tau parameter for the minimun maching degree required to the KB sT.nextToken(); valor = sT.nextToken(); tau = Double.parseDouble(valor.trim()); // we read the Rate of Rules that don't are eliminated sT.nextToken(); valor = sT.nextToken(); porc_min_reglas = Double.parseDouble(valor.trim()); // we read the Rate of rules to estimate the niche radio sT.nextToken(); valor = sT.nextToken(); porc_radio_reglas = Double.parseDouble(valor.trim()); // we read the Alfa parameter for the Power Law sT.nextToken(); valor = sT.nextToken(); alfa = Double.parseDouble(valor.trim()); // we read the Type of Fitness Function sT.nextToken(); valor = sT.nextToken(); tipo_fitness = Integer.parseInt(valor.trim()); // we select the numero de soluciones n_soluciones = 1; // we read the Cross Probability sT.nextToken(); valor = sT.nextToken(); cruce = Double.parseDouble(valor.trim()); // we read the Mutation Probability sT.nextToken(); valor = sT.nextToken(); mutacion = Double.parseDouble(valor.trim()); // we create all the objects tabla = new MiDataset(fich_datos_chequeo, false); if (tabla.salir == false) { tabla_val = new MiDataset(fich_datos_val, false); tabla_tst = new MiDataset(fich_datos_tst, false); base_total = new BaseR_TSK(fichero_br, tabla, true); base_reglas = new BaseR_TSK(base_total.n_reglas, tabla); fun_adap = new Adap_Sel(tabla, tabla_tst, base_reglas, base_total, base_total.n_reglas, porc_radio_reglas, porc_min_reglas, n_soluciones, tau, alfa, tipo_fitness); alg_gen = new AG(long_poblacion, base_total.n_reglas, cruce, mutacion, fun_adap); } } public void run() { int i, j; double ec, el, min_CR, ectst, eltst; /* We read the configutate file and we initialize the structures and variables */ leer_conf(); if (tabla.salir == false) { /* Inicializacion del contador de soluciones ya generadas */ cont_soluciones = 0; System.out.println("Simplif-TSK"); do { /* Generation of the initial population */ alg_gen.Initialize(); Gen = 0; /* Evaluation of the initial population */ alg_gen.Evaluate(); Gen++; /* Main of the genetic algorithm */ do { /* Interchange of the new and old population */ alg_gen.Intercambio(); /* Selection by means of Baker */ alg_gen.Select(); /* Crossover */ alg_gen.Cruce_Multipunto(); /* Mutation */ alg_gen.Mutacion_Uniforme(); /* Elitist selection */ alg_gen.Elitist(); /* Evaluation of the current population */ alg_gen.Evaluate(); /* we increment the counter */ Gen++; } while (Gen <= n_generaciones); /* we store the RB in the Tabu list */ if (Aceptar(alg_gen.solucion()) == 1) { fun_adap.guardar_solucion(alg_gen.solucion()); /* we increment the number of solutions */ cont_soluciones++; fun_adap.Decodifica(alg_gen.solucion()); fun_adap.Cubrimientos_Base(); /* we calcule the MSEs */ fun_adap.Error_tra(); ec = fun_adap.EC; el = fun_adap.EL; fun_adap.tabla_tst = tabla_tst; fun_adap.Error_tst(); ectst = fun_adap.EC; eltst = fun_adap.EL; /* we calculate the minimum and maximum matching */ min_CR = 1.0; for (i = 0; i < tabla.long_tabla; i++) { min_CR = Adap.Minimo(min_CR, tabla.datos[i].maximo_cubrimiento); } /* we write the RB */ cadenaReglas = base_reglas.BRtoString(); cadenaReglas += "\n\nMinimum of C_R: " + min_CR + " Minimum covering degree: " + fun_adap.mincb + "\nAverage covering degree: " + fun_adap.medcb + " MLE: " + el + "\nMSEtra: " + ec + " , MSEtst: " + ectst + "\n"; Fichero.escribeFichero(fichero_reglas, cadenaReglas); /* we write the obligatory output files*/ String salida_tra = tabla.getCabecera(); salida_tra += fun_adap.getSalidaObli(tabla_val); Fichero.escribeFichero(fich_tra_obli, salida_tra); String salida_tst = tabla_tst.getCabecera(); salida_tst += fun_adap.getSalidaObli(tabla_tst); Fichero.escribeFichero(fich_tst_obli, salida_tst); /* we write the MSEs in specific files */ Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunR.txt", "" + base_reglas.n_reglas + "\n"); Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTRA.txt", "" + ec + "\n"); Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTST.txt", "" + ectst + "\n"); } /* the multimodal GA finish when the condition is true */ } while (Parada() == 0); } } /** Criterion of stop */ public int Parada() { if (cont_soluciones == n_soluciones) { return (1); } else { return (0); } } /** Criterion to accept the solutions */ int Aceptar(char[] cromosoma) { return (1); } }
SCI2SUGR/KEEL
src/keel/Algorithms/RE_SL_Methods/LEL_TSK/Simplif.java
Java
gpl-3.0
10,008
package com.orcinuss.reinforcedtools.item.tools; import com.google.common.collect.Sets; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.EnumRarity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemTool; import java.util.Set; public class ItemRTMHarvester extends ItemTool{ private static final Set blocksToBreak = Sets.newHashSet(new Block[]{Blocks.glowstone}); public EnumRarity rarity; public ItemRTMHarvester(Item.ToolMaterial material) { this(material, EnumRarity.common); } public ItemRTMHarvester(Item.ToolMaterial material, EnumRarity rarity ){ super(0.0F, material, blocksToBreak); this.rarity = rarity; this.maxStackSize = 1; } }
Orcinuss/ReinforcedTools
src/main/java/com/orcinuss/reinforcedtools/item/tools/ItemRTMHarvester.java
Java
gpl-3.0
803
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net; using System.Net.Http; using System.Net.Http.Formatting; namespace Admin.Models { public class FacilityClient { //private string BASE_URL = "http://ihmwcore.azurewebsites.net/api/"; private string BASE_URL = "http://localhost:52249/api/"; public IEnumerable<Facility> findAll() { try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(BASE_URL); client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync("Facility").Result; if (response.IsSuccessStatusCode) { return response.Content.ReadAsAsync<IEnumerable<Facility>>().Result; } else { return null; } } catch { return null; } } public Facility find(int id) { try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(BASE_URL); client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync("Facility/" + id).Result; if (response.IsSuccessStatusCode) { return response.Content.ReadAsAsync<Facility>().Result; } else { return null; } } catch { return null; } } public bool Create(Facility Facility) { try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(BASE_URL); client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PostAsJsonAsync("Facility", Facility).Result; return response.IsSuccessStatusCode; } catch { return false; } } public bool Edit(Facility Facility) { try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(BASE_URL); client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PutAsJsonAsync("Facility/" + Facility.facilityNumber, Facility).Result; return response.IsSuccessStatusCode; } catch { return false; } } public bool Delete(int id) { try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(BASE_URL); client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.DeleteAsync("Facility/" + id).Result; return response.IsSuccessStatusCode; } catch { return false; } } } }
KevinEsquivel21/iHMW
Admin/Admin/Models/FacilityClient.cs
C#
gpl-3.0
3,799
#include "XmlSerializer.h" namespace dnc { namespace Xml { XmlSerializer::XmlSerializer() {} XmlSerializer::~XmlSerializer() {} std::string XmlSerializer::ToString() { return std::string("System.Xml.XmlSerializer"); } std::string XmlSerializer::GetTypeString() { return std::string("XmlSerializer"); } String XmlSerializer::ToXml(Serializable* obj, Collections::Generic::List<unsigned long long>& _childPtrs) { unsigned long long hash = 0; String res; size_t len; //Serializable* seri = nullptr; /*if(std::is_same<T, Serializable*>::value) { seri = (Serializable*) obj; } else { seri = static_cast<Serializable*>(&obj); }*/ len = obj->AttrLen(); res = "<" + obj->Name() + " ID=\"" + obj->getHashCode() + "\">"; for(size_t i = 0; i < len; i++) { SerializableAttribute& t = obj->Attribute(i); // Get Values String attrName = t.AttributeName(); Object& val = t.Member(); // Check Serializable Serializable* child = dynamic_cast<Serializable*>(&val); if(child == nullptr) { // Just serialize res += "<" + attrName + " type=\"" + val.GetTypeString() + "\">"; res += val.ToString(); res += "</" + attrName + ">"; } else { // Is Serializable hash = child->getHashCode(); if(_childPtrs.Contains(hash)) { // Just add a reference res += "<" + attrName + " ref=\"" + hash + "\"/>"; } else { // Call serialize _childPtrs.Add(hash); res += "<" + attrName + " type=\"" + val.GetTypeString() + "\">"; res += ToXml(child, _childPtrs); res += "</" + attrName + ">"; } } } res += "</" + obj->Name() + ">\r\n"; return res; } } }
OperationDarkside/ProjectDNC
DNC/XmlSerializer.cpp
C++
gpl-3.0
1,718
package org.hl7.v3; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>AgeDetectedIssueCodeのJavaクラス。 * * <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。 * <p> * <pre> * &lt;simpleType name="AgeDetectedIssueCode"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="AGE"/> * &lt;enumeration value="DOSEHINDA"/> * &lt;enumeration value="DOSELINDA"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "AgeDetectedIssueCode") @XmlEnum public enum AgeDetectedIssueCode { AGE, DOSEHINDA, DOSELINDA; public String value() { return name(); } public static AgeDetectedIssueCode fromValue(String v) { return valueOf(v); } }
ricecakesoftware/CommunityMedicalLink
ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/AgeDetectedIssueCode.java
Java
gpl-3.0
913
<?php /** * @package Arastta eCommerce * @copyright Copyright (C) 2015 Arastta Association. All rights reserved. (arastta.org) * @license GNU General Public License version 3; see LICENSE.txt */ // Heading $_['heading_title'] = 'Produktegenskaper - Grupper'; // Text $_['text_success'] = 'Endringer ble vellykket lagret.'; $_['text_list'] = 'Liste'; $_['text_add'] = 'Legg til'; $_['text_edit'] = 'Endre'; // Column $_['column_name'] = 'Navn'; $_['column_sort_order'] = 'Sortering'; $_['column_action'] = 'Valg'; // Entry $_['entry_name'] = 'Navn'; $_['entry_sort_order'] = 'Sortering'; // Error $_['error_permission'] = 'Du har ikke rettigheter til å utføre valgte handling.'; $_['error_name'] = 'Navn må inneholde mellom 3 og 64 tegn.'; $_['error_attribute'] = 'Denne gruppen kan ikke slettes ettersom den er tilknyttet %s produktegenskaper.'; $_['error_product'] = 'Denne gruppen kan ikke slettes ettersom den er tilknyttet %s produkter.';
interspiresource/interspire
admin/language/nb-NO/catalog/attribute_group.php
PHP
gpl-3.0
1,022
<?php /** * @package Joomla.Platform * @subpackage Data * * @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * JDataSet is a collection class that allows the developer to operate on a set of JData objects as if they were in a * typical PHP array. * * @since 12.3 */ class JDataSet implements JDataDumpable, ArrayAccess, Countable, Iterator { /** * The current position of the iterator. * * @var integer * @since 12.3 */ private $_current = false; /** * The iterator objects. * * @var array * @since 12.3 */ private $_objects = array(); /** * The class constructor. * * @param array $objects An array of JData objects to bind to the data set. * * @since 12.3 * @throws InvalidArgumentException if an object is not an instance of JData. */ public function __construct(array $objects = array()) { // Set the objects. $this->_initialise($objects); } /** * The magic call method is used to call object methods using the iterator. * * Example: $array = $objectList->foo('bar'); * * The object list will iterate over its objects and see if each object has a callable 'foo' method. * If so, it will pass the argument list and assemble any return values. If an object does not have * a callable method no return value is recorded. * The keys of the objects and the result array are maintained. * * @param string $method The name of the method called. * @param array $arguments The arguments of the method called. * * @return array An array of values returned by the methods called on the objects in the data set. * * @since 12.3 */ public function __call($method, $arguments = array()) { $return = array(); // Iterate through the objects. foreach ($this->_objects as $key => $object) { // Create the object callback. $callback = array($object, $method); // Check if the callback is callable. if (is_callable($callback)) { // Call the method for the object. $return[$key] = call_user_func_array($callback, $arguments); } } return $return; } /** * The magic get method is used to get a list of properties from the objects in the data set. * * Example: $array = $dataSet->foo; * * This will return a column of the values of the 'foo' property in all the objects * (or values determined by custom property setters in the individual JData's). * The result array will contain an entry for each object in the list (compared to __call which may not). * The keys of the objects and the result array are maintained. * * @param string $property The name of the data property. * * @return array An associative array of the values. * * @since 12.3 */ public function __get($property) { $return = array(); // Iterate through the objects. foreach ($this->_objects as $key => $object) { // Get the property. $return[$key] = $object->$property; } return $return; } /** * The magic isset method is used to check the state of an object property using the iterator. * * Example: $array = isset($objectList->foo); * * @param string $property The name of the property. * * @return boolean True if the property is set in any of the objects in the data set. * * @since 12.3 */ public function __isset($property) { $return = array(); // Iterate through the objects. foreach ($this->_objects as $object) { // Check the property. $return[] = isset($object->$property); } return in_array(true, $return, true) ? true : false; } /** * The magic set method is used to set an object property using the iterator. * * Example: $objectList->foo = 'bar'; * * This will set the 'foo' property to 'bar' in all of the objects * (or a value determined by custom property setters in the JData). * * @param string $property The name of the property. * @param mixed $value The value to give the data property. * * @return void * * @since 12.3 */ public function __set($property, $value) { // Iterate through the objects. foreach ($this->_objects as $object) { // Set the property. $object->$property = $value; } } /** * The magic unset method is used to unset an object property using the iterator. * * Example: unset($objectList->foo); * * This will unset all of the 'foo' properties in the list of JData's. * * @param string $property The name of the property. * * @return void * * @since 12.3 */ public function __unset($property) { // Iterate through the objects. foreach ($this->_objects as $object) { unset($object->$property); } } /** * Gets the number of data objects in the set. * * @return integer The number of objects. * * @since 12.3 */ public function count() { return count($this->_objects); } /** * Clears the objects in the data set. * * @return JDataSet Returns itself to allow chaining. * * @since 12.3 */ public function clear() { $this->_objects = array(); $this->rewind(); return $this; } /** * Get the current data object in the set. * * @return JData The current object, or false if the array is empty or the pointer is beyond the end of the elements. * * @since 12.3 */ public function current() { return is_scalar($this->_current) ? $this->_objects[$this->_current] : false; } /** * Dumps the data object in the set, recursively if appropriate. * * @param integer $depth The maximum depth of recursion (default = 3). * For example, a depth of 0 will return a stdClass with all the properties in native * form. A depth of 1 will recurse into the first level of properties only. * @param SplObjectStorage $dumped An array of already serialized objects that is used to avoid infinite loops. * * @return array An associative array of the date objects in the set, dumped as a simple PHP stdClass object. * * @see JData::dump() * @since 12.3 */ public function dump($depth = 3, SplObjectStorage $dumped = null) { // Check if we should initialise the recursion tracker. if ($dumped === null) { $dumped = new SplObjectStorage; } // Add this object to the dumped stack. $dumped->attach($this); $objects = array(); // Make sure that we have not reached our maximum depth. if ($depth > 0) { // Handle JSON serialization recursively. foreach ($this->_objects as $key => $object) { $objects[$key] = $object->dump($depth, $dumped); } } return $objects; } /** * Gets the data set in a form that can be serialised to JSON format. * * Note that this method will not return an associative array, otherwise it would be encoded into an object. * JSON decoders do not consistently maintain the order of associative keys, whereas they do maintain the order of arrays. * * @param mixed $serialized An array of objects that have already been serialized that is used to infinite loops * (null on first call). * * @return array An array that can be serialised by json_encode(). * * @since 12.3 */ public function jsonSerialize($serialized = null) { // Check if we should initialise the recursion tracker. if ($serialized === null) { $serialized = array(); } // Add this object to the serialized stack. $serialized[] = spl_object_hash($this); $return = array(); // Iterate through the objects. foreach ($this->_objects as $object) { // Call the method for the object. $return[] = $object->jsonSerialize($serialized); } return $return; } /** * Gets the key of the current object in the iterator. * * @return scalar The object key on success; null on failure. * * @since 12.3 */ public function key() { return $this->_current; } /** * Gets the array of keys for all the objects in the iterator (emulates array_keys). * * @return array The array of keys * * @since 12.3 */ public function keys() { return array_keys($this->_objects); } /** * Advances the iterator to the next object in the iterator. * * @return void * * @since 12.3 */ public function next() { // Get the object offsets. $keys = $this->keys(); // Check if _current has been set to false but offsetUnset. if ($this->_current === false && isset($keys[0])) { // This is a special case where offsetUnset was used in a foreach loop and the first element was unset. $this->_current = $keys[0]; } else { // Get the current key. $position = array_search($this->_current, $keys); // Check if there is an object after the current object. if ($position !== false && isset($keys[$position + 1])) { // Get the next id. $this->_current = $keys[$position + 1]; } else { // That was the last object or the internal properties have become corrupted. $this->_current = null; } } } /** * Checks whether an offset exists in the iterator. * * @param mixed $offset The object offset. * * @return boolean True if the object exists, false otherwise. * * @since 12.3 */ public function offsetExists($offset) { return isset($this->_objects[$offset]); } /** * Gets an offset in the iterator. * * @param mixed $offset The object offset. * * @return JData The object if it exists, null otherwise. * * @since 12.3 */ public function offsetGet($offset) { return isset($this->_objects[$offset]) ? $this->_objects[$offset] : null; } /** * Sets an offset in the iterator. * * @param mixed $offset The object offset. * @param JData $object The object object. * * @return void * * @since 12.3 * @throws InvalidArgumentException if an object is not an instance of JData. */ public function offsetSet($offset, $object) { // Check if the object is a JData object. if (!($object instanceof JData)) { throw new InvalidArgumentException(sprintf('%s("%s", *%s*)', __METHOD__, $offset, gettype($object))); } // Set the offset. $this->_objects[$offset] = $object; } /** * Unsets an offset in the iterator. * * @param mixed $offset The object offset. * * @return void * * @since 12.3 */ public function offsetUnset($offset) { if (!$this->offsetExists($offset)) { // Do nothing if the offset does not exist. return; } // Check for special handling of unsetting the current position. if ($offset == $this->_current) { // Get the current position. $keys = $this->keys(); $position = array_search($this->_current, $keys); // Check if there is an object before the current object. if ($position > 0) { // Move the current position back one. $this->_current = $keys[$position - 1]; } else { // We are at the start of the keys AND let's assume we are in a foreach loop and `next` is going to be called. $this->_current = false; } } unset($this->_objects[$offset]); } /** * Rewinds the iterator to the first object. * * @return void * * @since 12.3 */ public function rewind() { // Set the current position to the first object. if (empty($this->_objects)) { $this->_current = false; } else { $keys = $this->keys(); $this->_current = array_shift($keys); } } /** * Validates the iterator. * * @return boolean True if valid, false otherwise. * * @since 12.3 */ public function valid() { // Check the current position. if (!is_scalar($this->_current) || !isset($this->_objects[$this->_current])) { return false; } return true; } /** * Initialises the list with an array of objects. * * @param array $input An array of objects. * * @return void * * @since 12.3 * @throws InvalidArgumentException if an object is not an instance of JData. */ private function _initialise(array $input = array()) { foreach ($input as $key => $object) { if (!is_null($object)) { $this->offsetSet($key, $object); } } $this->rewind(); } }
MasiaArmato/coplux
libraries/joomla/data/set.php
PHP
gpl-3.0
12,869
package medium_challenges; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class BenderSolution { public static void main(String args[]) { @SuppressWarnings("resource") Scanner in = new Scanner(System.in); int R = in.nextInt(); int C = in.nextInt(); in.nextLine(); List<Node> teleports = new ArrayList<>(); Node start = null; // Create (x,y) map and store starting point char[][] map = new char[C][R]; for (int y = 0; y < R; y++) { String row = in.nextLine(); for (int x = 0; x < C; x++){ char item = row.charAt(x); map[x][y] = item; if (item == '@') { start = new Node(x,y); } if (item == 'T') { teleports.add(new Node(x,y)); } } } // Create new robot with map Bender bender = new Bender(start, map, teleports); // Limit iterations boolean circular = false; final int MAX_ITERATIONS = 200; // Collect all moves. List<String> moves = new ArrayList<>(); while (bender.alive && !circular) { moves.add(bender.move()); circular = moves.size() > MAX_ITERATIONS; } // Output Result if (circular) System.out.println("LOOP"); else { for (String s: moves) System.out.println(s); } } /** Simple object to store coordinate pair */ private static class Node { final int x, y; Node(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Node other = (Node) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } /** Object to store state and behavior of Bender */ private static class Bender { Node position; char[][] map; boolean directionToggle; boolean alive; Direction facing; boolean beerToggle; List<Node> teleports; /** Direction enum includes the ability to find next node based on direction Bender is facing. */ private enum Direction { SOUTH(0, 1), EAST(1, 0), NORTH(0, -1), WEST(-1, 0); private int dx; private int dy; Direction (int dx, int dy) { this.dx = dx; this.dy = dy; } public Node newNode(Node original) { return new Node(original.x + dx, original.y + dy); } public Direction nextDirection(boolean toggle) { if (toggle) { switch (this) { case SOUTH: return EAST; case EAST: return NORTH; default: return WEST; } } else { switch (this) { case WEST: return NORTH; case NORTH: return EAST; default: return SOUTH; } } } } public Bender(Node start, char[][] map, List<Node> teleports) { this.position = start; this.map = map; this.alive = true; this.facing = Direction.SOUTH; this.directionToggle = true; this.beerToggle = false; this.teleports = teleports; } /** Updates the state of bender. Returns direction of the move. */ public String move() { char currentContent = map[position.x][position.y]; // Check for Teleporters if (currentContent == 'T') { position = (teleports.get(0).equals(position)) ? teleports.get(1) : teleports.get(0); } // Check for immediate move command if ((""+currentContent).matches("[NESW]")) { switch (currentContent) { case 'N': facing = Direction.NORTH; position = facing.newNode(position); return Direction.NORTH.toString(); case 'W': facing = Direction.WEST; position = facing.newNode(position); return Direction.WEST.toString(); case 'S': facing = Direction.SOUTH; position = facing.newNode(position); return Direction.SOUTH.toString(); default: facing = Direction.EAST; position = facing.newNode(position); return Direction.EAST.toString(); } } // Check for inversion if (currentContent == 'I') { directionToggle = !directionToggle; } // Check for beer if (currentContent == 'B') { beerToggle = !beerToggle; } // Trial next possibility Node trial = facing.newNode(position); char content = map[trial.x][trial.y]; // Check if Bender dies if (content == '$') { alive = false; return facing.toString(); } // Check for beer power to remove X barrier if (beerToggle && content == 'X') { content = ' '; map[trial.x][trial.y] = ' '; } // Check for Obstacles boolean initialCheck = true; while (content == 'X' || content == '#') { // Check for obstacles if (content == 'X' || content == '#') { if (initialCheck) { facing = directionToggle ? Direction.SOUTH : Direction.WEST; initialCheck = false; } else { facing = facing.nextDirection(directionToggle); } } // Update position and facing trial = facing.newNode(position); content = map[trial.x][trial.y]; } // If we made it to this point, it's okay to move bender position = facing.newNode(position); if (content == '$') alive = false; return facing.toString(); } } }
workwelldone/bright-eyes
src/medium_challenges/BenderSolution.java
Java
gpl-3.0
5,937
package me.zsj.moment.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Paint; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; /** * @author zsj */ public class CircleTransform extends BitmapTransformation { public CircleTransform(Context context) { super(context); } @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { return circleCrop(pool, toTransform); } private static Bitmap circleCrop(BitmapPool pool, Bitmap source) { if (source == null) return null; int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); if (result == null) { result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(result); Paint paint = new Paint(); paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP)); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); squared.recycle(); return result; } @Override public String getId() { return getClass().getName(); } }
Assassinss/Moment
app/src/main/java/me/zsj/moment/utils/CircleTransform.java
Java
gpl-3.0
1,691
package clientdata.visitors; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.HashMap; import java.util.Map; import org.apache.mina.core.buffer.IoBuffer; import clientdata.VisitorInterface; public class SlotDefinitionVisitor implements VisitorInterface { public static class SlotDefinition { public String slotName; public byte global; public byte canMod; public byte exclusive; public String hardpointName; public int unk1; } public SlotDefinitionVisitor() { definitions = new HashMap<String, SlotDefinition>(); } private Map<String, SlotDefinition> definitions; public Map<String, SlotDefinition> getDefinitions() { return definitions; } @Override public void parseData(String nodename, IoBuffer data, int depth, int size) throws Exception { if(nodename.endsWith("DATA")) { CharsetDecoder cd = Charset.forName("US-ASCII").newDecoder(); while(data.hasRemaining()) { SlotDefinition next = new SlotDefinition(); next.slotName = data.getString(cd); cd.reset(); next.global = data.get(); next.canMod = data.get(); next.exclusive = data.get(); next.hardpointName = data.getString(cd); cd.reset(); next.unk1 = data.getInt(); definitions.put(next.slotName, next); } } } @Override public void notifyFolder(String nodeName, int depth) throws Exception {} }
swgopenge/openge
src/clientdata/visitors/SlotDefinitionVisitor.java
Java
gpl-3.0
1,410
class CustomUrl < ActiveRecord::Base belongs_to :media_resource belongs_to :creator, class_name: 'User', foreign_key: :creator_id belongs_to :updator, class_name: 'User', foreign_key: :updator_id default_scope lambda{order(id: :asc)} end
zhdk/madek
app/models/custom_url.rb
Ruby
gpl-3.0
247
package me.anthonybruno.soccerSim.team.member; import me.anthonybruno.soccerSim.models.Range; /** * Player is a class that contains information about a player. */ public class Player extends TeamMember { private final Range shotRange; private final int goal; /** * Creates a new player with a name, shot range (how likely a shot will be attributed to the player) and a goal * rating (how likely they are to score a goal). * * @param name The name of the player * @param shotRange Shot range of player. Defines how likely a shot on goal will be attributed to this player (see * rule files for more information. Is the maximum value when lower and upper bounds given by the * rules. * @param goal How likely a shot from the player will go in. When shot is taken, a number from 1-10 is generated. * If the generated number is above or equal to goal rating, the player scores. */ public Player(String name, Range shotRange, int goal, int multiplier) { super(name, multiplier); this.shotRange = shotRange; this.goal = goal; } /** * Returns the shot range of player. * * @return the player's shot range. */ public Range getShotRange() { return shotRange; } /** * Returns the goal rating of the player. * * @return the player's goal range. */ public int getGoal() { return goal; } }
AussieGuy0/soccerSim
src/main/java/me/anthonybruno/soccerSim/team/member/Player.java
Java
gpl-3.0
1,523
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Newtonsoft.Json; using SmartStore.Core.Infrastructure; namespace SmartStore.Collections { public abstract class TreeNodeBase<T> where T : TreeNodeBase<T> { private T _parent; private List<T> _children = new List<T>(); private int? _depth = null; private int _index = -1; protected object _id; private IDictionary<object, TreeNodeBase<T>> _idNodeMap; protected IDictionary<string, object> _metadata; private readonly static ContextState<Dictionary<string, object>> _contextState = new ContextState<Dictionary<string, object>>("TreeNodeBase.ThreadMetadata"); public TreeNodeBase() { } #region Id public object Id { get { return _id; } set { _id = value; if (_parent != null) { var map = GetIdNodeMap(); if (_id != null && map.ContainsKey(_id)) { // Remove old id from map map.Remove(_id); } if (value != null) { map[value] = this; } } } } public T SelectNodeById(object id) { if (id == null || IsLeaf) return null; var map = GetIdNodeMap(); var node = (T)map?.Get(id); if (node != null && !this.IsAncestorOfOrSelf(node)) { // Found node is NOT a child of this node return null; } return node; } private IDictionary<object, TreeNodeBase<T>> GetIdNodeMap() { var map = this.Root._idNodeMap; if (map == null) { map = this.Root._idNodeMap = new Dictionary<object, TreeNodeBase<T>>(); } return map; } #endregion #region Metadata public IDictionary<string, object> Metadata { get { return _metadata ?? (_metadata = new Dictionary<string, object>()); } set { _metadata = value; } } public void SetMetadata(string key, object value) { Guard.NotEmpty(key, nameof(key)); Metadata[key] = value; } public void SetThreadMetadata(string key, object value) { Guard.NotEmpty(key, nameof(key)); var state = _contextState.GetState(); if (state == null) { state = new Dictionary<string, object>(); _contextState.SetState(state); } state[GetContextKey(this, key)] = value; } public TMetadata GetMetadata<TMetadata>(string key, bool recursive = true) { Guard.NotEmpty(key, nameof(key)); object metadata; if (!recursive) { return TryGetMetadataForNode(this, key, out metadata) ? (TMetadata)metadata : default(TMetadata); } // recursively search for the metadata value in current node and ancestors var current = this; while (!TryGetMetadataForNode(current, key, out metadata)) { current = current.Parent; if (current == null) break; } if (metadata != null) { return (TMetadata)metadata; } return default(TMetadata); } private bool TryGetMetadataForNode(TreeNodeBase<T> node, string key, out object metadata) { metadata = null; var state = _contextState.GetState(); if (state != null) { var contextKey = GetContextKey(node, key); if (state.ContainsKey(contextKey)) { metadata = state[contextKey]; return true; } } if (node._metadata != null && node._metadata.ContainsKey(key)) { metadata = node._metadata[key]; return true; } return false; } private static string GetContextKey(TreeNodeBase<T> node, string key) { return node.GetHashCode().ToString() + key; } #endregion private List<T> ChildrenInternal { get { if (_children == null) { _children = new List<T>(); } return _children; } } private void AddChild(T node, bool clone, bool append = true) { var newNode = node; if (clone) { newNode = node.Clone(true); } newNode.AttachTo((T)this, append ? (int?)null : 0); } private void AttachTo(T newParent, int? index) { Guard.NotNull(newParent, nameof(newParent)); var prevParent = _parent; if (_parent != null) { // Detach from parent _parent.Remove((T)this); } if (index == null) { newParent.ChildrenInternal.Add((T)this); _index = newParent.ChildrenInternal.Count - 1; } else { newParent.ChildrenInternal.Insert(index.Value, (T)this); _index = index.Value; FixIndexes(newParent._children, _index + 1, 1); } _parent = newParent; FixIdNodeMap(prevParent, newParent); } /// <summary> /// Responsible for propagating node ids when detaching/attaching nodes /// </summary> private void FixIdNodeMap(T prevParent, T newParent) { ICollection<TreeNodeBase<T>> keyedNodes = null; if (prevParent != null) { // A node is moved. We need to detach first. keyedNodes = new List<TreeNodeBase<T>>(); // Detach ids from prev map var prevMap = prevParent.GetIdNodeMap(); Traverse(x => { // Collect all child node's ids if (x._id != null) { keyedNodes.Add(x); if (prevMap.ContainsKey(x._id)) { // Remove from map prevMap.Remove(x._id); } } }, true); } if (keyedNodes == null && _idNodeMap != null) { // An orphan/root node is attached keyedNodes = _idNodeMap.Values; } if (newParent != null) { // Get new *root map var map = newParent.GetIdNodeMap(); // Merge *this map with *root map if (keyedNodes != null) { foreach (var node in keyedNodes) { map[node._id] = node; } // Get rid of *this map after memorizing keyed nodes if (_idNodeMap != null) { _idNodeMap.Clear(); _idNodeMap = null; } } if (prevParent == null && _id != null) { // When *this was a root, but is keyed, then *this id // was most likely missing in the prev id-node-map. map[_id] = (T)this; } } } [JsonIgnore] public T Parent { get { return _parent; } } public T this[int i] { get { return _children?[i]; } } public IReadOnlyList<T> Children { get { return ChildrenInternal; } } [JsonIgnore] public IEnumerable<T> LeafNodes { get { return _children != null ? _children.Where(x => x.IsLeaf) : Enumerable.Empty<T>(); } } [JsonIgnore] public IEnumerable<T> NonLeafNodes { get { return _children != null ? _children.Where(x => !x.IsLeaf) : Enumerable.Empty<T>(); } } [JsonIgnore] public T FirstChild { get { return _children?.FirstOrDefault(); } } [JsonIgnore] public T LastChild { get { return _children?.LastOrDefault(); } } [JsonIgnore] public bool IsLeaf { get { return _children == null || _children.Count == 0; } } [JsonIgnore] public bool HasChildren { get { return _children == null || _children.Count > 0; } } [JsonIgnore] public bool IsRoot { get { return _parent == null; } } [JsonIgnore] public int Index { get { return _index; } } /// <summary> /// Root starts with 0 /// </summary> [JsonIgnore] public int Depth { get { if (!_depth.HasValue) { var node = this; int depth = 0; while (node != null && !node.IsRoot) { depth++; node = node.Parent; } _depth = depth; } return _depth.Value; } } [JsonIgnore] public T Root { get { var root = this; while (root._parent != null) { root = root._parent; } return (T)root; } } [JsonIgnore] public T First { get { return _parent?._children?.FirstOrDefault(); } } [JsonIgnore] public T Last { get { return _parent?._children?.LastOrDefault(); } } [JsonIgnore] public T Next { get { return _parent?._children?.ElementAtOrDefault(_index + 1); } } [JsonIgnore] public T Previous { get { return _parent?._children?.ElementAtOrDefault(_index - 1); } } public bool IsDescendantOf(T node) { var parent = _parent; while (parent != null) { if (parent == node) { return true; } parent = parent._parent; } return false; } public bool IsDescendantOfOrSelf(T node) { if (node == (T)this) return true; return IsDescendantOf(node); } public bool IsAncestorOf(T node) { return node.IsDescendantOf((T)this); } public bool IsAncestorOfOrSelf(T node) { if (node == (T)this) return true; return node.IsDescendantOf((T)this); } [JsonIgnore] public IEnumerable<T> Trail { get { var trail = new List<T>(); var node = (T)this; do { trail.Insert(0, node); node = node._parent; } while (node != null); return trail; } } /// <summary> /// Gets the first element that matches the predicate by testing the node itself /// and traversing up through its ancestors in the tree. /// </summary> /// <param name="predicate">predicate</param> /// <returns>The closest node</returns> public T Closest(Expression<Func<T, bool>> predicate) { Guard.NotNull(predicate, nameof(predicate)); var test = predicate.Compile(); if (test((T)this)) { return (T)this; } var parent = _parent; while (parent != null) { if (test(parent)) { return parent; } parent = parent._parent; } return null; } public T Append(T value) { this.AddChild(value, false, true); return value; } public void AppendRange(IEnumerable<T> values) { values.Each(x => Append(x)); } public void AppendChildrenOf(T node) { if (node?._children != null) { node._children.Each(x => this.AddChild(x, true, true)); } } public T Prepend(T value) { this.AddChild(value, false, false); return value; } public void InsertAfter(int index) { var refNode = _children?.ElementAtOrDefault(index); if (refNode != null) { InsertAfter(refNode); } throw new ArgumentOutOfRangeException(nameof(index)); } public void InsertAfter(T refNode) { this.Insert(refNode, true); } public void InsertBefore(int index) { var refNode = _children?.ElementAtOrDefault(index); if (refNode != null) { InsertBefore(refNode); } throw new ArgumentOutOfRangeException(nameof(index)); } public void InsertBefore(T refNode) { this.Insert(refNode, false); } private void Insert(T refNode, bool after) { Guard.NotNull(refNode, nameof(refNode)); var refParent = refNode._parent; if (refParent == null) { throw Error.Argument("refNode", "The reference node cannot be a root node and must be attached to the tree."); } AttachTo(refParent, refNode._index + (after ? 1 : 0)); } public T SelectNode(Expression<Func<T, bool>> predicate, bool includeSelf = false) { Guard.NotNull(predicate, nameof(predicate)); return this.FlattenNodes(predicate, includeSelf).FirstOrDefault(); } /// <summary> /// Selects all nodes (recursively) witch match the given <c>predicate</c> /// </summary> /// <param name="predicate">The predicate to match against</param> /// <returns>A readonly collection of node matches</returns> public IEnumerable<T> SelectNodes(Expression<Func<T, bool>> predicate, bool includeSelf = false) { Guard.NotNull(predicate, nameof(predicate)); return this.FlattenNodes(predicate, includeSelf); } private void FixIndexes(IList<T> list, int startIndex, int summand = 1) { if (startIndex < 0 || startIndex >= list.Count) return; for (var i = startIndex; i < list.Count; i++) { list[i]._index += summand; } } public void Remove(T node) { Guard.NotNull(node, nameof(node)); if (!node.IsRoot) { var list = node._parent?._children; if (list.Remove(node)) { node.FixIdNodeMap(node._parent, null); FixIndexes(list, node._index, -1); node._index = -1; node._parent = null; node.Traverse(x => x._depth = null, true); } } } public void Clear() { Traverse(x => x._depth = null, false); if (_children != null) { _children.Clear(); } FixIdNodeMap(_parent, null); } public void Traverse(Action<T> action, bool includeSelf = false) { Guard.NotNull(action, nameof(action)); if (includeSelf) action((T)this); if (_children != null) { foreach (var child in _children) child.Traverse(action, true); } } public void TraverseParents(Action<T> action, bool includeSelf = false) { Guard.NotNull(action, nameof(action)); if (includeSelf) action((T)this); var parent = _parent; while (parent != null) { action(parent); parent = parent._parent; } } public IEnumerable<T> FlattenNodes(bool includeSelf = true) { return this.FlattenNodes(null, includeSelf); } protected IEnumerable<T> FlattenNodes(Expression<Func<T, bool>> predicate, bool includeSelf = true) { IEnumerable<T> list; if (includeSelf) { list = new[] { (T)this }; } else { list = Enumerable.Empty<T>(); } if (_children == null) return list; var result = list.Union(_children.SelectMany(x => x.FlattenNodes())); if (predicate != null) { result = result.Where(predicate.Compile()); } return result; } public T Clone() { return Clone(true); } public virtual T Clone(bool deep) { var clone = CreateInstance(); if (deep) { clone.AppendChildrenOf((T)this); } return clone; } protected abstract T CreateInstance(); } }
smartstoreag/SmartStoreNET
src/Libraries/SmartStore.Core/Collections/TreeNodeBase.cs
C#
gpl-3.0
13,704
package vizardous.delegate.dataFilter; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import vizardous.util.Converter; /** * Filter class that provides filter functionality for data structures with comparable content * * @author Johannes Seiffarth <j.seiffarth@fz-juelich.de> */ public class ComparableFilter { /** * Filters a map. All values (not keys!) that equal kick will be removed * @param map to filter * @param kick Value to kick out */ public static <T extends Comparable<T>, K> void filter(Map<K,T> map, T kick) { Set<Map.Entry<K, T>> entrySet = map.entrySet(); for(Iterator<Map.Entry<K,T>> it = entrySet.iterator(); it.hasNext();) { Map.Entry<K, T> entry = it.next(); if(entry.getValue().equals(kick)) it.remove(); } } /** * Filters a list. All values that equal kick will be removed * @param list to filter * @param kick Value to kick out * @return a reference to list (no new list!) */ public static <T extends Comparable<T>> List<T> filter(List<T> list, T kick) { for(Iterator<T> it = list.iterator(); it.hasNext();) { T val = it.next(); if(val.equals(kick)) it.remove(); } return list; } /** * Filters a double array. All values that equal kick will be removed * @param data array to filter * @param kick Value to kick out * @return a new filtered array */ public static double[] filter(double[] data, double kick) { LinkedList<Double> list = new LinkedList<Double>(); for(double value : data) { if(value != kick) list.add(value); } return Converter.listToArray(list); } }
modsim/vizardous
src/main/java/vizardous/delegate/dataFilter/ComparableFilter.java
Java
gpl-3.0
1,741
<?php return array( 'title' => 'Publicaciones', 'parent' => 'Contenido', 'name' => 'publicación|publicaciones', 'table' => array( 'id' => 'ID', 'action' => 'Acción', 'title' => 'Título', 'category_id' => 'Categoría', 'author_id' => 'Autor', 'url_alias' => 'Alias de la URL', 'author_alias' => 'Alias del autor', 'image_file' => 'Imagen', 'description' => 'Descripción', 'content' => 'Contenido', 'created_at' => 'Creado', 'status' => 'Estado', ), );
systemson/BlankBoard
resources/lang/es/articles.php
PHP
gpl-3.0
516
package com.albion.common.graph.algorithms; import com.albion.common.graph.core.v1.Edge; import com.albion.common.graph.core.v1.Graph; import com.albion.common.graph.core.v1.Vertex; import java.util.ArrayList; import java.util.List; public class BreathFirstSearch { public static Vertex locate(Graph graph, Integer source, Integer target){ List<Vertex> queue = new ArrayList<>(); Vertex root = graph.getVertex(source); queue.add(root); while(!queue.isEmpty()){ Vertex v = queue.remove(0); if(v.getId() == target.intValue()){ v.setVisited(true); return v; } List<Edge> edgeList = v.getEdgeList(); for(Edge edge : edgeList){ int vertexId = edge.getY(); Vertex w = graph.getVerticesMap().get(vertexId); if(w.isVisited() == false){ w.setVisited(true); queue.add(w); } } } return null; } }
KyleLearnedThis/data-structures
src/main/java/com/albion/common/graph/algorithms/BreathFirstSearch.java
Java
gpl-3.0
868
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Athame.PluginAPI.Service { /// <summary> /// Represents a collection of items that are retrieved as pages from a service. /// </summary> /// <typeparam name="T">The type of each item.</typeparam> public abstract class PagedMethod<T> : PagedList<T> { /// <summary> /// Default constructor. /// </summary> /// <param name="itemsPerPage">The amount of items per page to load.</param> protected PagedMethod(int itemsPerPage) { ItemsPerPage = itemsPerPage; } /// <summary> /// Retrieves the next page asynchronously and appends the result to <see cref="AllItems"/>. /// </summary> /// <returns>The next page's contents.</returns> public abstract Task<IList<T>> GetNextPageAsync(); /// <summary> /// Retrieves each page sequentially until there are none left. /// </summary> public virtual async Task LoadAllPagesAsync() { while (HasMoreItems) { await GetNextPageAsync(); } } } }
svbnet/Athame
Athame.PluginAPI/Service/PagedMethod.cs
C#
gpl-3.0
1,242
namespace Animals.Animals { public class Kitten : Cat { public Kitten(string name, int age) : base(name, age, "Female") { } public override string ProduceSound() { return "Meow"; } } }
martinmladenov/SoftUni-Solutions
CSharp OOP Basics/Exercises/04. Inheritance - Exercise/Animals/Animals/Kitten.cs
C#
gpl-3.0
261
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Platform-specific code for FreeBSD goes here. For the POSIX-compatible // parts, the implementation is in platform-posix.cc. #include <osconfig.h> #ifdef FreeBSD #include <pthread.h> #include <semaphore.h> #include <signal.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/types.h> #include <sys/ucontext.h> #include <stdlib.h> #include <sys/types.h> // mmap & munmap #include <sys/mman.h> // mmap & munmap #include <sys/stat.h> // open #include <sys/fcntl.h> // open #include <unistd.h> // getpagesize // If you don't have execinfo.h then you need devel/libexecinfo from ports. #include <strings.h> // index #include <errno.h> #include <stdarg.h> #include <limits.h> #undef MAP_TYPE #include "v8.h" #include "v8threads.h" #include "platform.h" namespace v8 { namespace internal { const char* OS::LocalTimezone(double time, TimezoneCache* cache) { if (std::isnan(time)) return ""; time_t tv = static_cast<time_t>(std::floor(time/msPerSecond)); struct tm* t = localtime(&tv); if (NULL == t) return ""; return t->tm_zone; } double OS::LocalTimeOffset(TimezoneCache* cache) { time_t tv = time(NULL); struct tm* t = localtime(&tv); // tm_gmtoff includes any daylight savings offset, so subtract it. return static_cast<double>(t->tm_gmtoff * msPerSecond - (t->tm_isdst > 0 ? 3600 * msPerSecond : 0)); } void* OS::Allocate(const size_t requested, size_t* allocated, bool executable) { const size_t msize = RoundUp(requested, getpagesize()); int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0); void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0); if (mbase == MAP_FAILED) { LOG(Isolate::Current(), StringEvent("OS::Allocate", "mmap failed")); return NULL; } *allocated = msize; return mbase; } class PosixMemoryMappedFile : public OS::MemoryMappedFile { public: PosixMemoryMappedFile(FILE* file, void* memory, int size) : file_(file), memory_(memory), size_(size) { } virtual ~PosixMemoryMappedFile(); virtual void* memory() { return memory_; } virtual int size() { return size_; } private: FILE* file_; void* memory_; int size_; }; OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) { FILE* file = fopen(name, "r+"); if (file == NULL) return NULL; fseek(file, 0, SEEK_END); int size = ftell(file); void* memory = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size, void* initial) { FILE* file = fopen(name, "w+"); if (file == NULL) return NULL; int result = fwrite(initial, size, 1, file); if (result < 1) { fclose(file); return NULL; } void* memory = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } PosixMemoryMappedFile::~PosixMemoryMappedFile() { if (memory_) munmap(memory_, size_); fclose(file_); } static unsigned StringToLong(char* buffer) { return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT } void OS::LogSharedLibraryAddresses(Isolate* isolate) { static const int MAP_LENGTH = 1024; int fd = open("/proc/self/maps", O_RDONLY); if (fd < 0) return; while (true) { char addr_buffer[11]; addr_buffer[0] = '0'; addr_buffer[1] = 'x'; addr_buffer[10] = 0; int result = read(fd, addr_buffer + 2, 8); if (result < 8) break; unsigned start = StringToLong(addr_buffer); result = read(fd, addr_buffer + 2, 1); if (result < 1) break; if (addr_buffer[2] != '-') break; result = read(fd, addr_buffer + 2, 8); if (result < 8) break; unsigned end = StringToLong(addr_buffer); char buffer[MAP_LENGTH]; int bytes_read = -1; do { bytes_read++; if (bytes_read >= MAP_LENGTH - 1) break; result = read(fd, buffer + bytes_read, 1); if (result < 1) break; } while (buffer[bytes_read] != '\n'); buffer[bytes_read] = 0; // Ignore mappings that are not executable. if (buffer[3] != 'x') continue; char* start_of_path = index(buffer, '/'); // There may be no filename in this line. Skip to next. if (start_of_path == NULL) continue; buffer[bytes_read] = 0; LOG(isolate, SharedLibraryEvent(start_of_path, start, end)); } close(fd); } void OS::SignalCodeMovingGC() { } // Constants used for mmap. static const int kMmapFd = -1; static const int kMmapFdOffset = 0; VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { } VirtualMemory::VirtualMemory(size_t size) : address_(ReserveRegion(size)), size_(size) { } VirtualMemory::VirtualMemory(size_t size, size_t alignment) : address_(NULL), size_(0) { ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment()))); size_t request_size = RoundUp(size + alignment, static_cast<intptr_t>(OS::AllocateAlignment())); void* reservation = mmap(OS::GetRandomMmapAddr(), request_size, PROT_NONE, MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, kMmapFd, kMmapFdOffset); if (reservation == MAP_FAILED) return; Address base = static_cast<Address>(reservation); Address aligned_base = RoundUp(base, alignment); ASSERT_LE(base, aligned_base); // Unmap extra memory reserved before and after the desired block. if (aligned_base != base) { size_t prefix_size = static_cast<size_t>(aligned_base - base); OS::Free(base, prefix_size); request_size -= prefix_size; } size_t aligned_size = RoundUp(size, OS::AllocateAlignment()); ASSERT_LE(aligned_size, request_size); if (aligned_size != request_size) { size_t suffix_size = request_size - aligned_size; OS::Free(aligned_base + aligned_size, suffix_size); request_size -= suffix_size; } ASSERT(aligned_size == request_size); address_ = static_cast<void*>(aligned_base); size_ = aligned_size; } VirtualMemory::~VirtualMemory() { if (IsReserved()) { bool result = ReleaseRegion(address(), size()); ASSERT(result); USE(result); } } bool VirtualMemory::IsReserved() { return address_ != NULL; } void VirtualMemory::Reset() { address_ = NULL; size_ = 0; } bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) { return CommitRegion(address, size, is_executable); } bool VirtualMemory::Uncommit(void* address, size_t size) { return UncommitRegion(address, size); } bool VirtualMemory::Guard(void* address) { OS::Guard(address, OS::CommitPageSize()); return true; } void* VirtualMemory::ReserveRegion(size_t size) { void* result = mmap(OS::GetRandomMmapAddr(), size, PROT_NONE, MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, kMmapFd, kMmapFdOffset); if (result == MAP_FAILED) return NULL; return result; } bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) { int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0); if (MAP_FAILED == mmap(base, size, prot, MAP_PRIVATE | MAP_ANON | MAP_FIXED, kMmapFd, kMmapFdOffset)) { return false; } return true; } bool VirtualMemory::UncommitRegion(void* base, size_t size) { return mmap(base, size, PROT_NONE, MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED, kMmapFd, kMmapFdOffset) != MAP_FAILED; } bool VirtualMemory::ReleaseRegion(void* base, size_t size) { return munmap(base, size) == 0; } bool VirtualMemory::HasLazyCommits() { // TODO(alph): implement for the platform. return false; } } } // namespace v8::internal #endif
jiachenning/fibjs
vender/src/v8/src/platform-freebsd.cc
C++
gpl-3.0
8,266
#! /usr/bin/env python import logging, logtool from .page import Page from .xlate_frame import XlateFrame LOG = logging.getLogger (__name__) class Contents: @logtool.log_call def __init__ (self, canvas, objects): self.canvas = canvas self.objects = objects @logtool.log_call def render (self): with Page (self.canvas) as pg: for obj in self.objects: coords = pg.next (obj.asset) with XlateFrame (self.canvas, obj.tile_type, *coords, inset_by = "margin"): # print ("Obj: ", obj.asset) obj.render ()
clearclaw/xxpaper
xxpaper/contents.py
Python
gpl-3.0
590
class CfgWeapons { // Base classes class ItemCore; class H_HelmetB; class H_Cap_red; class H_Bandanna_khk; class rhs_booniehat2_marpatd; // RHSSAF class rhssaf_helmet_base : H_HelmetB{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m59_85_nocamo : rhssaf_helmet_base{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m59_85_oakleaf : rhssaf_helmet_base{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_olive_nocamo : rhssaf_helmet_base{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_olive_nocamo_black_ess : rhssaf_helmet_base{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_olive_nocamo_black_ess_bare: rhssaf_helmet_m97_olive_nocamo_black_ess{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_black_nocamo : rhssaf_helmet_m97_olive_nocamo{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_black_nocamo_black_ess : rhssaf_helmet_m97_olive_nocamo_black_ess{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_black_nocamo_black_ess_bare: rhssaf_helmet_m97_olive_nocamo_black_ess_bare{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_woodland : rhssaf_helmet_base{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_digital : rhssaf_helmet_m97_woodland{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_md2camo : rhssaf_helmet_m97_woodland{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_oakleaf : rhssaf_helmet_m97_woodland{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_nostrap_blue : rhssaf_helmet_m97_woodland{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_nostrap_blue_tan_ess : rhssaf_helmet_m97_woodland{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_nostrap_blue_tan_ess_bare : rhssaf_helmet_m97_woodland{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_woodland_black_ess : rhssaf_helmet_m97_olive_nocamo_black_ess{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_digital_black_ess : rhssaf_helmet_m97_woodland_black_ess{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_md2camo_black_ess : rhssaf_helmet_m97_woodland_black_ess{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_oakleaf_black_ess : rhssaf_helmet_m97_woodland_black_ess{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_woodland_black_ess_bare: rhssaf_helmet_m97_woodland_black_ess{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_digital_black_ess_bare : rhssaf_helmet_m97_woodland_black_ess_bare{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_md2camo_black_ess_bare : rhssaf_helmet_m97_woodland_black_ess_bare{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_oakleaf_black_ess_bare : rhssaf_helmet_m97_woodland_black_ess_bare{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_veil_Base : rhssaf_helmet_m97_woodland{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_veil_woodland : rhssaf_helmet_m97_veil_Base{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_veil_digital : rhssaf_helmet_m97_veil_Base{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_veil_md2camo : rhssaf_helmet_m97_veil_Base{ rgoc_canAcceptNVG = 1; }; class rhssaf_helmet_m97_veil_oakleaf : rhssaf_helmet_m97_veil_Base{ rgoc_canAcceptNVG = 1; }; class rhssaf_beret_green : rhssaf_helmet_base{ rgoc_canAcceptNVG = 0; }; class rhssaf_beret_red : rhssaf_beret_green{ rgoc_canAcceptNVG = 0; }; class rhssaf_beret_para : rhssaf_beret_green{ rgoc_canAcceptNVG = 0; }; class rhssaf_beret_black : rhssaf_beret_green{ rgoc_canAcceptNVG = 0; }; class rhssaf_beret_blue_un : rhssaf_helmet_base{ rgoc_canAcceptNVG = 0; }; class rhssaf_booniehat_digital: rhs_booniehat2_marpatd{ rgoc_canAcceptNVG = 0; }; class rhssaf_booniehat_md2camo: rhs_booniehat2_marpatd{ rgoc_canAcceptNVG = 0; }; class rhssaf_booniehat_woodland: rhs_booniehat2_marpatd{ rgoc_canAcceptNVG = 0; }; class rhssaf_bandana_digital: H_Bandanna_khk{ rgoc_canAcceptNVG = 0; }; class rhssaf_bandana_digital_desert: rhssaf_bandana_digital{ rgoc_canAcceptNVG = 0; }; class rhssaf_bandana_oakleaf: rhssaf_bandana_digital{ rgoc_canAcceptNVG = 0; }; class rhssaf_bandana_smb: rhssaf_bandana_digital{ rgoc_canAcceptNVG = 0; }; class rhssaf_bandana_md2camo: rhssaf_bandana_digital{ rgoc_canAcceptNVG = 0; }; };
finesseseth/SOCOMD
rgoc_rhssaf_compat/CfgWeapons.hpp
C++
gpl-3.0
4,218
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package services; import FareCalculator.Calculate; import java.util.ArrayList; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.PathParam; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.ClassNotFoundException; import java.net.URI; import javax.ws.rs.DefaultValue; import javax.ws.rs.QueryParam; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import localstorage.FaresType; /** * * @author peppa */ @Path("/") public class calculatorService { @Context private UriInfo context; public calculatorService(){ } @GET @Path("/calculate") @Produces({"application/xml"}) public Response fareCalculator(@DefaultValue("TK") @QueryParam("carrier") String carrier, @DefaultValue("2012-01-01") @QueryParam("date") String date, @DefaultValue("ADB") @QueryParam("origCode") String origCode, @DefaultValue("ESB") @QueryParam("destCode") String destCode, @DefaultValue("Economy") @QueryParam("fareClass") String fareClass) { Calculate cal = new Calculate(); FaresType fare = cal.fareCalculate(carrier, date, origCode, destCode, fareClass); return Response.ok(new JAXBElement<FaresType>(new QName("faresType"), FaresType.class, fare)).build(); } }
ecemandirac/FlightTracker
Fare_Module/src/java/services/calculatorService.java
Java
gpl-3.0
1,825
package xyw.ning.juicer.poco.model; import xyw.ning.juicer.base.NoProguard; /** * Created by Ning-win on 2016/7/30. */ public class Size implements NoProguard { public String url; public long width; public long height; }
ningshu/Juicer
app/src/main/java/xyw/ning/juicer/poco/model/Size.java
Java
gpl-3.0
237
#include <gtest/gtest.h> #include "math/integr/WeightedIntegral.h" #include "math/integr/IntegrationDensities.h" #include <stdexcept> #include <cmath> class WeightedIntegralTest: public testing::Test { }; TEST_F(WeightedIntegralTest,Test) { rql::integr::WeightedIntegral wi(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Constant(1.0)); const double integral = wi.integrate<double(*)(double)>(cos); const double sin1 = sin(1.0); ASSERT_NEAR(sin1, integral, 1E-5); rql::integr::WeightedIntegral ws(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Sine(2.0)); const double integral2 = ws.integrate<double(*)(double)>(cos); const double cos1 = cos(1.0); const double expected2 = (1-pow(cos1, 3))*2.0/3; ASSERT_NEAR(expected2, integral2, 1E-8); rql::integr::WeightedIntegral wc(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Cosine(2.0)); const double integral3 = wc.integrate<double(*)(double)>(sin); const double expected3 = (3*cos1 - cos(3.0)-2)/6.0; ASSERT_NEAR(expected3, integral3, 1E-8); } double constant_one(double x) { return 1; } double linear(double x) { return x; } TEST_F(WeightedIntegralTest,Sine) { rql::integr::WeightedIntegral wu(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Constant(1.0)); const double integral_u = wu.integrate<double(*)(double)>(sin); ASSERT_NEAR(1 - cos(1.0), integral_u, 1E-5) << "unity"; rql::integr::WeightedIntegral ws(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Sine(1.0)); const double integral_s = ws.integrate(constant_one); ASSERT_NEAR(1 - cos(1.0), integral_s, 1E-10) << "sine_weight"; const double integral_linear = ws.integrate(linear); ASSERT_NEAR(sin(1.0) - cos(1.0), integral_linear, 1E-10); }
rilwen/open-quantum-systems
math-test/integr/WeightedIntegralTest.cpp
C++
gpl-3.0
1,913
/* * Copyright (C) 2014 Matej Kormuth <http://matejkormuth.eu> * * 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 ts3bot.helpers; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Helper for testing method signatures. */ public final class MethodSignatureTester { // Object methods. private static final List<MethodSignature> objectMethodSignatures = new ArrayList<MethodSignatureTester.MethodSignature>(); static { for (Method m : Object.class.getDeclaredMethods()) { objectMethodSignatures.add(new MethodSignature(m.getName(), m.getParameterTypes())); } } /** * Checks whether specified interface declares all of public methods implementation class declares. * * @param impl * implementation class * @param interf * interface class * @throws RuntimeException * When interface does not declare public method implementation class does */ public static final void hasInterfAllImplPublicMethods(final Class<?> impl, final Class<?> interf) { List<MethodSignature> interfMethodSignatures = new ArrayList<MethodSignature>( 100); // Generate interface method signatures. for (Method m : interf.getDeclaredMethods()) { // Interface has only public abstract methods. interfMethodSignatures.add(new MethodSignature(m.getName(), m.getParameterTypes())); } for (Method m : impl.getDeclaredMethods()) { // Checking only public methods. MethodSignature ms; if (Modifier.isPublic(m.getModifiers())) { // Build method signature. ms = new MethodSignature(m.getName(), m.getParameterTypes()); // Don't check methods derived from Object. if (!objectMethodSignatures.contains(ms)) { // Check if interface declares it. if (!interfMethodSignatures.contains(ms)) { throw new RuntimeException( "Interface '" + interf.getName() + "' does not declare method " + ms.toString() + " implemented in class '" + impl.getName() + "'!"); } } } } } /** * Class that specified method signature in Java. */ private static class MethodSignature { private final String name; private final Class<?>[] params; public MethodSignature(final String name, final Class<?>[] params) { this.name = name; this.params = params; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); result = prime * result + ((this.params == null) ? 0 : this.params.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; MethodSignature other = (MethodSignature) obj; if (this.name == null) { if (other.name != null) return false; } else if (!this.name.equals(other.name)) return false; if (this.params == null) { if (other.params != null) return false; } else if (this.params.length != other.params.length) return false; for (int i = 0; i < this.params.length; i++) { if (!this.params[i].equals(other.params[i])) { return false; } } return true; } @Override public String toString() { return "MethodSignature [name=" + this.name + ", params=" + Arrays.toString(this.params) + "]"; } } }
dobrakmato/Sergius
src/test/java/ts3bot/helpers/MethodSignatureTester.java
Java
gpl-3.0
4,969
<?php require('../../php/bdd.php'); $bdd->query('DELETE FROM general WHERE 1'); $reqe = $bdd->prepare('INSERT INTO general (name, text, date) VALUES (:label, :text, 0)'); $reqe->execute(array( "label" => 'titre_accueil', "text" => $_POST['title'] )); $reqe->CloseCursor(); $reqe = $bdd->prepare('INSERT INTO general (name, text, date) VALUES (:label, :text, 0)'); $reqe->execute(array( "label" => 'text_accueil', "text" => $_POST['text'] )); $reqe->CloseCursor(); $reqe = $bdd->prepare('INSERT INTO general (name, text, date) VALUES (:label, :text, 0)'); $reqe->execute(array( "label" => 'foot_accueil', "text" => $_POST['foot'] )); $reqe->CloseCursor(); echo "Effectué !"; ?>
atomgenie/B2cave
b2cave/b2cave/admin/php/modif_general.php
PHP
gpl-3.0
703
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Navigation; using Newegg.Oversea.Silverlight.Controls; using Newegg.Oversea.Silverlight.ControlPanel.Core.Base; using ECCentral.Portal.UI.MKT.Models; using ECCentral.Portal.UI.MKT.UserControls.Keywords; using Newegg.Oversea.Silverlight.Controls.Components; using ECCentral.Portal.UI.MKT.Facades; using ECCentral.Portal.Basic.Utilities; using ECCentral.QueryFilter.MKT; using ECCentral.BizEntity.MKT; using ECCentral.Portal.Basic; using ECCentral.BizEntity.Common; using ECCentral.BizEntity.Enum.Resources; using Newegg.Oversea.Silverlight.ControlPanel.Core; using ECCentral.Portal.UI.MKT.Resources; using Newegg.Oversea.Silverlight.Utilities.Validation; namespace ECCentral.Portal.UI.MKT.Views { [View(IsSingleton = true, SingletonType = SingletonTypes.Url)] public partial class HotKeywords : PageBase { private HotKeywordsQueryFacade facade; private HotKeywordsQueryFilter filter; private List<HotKeywordsVM> gridVM; private HotKeywordsQueryVM queryVM; private HotKeywordsQueryFilter filterVM; public HotKeywords() { InitializeComponent(); } /// <summary> /// 数据全部导出 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void QueryResultGrid_ExportAllClick(object sender, EventArgs e) { if (filterVM == null || this.QueryResultGrid.TotalCount < 1) { Window.Alert(ResKeywords.Information_ExportFailed); return; } ColumnSet col = new ColumnSet(this.QueryResultGrid); filter = queryVM.ConvertVM<HotKeywordsQueryVM, HotKeywordsQueryFilter>(); filter.PageInfo = new ECCentral.QueryFilter.Common.PagingInfo() { PageSize = ConstValue.MaxRowCountLimit, PageIndex = 0, SortBy = string.Empty }; facade.ExportExcelFile(filterVM, new ColumnSet[] { col }); } public override void OnPageLoad(object sender, EventArgs e) { facade = new HotKeywordsQueryFacade(this); filter = new HotKeywordsQueryFilter(); queryVM = new HotKeywordsQueryVM(); queryVM.CompanyCode = CPApplication.Current.CompanyCode; queryVM.ChannelID = "1"; QuerySection.DataContext = queryVM; facade.GetHotKeywordsEditUserList(CPApplication.Current.CompanyCode, (s, args) => { if (args.FaultsHandle()) return; BindEditUserList(args.Result); }); base.OnPageLoad(sender, e); } private void BindEditUserList(List<UserInfo> userList) { if (userList == null) { userList = new List<UserInfo>(); } userList.Insert(0, new UserInfo { SysNo = null, UserName = ResCommonEnum.Enum_All }); comEditUser.ItemsSource = userList; } private void QueryResultGrid_LoadingDataSource(object sender, Newegg.Oversea.Silverlight.Controls.Data.LoadingDataEventArgs e) { facade.QueryHotKeywords(QueryResultGrid.QueryCriteria as HotKeywordsQueryFilter, e.PageSize, e.PageIndex, e.SortField, (s, args) => { if (args.FaultsHandle()) return; gridVM = DynamicConverter<HotKeywordsVM>.ConvertToVMList<List<HotKeywordsVM>>(args.Result.Rows); QueryResultGrid.ItemsSource = gridVM; QueryResultGrid.TotalCount = args.Result.TotalCount; if (gridVM != null) { btnVoidItem.IsEnabled = true; btnAvailableItem.IsEnabled = true; } else { btnVoidItem.IsEnabled = false; btnAvailableItem.IsEnabled = false; } }); } /// <summary> /// 预览 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void hlViewItem_Click(object sender, RoutedEventArgs e) { HotKeywordsVM vm = QueryResultGrid.SelectedItem as HotKeywordsVM; HotKeywordsVM vmItem = gridVM.SingleOrDefault(a => a.SysNo.Value == vm.SysNo.Value); HotSearchKeyWords item = EntityConvertorExtensions.ConvertVM<HotKeywordsVM, HotSearchKeyWords>(vmItem, (v, t) => { t.Keywords = new BizEntity.LanguageContent(ConstValue.BizLanguageCode, v.Keywords); }); UCViewHotSearchKeywords usercontrol = new UCViewHotSearchKeywords(); usercontrol.Model = item; usercontrol.Dialog = Window.ShowDialog(ResKeywords.Title_ReviewHotKeywords, usercontrol, OnMaintainDialogResult); } private void btnNewItem_Click(object sender, RoutedEventArgs e) { UCAddHotKeywords usercontrol = new UCAddHotKeywords(); usercontrol.Dialog = Window.ShowDialog(ResKeywords.Title_NewHotKeywords, usercontrol, OnMaintainDialogResult); } private void OnMaintainDialogResult(object sender, ResultEventArgs args) { if (args.DialogResult == DialogResultType.OK) { filter = queryVM.ConvertVM<HotKeywordsQueryVM, HotKeywordsQueryFilter>(); filter.PageType = ucPageType.PageType; filter.PageID = ucPageType.PageID; filterVM = Newegg.Oversea.Silverlight.Utilities.UtilityHelper.DeepClone<HotKeywordsQueryFilter>(filter); QueryResultGrid.QueryCriteria = this.filter; QueryResultGrid.Bind(); } } /// <summary> /// 屏蔽 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnVoidItem_Click(object sender, RoutedEventArgs e) { List<int> invalidSysNo = new List<int>(); gridVM.ForEach(item => { if (item.IsChecked == true) invalidSysNo.Add(item.SysNo.Value); }); if (invalidSysNo.Count > 0) facade.BatchSetHotKeywordsInvalid(invalidSysNo, (obj, args) => { if (args.FaultsHandle()) return; QueryResultGrid.Bind(); Window.Alert(ResKeywords.Information_OperateSuccessful, MessageType.Information); }); else Window.Alert(ResKeywords.Information_MoreThanOneRecord, MessageType.Error); } /// <summary> /// 编辑 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void hlEdit_Click(object sender, RoutedEventArgs e) { HotKeywordsVM item = this.QueryResultGrid.SelectedItem as HotKeywordsVM; UCAddHotKeywords usercontrol = new UCAddHotKeywords(); //usercontrol.SysNo = item.SysNo.Value; usercontrol.VM = gridVM.Single(a => a.SysNo.Value == item.SysNo.Value);//item; usercontrol.Dialog = Window.ShowDialog(ResKeywords.Title_EditHotKeywords, usercontrol, OnMaintainDialogResult); } private void Button_Search_Click(object sender, RoutedEventArgs e) { if (ValidationManager.Validate(this.QuerySection)) { filter = queryVM.ConvertVM<HotKeywordsQueryVM, HotKeywordsQueryFilter>(); filter.PageType = ucPageType.PageType; filter.PageID = ucPageType.PageID; filterVM = Newegg.Oversea.Silverlight.Utilities.UtilityHelper.DeepClone<HotKeywordsQueryFilter>(filter); QueryResultGrid.QueryCriteria = this.filter; QueryResultGrid.Bind(); } } private void ckbSelectRow_Click(object sender, RoutedEventArgs e) { var checkBoxAll = sender as CheckBox; if (gridVM == null || checkBoxAll == null) return; gridVM.ForEach(item => { item.IsChecked = checkBoxAll.IsChecked ?? false; }); } /// <summary> /// 有效 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAvailableItem_Click(object sender, RoutedEventArgs e) { List<int> invalidSysNo = new List<int>(); gridVM.ForEach(item => { if (item.IsChecked == true) invalidSysNo.Add(item.SysNo.Value); }); if (invalidSysNo.Count > 0) facade.BatchSetHotKeywordsAvailable(invalidSysNo, (obj, args) => { if (args.FaultsHandle()) return; QueryResultGrid.Bind(); Window.Alert(ResKeywords.Information_OperateSuccessful, MessageType.Information); }); else Window.Alert(ResKeywords.Information_MoreThanOneRecord, MessageType.Error); } } }
ZeroOne71/ql
02_ECCentral/02_Portal/UI/ECCentral.Portal.UI.MKT/Views/HotKeywords.xaml.cs
C#
gpl-3.0
9,684
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; public class SelectOnInput : MonoBehaviour { public EventSystem eventSystem; public GameObject selectedObject; private bool buttonSelected; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetAxisRaw("Vertical") != 0 && buttonSelected == false) { eventSystem.SetSelectedGameObject(selectedObject); buttonSelected = true; } } private void OnDisable() { buttonSelected = false; } }
TheMrNomis/T-racing
Assets/Scripts/UI/SelectOnInput.cs
C#
gpl-3.0
617
package org.anddev.amatidev.pvb; import java.util.LinkedList; import org.amatidev.util.AdEnviroment; import org.amatidev.util.AdPrefs; import org.anddev.amatidev.pvb.bug.BugBeetle; import org.anddev.amatidev.pvb.card.Card; import org.anddev.amatidev.pvb.card.CardTomato; import org.anddev.amatidev.pvb.obj.Dialog; import org.anddev.amatidev.pvb.plant.Plant; import org.anddev.amatidev.pvb.singleton.GameData; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.text.Text; public class Tutorial extends MainGame { private Sprite mArrow; private int mTutorialStep = 1; @Override public void createScene() { // sfondo e tabellone Sprite back = new Sprite(0, 0, GameData.getInstance().mBackground); Sprite table = new Sprite(0, 0, GameData.getInstance().mTable); getChild(BACKGROUND_LAYER).attachChild(back); getChild(BACKGROUND_LAYER).attachChild(table); Sprite seed = new Sprite(25, 14, GameData.getInstance().mSeed); table.attachChild(seed); GameData.getInstance().mMySeed.setParent(null); table.attachChild(GameData.getInstance().mMySeed); // field position for (int i = 0; i < FIELDS; i++) { int x = i % 9; int y = (int)(i / 9); Rectangle field = new Rectangle(0, 0, 68, 74); field.setColor(0f, 0f, 0f); if (i % 2 == 0) field.setAlpha(0.05f); else field.setAlpha(0.08f); field.setPosition(42 + x * 71, 96 + y * 77); getChild(GAME_LAYER).attachChild(field); registerTouchArea(field); } } protected void initLevel() { // contatori per individuare se in una riga c'e' un nemico AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "enemy"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "enemy_killed"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count96.0"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count173.0"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count250.0"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count327.0"); AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count404.0"); GameData.getInstance().mMySeed.resetScore(); LinkedList<Card> cards = GameData.getInstance().mCards; cards.clear(); cards.add(new CardTomato()); // TUTORIAL this.mArrow = new Sprite(106, 95, GameData.getInstance().mArrow); this.mArrow.setColor(1f, 0.4f, 0.4f); this.mArrow.registerEntityModifier( new LoopEntityModifier( null, -1, null, new SequenceEntityModifier( new ScaleModifier(0.5f, 1f, 1.2f), new ScaleModifier(0.5f, 1.2f, 1f) ) ) ); getChild(GUI_LAYER).attachChild(this.mArrow); AdEnviroment.getInstance().showMessage("Select a card to use"); AdEnviroment.getInstance().showMessage("Each card has a recharge time and price"); } @Override public void startScene() { initLevel(); // add card LinkedList<Card> cards = GameData.getInstance().mCards; int start_x = 106; for (int i = 0; i < cards.size(); i++) { Card c = cards.get(i); c.setPosition(start_x + i * 69, 7); getChild(BACKGROUND_LAYER).attachChild(c); } Text skip = new Text(0, 0, GameData.getInstance().mFontTutorial, "Skip"); skip.setColor(1.0f, 0.3f, 0.3f); skip.setPosition(37, 360); getChild(GUI_LAYER).attachChild(skip); registerTouchArea(skip); } public void checkLevelFinish() { if (this.mGameOver == false && this.mLevelFinish == false) { registerUpdateHandler(new TimerHandler(2f, false, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { if (Tutorial.this.mTutorialStep == 4) { final Sprite e = new Sprite(12, 25, GameData.getInstance().mSeed); IEntity field = getChild(GAME_LAYER).getChild(12); if (field.getChildCount() == 0) field.attachChild(e); Tutorial.this.mTutorialStep++; Tutorial.this.mArrow.setPosition(310, 135); Tutorial.this.mArrow.setRotation(-132f); AdEnviroment.getInstance().showMessage("Pick the seeds producing the field to increase the stock"); } } })); } } private void levelFinish() { if (this.mGameOver == false && this.mLevelFinish == false) { Dialog dialog = new Dialog("Tutorial\nComplete"); getChild(GUI2_LAYER).attachChild(dialog); clearScene(); registerUpdateHandler(new TimerHandler(6, false, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { AdEnviroment.getInstance().nextScene(); } })); this.mLevelFinish = true; GameData.getInstance().mMyScore.resetScore(); } } @Override public void manageAreaTouch(ITouchArea pTouchArea) { if (pTouchArea instanceof Card) { GameData.getInstance().mSoundCard.play(); this.mSelect = ((Card) pTouchArea).makeSelect(); // TUTORIAL if (this.mTutorialStep == 1) { this.mTutorialStep++; this.mArrow.setPosition(595, 203); this.mArrow.setRotation(132f); AdEnviroment.getInstance().showMessage("If bugs incoming, try to kill them by planting"); BugBeetle e = new BugBeetle(250f); getChild(GAME_LAYER).attachChild(e); registerUpdateHandler(new TimerHandler(6f, false, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { Tutorial.this.mTutorialStep++; Tutorial.this.mArrow.setPosition(100, 203); Tutorial.this.mArrow.setRotation(-132f); AdEnviroment.getInstance().showMessage("If you have enough seeds you can plant"); } })); } } else { IEntity field = (IEntity) pTouchArea; if (field.getChildCount() == 1 && !(field.getFirstChild() instanceof Plant)) { GameData.getInstance().mSoundSeed.play(); GameData.getInstance().mMySeed.addScore(1); AdEnviroment.getInstance().safeDetachEntity(field.getFirstChild()); if (this.mTutorialStep == 5) { this.mTutorialStep++; this.mArrow.setPosition(17, 95); this.mArrow.setRotation(0f); AdEnviroment.getInstance().showMessage("Seeds stock are increased to +1"); AdEnviroment.getInstance().showMessage("Kill bugs to complete levels and obtain score and new plants"); registerUpdateHandler(new TimerHandler(9f, false, new ITimerCallback() { @Override public void onTimePassed(TimerHandler pTimerHandler) { AdEnviroment.getInstance().getEngine().runOnUpdateThread(new Runnable() { @Override public void run() { Tutorial.this.levelFinish(); } }); } })); } } else if (field instanceof Text) { GameData.getInstance().mSoundMenu.play(); AdEnviroment.getInstance().nextScene(); } else { if (this.mSelect != null && this.mSelect.isReady() && field.getChildCount() == 0 && this.mTutorialStep >= 3 && field.getY() == 250.0f) { if (GameData.getInstance().mMySeed.getScore() >= this.mSelect.getPrice()) { GameData.getInstance().mMySeed.addScore(-this.mSelect.getPrice()); this.mSelect.startRecharge(); field.attachChild(this.mSelect.getPlant()); // TUTORIAL if (this.mTutorialStep == 3) { this.mTutorialStep++; this.mArrow.setPosition(17, 95); this.mArrow.setRotation(0f); AdEnviroment.getInstance().showMessage("Seeds stock are decreased because you bought a plant"); } } } } } } }
amatig/PlantsVsBugs
src/org/anddev/amatidev/pvb/Tutorial.java
Java
gpl-3.0
7,881
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn 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. * * Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.engine.backgroundtasks.config; /** * <p> * Class containing strings that describe the Kafka queues and groups * </p> * * @author Denis Lobanov, alexandraorth */ public interface KafkaTerms { String TASK_RUNNER_GROUP = "task-runners"; String SCHEDULERS_GROUP = "schedulers"; String WORK_QUEUE_TOPIC = "work-queue"; String NEW_TASKS_TOPIC = "new-tasks"; String LOG_TOPIC = "logs"; }
mikonapoli/grakn
grakn-engine/src/main/java/ai/grakn/engine/backgroundtasks/config/KafkaTerms.java
Java
gpl-3.0
1,152
function HistoryAssistant() { } HistoryAssistant.prototype.setup = function() { this.appMenuModel = { visible: true, items: [ { label: $L("About"), command: 'about' }, { label: $L("Help"), command: 'tutorial' }, ] }; this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel); var attributes = {}; this.model = { //backgroundImage : 'images/glacier.png', background: 'black', onLeftFunction : this.wentLeft.bind(this), onRightFunction : this.wentRight.bind(this) } this.controller.setupWidget('historydiv', attributes, this.model); this.myPhotoDivElement = $('historydiv'); this.timestamp = new Date().getTime(); var env = Mojo.Environment.DeviceInfo; if (env.screenHeight <= 400) this.myPhotoDivElement.style.height = "372px"; } HistoryAssistant.prototype.wentLeft = function(event){ this.timestamp = this.timestamp - (1000*60*60*24); var timenow = new Date(this.timestamp); var timenowstring = ""; var Ayear = timenow.getUTCFullYear(); var Amonth = timenow.getUTCMonth()+1; if(Amonth.toString().length < 2) Amonth = "0" + Amonth; var Aday = timenow.getUTCDate(); if(Aday.toString().length < 2) Aday = "0" + Aday; /*var Ahours = timenow.getUTCHours(); if(Ahours.toString().length < 2) Ahours = "0" + Ahours;*/ Ahours = "00"; if (this.timestamp > 1276146000000) { if (this.timestamp > 1276146000000 + (1000 * 60 * 60 * 24)) { this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png"); } this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png"); this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png"); } $('text').innerHTML = "<center>Histoy Of Pixels&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;" + Ayear + " / " + Amonth + " / " + Aday + "</center>"; } HistoryAssistant.prototype.wentRight = function(event){ this.timestamp = this.timestamp + (1000*60*60*24); var timenow = new Date(this.timestamp); var timenowstring = ""; var Ayear = timenow.getUTCFullYear(); var Amonth = timenow.getUTCMonth()+1; if(Amonth.toString().length < 2) Amonth = "0" + Amonth; var Aday = timenow.getUTCDate(); if(Aday.toString().length < 2) Aday = "0" + Aday; /*var Ahours = timenow.getUTCHours(); if(Ahours.toString().length < 2) Ahours = "0" + Ahours;*/ Ahours = "00"; if (this.timestamp < new Date().getTime()) { this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png"); this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png"); if (this.timestamp + (1000*60*60*24) < new Date().getTime()) { this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png"); } } $('text').innerHTML = "<center>Histoy Of Pixels&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;" + Ayear + " / " + Amonth + " / " + Aday + "</center>"; } HistoryAssistant.prototype.activate = function(event) { var timenow = new Date(this.timestamp); var timenowstring = ""; var Ayear = timenow.getUTCFullYear(); var Amonth = timenow.getUTCMonth()+1; if(Amonth.toString().length < 2) Amonth = "0" + Amonth; var Aday = timenow.getUTCDate(); if(Aday.toString().length < 2) Aday = "0" + Aday; /*var Ahours = timenow.getUTCHours(); if(Ahours.toString().length < 2) Ahours = "0" + Ahours;*/ Ahours = "00"; this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday-1) + Ahours + ".png"); this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png"); //this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday+1) + Ahours + ".png"); $('text').innerHTML = "<center>Histoy Of Pixels&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;" + Ayear + " / " + Amonth + " / " + Aday + "</center>"; } HistoryAssistant.prototype.deactivate = function(event) { } HistoryAssistant.prototype.cleanup = function(event) { } HistoryAssistant.prototype.handleCommand = function(event){ if(event.type == Mojo.Event.command) { switch (event.command) { case 'about': Mojo.Controller.stageController.pushScene("about"); break; case 'tutorial': this.controller.showAlertDialog({ onChoose: function(value) {}, title:"Help", message:"This is the history of all pixels user have every created. Every night there is made a new snapshot.<br><br>Flip the image left or right to go through the history. Zoom into the image for more details.", allowHTMLMessage: true, choices:[ {label:'OK', value:'OK', type:'color'} ] }); break; } } }
sebastianha/webos-app_de.omoco.100pixels
app/assistants/history-assistant.js
JavaScript
gpl-3.0
4,982
/* Copyright 2016 Devon Call, Zeke Hunter-Green, Paige Ormiston, Joe Renner, Jesse Sliter This file is part of Myrge. Myrge 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. Myrge 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 Myrge. If not, see <http://www.gnu.org/licenses/>. */ app.controller('NavCtrl', [ '$scope', '$state', 'auth', function($scope, $state, auth){ $scope.isLoggedIn = auth.isLoggedIn; $scope.currentUser = auth.currentUser; $scope.logOut = auth.logOut; $scope.loggedin = auth.isLoggedIn(); if($scope.loggedin){ auth.validate(auth.getToken()).success(function(data){ if(!data.valid){ auth.logOut(); $state.go("login"); } }); } }]);
Decision-Maker/sp
public/javascripts/Controllers/navController.js
JavaScript
gpl-3.0
1,136
# Topydo - A todo.txt client written in Python. # Copyright (C) 2014 - 2015 Bram Schoenmakers <bram@topydo.org> # # 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/>. """ This module provides the Todo class. """ from datetime import date from topydo.lib.Config import config from topydo.lib.TodoBase import TodoBase from topydo.lib.Utils import date_string_to_date class Todo(TodoBase): """ This class adds common functionality with respect to dates to the Todo base class, mainly by interpreting the start and due dates of task. """ def __init__(self, p_str): TodoBase.__init__(self, p_str) self.attributes = {} def get_date(self, p_tag): """ Given a date tag, return a date object. """ string = self.tag_value(p_tag) result = None try: result = date_string_to_date(string) if string else None except ValueError: pass return result def start_date(self): """ Returns a date object of the todo's start date. """ return self.get_date(config().tag_start()) def due_date(self): """ Returns a date object of the todo's due date. """ return self.get_date(config().tag_due()) def is_active(self): """ Returns True when the start date is today or in the past and the task has not yet been completed. """ start = self.start_date() return not self.is_completed() and (not start or start <= date.today()) def is_overdue(self): """ Returns True when the due date is in the past and the task has not yet been completed. """ return not self.is_completed() and self.days_till_due() < 0 def days_till_due(self): """ Returns the number of days till the due date. Returns a negative number of days when the due date is in the past. Returns 0 when the task has no due date. """ due = self.due_date() if due: diff = due - date.today() return diff.days return 0 def length(self): """ Returns the length (in days) of the task, by considering the start date and the due date. When there is no start date, its creation date is used. Returns 0 when one of these dates is missing. """ start = self.start_date() or self.creation_date() due = self.due_date() if start and due and start < due: diff = due - start return diff.days else: return 0
bram85/topydo
topydo/lib/Todo.py
Python
gpl-3.0
3,165
import java.util.Scanner; public class FeetMeters { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Number of feet: "); float feet = keyboard.nextInt(); float foottometers = (float) .305; System.out.println(""); System.out.print("Number of meters: "); float meters = (float) .305 * feet; System.out.println(meters); } }
semiconductor7/java-101
Projects_import/Project1/src/FeetMeters.java
Java
gpl-3.0
467
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Web service functions relating to point grades and grading. * * @package core_grades * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ declare(strict_types = 1); namespace core_grades\grades\grader\gradingpanel\point\external; use coding_exception; use context; use core_user; use core_grades\component_gradeitem as gradeitem; use core_grades\component_gradeitems; use external_api; use external_function_parameters; use external_multiple_structure; use external_single_structure; use external_value; use external_warnings; use moodle_exception; use required_capability_exception; /** * External grading panel point API * * @package core_grades * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class store extends external_api { /** * Describes the parameters for fetching the grading panel for a simple grade. * * @return external_function_parameters * @since Moodle 3.8 */ public static function execute_parameters(): external_function_parameters { return new external_function_parameters ([ 'component' => new external_value( PARAM_ALPHANUMEXT, 'The name of the component', VALUE_REQUIRED ), 'contextid' => new external_value( PARAM_INT, 'The ID of the context being graded', VALUE_REQUIRED ), 'itemname' => new external_value( PARAM_ALPHANUM, 'The grade item itemname being graded', VALUE_REQUIRED ), 'gradeduserid' => new external_value( PARAM_INT, 'The ID of the user show', VALUE_REQUIRED ), 'notifyuser' => new external_value( PARAM_BOOL, 'Wheteher to notify the user or not', VALUE_DEFAULT, false ), 'formdata' => new external_value( PARAM_RAW, 'The serialised form data representing the grade', VALUE_REQUIRED ), ]); } /** * Fetch the data required to build a grading panel for a simple grade. * * @param string $component * @param int $contextid * @param string $itemname * @param int $gradeduserid * @param bool $notifyuser * @param string $formdata * @return array * @throws \dml_exception * @throws \invalid_parameter_exception * @throws \restricted_context_exception * @throws coding_exception * @throws moodle_exception * @since Moodle 3.8 */ public static function execute(string $component, int $contextid, string $itemname, int $gradeduserid, bool $notifyuser, string $formdata): array { global $USER; [ 'component' => $component, 'contextid' => $contextid, 'itemname' => $itemname, 'gradeduserid' => $gradeduserid, 'notifyuser' => $notifyuser, 'formdata' => $formdata, ] = self::validate_parameters(self::execute_parameters(), [ 'component' => $component, 'contextid' => $contextid, 'itemname' => $itemname, 'gradeduserid' => $gradeduserid, 'notifyuser' => $notifyuser, 'formdata' => $formdata, ]); // Validate the context. $context = context::instance_by_id($contextid); self::validate_context($context); // Validate that the supplied itemname is a gradable item. if (!component_gradeitems::is_valid_itemname($component, $itemname)) { throw new coding_exception("The '{$itemname}' item is not valid for the '{$component}' component"); } // Fetch the gradeitem instance. $gradeitem = gradeitem::instance($component, $context, $itemname); // Validate that this gradeitem is actually enabled. if (!$gradeitem->is_grading_enabled()) { throw new moodle_exception("Grading is not enabled for {$itemname} in this context"); } // Fetch the record for the graded user. $gradeduser = \core_user::get_user($gradeduserid); // Require that this user can save grades. $gradeitem->require_user_can_grade($gradeduser, $USER); if (!$gradeitem->is_using_direct_grading()) { throw new moodle_exception("The {$itemname} item in {$component}/{$contextid} is not configured for direct grading"); } // Parse the serialised string into an object. $data = []; parse_str($formdata, $data); // Grade. $gradeitem->store_grade_from_formdata($gradeduser, $USER, (object) $data); $hasgrade = $gradeitem->user_has_grade($gradeduser); // Notify. if ($notifyuser) { // Send notification. $gradeitem->send_student_notification($gradeduser, $USER); } // Fetch the updated grade back out. $grade = $gradeitem->get_grade_for_user($gradeduser, $USER); return fetch::get_fetch_data($grade, $hasgrade, 0); } /** * Describes the data returned from the external function. * * @return external_single_structure * @since Moodle 3.8 */ public static function execute_returns(): external_single_structure { return fetch::execute_returns(); } }
dustinbrisebois/moodle
grade/classes/grades/grader/gradingpanel/point/external/store.php
PHP
gpl-3.0
6,329
from pupa.scrape import Jurisdiction, Organization from .bills import MNBillScraper from .committees import MNCommitteeScraper from .people import MNPersonScraper from .vote_events import MNVoteScraper from .events import MNEventScraper from .common import url_xpath """ Minnesota legislative data can be found at the Office of the Revisor of Statutes: https://www.revisor.mn.gov/ Votes: There are not detailed vote data for Senate votes, simply yes and no counts. Bill pages have vote counts and links to House details, so it makes more sense to get vote data from the bill pages. """ class Minnesota(Jurisdiction): division_id = "ocd-division/country:us/state:mn" classification = "government" name = "Minnesota" url = "http://state.mn.us/" check_sessions = True scrapers = { "bills": MNBillScraper, "committees": MNCommitteeScraper, "people": MNPersonScraper, "vote_events": MNVoteScraper, "events": MNEventScraper, } parties = [{'name': 'Republican'}, {'name': 'Democratic-Farmer-Labor'}] legislative_sessions = [ { '_scraped_name': '86th Legislature, 2009-2010', 'classification': 'primary', 'identifier': '2009-2010', 'name': '2009-2010 Regular Session' }, { '_scraped_name': '86th Legislature, 2010 1st Special Session', 'classification': 'special', 'identifier': '2010 1st Special Session', 'name': '2010, 1st Special Session' }, { '_scraped_name': '86th Legislature, 2010 2nd Special Session', 'classification': 'special', 'identifier': '2010 2nd Special Session', 'name': '2010, 2nd Special Session' }, { '_scraped_name': '87th Legislature, 2011-2012', 'classification': 'primary', 'identifier': '2011-2012', 'name': '2011-2012 Regular Session' }, { '_scraped_name': '87th Legislature, 2011 1st Special Session', 'classification': 'special', 'identifier': '2011s1', 'name': '2011, 1st Special Session' }, { '_scraped_name': '87th Legislature, 2012 1st Special Session', 'classification': 'special', 'identifier': '2012s1', 'name': '2012, 1st Special Session' }, { '_scraped_name': '88th Legislature, 2013-2014', 'classification': 'primary', 'identifier': '2013-2014', 'name': '2013-2014 Regular Session' }, { '_scraped_name': '88th Legislature, 2013 1st Special Session', 'classification': 'special', 'identifier': '2013s1', 'name': '2013, 1st Special Session' }, { '_scraped_name': '89th Legislature, 2015-2016', 'classification': 'primary', 'identifier': '2015-2016', 'name': '2015-2016 Regular Session' }, { '_scraped_name': '89th Legislature, 2015 1st Special Session', 'classification': 'special', 'identifier': '2015s1', 'name': '2015, 1st Special Session' }, { '_scraped_name': '90th Legislature, 2017-2018', 'classification': 'primary', 'identifier': '2017-2018', 'name': '2017-2018 Regular Session' }, ] ignored_scraped_sessions = [ '85th Legislature, 2007-2008', '85th Legislature, 2007 1st Special Session', '84th Legislature, 2005-2006', '84th Legislature, 2005 1st Special Session', '83rd Legislature, 2003-2004', '83rd Legislature, 2003 1st Special Session', '82nd Legislature, 2001-2002', '82nd Legislature, 2002 1st Special Session', '82nd Legislature, 2001 1st Special Session', '81st Legislature, 1999-2000', '80th Legislature, 1997-1998', '80th Legislature, 1998 1st Special Session', '80th Legislature, 1997 3rd Special Session', '80th Legislature, 1997 2nd Special Session', '80th Legislature, 1997 1st Special Session', '79th Legislature, 1995-1996', '79th Legislature, 1995 1st Special Session', '89th Legislature, 2015-2016', ] def get_organizations(self): legis = Organization('Minnesota Legislature', classification='legislature') upper = Organization('Minnesota Senate', classification='upper', parent_id=legis._id) lower = Organization('Minnesota House of Representatives', classification='lower', parent_id=legis._id) for n in range(1, 68): upper.add_post(label=str(n), role='Senator', division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n)) lower.add_post(label=str(n) + 'A', role='Representative', division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n)) lower.add_post(label=str(n) + 'B', role='Representative', division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n)) yield legis yield upper yield lower def get_session_list(self): return url_xpath('https://www.revisor.mn.gov/revisor/pages/' 'search_status/status_search.php?body=House', '//select[@name="session"]/option/text()')
cliftonmcintosh/openstates
openstates/mn/__init__.py
Python
gpl-3.0
5,612