repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
mannd/epcalipers-windows | epcalipers/epcalipers/Properties/AboutBox1.cs | 3772 | using System;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Windows.Forms;
namespace epcalipers.Properties
{
partial class AboutBox1 : Form
{
public AboutBox1()
{
InitializeComponent();
this.Text = String.Format(CultureInfo.CurrentCulture, "About {0}", AssemblyTitle);
this.labelProductName.Text = AssemblyProduct;
this.labelVersion.Text = String.Format(CultureInfo.CurrentCulture, "Version {0}", AssemblyVersion);
this.labelCopyright.Text = AssemblyCopyright;
this.labelCompanyName.Text = AssemblyCompany;
this.textBoxDescription.Text = AssemblyDescription;
}
#region Assembly Attribute Accessors
public static string AssemblyTitle
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
if (attributes.Length > 0)
{
AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
if (!String.IsNullOrEmpty(titleAttribute.Title))
{
return titleAttribute.Title;
}
}
return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
public static string AssemblyVersion
{
get
{
Assembly assembly = Assembly.GetExecutingAssembly();
return FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion;
}
}
public static string AssemblyDescription
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyDescriptionAttribute)attributes[0]).Description;
}
}
public static string AssemblyProduct
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyProductAttribute)attributes[0]).Product;
}
}
public static string AssemblyCopyright
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}
public static string AssemblyCompany
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
#endregion
private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
this.LinkLabel1.LinkVisited = true;
// Navigate to a URL.
System.Diagnostics.Process.Start("https://www.epstudiossoftware.com");
}
}
}
| gpl-3.0 |
RobertLemmens/JVerify | src/codebulb/engines/TrackingEngine.java | 3165 | package codebulb.engines;
import codebulb.controllers.TrackingController;
import codebulb.models.HashedFile;
import java.io.File;
/**
* his class is in charge of tracking the folder we've selected in the TrackingSouthPanel. It will notify the trackingcontroller of any newly found files. The trackingcontroller is in charge of telling the tree
* view that there is a new file so it can update itself.
*/
public class TrackingEngine implements Runnable{
private boolean isRunning = false;
private Thread draad;
private String folderToTrack = "";
private File trackedFolder;
private TrackingController trackingController;
/**
* Constructor sets the objects needed to start the thread
*
* @param folderToTrack
* @param trackingController
*/
public TrackingEngine(String folderToTrack, TrackingController trackingController) {
this.folderToTrack = folderToTrack;
trackedFolder = new File(folderToTrack);
this.trackingController = trackingController;
}
/**
* Start the thread. If theres no folder do nothing.
*/
public synchronized void start() {
if(folderToTrack.equals("")) {
System.out.println("No folder selected");
} else {
System.out.println("Starting thread");
draad = new Thread(this);
isRunning = true;
draad.start();
}
}
/**
* Stop the thread.
*/
public synchronized void stop() {
isRunning = false;
if(isRunning == false) {
System.out.println("Thread already stopped");
} else {
try {
draad.join(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
draad = null;
}
}
@Override
public void run() {
while(isRunning) {
fileSearcher();
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println(e.getMessage());
System.out.println("Thread mocht niet slapen");
}
}
}
private int currentSize = 0;
/**
* Method that looks for new files in the supplied directory.
*
* Gets called every thread cycle.
*/
public void fileSearcher() {
trackedFolder = new File(folderToTrack);
for(File f : trackedFolder.listFiles()) {
if(f.isFile()) {
trackingController.addToFiles(f);
if(trackingController.getFiles().size() > currentSize) {
System.out.println("A file was added.");
currentSize = trackingController.getFiles().size();
System.out.println("Size: " + currentSize);
trackingController.hashFile(f, true);
trackingController.addToUniekIdLijst(HashedFile.hashCounter);
trackingController.updateTreeView(f);
}
System.out.println("Elements in set: " + trackingController.getFiles().size());
}
}
}
}
| gpl-3.0 |
tbille/mapus | app/src/main/java/com/m2dl/mapus/mapus/edt/EmploiDuTempsAdapter.java | 2604 | package com.m2dl.mapus.mapus.edt;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.vision.text.Text;
import com.m2dl.mapus.mapus.R;
import com.m2dl.mapus.mapus.model.Event;
import java.util.ArrayList;
/**
* Created by Clement on 16/03/2017.
*/
public class EmploiDuTempsAdapter extends ArrayAdapter<Event> implements View.OnClickListener{
private ArrayList<Event> ListeCours;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtVersion;
ImageView info;
}
public EmploiDuTempsAdapter(ArrayList<Event> data, Context context) {
super(context, R.layout.emploi_du_temps_row, data);
this.ListeCours = data;
this.mContext=context;
}
@Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
Event dataModel=(Event)object;
}
private int lastPosition = -1;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Event cours = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
TextView coursName = new TextView(mContext);
TextView salle = new TextView(mContext);
TextView startTime = new TextView(mContext);
TextView endTime = new TextView(mContext);
final View result;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.emploi_du_temps_row, parent, false);
coursName = (TextView) convertView.findViewById(R.id.matiere);
salle = (TextView) convertView.findViewById(R.id.salle);
startTime = (TextView) convertView.findViewById(R.id.start_date);
endTime = (TextView) convertView.findViewById(R.id.end_date);
result=convertView;
} else {
result=convertView;
}
lastPosition = position;
coursName.setText(cours.getMatiere());
salle.setText(cours.getSalle());
startTime.setText(cours.getStartTime());
endTime.setText(cours.getEndTime());
// Return the completed view to render on screen
return convertView;
}
} | gpl-3.0 |
stedt-project/sss | site/variations/disabled20110819/search_experiment/gloss.php | 624 | <?php
ini_set('display_errors', 'On');
$input = mysql_escape_string($_GET["q"]);
$data = array();
// query your DataBase here looking for a match to $input
$mysql=mysql_connect('localhost','root','');
mysql_select_db('stedt');
$query = mysql_query("SELECT word FROM stedt.searchwords WHERE word LIKE '$input%' limit 30");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = preg_replace("/[\)\(\]\[\*]/","",$row['word']);
$json['name'] = 'word';
$data[] = $json;
}
// header("Content-type: text/json");
echo json_encode($data);
?> | gpl-3.0 |
CeON/saos | saos-restful-web-api/src/main/java/pl/edu/icm/saos/api/dump/judgment/views/DumpJudgmentsView.java | 5585 | package pl.edu.icm.saos.api.dump.judgment.views;
import java.io.Serializable;
import pl.edu.icm.saos.api.dump.judgment.item.representation.JudgmentItem;
import pl.edu.icm.saos.api.dump.judgment.views.DumpJudgmentsView.Info;
import pl.edu.icm.saos.api.dump.judgment.views.DumpJudgmentsView.QueryTemplate;
import pl.edu.icm.saos.api.services.representations.success.CollectionRepresentation;
import pl.edu.icm.saos.api.services.representations.success.template.JudgmentDateFromTemplate;
import pl.edu.icm.saos.api.services.representations.success.template.JudgmentDateToTemplate;
import pl.edu.icm.saos.api.services.representations.success.template.PageNumberTemplate;
import pl.edu.icm.saos.api.services.representations.success.template.PageSizeTemplate;
import pl.edu.icm.saos.api.services.representations.success.template.QueryParameterRepresentation;
import pl.edu.icm.saos.api.services.representations.success.template.WithGeneratedTemplate;
import com.google.common.base.Objects;
/**
* Represents dump judgment's view.
* @author pavtel
*/
public class DumpJudgmentsView extends CollectionRepresentation<JudgmentItem,QueryTemplate,Info>{
private static final long serialVersionUID = 4022463253207924760L;
public static class QueryTemplate implements Serializable {
private static final long serialVersionUID = 2917013631537796073L;
private PageNumberTemplate pageNumber;
private PageSizeTemplate pageSize;
private JudgmentDateFromTemplate judgmentStartDate;
private JudgmentDateToTemplate judgmentEndDate;
private SinceModificationDateTemplate sinceModificationDate;
private WithGeneratedTemplate withGeneratedTemplate;
//------------------------ GETTERS --------------------------
public PageNumberTemplate getPageNumber() {
return pageNumber;
}
public PageSizeTemplate getPageSize() {
return pageSize;
}
public JudgmentDateFromTemplate getJudgmentStartDate() {
return judgmentStartDate;
}
public JudgmentDateToTemplate getJudgmentEndDate() {
return judgmentEndDate;
}
public SinceModificationDateTemplate getSinceModificationDate() {
return sinceModificationDate;
}
public WithGeneratedTemplate getWithGenerated() {
return withGeneratedTemplate;
}
//------------------------ SETTERS --------------------------
public void setPageNumber(PageNumberTemplate pageNumber) {
this.pageNumber = pageNumber;
}
public void setPageSize(PageSizeTemplate pageSize) {
this.pageSize = pageSize;
}
public void setJudgmentStartDate(JudgmentDateFromTemplate judgmentStartDate) {
this.judgmentStartDate = judgmentStartDate;
}
public void setJudgmentEndDate(JudgmentDateToTemplate judgmentEndDate) {
this.judgmentEndDate = judgmentEndDate;
}
public void setSinceModificationDate(SinceModificationDateTemplate sinceModificationDate) {
this.sinceModificationDate = sinceModificationDate;
}
public void setWithGenerated(WithGeneratedTemplate withGeneratedTemplate) {
this.withGeneratedTemplate = withGeneratedTemplate;
}
//------------------------ HashCode & Equals --------------------------
@Override
public int hashCode() {
return Objects.hashCode(pageNumber, pageSize, judgmentStartDate, judgmentEndDate, sinceModificationDate, withGeneratedTemplate);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final QueryTemplate other = (QueryTemplate) obj;
return Objects.equal(this.pageNumber, other.pageNumber)
&& Objects.equal(this.pageSize, other.pageSize)
&& Objects.equal(this.judgmentStartDate, other.judgmentStartDate)
&& Objects.equal(this.judgmentEndDate, other.judgmentEndDate)
&& Objects.equal(this.sinceModificationDate, other.sinceModificationDate)
&& Objects.equal(this.withGeneratedTemplate, other.withGeneratedTemplate);
}
//------------------------ toString --------------------------
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("pageNumber", pageNumber)
.add("pageSize", pageSize)
.add("judgmentStartDate", judgmentStartDate)
.add("judgmentEndDate", judgmentEndDate)
.add("sinceModificationDate", sinceModificationDate)
.add("withGenerated", withGeneratedTemplate)
.toString();
}
}
public static class SinceModificationDateTemplate extends QueryParameterRepresentation<String, String>{
public SinceModificationDateTemplate(String value) {
super(value);
setDescription("Allows you to select judgments which were modified later than the specified dateTime");
setAllowedValues("DateTime in format : yyyy-MM-dd'T'HH:mm:ss.SSS");
}
}
public static class Info implements Serializable {
private static final long serialVersionUID = -5251423299613288852L;
}
}
| gpl-3.0 |
zeduardu/moodle | lib/tests/gradelib_test.php | 7477 | <?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/>.
/**
* Unit tests for /lib/gradelib.php.
*
* @package core_grades
* @category phpunit
* @copyright 2012 Andrew Davis
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->libdir . '/gradelib.php');
class core_gradelib_testcase extends advanced_testcase {
public function test_grade_update_mod_grades() {
$this->resetAfterTest(true);
// Create a broken module instance.
$modinstance = new stdClass();
$modinstance->modname = 'doesntexist';
$this->assertFalse(grade_update_mod_grades($modinstance));
// A debug message should have been generated.
$this->assertDebuggingCalled();
// Create a course and instance of mod_assign.
$course = $this->getDataGenerator()->create_course();
$assigndata['course'] = $course->id;
$assigndata['name'] = 'lightwork assignment';
$modinstance = self::getDataGenerator()->create_module('assign', $assigndata);
// Function grade_update_mod_grades() requires 2 additional properties, cmidnumber and modname.
$cm = get_coursemodule_from_instance('assign', $modinstance->id, 0, false, MUST_EXIST);
$modinstance->cmidnumber = $cm->id;
$modinstance->modname = 'assign';
$this->assertTrue(grade_update_mod_grades($modinstance));
}
/**
* Tests the function remove_grade_letters().
*/
public function test_remove_grade_letters() {
global $DB;
$this->resetAfterTest();
$course = $this->getDataGenerator()->create_course();
$context = context_course::instance($course->id);
// Add a grade letter to the course.
$letter = new stdClass();
$letter->letter = 'M';
$letter->lowerboundary = '100';
$letter->contextid = $context->id;
$DB->insert_record('grade_letters', $letter);
remove_grade_letters($context, false);
// Confirm grade letter was deleted.
$this->assertEquals(0, $DB->count_records('grade_letters'));
}
/**
* Tests the function grade_course_category_delete().
*/
public function test_grade_course_category_delete() {
global $DB;
$this->resetAfterTest();
$category = core_course_category::create(array('name' => 'Cat1'));
// Add a grade letter to the category.
$letter = new stdClass();
$letter->letter = 'M';
$letter->lowerboundary = '100';
$letter->contextid = context_coursecat::instance($category->id)->id;
$DB->insert_record('grade_letters', $letter);
grade_course_category_delete($category->id, '', false);
// Confirm grade letter was deleted.
$this->assertEquals(0, $DB->count_records('grade_letters'));
}
/**
* Tests the function grade_regrade_final_grades().
*/
public function test_grade_regrade_final_grades() {
global $DB;
$this->resetAfterTest();
// Setup some basics.
$course = $this->getDataGenerator()->create_course();
$user = $this->getDataGenerator()->create_user();
$this->getDataGenerator()->enrol_user($user->id, $course->id, 'student');
// We need two grade items.
$params = ['idnumber' => 'g1', 'courseid' => $course->id];
$g1 = new grade_item($this->getDataGenerator()->create_grade_item($params));
unset($params['idnumber']);
$g2 = new grade_item($this->getDataGenerator()->create_grade_item($params));
$category = new grade_category($this->getDataGenerator()->create_grade_category($params));
$catitem = $category->get_grade_item();
// Now set a calculation.
$catitem->set_calculation('=[[g1]]');
$catitem->update();
// Everything needs updating.
$this->assertEquals(4, $DB->count_records('grade_items', ['courseid' => $course->id, 'needsupdate' => 1]));
grade_regrade_final_grades($course->id);
// See that everything has been updated.
$this->assertEquals(0, $DB->count_records('grade_items', ['courseid' => $course->id, 'needsupdate' => 1]));
$g1->delete();
// Now there is one that needs updating.
$this->assertEquals(1, $DB->count_records('grade_items', ['courseid' => $course->id, 'needsupdate' => 1]));
// This can cause an infinite loop if things go... poorly.
grade_regrade_final_grades($course->id);
// Now because of the failure, two things need updating.
$this->assertEquals(2, $DB->count_records('grade_items', ['courseid' => $course->id, 'needsupdate' => 1]));
}
/**
* Tests for the grade_get_date_for_user_grade function.
*
* @dataProvider grade_get_date_for_user_grade_provider
* @param stdClass $grade
* @param stdClass $user
* @param int $expected
*/
public function test_grade_get_date_for_user_grade(stdClass $grade, stdClass $user, int $expected): void {
$this->assertEquals($expected, grade_get_date_for_user_grade($grade, $user));
}
/**
* Data provider for tests of the grade_get_date_for_user_grade function.
*
* @return array
*/
public function grade_get_date_for_user_grade_provider(): array {
$u1 = (object) [
'id' => 42,
];
$u2 = (object) [
'id' => 930,
];
$d1 = 1234567890;
$d2 = 9876543210;
$g1 = (object) [
'usermodified' => $u1->id,
'dategraded' => $d1,
'datesubmitted' => $d2,
];
$g2 = (object) [
'usermodified' => $u1->id,
'dategraded' => $d1,
'datesubmitted' => 0,
];
return [
'If the user is the last person to have modified the grade_item then show the date that it was graded' => [
$g1,
$u1,
$d1,
],
'If the user is not the last person to have modified the grade_item, ' .
'and there is no submission date, then show the date that it was submitted' => [
$g1,
$u2,
$d2,
],
'If the user is not the last person to have modified the grade_item, ' .
'but there is no submission date, then show the date that it was graded' => [
$g2,
$u2,
$d1,
],
'If the user is the last person to have modified the grade_item, ' .
'and there is no submission date, then still show the date that it was graded' => [
$g2,
$u1,
$d1,
],
];
}
}
| gpl-3.0 |
Madek/madek-api | spec/resources/collections/filter/collection_filter_spec.rb | 1999 | require 'spec_helper'
describe 'filtering collections' do
let :collections_relation do
client.get.relation('collections')
end
def get_collections(filter = nil)
collections_relation.get(filter).data['collections']
end
context 'by collection_id' do
include_context :json_roa_client_for_authenticated_user do
it 'as single filter option' do
@collection = FactoryGirl.create(:collection)
5.times do
@collection.collections << FactoryGirl.create(:collection)
end
get_collections('collection_id' => @collection.id)
.each do |c|
collection = Collection.unscoped.find(c['id'])
expect(@collection.collections).to include collection
end
end
it 'combined with other filter option' do
@collection = FactoryGirl.create(:collection)
collection_1 = FactoryGirl.create(:collection,
get_metadata_and_previews: false)
collection_2 = FactoryGirl.create(:collection,
get_metadata_and_previews: true)
collection_3 = FactoryGirl.create(:collection,
get_metadata_and_previews: false)
collection_3.user_permissions << \
FactoryGirl.create(:collection_user_permission,
user: user,
get_metadata_and_previews: true)
[collection_1, collection_2, collection_3].each do |c|
@collection.collections << c
end
response = get_collections('collection_id' => @collection.id,
'me_get_metadata_and_previews' => true)
expect(response.count).to be == 2
response.each do |me|
collection = Collection.unscoped.find(me['id'])
expect(collection).not_to be == collection_1
expect(@collection.collections).to include collection
end
end
end
end
end
| gpl-3.0 |
transwarpio/rapidminer | rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/operator/features/aggregation/AggregationPopulationPlotter.java | 6545 | /**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.features.aggregation;
import com.rapidminer.ObjectVisualizer;
import com.rapidminer.datatable.SimpleDataTable;
import com.rapidminer.datatable.SimpleDataTableRow;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.generator.FeatureGenerator;
import com.rapidminer.generator.GenerationException;
import com.rapidminer.gui.plotter.ScatterPlotter;
import com.rapidminer.gui.plotter.SimplePlotterDialog;
import com.rapidminer.gui.processeditor.results.ResultDisplayTools;
import com.rapidminer.gui.tools.ExtendedJScrollPane;
import com.rapidminer.operator.performance.PerformanceVector;
import com.rapidminer.tools.Tools;
import java.awt.BorderLayout;
import java.awt.Component;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
/**
* Plots the current generation's Pareto set.
*
* @author Ingo Mierswa, Sebastian Land
*/
public class AggregationPopulationPlotter implements ObjectVisualizer {
/** The original example set. */
private ExampleSet originalExampleSet;
/** All original attributes. */
private Attribute[] allAttributes;
/** The feature generator which should be used to create the individuals. */
private FeatureGenerator generator;
/** The plotter. */
private SimplePlotterDialog plotter = null;
/** The data table containing the individuals criteria data. */
private SimpleDataTable criteriaDataTable = null;
/** The last population. */
private List<AggregationIndividual> lastPopulation;
/** Creates plotter panel which is repainted every generation. */
public AggregationPopulationPlotter(ExampleSet originalExampleSet, Attribute[] allAttributes, FeatureGenerator generator) {
this.originalExampleSet = originalExampleSet;
this.allAttributes = allAttributes;
this.generator = generator;
}
public void operate(List<AggregationIndividual> pop) {
if (pop.size() == 0) {
return;
}
// init data table
if (criteriaDataTable == null) {
this.criteriaDataTable = createDataTable(pop);
}
// fill data table
int numberOfCriteria = fillDataTable(this.criteriaDataTable, pop);
// create plotter
if (plotter == null) {
plotter = new SimplePlotterDialog(criteriaDataTable, false);
if (numberOfCriteria == 1) {
plotter.setXAxis(0);
plotter.plotColumn(0, true);
} else if (numberOfCriteria == 2) {
plotter.setXAxis(0);
plotter.plotColumn(1, true);
} else if (numberOfCriteria > 2) {
plotter.setXAxis(0);
plotter.setYAxis(1);
plotter.plotColumn(2, true);
}
plotter.setPointType(ScatterPlotter.POINTS);
plotter.setVisible(true);
plotter.addObjectVisualizer(this);
}
this.lastPopulation = pop;
}
public SimpleDataTable createDataTable(List<AggregationIndividual> pop) {
PerformanceVector prototype = pop.get(0).getPerformance();
SimpleDataTable dataTable = new SimpleDataTable("Population", prototype.getCriteriaNames());
return dataTable;
}
public int fillDataTable(SimpleDataTable dataTable, List<AggregationIndividual> pop) {
dataTable.clear();
int numberOfCriteria = 0;
for (int i = 0; i < pop.size(); i++) {
StringBuffer id = new StringBuffer(i + " (");
PerformanceVector current = pop.get(i).getPerformance();
numberOfCriteria = Math.max(numberOfCriteria, current.getSize());
double[] data = new double[current.getSize()];
for (int d = 0; d < data.length; d++) {
data[d] = current.getCriterion(d).getFitness();
if (d != 0) {
id.append(", ");
}
id.append(Tools.formatNumber(data[d]));
}
id.append(")");
dataTable.add(new SimpleDataTableRow(data, id.toString()));
}
return numberOfCriteria;
}
// ================================================================================
@Override
public boolean isCapableToVisualize(Object id) {
int index = 0;
if (id instanceof String) {
String idString = (String) id;
index = Integer.parseInt(idString.substring(0, idString.indexOf("(")).trim());
} else {
index = ((Double) id).intValue();
}
return ((index >= 0) && (index < lastPopulation.size()));
}
@Override
public String getTitle(Object id) {
return id instanceof String ? (String) id : ((Double) id).toString();
}
@Override
public String getDetailData(Object id, String fieldName) {
return null;
}
@Override
public String[] getFieldNames(Object id) {
return new String[0];
}
@Override
public void stopVisualization(Object id) {}
@Override
public void startVisualization(Object id) {
int index = 0;
if (id instanceof String) {
String idString = (String) id;
index = Integer.parseInt(idString.substring(0, idString.indexOf("(")).trim());
} else {
index = ((Double) id).intValue();
}
AggregationIndividual individual = lastPopulation.get(index);
ExampleSet es = null;
try {
es = individual.createExampleSet(originalExampleSet, allAttributes, generator);
} catch (GenerationException e) {
throw new RuntimeException("Cannot visualize individual '" + index + "': " + e.getMessage());
}
Component visualizationComponent = ResultDisplayTools.createVisualizationComponent(es, null, es.getName());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new ExtendedJScrollPane(visualizationComponent), BorderLayout.CENTER);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
| gpl-3.0 |
marcosemiao/log4jdbc | core/log4jdbc-impl/src/main/java/fr/ms/log4jdbc/lang/reflect/TimeInvocationHandler.java | 1555 | /*
* This file is part of Log4Jdbc.
*
* Log4Jdbc 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.
*
* Log4Jdbc 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 Log4Jdbc. If not, see <http://www.gnu.org/licenses/>.
*
*/
package fr.ms.log4jdbc.lang.reflect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
*
* @see <a href="http://marcosemiao4j.wordpress.com">Marco4J</a>
*
*
* @author Marco Semiao
*
*/
public class TimeInvocationHandler implements InvocationHandler {
private final InvocationHandler invocationHandler;
public TimeInvocationHandler(final Object implementation) {
this.invocationHandler = new WrapInvocationHandler(implementation);
}
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
final TimeInvocation timeInvoke = new TimeInvocation();
try {
final WrapInvocation wrapInvocation = (WrapInvocation) invocationHandler.invoke(proxy, method, args);
timeInvoke.setWrapInvocation(wrapInvocation);
} finally {
timeInvoke.finish();
}
return timeInvoke;
}
}
| gpl-3.0 |
kms77/Fayabank | src/test/javascript/spec/app/account/reset/finish/reset.finish.controller.spec.js | 3655 | /*
* Copyright (c) 2017 dtrouillet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
describe('Controller Tests', function() {
beforeEach(mockApiAccountCall);
beforeEach(mockI18nCalls);
describe('ResetFinishController', function() {
var $scope, $q; // actual implementations
var MockStateParams, MockTimeout, MockAuth; // mocks
var createController; // local utility function
beforeEach(inject(function($injector) {
$q = $injector.get('$q');
$scope = $injector.get('$rootScope').$new();
MockStateParams = jasmine.createSpy('MockStateParams');
MockTimeout = jasmine.createSpy('MockTimeout');
MockAuth = jasmine.createSpyObj('MockAuth', ['resetPasswordInit']);
var locals = {
'$scope': $scope,
'$stateParams': MockStateParams,
'$timeout': MockTimeout,
'Auth': MockAuth
};
createController = function() {
return $injector.get('$controller')('ResetFinishController as vm', locals);
};
}));
it('should define its initial state', function() {
// given
MockStateParams.key = 'XYZPDQ';
createController();
// then
expect($scope.vm.keyMissing).toBeFalsy();
expect($scope.vm.doNotMatch).toBeNull();
expect($scope.vm.resetAccount).toEqual({});
});
it('registers a timeout handler set set focus', function() {
// given
var MockAngular = jasmine.createSpyObj('MockAngular', ['element']);
var MockElement = jasmine.createSpyObj('MockElement', ['focus']);
MockAngular.element.and.returnValue(MockElement);
MockTimeout.and.callFake(function(callback) {
withMockedAngular(MockAngular, callback)();
});
createController();
// then
expect(MockTimeout).toHaveBeenCalledWith(jasmine.any(Function));
expect(MockAngular.element).toHaveBeenCalledWith('#password');
expect(MockElement.focus).toHaveBeenCalled();
});
});
});
| gpl-3.0 |
Antergos/Cnchi | src/geoip.py | 4692 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# geoip.py
#
# Copyright © 2013-2018 Antergos
#
# This file is part of Cnchi.
#
# Cnchi 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.
#
# Cnchi 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.
#
# The following additional terms are in effect as per Section 7 of the license:
#
# The preservation of all legal notices and author attributions in
# the material or in the Appropriate Legal Notices displayed
# by works containing it is required.
#
# You should have received a copy of the GNU General Public License
# along with Cnchi; If not, see <http://www.gnu.org/licenses/>.
""" GeoIP Location module
Needs python-geoip2 python-maxminddb geoip2-database """
import json
import logging
import os
import time
import requests
import maxminddb
import geoip2.database
import misc.extra as misc
class GeoIP():
""" Store GeoIP information """
REPO_CITY_DATABASE = '/usr/share/GeoIP/GeoLite2-City.mmdb'
LOCAL_CITY_DATABASE = '/usr/share/cnchi/data/GeoLite2-City.mmdb'
def __init__(self):
self.record = None
self._maybe_wait_for_network()
self._load_data_and_ip()
@staticmethod
def _maybe_wait_for_network():
# Wait until there is an Internet connection available
if not misc.has_connection():
logging.warning(
"Can't get network status. Cnchi will try again in a moment")
while not misc.has_connection():
time.sleep(4) # Wait 4 seconds and try again
logging.debug("A working network connection has been detected.")
def _load_data_and_ip(self):
""" Gets public IP and loads GeoIP2 database """
db_path = GeoIP.REPO_CITY_DATABASE
if not os.path.exists(db_path):
db_path = GeoIP.LOCAL_CITY_DATABASE
if os.path.exists(db_path):
myip = self._get_external_ip_address()
logging.debug("Your external IP address is: %s", myip)
if myip:
self._load_database(db_path, myip)
if self.record:
logging.debug("GeoIP database loaded (%s)", db_path)
else:
logging.error("Cannot get your external IP address!")
else:
logging.error("Cannot find Cities GeoIP database")
@staticmethod
def _get_external_ip_address():
""" Get external IP Address """
server = "=yek_ssecca?kcehc/moc.kcatspi.ipa"
key = "a75b99fb88ab4808060b8241931a012c"
try:
server = "http://" + server[::-1] + key[::-1]
json_text = requests.get(server).text
data = json.loads(json_text)
return data['ip']
except (KeyError, requests.ConnectionError, json.decoder.JSONDecodeError) as err:
logging.warning("Error getting external IP from %s: %s", server, err)
def _load_database(self, db_path, myip):
""" Loads cities database """
try:
reader = geoip2.database.Reader(db_path)
self.record = reader.city(myip)
except maxminddb.errors.InvalidDatabaseError as err:
logging.error(err)
def get_city(self):
""" Returns city information
'city': {'geoname_id', 'names'} """
if self.record:
return self.record.city
return None
def get_country(self):
""" Returns country information
'country': {'geoname_id', 'is_in_european_union', 'iso_code', 'names'} """
if self.record:
return self.record.country
return None
def get_continent(self):
""" Returns continent information
'continent': {'code', 'geoname_id', 'names'} """
if self.record:
return self.record.continent
return None
def get_location(self):
""" Returns location information
'location': {'accuracy_radius', 'latitude', 'longitude', 'time_zone'} """
if self.record:
return self.record.location
return None
def test_module():
""" Test module """
geo = GeoIP()
print("City:", geo.get_city())
print("Country:", geo.get_country())
print("Continent:", geo.get_continent())
print("Location:", geo.get_location())
if __name__ == "__main__":
test_module()
| gpl-3.0 |
nfell2009/Skript | src/test/java/ch/njol/skript/config/NodeTest.java | 1757 | /*
* This file is part of Skript.
*
* Skript 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.
*
* Skript 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 Skript. If not, see <http://www.gnu.org/licenses/>.
*
*
* Copyright 2011-2014 Peter Güttinger
*
*/
package ch.njol.skript.config;
import static org.junit.Assert.*;
import org.junit.Test;
import ch.njol.util.NonNullPair;
/**
* @author Peter Güttinger
*/
@SuppressWarnings("null")
public class NodeTest {
@Test
public void splitLineTest() {
final String[][] data = {
{"", "", ""},
{"ab", "ab", ""},
{"ab#", "ab", "#"},
{"ab##", "ab#", ""},
{"ab###", "ab#", "#"},
{"#ab", "", "#ab"},
{"ab#cd", "ab", "#cd"},
{"ab##cd", "ab#cd", ""},
{"ab###cd", "ab#", "#cd"},
{"######", "###", ""},
{"#######", "###", "#"},
{"#### # ####", "## ", "# ####"},
{"##### ####", "##", "# ####"},
{"#### #####", "## ##", "#"},
{"#########", "####", "#"},
{"a##b#c##d#e", "a#b", "#c##d#e"},
{" a ## b # c ## d # e ", " a # b ", "# c ## d # e "},
};
for (final String[] d : data) {
final NonNullPair<String, String> p = Node.splitLine(d[0]);
assertArrayEquals(d[0], new String[] {d[1], d[2]}, new String[] {p.getFirst(), p.getSecond()});
}
}
}
| gpl-3.0 |
discoleo/FontStats | main/Frame.java | 4525 | // Copyright (c) 2016 Leonard Mada and Syonic SRL
// [email protected]
//
// This file is part of FontStats.
//
// FontStats 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.
//
// FontStats 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 FontStats. If not, see <http://www.gnu.org/licenses/>.
//
//
package main;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Map;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import tbl.cell.FontRenderer;
import tbl.gui.TblDimensions;
import tools.FontListObj;
import tools.FontStat;
import tools.FontStatMap;
import tools.FontStatObj;
public class Frame extends JPanel {
private final TblDimensions config = TblDimensions.GetThis();
public Frame() {
final FontListObj fonts = new FontListObj();
final FontStat stat = new FontStat("LibreOffice");
//for(Font font : fonts) {
// stat.Stats(font.deriveFont(20.0f));
//}
// parallel processing
fonts.parallelStream().forEach(
(font) -> {stat.Stats(font.deriveFont(20.0f));} );
// +++ View
// Table
final JTable table = CreateTable(stat.GetStat(), stat.GetText());
final JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(this.GetLargeTableSize());
this.add(scrollPane);
//this.add(table);
}
protected JTable CreateTable(final FontStatMap fontStat, final String sample) {
final int nCol = 2; // hardcoded
final FontTblModel model = new FontTblModel(fontStat, nCol, Font.class);
final JTable table = new JTable(model);
// Set Special Column
table.setDefaultRenderer(Font.class, new FontRenderer(sample));
// Customize table
table.setRowHeight(config.GetTblCellMinHeight());
table.setRowSorter(this.GetNewSorter(model));
return table;
}
public TableRowSorter<FontTblModel> GetNewSorter(final FontTblModel model) {
return new TableRowSorter<FontTblModel>(model);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(800 + 10, 400 + 20);
}
public Dimension GetLargeTableSize() {
return new Dimension(800, 400);
}
// +++++++++++++++++++++++++++++++++++++
public static void main(String[] args) {
final JFrame frame = new JFrame("");
final Frame panel = new Frame();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
// ++++ helper Classes ++++
public class FontTblModel extends DefaultTableModel {
final int nFontCol;
final Class<?> specialCl;
final int [] nBoolCol;
public FontTblModel(final FontStatMap stat, final int nCol, final Class<?> cl) {
this.setColumnIdentifiers(FontStatObj.GetNames());
final int nColumnCount = this.getColumnCount();
this.nFontCol = nCol;
this.specialCl = cl;
this.nBoolCol = FontStatObj.GetBooleanColumns();
// Set Table data
int nRow = 1;
for( Map.Entry<Font, FontStatObj> entry : stat.entrySet()) {
final Vector<Object> vRow = new Vector<Object>(nColumnCount);
final FontStatObj val = entry.getValue();
vRow.add(nRow++);
vRow.add(entry.getKey().getFontName());
vRow.add(entry.getKey());
// Stat
val.PutAll(vRow);
this.addRow(vRow);
}
}
// +++++++++ MEMBER FUNCTIONS +++++++++
@Override
public Class<?> getColumnClass(final int nCol) {
if(this.nFontCol == nCol) {
return specialCl;
} else {
for(int npos : nBoolCol) {
if(nCol == npos) {
return Boolean.class;
}
}
}
return super.getColumnClass(nCol);
}
}
}
| gpl-3.0 |
montadar97/montadar-100k | plugin/TH3BOSS4.lua | 1757 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ مساعدة4 ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
function mohammed(msg, matches)
local reply_id = msg['id']
local S = [[
❗️ أوامر الحماية في المجموعة
➖🔹➖🔹➖🔹➖🔹➖🔹
▫️ قفل الفيديو :: لقفل الفيديو
▫️ قفل الصور :: لقفل الصور
▫️ قفل الصوت :: لقفل الصوت
▫️ قفل الوسائط :: لقفل الوسائط
▫️ قفل الملصقات :: لقفل الملصقات
▫️ قفل الصور المتحركة :: لقفل المتحركه
➖🔹➖🔹➖🔹➖🔹➖🔹
▫️ فتح الفيديو :: لفتح الفيديو
▫️ فتح الصور :: لفتح الصور
▫️ فتح الصوت :: لفتح الصوت
▫️ فتح الوسائط :: لفتح الوسائط
▫️ فتح الملصقات :: لفتح الملصقات
▫️ فتح الصور المتحركة :: لفتح التحركه
➖🔹➖🔹➖🔹➖🔹➖🔹
💯-Đєⱴ💀: @II303II
]]
reply_msg(reply_id, S, ok_cb, false)
end
return {
description = "Help list",
usage = "Help list",
patterns = {
"^(م4)$",
},
run = mohammed
}
end
| gpl-3.0 |
ItakPC/Plasmatic-Revolution | src/com/ItakPC/plasmatic_rev/world/Chunk.java | 3096 | package com.ItakPC.plasmatic_rev.world;
import com.ItakPC.plasmatic_rev.Game;
import com.ItakPC.plasmatic_rev.Material;
import com.ItakPC.plasmatic_rev.SimplexNoise;
import java.awt.*;
import static com.ItakPC.plasmatic_rev.reference.Reference.*;
import static com.ItakPC.plasmatic_rev.Game.*;
public class Chunk {
Tile[][] tiles;
int chunkX;
int chunkY;
public Chunk(int chunkX, int chunkY){
this.chunkX = chunkX;
this.chunkY = chunkY;
}
public void populate(){
tiles = new Tile[tileAmountX][tileAmountY];
SimplexNoise simplexNoise = new SimplexNoise(7, 0.1);
double xStart = chunkX*tileAmountX;
double xEnd = xStart+tileAmountX;
double yStart = chunkY*tileAmountY;
double yEnd = yStart+tileAmountY;
int xResolution = tileAmountX;
int yResolution = tileAmountY;
double[][] data = new double[xResolution][yResolution];
for(int i = 0; i < xResolution; i++){
for(int j = 0; j < yResolution; j++){
int x = (int)(xStart+(i*(xEnd-xStart)/xResolution));
int y = (int)(yStart+(j*(yEnd-yStart)/yResolution));
double noise = (1+simplexNoise.getNoise(x, y))/2;
Material material;
if(noise < 0.495F)
material = Material.DEEPWATER;
else if(noise < 0.5F)
material = Material.WATER;
else if(noise < 0.525F)
material = Material.SAND;
else if(noise < 0.545F)
material = Material.GRASS;
else
material = Material.ROCK;
tiles[i][j] = new Tile(material);
data[i][j] = noise;
}
}
}
public void render(Graphics g) {
int posX = ceil((chunkX * tileAmountX * tileSize * pixelSize - Game.instance.player.posX * tileSize * pixelSize - tileSize * pixelSize / 2) * pixelScaleWidth + screenWidth / 2);
int posY = ceil((chunkY * tileAmountY * tileSize * pixelSize - Game.instance.player.posY * tileSize * pixelSize - tileSize * pixelSize / 2) * pixelScaleHeight + screenHeight / 2);
for (int x = 0; x < tiles.length; x++) {
for (int y = 0; y < tiles[0].length; y++) {
tiles[x][y].render(g, ceil(x * tileSize * pixelSize * pixelScaleWidth + posX), ceil(y * tileSize * pixelSize * pixelScaleHeight + posY));
//g.drawImage(tiles[x][y].texture, ceil(x * tileSize * pixelSize * pixelScaleWidth + posX), ceil(y * tileSize * pixelSize * pixelScaleHeight + posY), ceil(tileSize * pixelSize * pixelScaleWidth), ceil(tileSize * pixelSize * pixelScaleHeight), null);
}
}
g.drawLine(posX, 0, posX, screenHeight);
g.drawLine(0, posY, screenWidth, posY);
}
public boolean equals(Object object){
if(!(object instanceof Chunk))
return false;
Chunk chunk = (Chunk) object;
return chunkX == chunk.chunkX && chunkY == chunk.chunkY;
}
}
| gpl-3.0 |
JavaBaas/JavaBaas_SDK_Java | src/main/java/com/javabaas/javasdk/annotation/scanner/OnHookScanner.java | 2414 | package com.javabaas.javasdk.annotation.scanner;
import com.javabaas.javasdk.JB;
import com.javabaas.javasdk.annotation.HookEvent;
import com.javabaas.javasdk.annotation.OnHook;
import com.javabaas.javasdk.cloud.HookListener;
import com.javabaas.javasdk.cloud.HookRequest;
import com.javabaas.javasdk.cloud.HookResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by Codi on 2018/7/18.
*/
public class OnHookScanner implements AnnotationScanner {
@Override
public Class<? extends Annotation> getScanAnnotation() {
return OnHook.class;
}
@Override
public void addListener(JB jb, final Object object, final Method method, Annotation annot) {
OnHook annotation = (OnHook) annot;
//云方法名称
String name = annotation.value();
if (name.trim().length() == 0) {
throw new IllegalArgumentException("OnCloud注解必须指定云方法名!");
}
HookEvent event = annotation.event();
final int HookRequestIndex = paramIndex(method, HookRequest.class);
//注入方法
jb.addHookListener(name, event, new HookListener() {
@Override
public HookResponse onHook(HookRequest hookRequest) throws Throwable {
Object[] args = new Object[method.getParameterTypes().length];
if (HookRequestIndex != -1) {
args[HookRequestIndex] = hookRequest;
}
try {
return (HookResponse) method.invoke(object, args);
} catch (IllegalAccessException | InvocationTargetException e) {
throw e.getCause();
}
}
});
}
@Override
public void validate(Method method, Class<?> clazz) {
if (!HookResponse.class.equals(method.getReturnType())) {
//返回类型错误
throw new IllegalArgumentException("钩子返回类型错误 返回类型必须为HookResponse " + clazz + "." + method.getName());
}
}
private int paramIndex(Method method, Class<?> clazz) {
int index = 0;
for (Class<?> type : method.getParameterTypes()) {
if (type.equals(clazz)) {
return index;
}
index++;
}
return -1;
}
}
| gpl-3.0 |
optimusmoose/miniML | src/main/java/backend/DatasetBuilder.java | 3246 | package backend;
import utils.Logging.MiniMLLogger;
import weka.core.Instances;
import workflow.Keys;
import workflow.WorkflowManager;
import workflow.context.ParameterContext;
import java.util.Arrays;
import java.util.Collections;
/**
* Hold the master dataset Instance key and give out carefully prepared sections as needed.
*
* This should not only reinforce user expectations but also implement random feature search.
*
* THIS OBJECT HANDLES ITS OWN CONTEXT KEYS.
*/
public class DatasetBuilder {
private Instances master;
protected int[] userAttributeSelectionIndices;
protected int classIndex;
public DatasetBuilder(){
MiniMLLogger.INSTANCE.info("in ctor");
this.collect();
this.log_all();
}
/**
* Collect all of the context values this builder needs from keys.
*/
private void collect(){
//Get the master Instance of our data
ParameterContext masterContext = (ParameterContext) WorkflowManager.INSTANCE.getContextByKey(Keys.RootWekaInstnace);
this.master = (Instances) masterContext.getValue();
//Get the class index
ParameterContext classIndexContext= (ParameterContext) WorkflowManager.INSTANCE.getContextByKey(Keys.SelectedClassifier);
this.classIndex = (int) classIndexContext.getValue();
//Get the selected attribute indices
ParameterContext selectedAttributeIndices = (ParameterContext) WorkflowManager.INSTANCE.getContextByKey(Keys.SelectedAttributes);
this.userAttributeSelectionIndices = (int[]) selectedAttributeIndices.getValue();
}
/**
* Print out what's going on in here. Useful for debugging.
*/
public void log_all(){
MiniMLLogger.INSTANCE.info(this.master.toString());
MiniMLLogger.INSTANCE.info("attributes:");
for(int val: this.userAttributeSelectionIndices) {
MiniMLLogger.INSTANCE.info(Integer.toString(val));
}
MiniMLLogger.INSTANCE.info("Class index");
MiniMLLogger.INSTANCE.info(Integer.toString(this.classIndex));
//System.exit(1);
}
/**
* Create a new, smaller data Instances that contains only the attributes the user selected.
*
* It does this by counting out the indices that the user wanted and removing anything that doesn't match.
* If it were elegant, it wouldn't be java. :/
*
* @return Instances newData
*/
public Instances getUserSpecifiedDataset(){
Instances newData = new Instances(this.master);
newData.setClass(newData.attribute(this.classIndex));
//need to reverse sort them so our array doesn't get screwed up.
Integer[] keepAttributes = new Integer[this.userAttributeSelectionIndices.length];
for (int i = 0; i < this.userAttributeSelectionIndices.length; i++) {
keepAttributes[i] = Integer.valueOf(this.userAttributeSelectionIndices[i]);
}
Arrays.sort(keepAttributes, Collections.reverseOrder());
for(Integer i = this.userAttributeSelectionIndices.length; i >= 0; --i){
if(! Arrays.asList(keepAttributes).contains(i)){
newData.deleteAttributeAt(i);
}
}
return(newData);
}
}
| gpl-3.0 |
portablemind/compass_agile_enterprise | erp_txns_and_accts/app/controllers/api/v1/biz_txn_acct_roots_controller.rb | 4839 | module Api
module V1
class BizTxnAcctRootsController < BaseController
def index
sort = nil
dir = nil
limit = nil
start = nil
unless params[:sort].blank?
sort_hash = params[:sort].blank? ? {} : Hash.symbolize_keys(JSON.parse(params[:sort]).first)
sort = sort_hash[:property] || 'description'
dir = sort_hash[:direction] || 'ASC'
limit = params[:limit] || 25
start = params[:start] || 0
end
query_filter = params[:query_filter].blank? ? {} : JSON.parse(params[:query_filter]).symbolize_keys
# hook method to apply any scopes passed via parameters to this api
biz_txn_acct_roots = BizTxnAcctRoot.apply_filters(query_filter)
# scope by dba_organizations if there are no parties passed as filters
dba_organizations = [current_user.party.dba_organization]
dba_organizations = dba_organizations.concat(current_user.party.dba_organization.child_dba_organizations)
biz_txn_acct_roots = biz_txn_acct_roots.scope_by_dba_organization(dba_organizations)
respond_to do |format|
format.json do
if sort and dir
biz_txn_acct_roots = biz_txn_acct_roots.order("#{sort} #{dir}")
end
total_count = biz_txn_acct_roots.count
if start and limit
biz_txn_acct_roots = biz_txn_acct_roots.offset(start).limit(limit)
end
render :json => {success: true,
total_count: total_count,
biz_txn_acct_roots: biz_txn_acct_roots.collect { |item| item.to_data_hash }}
end
format.tree do
if params[:parent_id]
render :json => {success: true,
biz_txn_acct_roots: BizTxnAcctRoot.find(params[:parent_id]).children_to_tree_hash}
else
nodes = [].tap do |nodes|
biz_txn_acct_roots.roots.each do |root|
nodes.push(root.to_tree_hash)
end
end
render :json => {success: true,
biz_txn_acct_roots: nodes}
end
end
format.all_representation do
if params[:parent_id].present?
render :json => {success: true,
biz_txn_acct_roots: BizTxnAcctRoot.to_all_representation(BizTxnAcctRoot.find(params[:parent_id]))}
else
render :json => {success: true,
biz_txn_acct_roots: BizTxnAcctRoot.to_all_representation(nil, [], 0, biz_txn_acct_roots.roots)}
end
end
end
end
def create
description = params[:description].strip
external_identifier = params[:external_identifier].strip
begin
ActiveRecord::Base.transaction do
biz_txn_acct_root = BizTxnAcctRoot.create(description: description,
internal_identifier: description.to_iid,
external_identifier: external_identifier)
if !params[:parent].blank? and params[:parent] != 'No Parent'
parent = BizTxnAcctRoot.iid(params[:parent])
biz_txn_acct_root.move_to_child_of(parent)
elsif !params[:default_parent].blank?
parent = BizTxnAcctRoot.iid(params[:default_parent])
biz_txn_acct_root.move_to_child_of(parent)
end
if params[:biz_txn_acct_type_iid]
biz_txn_acct_root.biz_txn_acct_type = BizTxnAcctType.iid(params[:biz_txn_acct_type_iid])
end
BizTxnAcctPartyRole.create(biz_txn_acct_root: biz_txn_acct_root,
party: current_user.party.dba_organization,
biz_txn_acct_pty_rtype: BizTxnAcctPtyRtype.find_or_create('dba_org', 'DBA Organization'))
biz_txn_acct_root.created_by_party = current_user.party
biz_txn_acct_root.save!
render :json => {success: true, biz_txn_type: biz_txn_acct_root.to_data_hash}
end
rescue ActiveRecord::RecordInvalid => invalid
Rails.logger.error invalid.record.errors.full_messages
render json: {:success => false, :message => invalid.record.errors.full_messages.join('</br>')}
rescue => ex
Rails.logger.error ex.message
Rails.logger.error ex.backtrace.join("\n")
ExceptionNotifier.notify_exception(ex) if defined? ExceptionNotifier
render json: {:success => false, :message => "Error creating record"}
end
end
end # BizTxnAcctRootsController
end # V1
end # Api | gpl-3.0 |
Luc1412/EasyMaintenance | src/main/java/noteblockapi/CustomInstrument.java | 1118 | package noteblockapi;
import org.bukkit.Sound;
/**
* Created by Luc1412 on 03.12.2017 at 19:19
*/
public class CustomInstrument {
private byte index;
private String name;
private String soundfile;
private byte pitch;
private byte press;
private Sound sound;
public CustomInstrument(byte index, String name, String soundfile, byte pitch, byte press) {
this.index = index;
this.name = name;
this.soundfile = soundfile.replaceAll(".ogg", "");
if (this.soundfile.equalsIgnoreCase("pling")) {
switch (CompatibilityUtils.getCompatibility()) {
case CompatibilityUtils.NoteBlockCompatibility.pre1_9:
this.sound = Sound.valueOf("NOTE_PLING");
break;
case CompatibilityUtils.NoteBlockCompatibility.pre1_12:
case CompatibilityUtils.NoteBlockCompatibility.post1_12:
this.sound = Sound.valueOf("BLOCK_NOTE_PLING");
break;
}
}
this.pitch = pitch;
this.press = press;
}
public byte getIndex() {
return index;
}
public String getName() {
return name;
}
public String getSoundfile() {
return soundfile;
}
public Sound getSound() {
return sound;
}
}
| gpl-3.0 |
rsjaffe/MIDI2LR | src/plugin/Client.lua | 74070 | --[[----------------------------------------------------------------------------
Client.lua
Receives and processes commands from MIDI2LR
Sends parameters to MIDI2LR
This file is part of MIDI2LR. Copyright 2015 by Rory Jaffe.
MIDI2LR 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.
MIDI2LR 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
MIDI2LR. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------------]]
--[[-----------debug section, enable by adding - to beginning this line
local LrMobdebug = import 'LrMobdebug'
LrMobdebug.start()
--]]-----------end debug section
local Database = require 'Database'
local LrTasks = import 'LrTasks'
-- Main task
LrTasks.startAsyncTask(
function()
--[[-----------debug section, enable by adding - to beginning this line
LrMobdebug.on()
--]]-----------end debug section
-------------preferences
local Preferences = require 'Preferences'
Preferences.Load()
-------------end preferences section
local LrFunctionContext = import 'LrFunctionContext'
local LrPathUtils = import 'LrPathUtils'
do --save localized file for app
local LrFileUtils = import 'LrFileUtils'
local LrLocalization = import 'LrLocalization'
local Info = require 'Info'
local versionmismatch = false
if ProgramPreferences.DataStructure == nil then
versionmismatch = true
else
for k,v in pairs(Info.VERSION) do
versionmismatch = versionmismatch or ProgramPreferences.DataStructure.version[k] ~= v
end
end
if
versionmismatch or
LrFileUtils.exists(Database.AppTrans) ~= 'file' or
ProgramPreferences.DataStructure.language ~= LrLocalization.currentLanguage()
then
ProgramPreferences.DataStructure = {version={},language = LrLocalization.currentLanguage()}
Database.WriteAppTrans(ProgramPreferences.DataStructure.language)
for k,v in pairs(Info.VERSION) do
ProgramPreferences.DataStructure.version[k] = v
end
Preferences.Save() --ensure that new version/language info saved
end
end --save localized file for app
--delay loading most modules until after data structure refreshed
local ActionSeries = require 'ActionSeries'
local CU = require 'ClientUtilities'
local DebugInfo = require 'DebugInfo'
local Info = require 'Info'
local Keys = require 'Keys'
local KS = require 'KeyShortcuts'
local Keywords = require 'Keywords'
local Limits = require 'Limits'
local LocalPresets = require 'LocalPresets'
local Mask = require 'Mask'
local Presets = require 'Presets'
local Profiles = require 'Profiles'
local Virtual = require 'Virtual'
local LrApplication = import 'LrApplication'
local LrApplicationView = import 'LrApplicationView'
local LrDevelopController = import 'LrDevelopController'
local LrDialogs = import 'LrDialogs'
local LrSelection = import 'LrSelection'
local LrUndo = import 'LrUndo'
--global variables
MIDI2LR = {PARAM_OBSERVER = {}, SERVER = {}, CLIENT = {}, RUNNING = true} --non-local but in MIDI2LR namespace
--local variables
local LastParam = ''
local UpdateParamPickup, UpdateParamNoPickup, UpdateParam
local sendIsConnected = false --tell whether send socket is up or not
--local constants--may edit these to change program behaviors
local BUTTON_ON = 0.40 -- sending 1.0, but use > BUTTON_ON because of note keypressess not hitting 100%
local PICKUP_THRESHOLD = 0.03 -- roughly equivalent to 4/127
local RECEIVE_PORT = 58763
local SEND_PORT = 58764
local GradeFocusTable = {
SplitToningShadowHue = 'shadow',
SplitToningShadowSaturation = 'shadow',
ColorGradeShadowLum = 'shadow',
SplitToningHighlightHue = 'highlight',
SplitToningHighlightSaturation = 'highlight',
ColorGradeHighlightLum = 'highlight',
ColorGradeMidtoneHue = 'midtone',
ColorGradeMidtoneSat = 'midtone',
ColorGradeMidtoneLum = 'midtone',
ColorGradeGlobalHue = 'global',
ColorGradeGlobalSat = 'global',
ColorGradeGlobalLum = 'global',
ResetSplitToningShadowHue = 'shadow',
ResetSplitToningShadowSaturation = 'shadow',
ResetColorGradeShadowLum = 'shadow',
ResetSplitToningHighlightHue = 'highlight',
ResetSplitToningHighlightSaturation = 'highlight',
ResetColorGradeHighlightLum = 'highlight',
ResetColorGradeMidtoneHue = 'midtone',
ResetColorGradeMidtoneSat = 'midtone',
ResetColorGradeMidtoneLum = 'midtone',
ResetColorGradeGlobalHue = 'global',
ResetColorGradeGlobalSat = 'global',
ResetColorGradeGlobalLum = 'global',
}
local ACTIONS = {
AddOrRemoveFromTargetColl = CU.wrapForEachPhoto('addOrRemoveFromTargetCollection'),
AppInfoClear = function() Info.AppInfo = {}; end,
AppInfoDone = DebugInfo.write,
AutoLateralCA = CU.fToggle01('AutoLateralCA'),
AutoTone = function() LrDevelopController.setAutoTone(); LrDevelopController.revealPanel('adjustPanel'); end,
BrushFeatherLarger = CU.fSimulateKeys(KS.KeyCode.FeatherIncreaseKey,true,{dust=true, masking=true}),
BrushFeatherSmaller = CU.fSimulateKeys(KS.KeyCode.FeatherDecreaseKey,true,{dust=true, masking=true}),
BrushSizeLarger = CU.fSimulateKeys(KS.KeyCode.BrushIncreaseKey,true,{dust=true, masking=true}),
BrushSizeSmaller = CU.fSimulateKeys(KS.KeyCode.BrushDecreaseKey,true,{dust=true, masking=true}),
CloseApp = function() MIDI2LR.SERVER:send('TerminateApplication 1\n') end,
ColorGrade3Way = CU.wrapFOM(LrDevelopController.setActiveColorGradingView,'3-way'),
ColorGradeCopy = CU.cg_hsl_copy,
ColorGradeGlobal = CU.wrapFOM(LrDevelopController.setActiveColorGradingView,'global'),
ColorGradeHighlight = CU.wrapFOM(LrDevelopController.setActiveColorGradingView,'highlight'),
ColorGradeMidtone = CU.wrapFOM(LrDevelopController.setActiveColorGradingView,'midtone'),
ColorGradePaste = CU.cg_hsl_paste,
ColorGradeReset3way = CU.cg_reset_3way,
ColorGradeResetAll = CU.cg_reset_all,
ColorGradeResetCurrent = CU.cg_reset_current,
ColorGradeShadow = CU.wrapFOM(LrDevelopController.setActiveColorGradingView,'shadow'),
ColorLabelNone = function() LrSelection.setColorLabel("none") end,
ConvertToGrayscale = CU.fToggleTFasync('ConvertToGrayscale'),
CropConstrainToWarp = CU.fToggle01('CropConstrainToWarp'),
CropOverlay = CU.fToggleTool('crop'),
CycleLoupeViewInfo = LrApplicationView.cycleLoupeViewInfo,
CycleMaskOverlayColor = CU.fSimulateKeys(KS.KeyCode.CycleAdjustmentBrushOverlayKey,true),
DecreaseRating = LrSelection.decreaseRating,
DecrementLastDevelopParameter = function() CU.execFOM(LrDevelopController.decrement,LastParam) end,
EditPhotoshop = LrDevelopController.editInPhotoshop,
EnableCalibration = CU.fToggleTFasync('EnableCalibration'),
EnableColorAdjustments = CU.fToggleTFasync('EnableColorAdjustments'),
EnableColorGrading = CU.fToggleTFasync('EnableSplitToning'),
EnableDetail = CU.fToggleTFasync('EnableDetail'),
EnableEffects = CU.fToggleTFasync('EnableEffects'),
EnableGrayscaleMix = CU.fToggleTFasync('EnableGrayscaleMix'),
EnableLensCorrections = CU.fToggleTFasync('EnableLensCorrections'),
EnableRedEye = CU.fToggleTFasync('EnableRedEye'),
EnableRetouch = CU.fToggleTFasync('EnableRetouch'),
EnableToneCurve = CU.fToggleTFasync('EnableToneCurve'),
EnableTransform = CU.fToggleTFasync('EnableTransform'),
FilterNone = CU.RemoveFilters,
Filter_1 = CU.fApplyFilter(1),
Filter_10 = CU.fApplyFilter(10),
Filter_11 = CU.fApplyFilter(11),
Filter_12 = CU.fApplyFilter(12),
Filter_2 = CU.fApplyFilter(2),
Filter_3 = CU.fApplyFilter(3),
Filter_4 = CU.fApplyFilter(4),
Filter_5 = CU.fApplyFilter(5),
Filter_6 = CU.fApplyFilter(6),
Filter_7 = CU.fApplyFilter(7),
Filter_8 = CU.fApplyFilter(8),
Filter_9 = CU.fApplyFilter(9),
FullRefresh = CU.FullRefresh,
GetPluginInfo = DebugInfo.sendLog, -- not in db: internal use only
GridViewStyle = LrApplicationView.gridViewStyle,
IncreaseRating = LrSelection.increaseRating,
IncrementLastDevelopParameter = function() CU.execFOM(LrDevelopController.increment,LastParam) end,
Key1 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(1)..'\n') end,
Key10 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(10)..'\n') end,
Key11 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(11)..'\n') end,
Key12 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(12)..'\n') end,
Key13 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(13)..'\n') end,
Key14 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(14)..'\n') end,
Key15 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(15)..'\n') end,
Key16 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(16)..'\n') end,
Key17 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(17)..'\n') end,
Key18 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(18)..'\n') end,
Key19 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(19)..'\n') end,
Key2 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(2)..'\n') end,
Key20 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(20)..'\n') end,
Key21 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(21)..'\n') end,
Key22 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(22)..'\n') end,
Key23 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(23)..'\n') end,
Key24 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(24)..'\n') end,
Key25 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(25)..'\n') end,
Key26 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(26)..'\n') end,
Key27 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(27)..'\n') end,
Key28 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(28)..'\n') end,
Key29 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(29)..'\n') end,
Key3 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(3)..'\n') end,
Key30 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(30)..'\n') end,
Key31 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(31)..'\n') end,
Key32 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(32)..'\n') end,
Key33 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(33)..'\n') end,
Key34 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(34)..'\n') end,
Key35 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(35)..'\n') end,
Key36 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(36)..'\n') end,
Key37 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(37)..'\n') end,
Key38 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(38)..'\n') end,
Key39 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(39)..'\n') end,
Key4 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(4)..'\n') end,
Key40 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(40)..'\n') end,
Key5 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(5)..'\n') end,
Key6 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(6)..'\n') end,
Key7 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(7)..'\n') end,
Key8 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(8)..'\n') end,
Key9 = function() MIDI2LR.SERVER:send('SendKey '..Keys.GetKey(9)..'\n') end,
Keyword1 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[1]) end,
Keyword10 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[10]) end,
Keyword10Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[10]) end,
Keyword11 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[11]) end,
Keyword11Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[11]) end,
Keyword12 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[12]) end,
Keyword12Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[12]) end,
Keyword13 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[13]) end,
Keyword13Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[13]) end,
Keyword14 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[14]) end,
Keyword14Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[14]) end,
Keyword15 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[15]) end,
Keyword15Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[15]) end,
Keyword16 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[16]) end,
Keyword16Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[16]) end,
Keyword17 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[17]) end,
Keyword17Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[17]) end,
Keyword18 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[18]) end,
Keyword18Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[18]) end,
Keyword19 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[19]) end,
Keyword19Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[19]) end,
Keyword1Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[1]) end,
Keyword2 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[2]) end,
Keyword20 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[20]) end,
Keyword20Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[20]) end,
Keyword21 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[21]) end,
Keyword21Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[21]) end,
Keyword22 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[22]) end,
Keyword22Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[22]) end,
Keyword23 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[23]) end,
Keyword23Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[23]) end,
Keyword24 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[24]) end,
Keyword24Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[24]) end,
Keyword25 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[25]) end,
Keyword25Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[25]) end,
Keyword26 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[26]) end,
Keyword26Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[26]) end,
Keyword27 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[27]) end,
Keyword27Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[27]) end,
Keyword28 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[28]) end,
Keyword28Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[28]) end,
Keyword29 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[29]) end,
Keyword29Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[29]) end,
Keyword2Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[2]) end,
Keyword3 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[3]) end,
Keyword30 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[30]) end,
Keyword30Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[30]) end,
Keyword31 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[31]) end,
Keyword31Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[31]) end,
Keyword32 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[32]) end,
Keyword32Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[32]) end,
Keyword33 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[33]) end,
Keyword33Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[33]) end,
Keyword34 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[34]) end,
Keyword34Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[34]) end,
Keyword35 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[35]) end,
Keyword35Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[35]) end,
Keyword36 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[36]) end,
Keyword36Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[36]) end,
Keyword37 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[37]) end,
Keyword37Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[37]) end,
Keyword38 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[38]) end,
Keyword38Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[38]) end,
Keyword39 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[39]) end,
Keyword39Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[39]) end,
Keyword3Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[3]) end,
Keyword4 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[4]) end,
Keyword40 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[40]) end,
Keyword40Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[40]) end,
Keyword41 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[41]) end,
Keyword41Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[41]) end,
Keyword42 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[42]) end,
Keyword42Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[42]) end,
Keyword43 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[43]) end,
Keyword43Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[43]) end,
Keyword44 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[44]) end,
Keyword44Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[44]) end,
Keyword45 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[45]) end,
Keyword45Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[45]) end,
Keyword46 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[46]) end,
Keyword46Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[46]) end,
Keyword47 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[47]) end,
Keyword47Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[47]) end,
Keyword48 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[48]) end,
Keyword48Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[48]) end,
Keyword49 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[49]) end,
Keyword49Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[49]) end,
Keyword4Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[4]) end,
Keyword5 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[5]) end,
Keyword50 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[50]) end,
Keyword50Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[50]) end,
Keyword51 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[51]) end,
Keyword51Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[51]) end,
Keyword52 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[52]) end,
Keyword52Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[52]) end,
Keyword53 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[53]) end,
Keyword53Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[53]) end,
Keyword54 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[54]) end,
Keyword54Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[54]) end,
Keyword55 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[55]) end,
Keyword55Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[55]) end,
Keyword56 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[56]) end,
Keyword56Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[56]) end,
Keyword57 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[57]) end,
Keyword57Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[57]) end,
Keyword58 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[58]) end,
Keyword58Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[58]) end,
Keyword59 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[59]) end,
Keyword59Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[59]) end,
Keyword5Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[5]) end,
Keyword6 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[6]) end,
Keyword60 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[60]) end,
Keyword60Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[60]) end,
Keyword61 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[61]) end,
Keyword61Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[61]) end,
Keyword62 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[62]) end,
Keyword62Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[62]) end,
Keyword63 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[63]) end,
Keyword63Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[63]) end,
Keyword64 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[64]) end,
Keyword64Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[64]) end,
Keyword6Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[6]) end,
Keyword7 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[7]) end,
Keyword7Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[7]) end,
Keyword8 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[8]) end,
Keyword8Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[8]) end,
Keyword9 = function() Keywords.ApplyKeyword(ProgramPreferences.Keywords[9]) end,
Keyword9Toggle = function() Keywords.ToggleKeyword(ProgramPreferences.Keywords[9]) end,
LRCopy = CU.fSimulateKeys(KS.KeyCode.CopyKey,true),
LRPaste = CU.fSimulateKeys(KS.KeyCode.PasteKey,true),
LensProfileEnable = CU.fToggle01Async('LensProfileEnable'),
LocalPreset1 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[1]) end,
LocalPreset10 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[10]) end,
LocalPreset11 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[11]) end,
LocalPreset12 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[12]) end,
LocalPreset13 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[13]) end,
LocalPreset14 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[14]) end,
LocalPreset15 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[15]) end,
LocalPreset16 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[16]) end,
LocalPreset17 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[17]) end,
LocalPreset18 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[18]) end,
LocalPreset19 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[19]) end,
LocalPreset2 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[2]) end,
LocalPreset20 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[20]) end,
LocalPreset21 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[21]) end,
LocalPreset22 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[22]) end,
LocalPreset23 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[23]) end,
LocalPreset24 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[24]) end,
LocalPreset25 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[25]) end,
LocalPreset26 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[26]) end,
LocalPreset27 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[27]) end,
LocalPreset28 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[28]) end,
LocalPreset29 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[29]) end,
LocalPreset3 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[3]) end,
LocalPreset30 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[30]) end,
LocalPreset31 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[31]) end,
LocalPreset32 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[32]) end,
LocalPreset33 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[33]) end,
LocalPreset34 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[34]) end,
LocalPreset35 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[35]) end,
LocalPreset36 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[36]) end,
LocalPreset37 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[37]) end,
LocalPreset38 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[38]) end,
LocalPreset39 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[39]) end,
LocalPreset4 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[4]) end,
LocalPreset40 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[40]) end,
LocalPreset41 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[41]) end,
LocalPreset42 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[42]) end,
LocalPreset43 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[43]) end,
LocalPreset44 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[44]) end,
LocalPreset45 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[45]) end,
LocalPreset46 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[46]) end,
LocalPreset47 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[47]) end,
LocalPreset48 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[48]) end,
LocalPreset49 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[49]) end,
LocalPreset5 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[5]) end,
LocalPreset50 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[50]) end,
LocalPreset6 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[6]) end,
LocalPreset7 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[7]) end,
LocalPreset8 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[8]) end,
LocalPreset9 = function() LocalPresets.ApplyLocalPreset(ProgramPreferences.LocalPresets[9]) end,
Loupe = CU.fToggleTool('loupe'),
Mask = CU.fToggleTool('masking'),
MaskAddBrush = CU.wrapFOM(LrDevelopController.addToCurrentMask,'brush'),
MaskAddColor = CU.wrapFOM(LrDevelopController.addToCurrentMask,'rangeMask','color'),
MaskAddDepth = CU.wrapFOM(LrDevelopController.addToCurrentMask,'rangeMask','depth'),
MaskAddGrad = CU.wrapFOM(LrDevelopController.addToCurrentMask,'gradient'),
MaskAddLum = CU.wrapFOM(LrDevelopController.addToCurrentMask,'rangeMask','luminance'),
MaskAddRad = CU.wrapFOM(LrDevelopController.addToCurrentMask,'radialGradient'),
MaskAddSky = CU.wrapFOM(LrDevelopController.addToCurrentMask,'aiSelection','sky'),
MaskAddSubject = CU.wrapFOM(LrDevelopController.addToCurrentMask,'aiSelection','subject'),
MaskDelete = Mask.DeleteMask,
MaskDeleteTool = Mask.DeleteMaskTool,
MaskEnable = CU.fToggleTFasync('EnableMaskGroupBasedCorrections'),
MaskHide = Mask.ToggleHideMask,
MaskHideTool = Mask.ToggleHideMaskTool,
MaskIntBrush = CU.wrapFOM(LrDevelopController.intersectWithCurrentMask,'brush'),
MaskIntColor = CU.wrapFOM(LrDevelopController.intersectWithCurrentMask,'rangeMask','color'),
MaskIntDepth = CU.wrapFOM(LrDevelopController.intersectWithCurrentMask,'rangeMask','depth'),
MaskIntGrad = CU.wrapFOM(LrDevelopController.intersectWithCurrentMask,'gradient'),
MaskIntLum = CU.wrapFOM(LrDevelopController.intersectWithCurrentMask,'rangeMask','luminance'),
MaskIntRad = CU.wrapFOM(LrDevelopController.intersectWithCurrentMask,'radialGradient'),
MaskIntSky = CU.wrapFOM(LrDevelopController.intersectWithCurrentMask,'aiSelection','sky'),
MaskIntSubject = CU.wrapFOM(LrDevelopController.intersectWithCurrentMask,'aiSelection','subject'),
MaskInvertTool = Mask.ToggleInvertMaskTool,
MaskNewBrush = CU.wrapFOM(LrDevelopController.createNewMask,'brush'),
MaskNewColor = CU.wrapFOM(LrDevelopController.createNewMask,'rangeMask','color'),
MaskNewDepth = CU.wrapFOM(LrDevelopController.createNewMask,'rangeMask','depth'),
MaskNewGrad = CU.wrapFOM(LrDevelopController.createNewMask,'gradient'),
MaskNewLum = CU.wrapFOM(LrDevelopController.createNewMask,'rangeMask','luminance'),
MaskNewRad = CU.wrapFOM(LrDevelopController.createNewMask,'radialGradient'),
MaskNewSky = CU.wrapFOM(LrDevelopController.createNewMask,'aiSelection','sky'),
MaskNewSubject = CU.wrapFOM(LrDevelopController.createNewMask,'aiSelection','subject'),
MaskNext = Mask.NextMask,
MaskNextTool = Mask.NextTool,
MaskPrevious = Mask.PreviousMask,
MaskPreviousTool = Mask.PreviousTool,
MaskReset = CU.wrapFOM(LrDevelopController.resetMasking),
MaskSubBrush = CU.wrapFOM(LrDevelopController.subtractFromCurrentMask,'brush'),
MaskSubColor = CU.wrapFOM(LrDevelopController.subtractFromCurrentMask,'rangeMask','color'),
MaskSubDepth = CU.wrapFOM(LrDevelopController.subtractFromCurrentMask,'rangeMask','depth'),
MaskSubGrad = CU.wrapFOM(LrDevelopController.subtractFromCurrentMask,'gradient'),
MaskSubLum = CU.wrapFOM(LrDevelopController.subtractFromCurrentMask,'rangeMask','luminance'),
MaskSubRad = CU.wrapFOM(LrDevelopController.subtractFromCurrentMask,'radialGradient'),
MaskSubSky = CU.wrapFOM(LrDevelopController.subtractFromCurrentMask,'aiSelection','sky'),
MaskSubSubject = CU.wrapFOM(LrDevelopController.subtractFromCurrentMask,'aiSelection','subject'),
Next = LrSelection.nextPhoto,
NextScreenMode = LrApplicationView.nextScreenMode,
PV1 = CU.wrapFOM(LrDevelopController.setProcessVersion, 'Version 1'),
PV2 = CU.wrapFOM(LrDevelopController.setProcessVersion, 'Version 2'),
PV3 = CU.wrapFOM(LrDevelopController.setProcessVersion, 'Version 3'),
PV4 = CU.wrapFOM(LrDevelopController.setProcessVersion, 'Version 4'),
PV5 = CU.wrapFOM(LrDevelopController.setProcessVersion, 'Version 5'),
PVLatest = CU.wrapFOM(LrDevelopController.setProcessVersion, 'Version '..Database.LatestPVSupported),
Pause = function() LrTasks.sleep( 0.02 ) end,
Pick = LrSelection.flagAsPick,
PointCurveLinear = CU.UpdatePointCurve({ToneCurveName="Linear",ToneCurveName2012="Linear",ToneCurvePV2012={0,0,255,255,}}),
PointCurveMediumContrast = CU.UpdatePointCurve({ToneCurveName="Medium Contrast",ToneCurveName2012="Medium Contrast",ToneCurvePV2012={0,0,32,22,64,56,128,128,192,196,255,255,}}),
PointCurveStrongContrast = CU.UpdatePointCurve({ToneCurveName="Strong Contrast",ToneCurveName2012="Strong Contrast",ToneCurvePV2012={0,0,32,16,64,50,128,128,192,202,255,255,}}),
PostCropVignetteStyle = CU.fToggle1ModN('PostCropVignetteStyle', 3),
PostCropVignetteStyleColorPriority = CU.wrapFOM(LrDevelopController.setValue,'PostCropVignetteStyle',2),
PostCropVignetteStyleHighlightPriority = CU.wrapFOM(LrDevelopController.setValue,'PostCropVignetteStyle',1),
PostCropVignetteStylePaintOverlay = CU.wrapFOM(LrDevelopController.setValue,'PostCropVignetteStyle',3),
PresetNext = Presets.NextPreset,
PresetPrevious = Presets.PreviousPreset,
Preset_1 = Presets.fApplyPreset(1),
Preset_10 = Presets.fApplyPreset(10),
Preset_11 = Presets.fApplyPreset(11),
Preset_12 = Presets.fApplyPreset(12),
Preset_13 = Presets.fApplyPreset(13),
Preset_14 = Presets.fApplyPreset(14),
Preset_15 = Presets.fApplyPreset(15),
Preset_16 = Presets.fApplyPreset(16),
Preset_17 = Presets.fApplyPreset(17),
Preset_18 = Presets.fApplyPreset(18),
Preset_19 = Presets.fApplyPreset(19),
Preset_2 = Presets.fApplyPreset(2),
Preset_20 = Presets.fApplyPreset(20),
Preset_21 = Presets.fApplyPreset(21),
Preset_22 = Presets.fApplyPreset(22),
Preset_23 = Presets.fApplyPreset(23),
Preset_24 = Presets.fApplyPreset(24),
Preset_25 = Presets.fApplyPreset(25),
Preset_26 = Presets.fApplyPreset(26),
Preset_27 = Presets.fApplyPreset(27),
Preset_28 = Presets.fApplyPreset(28),
Preset_29 = Presets.fApplyPreset(29),
Preset_3 = Presets.fApplyPreset(3),
Preset_30 = Presets.fApplyPreset(30),
Preset_31 = Presets.fApplyPreset(31),
Preset_32 = Presets.fApplyPreset(32),
Preset_33 = Presets.fApplyPreset(33),
Preset_34 = Presets.fApplyPreset(34),
Preset_35 = Presets.fApplyPreset(35),
Preset_36 = Presets.fApplyPreset(36),
Preset_37 = Presets.fApplyPreset(37),
Preset_38 = Presets.fApplyPreset(38),
Preset_39 = Presets.fApplyPreset(39),
Preset_4 = Presets.fApplyPreset(4),
Preset_40 = Presets.fApplyPreset(40),
Preset_41 = Presets.fApplyPreset(41),
Preset_42 = Presets.fApplyPreset(42),
Preset_43 = Presets.fApplyPreset(43),
Preset_44 = Presets.fApplyPreset(44),
Preset_45 = Presets.fApplyPreset(45),
Preset_46 = Presets.fApplyPreset(46),
Preset_47 = Presets.fApplyPreset(47),
Preset_48 = Presets.fApplyPreset(48),
Preset_49 = Presets.fApplyPreset(49),
Preset_5 = Presets.fApplyPreset(5),
Preset_50 = Presets.fApplyPreset(50),
Preset_51 = Presets.fApplyPreset(51),
Preset_52 = Presets.fApplyPreset(52),
Preset_53 = Presets.fApplyPreset(53),
Preset_54 = Presets.fApplyPreset(54),
Preset_55 = Presets.fApplyPreset(55),
Preset_56 = Presets.fApplyPreset(56),
Preset_57 = Presets.fApplyPreset(57),
Preset_58 = Presets.fApplyPreset(58),
Preset_59 = Presets.fApplyPreset(59),
Preset_6 = Presets.fApplyPreset(6),
Preset_60 = Presets.fApplyPreset(60),
Preset_61 = Presets.fApplyPreset(61),
Preset_62 = Presets.fApplyPreset(62),
Preset_63 = Presets.fApplyPreset(63),
Preset_64 = Presets.fApplyPreset(64),
Preset_65 = Presets.fApplyPreset(65),
Preset_66 = Presets.fApplyPreset(66),
Preset_67 = Presets.fApplyPreset(67),
Preset_68 = Presets.fApplyPreset(68),
Preset_69 = Presets.fApplyPreset(69),
Preset_7 = Presets.fApplyPreset(7),
Preset_70 = Presets.fApplyPreset(70),
Preset_71 = Presets.fApplyPreset(71),
Preset_72 = Presets.fApplyPreset(72),
Preset_73 = Presets.fApplyPreset(73),
Preset_74 = Presets.fApplyPreset(74),
Preset_75 = Presets.fApplyPreset(75),
Preset_76 = Presets.fApplyPreset(76),
Preset_77 = Presets.fApplyPreset(77),
Preset_78 = Presets.fApplyPreset(78),
Preset_79 = Presets.fApplyPreset(79),
Preset_8 = Presets.fApplyPreset(8),
Preset_80 = Presets.fApplyPreset(80),
Preset_9 = Presets.fApplyPreset(9),
Prev = LrSelection.previousPhoto,
QuickDevBlacksLarge = CU.quickDevAdjust('Blacks',20,'QuickDevBlacksLarge'),
QuickDevBlacksLargeDec = CU.quickDevAdjust('Blacks',-20,'QuickDevBlacksLargeDec'),
QuickDevBlacksSmall = CU.quickDevAdjust('Blacks',5,'QuickDevBlacksSmall'),
QuickDevBlacksSmallDec = CU.quickDevAdjust('Blacks',-5,'QuickDevBlacksSmallDec'),
QuickDevClarityLarge = CU.quickDevAdjust('Clarity',20,'QuickDevClarityLarge'),
QuickDevClarityLargeDec = CU.quickDevAdjust('Clarity',-20,'QuickDevClarityLargeDec'),
QuickDevClaritySmall = CU.quickDevAdjust('Clarity',5,'QuickDevClaritySmall'),
QuickDevClaritySmallDec = CU.quickDevAdjust('Clarity',-5,'QuickDevClaritySmallDec'),
QuickDevContrastLarge = CU.quickDevAdjust('Contrast',20,'QuickDevContrastLarge'),
QuickDevContrastLargeDec = CU.quickDevAdjust('Contrast',-20,'QuickDevContrastLargeDec'),
QuickDevContrastSmall = CU.quickDevAdjust('Contrast',5,'QuickDevContrastSmall'),
QuickDevContrastSmallDec = CU.quickDevAdjust('Contrast',-5,'QuickDevContrastSmallDec'),
QuickDevCropAspect1x1 = function() CU.QuickCropAspect({w=1,h=1}) end,
QuickDevCropAspect2x3 = function() CU.QuickCropAspect({w=2,h=3}) end,
QuickDevCropAspect3x4 = function() CU.QuickCropAspect({w=3,h=4}) end,
QuickDevCropAspect4x5 = function() CU.QuickCropAspect({w=4,h=5}) end,
QuickDevCropAspect5x7 = function() CU.QuickCropAspect({w=5,h=7}) end,
QuickDevCropAspect85x11 = function() CU.QuickCropAspect({w=8.5,h=11}) end,
QuickDevCropAspect9x16 = function() CU.QuickCropAspect({w=9,h=16}) end,
QuickDevCropAspectAsShot = function() CU.QuickCropAspect('asshot') end,
QuickDevCropAspectOriginal = function() CU.QuickCropAspect('original') end,
QuickDevExpLarge = CU.quickDevAdjust('Exposure',50,'QuickDevExpLarge'),
QuickDevExpLargeDec = CU.quickDevAdjust('Exposure',-50,'QuickDevExpLargeDec'),
QuickDevExpSmall = CU.quickDevAdjust('Exposure',16.5,'QuickDevExpSmall'),
QuickDevExpSmallDec = CU.quickDevAdjust('Exposure',-16.5,'QuickDevExpSmallDec'),
QuickDevHighlightsLarge = CU.quickDevAdjust('Highlights',20,'QuickDevHighlightsLarge'),
QuickDevHighlightsLargeDec = CU.quickDevAdjust('Highlights',-20,'QuickDevHighlightsLargeDec'),
QuickDevHighlightsSmall = CU.quickDevAdjust('Highlights',5,'QuickDevHighlightsSmall'),
QuickDevHighlightsSmallDec = CU.quickDevAdjust('Highlights',-5,'QuickDevHighlightsSmallDec'),
QuickDevSatLarge = CU.quickDevAdjust('Saturation',20,'QuickDevSatLarge'),
QuickDevSatLargeDec = CU.quickDevAdjust('Saturation',-20,'QuickDevSatLargeDec'),
QuickDevSatSmall = CU.quickDevAdjust('Saturation',5,'QuickDevSatSmall'),
QuickDevSatSmallDec = CU.quickDevAdjust('Saturation',-5,'QuickDevSatSmallDec'),
QuickDevShadowsLarge = CU.quickDevAdjust('Shadows',20,'QuickDevShadowsLarge'),
QuickDevShadowsLargeDec = CU.quickDevAdjust('Shadows',-20,'QuickDevShadowsLargeDec'),
QuickDevShadowsSmall = CU.quickDevAdjust('Shadows',5,'QuickDevShadowsSmall'),
QuickDevShadowsSmallDec = CU.quickDevAdjust('Shadows',-5,'QuickDevShadowsSmallDec'),
QuickDevTempLarge = CU.quickDevAdjustWB('Temperature',20,'QuickDevTempLarge'),
QuickDevTempLargeDec = CU.quickDevAdjustWB('Temperature',-20,'QuickDevTempLargeDec'),
QuickDevTempSmall = CU.quickDevAdjustWB('Temperature',5,'QuickDevTempSmall'),
QuickDevTempSmalDec = CU.quickDevAdjustWB('Temperature',-5,'QuickDevTempSmalDec'),
QuickDevTintLarge = CU.quickDevAdjustWB('Tint',20,'QuickDevTintLarge'),
QuickDevTintLargeDec = CU.quickDevAdjustWB('Tint',-20,'QuickDevTintLargeDec'),
QuickDevTintSmall = CU.quickDevAdjustWB('Tint',5,'QuickDevTintSmall'),
QuickDevTintSmallDec = CU.quickDevAdjustWB('Tint',-5,'QuickDevTintSmallDec'),
QuickDevVibranceLarge = CU.quickDevAdjust('Vibrance',20,'QuickDevVibranceLarge'),
QuickDevVibranceLargeDec = CU.quickDevAdjust('Vibrance',-20,'QuickDevVibranceLargeDec'),
QuickDevVibranceSmall = CU.quickDevAdjust('Vibrance',5,'QuickDevVibranceSmall'),
QuickDevVibranceSmallDec = CU.quickDevAdjust('Vibrance',-5,'QuickDevVibranceSmallDec'),
QuickDevWBAuto = CU.wrapForEachPhoto('QuickDevWBAuto'),
QuickDevWBCloudy = CU.wrapForEachPhoto('QuickDevWBCloudy'),
QuickDevWBDaylight = CU.wrapForEachPhoto('QuickDevWBDaylight'),
QuickDevWBFlash = CU.wrapForEachPhoto('QuickDevWBFlash'),
QuickDevWBFluorescent = CU.wrapForEachPhoto('QuickDevWBFluorescent'),
QuickDevWBShade = CU.wrapForEachPhoto('QuickDevWBShade'),
QuickDevWBTungsten = CU.wrapForEachPhoto('QuickDevWBTungsten'),
QuickDevWhitesLarge = CU.quickDevAdjust('Whites',20,'QuickDevWhitesLarge'),
QuickDevWhitesLargeDec = CU.quickDevAdjust('Whites',-20,'QuickDevWhitesLargeDec'),
QuickDevWhitesSmall = CU.quickDevAdjust('Whites',5,'QuickDevWhitesSmall'),
QuickDevWhitesSmallDec = CU.quickDevAdjust('Whites',-5,'QuickDevWhitesSmallDec'),
RedEye = CU.fToggleTool('redeye'),
Redo = LrUndo.redo,
Reject = LrSelection.flagAsReject,
RemoveFlag = LrSelection.removeFlag,
ResetAll = CU.wrapFOM(LrDevelopController.resetAllDevelopAdjustments),
ResetAllGrayMixer = CU.ResetAllGrayMixer,
ResetAllHueAdjustment = CU.ResetAllHueAdjustment,
ResetAllLuminanceAdjustment = CU.ResetAllLuminanceAdjustment,
ResetAllSaturationAdjustment = CU.ResetAllSaturationAdjustment,
ResetCrop = CU.wrapFOM(LrDevelopController.resetCrop),
ResetLast = function() CU.execFOM(LrDevelopController.resetToDefault,LastParam) end,
ResetRedeye = CU.wrapFOM(LrDevelopController.resetRedeye),
ResetSpotRem = CU.wrapFOM(LrDevelopController.resetSpotRemoval),
ResetTransforms = CU.wrapFOM(LrDevelopController.resetTransforms),
RevealPanelAdjust = CU.fChangePanel('adjustPanel'),
RevealPanelCalibrate = CU.fChangePanel('calibratePanel'),
RevealPanelColorGrading = CU.fChangePanel('colorGradingPanel'),
RevealPanelDetail = CU.fChangePanel('detailPanel'),
RevealPanelEffects = CU.fChangePanel('effectsPanel'),
RevealPanelLens = CU.fChangePanel('lensCorrectionsPanel'),
RevealPanelMixer = CU.fChangePanel('mixerPanel'),
RevealPanelSplit = CU.fChangePanel('splitToningPanel'),
RevealPanelTone = CU.fChangePanel('tonePanel'),
RevealPanelTransform = CU.fChangePanel('transformPanel'),
RotateLeft = CU.wrapForEachPhoto('rotateLeft'),
RotateRight = CU.wrapForEachPhoto('rotateRight'),
Select1Left = function() LrSelection.extendSelection('left',1) end,
Select1Right = function() LrSelection.extendSelection('right',1) end,
SetRating0 = function() LrSelection.setRating(0) end,
SetRating1 = function() LrSelection.setRating(1) end,
SetRating2 = function() LrSelection.setRating(2) end,
SetRating3 = function() LrSelection.setRating(3) end,
SetRating4 = function() LrSelection.setRating(4) end,
SetRating5 = function() LrSelection.setRating(5) end,
SetTreatmentBW = CU.wrapForEachPhoto('SetTreatmentBW'),
SetTreatmentColor = CU.wrapForEachPhoto('SetTreatmentColor'),
ShoFullHidePanels = LrApplicationView.fullscreenHidePanels,
ShoFullPreview = LrApplicationView.fullscreenPreview,
ShoScndVwcompare = function() LrApplicationView.showSecondaryView('compare') end,
ShoScndVwgrid = function() LrApplicationView.showSecondaryView('grid') end,
ShoScndVwlive_loupe = function() LrApplicationView.showSecondaryView('live_loupe') end,
ShoScndVwlocked_loupe = function() LrApplicationView.showSecondaryView('locked_loupe') end,
ShoScndVwloupe = function() LrApplicationView.showSecondaryView('loupe') end,
ShoScndVwslideshow = function() LrApplicationView.showSecondaryView('slideshow') end,
ShoScndVwsurvey = function() LrApplicationView.showSecondaryView('survey') end,
ShoVwRefHoriz = function() LrApplicationView.showView('develop_reference_horiz') end,
ShoVwRefVert = function() LrApplicationView.showView('develop_reference_vert') end,
ShoVwcompare = function() LrApplicationView.showView('compare') end,
ShoVwdevelop_before = function() LrApplicationView.showView('develop_before') end,
ShoVwdevelop_before_after_horiz = function() LrApplicationView.showView('develop_before_after_horiz') end,
ShoVwdevelop_before_after_vert = function() LrApplicationView.showView('develop_before_after_vert') end,
ShoVwdevelop_loupe = function() LrApplicationView.showView('develop_loupe') end,
ShoVwgrid = function() LrApplicationView.showView('grid') end,
ShoVwloupe = function() LrApplicationView.showView('loupe') end,
ShoVwpeople = function() LrApplicationView.showView('people') end,
ShoVwsurvey = function() LrApplicationView.showView('survey') end,
ShowClipping = CU.wrapFOM(LrDevelopController.showClipping),
SliderDecrease = CU.fSimulateKeys(KS.KeyCode.SliderDecreaseKey,true),
SliderIncrease = CU.fSimulateKeys(KS.KeyCode.SliderIncreaseKey,true),
SpotRemoval = CU.fToggleTool1('dust'),
SwToMbook = CU.fChangeModule('book'),
SwToMdevelop = CU.fChangeModule('develop'),
SwToMlibrary = CU.fChangeModule('library'),
SwToMmap = CU.fChangeModule('map'),
SwToMprint = CU.fChangeModule('print'),
SwToMslideshow = CU.fChangeModule('slideshow'),
SwToMweb = CU.fChangeModule('web'),
ToggleBlue = LrSelection.toggleBlueLabel,
ToggleFlag = function() MIDI2LR.SERVER:send('SendKey '..KS.KeyCode.ToggleFlagKey..'\n') end,
ToggleGreen = LrSelection.toggleGreenLabel,
ToggleLoupe = LrApplicationView.toggleLoupe,
ToggleOverlay = LrDevelopController.toggleOverlay,
TogglePurple = LrSelection.togglePurpleLabel,
ToggleRed = LrSelection.toggleRedLabel,
ToggleScreenTwo = LrApplicationView.toggleSecondaryDisplay,
ToggleYellow = LrSelection.toggleYellowLabel,
ToggleZoomOffOn = LrApplicationView.toggleZoom,
Undo = LrUndo.undo,
UprightAuto = CU.wrapFOM(LrDevelopController.setValue,'PerspectiveUpright',1),
UprightFull = CU.wrapFOM(LrDevelopController.setValue,'PerspectiveUpright',2),
UprightGuided = CU.wrapFOM(LrDevelopController.setValue,'PerspectiveUpright',5),
UprightLevel = CU.wrapFOM(LrDevelopController.setValue,'PerspectiveUpright',3),
UprightOff = CU.wrapFOM(LrDevelopController.setValue,'PerspectiveUpright',0),
UprightVertical = CU.wrapFOM(LrDevelopController.setValue,'PerspectiveUpright',4),
VirtualCopy = function() LrApplication.activeCatalog():createVirtualCopies() end,
WhiteBalanceAs_Shot = CU.wrapFOM(LrDevelopController.setValue,'WhiteBalance','As Shot'),
WhiteBalanceAuto = LrDevelopController.setAutoWhiteBalance,
WhiteBalanceCloudy = CU.wrapFOM(LrDevelopController.setValue,'WhiteBalance','Cloudy'),
WhiteBalanceDaylight = CU.wrapFOM(LrDevelopController.setValue,'WhiteBalance','Daylight'),
WhiteBalanceFlash = CU.wrapFOM(LrDevelopController.setValue,'WhiteBalance','Flash'),
WhiteBalanceFluorescent = CU.wrapFOM(LrDevelopController.setValue,'WhiteBalance','Fluorescent'),
WhiteBalanceShade = CU.wrapFOM(LrDevelopController.setValue,'WhiteBalance','Shade'),
WhiteBalanceTungsten = CU.wrapFOM(LrDevelopController.setValue,'WhiteBalance','Tungsten'),
ZoomInLargeStep = LrApplicationView.zoomIn,
ZoomInSmallStep = LrApplicationView.zoomInSome,
ZoomOutLargeStep = LrApplicationView.zoomOut,
ZoomOutSmallStep = LrApplicationView.zoomOutSome,
ZoomTo100 = LrApplicationView.zoomToOneToOne,
openExportDialog = CU.wrapForEachPhoto('openExportDialog'),
openExportWithPreviousDialog = CU.wrapForEachPhoto('openExportWithPreviousDialog') ,
profile1 = function() Profiles.changeProfile('profile1', true) end,
profile10 = function() Profiles.changeProfile('profile10', true) end,
profile11 = function() Profiles.changeProfile('profile11', true) end,
profile12 = function() Profiles.changeProfile('profile12', true) end,
profile13 = function() Profiles.changeProfile('profile13', true) end,
profile14 = function() Profiles.changeProfile('profile14', true) end,
profile15 = function() Profiles.changeProfile('profile15', true) end,
profile16 = function() Profiles.changeProfile('profile16', true) end,
profile17 = function() Profiles.changeProfile('profile17', true) end,
profile18 = function() Profiles.changeProfile('profile18', true) end,
profile19 = function() Profiles.changeProfile('profile19', true) end,
profile2 = function() Profiles.changeProfile('profile2', true) end,
profile20 = function() Profiles.changeProfile('profile20', true) end,
profile21 = function() Profiles.changeProfile('profile21', true) end,
profile22 = function() Profiles.changeProfile('profile22', true) end,
profile23 = function() Profiles.changeProfile('profile23', true) end,
profile24 = function() Profiles.changeProfile('profile24', true) end,
profile25 = function() Profiles.changeProfile('profile25', true) end,
profile26 = function() Profiles.changeProfile('profile26', true) end,
profile3 = function() Profiles.changeProfile('profile3', true) end,
profile4 = function() Profiles.changeProfile('profile4', true) end,
profile5 = function() Profiles.changeProfile('profile5', true) end,
profile6 = function() Profiles.changeProfile('profile6', true) end,
profile7 = function() Profiles.changeProfile('profile7', true) end,
profile8 = function() Profiles.changeProfile('profile8', true) end,
profile9 = function() Profiles.changeProfile('profile9', true) end,
}
--need to refer to table after it is initially constructed, so can't put in initial construction statement
ACTIONS.ActionSeries1 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[1],ACTIONS) end
ACTIONS.ActionSeries2 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[2],ACTIONS) end
ACTIONS.ActionSeries3 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[3],ACTIONS) end
ACTIONS.ActionSeries4 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[4],ACTIONS) end
ACTIONS.ActionSeries5 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[5],ACTIONS) end
ACTIONS.ActionSeries6 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[6],ACTIONS) end
ACTIONS.ActionSeries7 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[7],ACTIONS) end
ACTIONS.ActionSeries8 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[8],ACTIONS) end
ACTIONS.ActionSeries9 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[9],ACTIONS) end
ACTIONS.ActionSeries10 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[10],ACTIONS) end
ACTIONS.ActionSeries11 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[11],ACTIONS) end
ACTIONS.ActionSeries12 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[12],ACTIONS) end
ACTIONS.ActionSeries13 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[13],ACTIONS) end
ACTIONS.ActionSeries14 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[14],ACTIONS) end
ACTIONS.ActionSeries15 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[15],ACTIONS) end
ACTIONS.ActionSeries16 = function() ActionSeries.Run(ProgramPreferences.ActionSeries[16],ACTIONS) end
local function notsupported() LrDialogs.showBezel(LOC('$$$/MIDI2LR/Dialog/NeedNewerLR=A newer version of Lightroom is required')) end
local SETTINGS = {
AppInfo = function(value) Info.AppInfo[#Info.AppInfo+1] = value end,
ChangedToDirectory = Profiles.setDirectory,
ChangedToFile = Profiles.setFile,
ChangedToFullPath = Profiles.setFullPath,
Pickup = function(enabled)
if tonumber(enabled) == 1 then -- state machine
UpdateParam = UpdateParamPickup
else
UpdateParam = UpdateParamNoPickup
end
end,
ProfileAmount = CU.ProfileAmount,
--[[
For SetRating, if send back sync value to controller, formula is:
(Rating * 2 + 1)/12
or,
0 = 0.083333333, 1 = 0.25, 2 = 4.16667, 3 = 0.583333, 4 = 0.75, 5 = 0.916667
Make sure to send back sync only when controller not in the range of current value, or we will
be yanking the controller out of people's hands, as "correct value" is 1/6th of fader's travel.
Will need to add code to AdjustmentChangeObserver and FullRefresh, and remember last fader
position received by SetRating.
--]]
SetRating = function(value)
local newrating = math.min(5,math.floor(tonumber(value)*6))
if newrating ~= LrSelection.getRating() then
LrSelection.setRating(newrating)
end
end,
}
function UpdateParamPickup() --closure
local paramlastmoved = {}
local lastfullrefresh = 0
return function(param, midi_value, silent)
if LrApplication.activeCatalog():getTargetPhoto() == nil then return end--unable to update param
local value
if LrApplicationView.getCurrentModuleName() ~= 'develop' then
LrApplicationView.switchToModule('develop')
LrTasks.yield() -- need this to allow module change before value sent
end
if Limits.Parameters[param] then
Limits.ClampValue(param)
end
if (math.abs(midi_value - CU.LRValueToMIDIValue(param)) <= PICKUP_THRESHOLD) or (paramlastmoved[param] ~= nil and paramlastmoved[param] + 0.5 > os.clock()) then -- pickup succeeded
paramlastmoved[param] = os.clock()
value = CU.MIDIValueToLRValue(param, midi_value)
if value ~= LrDevelopController.getValue(param) then
MIDI2LR.PARAM_OBSERVER[param] = value
LrDevelopController.setValue(param, value)
LastParam = param
if ProgramPreferences.ClientShowBezelOnChange and not silent then
CU.showBezel(param,value)
elseif type(silent) == 'string' then
LrDialogs.showBezel(silent)
end
end
if Database.CmdPanel[param] then
Profiles.changeProfile(Database.CmdPanel[param])
end
else --failed pickup
if ProgramPreferences.ClientShowBezelOnChange then -- failed pickup. do I display bezel?
value = CU.MIDIValueToLRValue(param, midi_value)
local actualvalue = LrDevelopController.getValue(param)
CU.showBezel(param,value,actualvalue)
end
if lastfullrefresh + 1 < os.clock() then --try refreshing controller once a second
CU.FullRefresh()
lastfullrefresh = os.clock()
end
end -- end of if pickup/elseif bezel group
end -- end of returned function
end
UpdateParamPickup = UpdateParamPickup() --complete closure
--called within LrRecursionGuard for setting
function UpdateParamNoPickup(param, midi_value, silent)
if LrApplication.activeCatalog():getTargetPhoto() == nil then return end--unable to update param
local value
if LrApplicationView.getCurrentModuleName() ~= 'develop' then
LrApplicationView.switchToModule('develop')
LrTasks.yield() -- need this to allow module change before value sent
end
--Don't need to clamp limited parameters without pickup, as MIDI controls will still work
--if value is outside limits range
value = CU.MIDIValueToLRValue(param, midi_value)
if value ~= LrDevelopController.getValue(param) then
MIDI2LR.PARAM_OBSERVER[param] = value
LrDevelopController.setValue(param, value)
LastParam = param
if ProgramPreferences.ClientShowBezelOnChange and not silent then
CU.showBezel(param,value)
elseif type(silent) == 'string' then
LrDialogs.showBezel(silent)
end
end
if Database.CmdPanel[param] then
Profiles.changeProfile(Database.CmdPanel[param])
end
end
UpdateParam = UpdateParamPickup --initial state
LrFunctionContext.callWithContext(
'socket_remote',
function( context )
--[[-----------debug section, enable by adding - to beginning this line
LrMobdebug.on()
--]]-----------end debug section
local LrShell = import 'LrShell'
local LrSocket = import 'LrSocket'
local CurrentObserver
--call following within guard for reading
local function AdjustmentChangeObserver()
local lastrefresh = 0 --will be set to os.clock + increment to rate limit
return function(observer) -- closure
if not sendIsConnected then return end -- can't send
if Limits.LimitsCanBeSet() and lastrefresh < os.clock() then
-- refresh crop values NOTE: this function is repeated in ClientUtilities and Profiles
local val_bottom = LrDevelopController.getValue("CropBottom")
MIDI2LR.SERVER:send(string.format('CropBottomRight %g\n', val_bottom))
MIDI2LR.SERVER:send(string.format('CropBottomLeft %g\n', val_bottom))
MIDI2LR.SERVER:send(string.format('CropAll %g\n', val_bottom))
MIDI2LR.SERVER:send(string.format('CropBottom %g\n', val_bottom))
local val_top = LrDevelopController.getValue("CropTop")
MIDI2LR.SERVER:send(string.format('CropTopRight %g\n', val_top))
MIDI2LR.SERVER:send(string.format('CropTopLeft %g\n', val_top))
MIDI2LR.SERVER:send(string.format('CropTop %g\n', val_top))
local val_left = LrDevelopController.getValue("CropLeft")
local val_right = LrDevelopController.getValue("CropRight")
MIDI2LR.SERVER:send(string.format('CropLeft %g\n', val_left))
MIDI2LR.SERVER:send(string.format('CropRight %g\n', val_right))
local range_v = (1 - (val_bottom - val_top))
if range_v == 0.0 then
MIDI2LR.SERVER:send('CropMoveVertical 0\n')
else
MIDI2LR.SERVER:send(string.format('CropMoveVertical %g\n', val_top / range_v))
end
local range_h = (1 - (val_right - val_left))
if range_h == 0.0 then
MIDI2LR.SERVER:send('CropMoveHorizontal 0\n')
else
MIDI2LR.SERVER:send(string.format('CropMoveHorizontal %g\n', val_left / range_h))
end
for param in pairs(Database.Parameters) do
local lrvalue = LrDevelopController.getValue(param)
if observer[param] ~= lrvalue and type(lrvalue) == 'number' then --testing for MIDI2LR.SERVER.send kills responsiveness
MIDI2LR.SERVER:send(string.format('%s %g\n', param, CU.LRValueToMIDIValue(param)))
observer[param] = lrvalue
LastParam = param
end
end
lastrefresh = os.clock() + 0.1 --1/10 sec between refreshes
end
end
end
AdjustmentChangeObserver = AdjustmentChangeObserver() --complete closure
local function InactiveObserver() end
CurrentObserver = AdjustmentChangeObserver -- will change when detect loss of MIDI controller
-- wrapped in function so can be called when connection lost
local function startServer(context1)
MIDI2LR.SERVER = LrSocket.bind {
functionContext = context1,
plugin = _PLUGIN,
port = SEND_PORT,
mode = 'send',
onClosed = function () sendIsConnected = false end,
onConnected = function () sendIsConnected = true end,
onError = function( socket )
sendIsConnected = false
if MIDI2LR.RUNNING then --
socket:reconnect()
end
end,
}
end
MIDI2LR.CLIENT = LrSocket.bind {
functionContext = context,
plugin = _PLUGIN,
port = RECEIVE_PORT,
mode = 'receive',
onMessage = function(_, message) --message processor
if type(message) == 'string' then
local split = message:find(' ',1,true)
local param = message:sub(1,split-1)
local value = message:sub(split+1)
if Database.Parameters[param] then
UpdateParam(param,tonumber(value),false)
local gradeFocus = GradeFocusTable[param]
if gradeFocus then
local currentView = LrDevelopController.getActiveColorGradingView()
if currentView ~= '3-way' or gradeFocus == 'global' then
if currentView ~= gradeFocus then
LrDevelopController.setActiveColorGradingView(gradeFocus)
end
end
end
elseif ACTIONS[param] then -- perform a one time action
if tonumber(value) > BUTTON_ON then
ACTIONS[param]()
end
elseif SETTINGS[param] then -- do something requiring the transmitted value to be known
SETTINGS[param](value)
elseif Virtual[param] then -- handle a virtual command
local lp = Virtual[param](value, UpdateParam)
if lp then
LastParam = lp
end
elseif param:sub(1,4) == 'Crop' then
CU.RatioCrop(param,value,UpdateParam)
elseif param:sub(1,5) == 'Reset' then -- perform a reset other than those explicitly coded in ACTIONS array
if tonumber(value) > BUTTON_ON then
local resetparam = param:sub(6)
if Database.Parameters[resetparam] then -- sanitize input: is it really a parameter?
CU.execFOM(LrDevelopController.resetToDefault,resetparam)
if ProgramPreferences.ClientShowBezelOnChange then
local lrvalue = LrDevelopController.getValue(resetparam)
CU.showBezel(resetparam,lrvalue)
end
local gradeFocus = GradeFocusTable[resetparam] -- scroll to correct view on color grading
if gradeFocus then
local currentView = LrDevelopController.getActiveColorGradingView()
if currentView ~= '3-way' or gradeFocus == 'global' then
if currentView ~= gradeFocus then
LrDevelopController.setActiveColorGradingView(gradeFocus)
end
end
end
end
end
end
end
end,
onClosed = function( socket )
if MIDI2LR.RUNNING then
-- MIDI2LR closed connection, allow for reconnection
socket:reconnect()
-- calling SERVER:reconnect causes LR to hang for some reason...
MIDI2LR.SERVER:close()
startServer(context)
end
end,
onError = function(socket, err)
if err == 'timeout' then -- reconnect if timed out
socket:reconnect()
end
end
}
startServer(context)
if WIN_ENV then
LrShell.openFilesInApp({LrPathUtils.child(_PLUGIN.path, 'Info.lua')}, LrPathUtils.child(_PLUGIN.path, 'MIDI2LR.exe'))
else
LrShell.openFilesInApp({LrPathUtils.child(_PLUGIN.path, 'Info.lua')}, LrPathUtils.child(_PLUGIN.path, 'MIDI2LR.app'))
end
-- add an observer for develop param changes--needs to occur in develop module
-- will drop out of loop if loadversion changes or if in develop module with selected photo
while MIDI2LR.RUNNING and ((LrApplicationView.getCurrentModuleName() ~= 'develop') or (LrApplication.activeCatalog():getTargetPhoto() == nil)) do
LrTasks.sleep ( .29 )
Profiles.checkProfile()
end --sleep away until ended or until develop module activated
LrTasks.sleep ( .2 ) --avoid "attempt to index field 'libraryImage' (a nil value) on fast machines: LR bug
if MIDI2LR.RUNNING then --didn't drop out of loop because of program termination
if ProgramPreferences.RevealAdjustedControls then --may be nil or false
LrDevelopController.revealAdjustedControls( true ) -- reveal affected parameter in panel track
end
if ProgramPreferences.TrackingDelay ~= nil then
LrDevelopController.setTrackingDelay(ProgramPreferences.TrackingDelay)
end
LrDevelopController.addAdjustmentChangeObserver(
context,
MIDI2LR.PARAM_OBSERVER,
function ( observer )
CurrentObserver(observer)
end
)
while MIDI2LR.RUNNING do --detect halt or reload
LrTasks.sleep( .29 )
Profiles.checkProfile()
end
end
end
)
end
)
| gpl-3.0 |
gmange/piscine-unity | vgs-d08/Assets/ex02/Scripts/EnemySpwaner.cs | 673 | using UnityEngine;
using System.Collections;
public class EnemySpwaner : MonoBehaviour {
public GameObject lambentMale;
public GameObject lambentFemale;
private Object spawn = null;
private float timer = 0;
void Start () {
spawnLambent ();
}
void Update () {
if (!spawn) {
if (timer < 0) {
spawnLambent();
} else {
timer -= Time.deltaTime;
}
}
}
void spawnLambent() {
if (Random.Range (0, 2) == 0) {
spawn = lambentMale;
} else {
spawn = lambentFemale;
}
spawn = Instantiate (spawn, transform.position, Quaternion.identity);
setTimer ();
}
void setTimer() {
timer = Random.Range (40, 100) / 20;
}
}
| gpl-3.0 |
eciis/web | backend/handlers/invite_user_handler.py | 3488 | # -*- coding: utf-8 -*-
"""Invite User Handler."""
from google.appengine.ext import ndb
import json
from util import login_required
from . import BaseHandler
from models import InstitutionProfile
from custom_exceptions import FieldException
from custom_exceptions import NotAuthorizedException
from utils import json_response
from utils import Utils
from util import JsonPatch
__all__ = ['InviteUserHandler']
def define_entity(dictionary):
"""Method of return instance of InstitutionProfile for using in jsonPacth."""
return InstitutionProfile
def check_if_user_is_member(user, institution):
"""Check if the user is already a member."""
return institution.has_member(user.key) and user.is_member(institution.key)
class InviteUserHandler(BaseHandler):
"""Invite User Handler."""
@json_response
@login_required
def delete(self, user, invite_urlsafe):
"""Change invite status from 'sent' to 'rejected'.
This method is called when a user reject an invite
to be member of an institution.
"""
invite_key = ndb.Key(urlsafe=invite_urlsafe)
invite = invite_key.get()
invite_class_name = invite.__class__.__name__
Utils._assert(invite_class_name != 'InviteUser',
"The invite's type is %s, but InviteUser is the expected one" %invite_class_name,
NotAuthorizedException)
Utils._assert(invite.status != 'sent',
"This invitation has already been processed",
NotAuthorizedException)
invite.change_status('rejected')
invite.put()
invite.send_response_notification(user.current_institution, user.key, 'REJECT')
@json_response
@login_required
@ndb.transactional(xg=True)
def patch(self, user, invite_urlsafe):
"""Handle PATCH Requests.
This method is called when an user accept
the invite to be a member of an institution.
"""
data = self.request.body
invite = ndb.Key(urlsafe=invite_urlsafe).get()
invite_class_name = invite.__class__.__name__
Utils._assert(invite_class_name != 'InviteUser',
"The invite's type is %s, but InviteUser is the expected one" % invite_class_name,
NotAuthorizedException)
Utils._assert(invite.status != 'sent',
"This invitation has already been processed",
NotAuthorizedException)
institution_key = invite.institution_key
institution = institution_key.get()
Utils._assert(check_if_user_is_member(user, institution),
"The user is already a member", NotAuthorizedException)
Utils._assert(not institution.is_active(),
"This institution is not active.", NotAuthorizedException)
invite.change_status('accepted')
user.add_institution(institution_key)
user.follow(institution_key)
user.change_state('active')
institution.add_member(user)
institution.follow(user.key)
JsonPatch.load(data, user, define_entity)
Utils._assert(
not InstitutionProfile.is_valid(user.institution_profiles),
"The profile is invalid.", FieldException
)
user.put()
invite.send_response_notification(user.current_institution, user.key, 'ACCEPT')
self.response.write(json.dumps(user.make(self.request)))
| gpl-3.0 |
kennisnet/Sparql-Query-Api | src/Admin/Controllers/Attributes/NoCacheAttribute.cs | 634 | using System;
using System.Web;
using System.Web.Mvc;
namespace Trezorix.Sparql.Api.Admin.Controllers.Attributes
{
public class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
var cacheSetting = filterContext.HttpContext.Response.Cache;
cacheSetting.SetExpires(DateTime.UtcNow.AddDays(-1));
cacheSetting.SetValidUntilExpires(false);
cacheSetting.SetRevalidation(HttpCacheRevalidation.AllCaches);
cacheSetting.SetCacheability(HttpCacheability.NoCache);
cacheSetting.SetNoStore();
base.OnResultExecuting(filterContext);
}
}
} | gpl-3.0 |
marcusfaccion/unnamed_app | web/js/home/actions.js | 7721 | $('body').on('click', '#home-user-navigation-stop', function(){
app.message_code = 'routes.stop.navigation';
app.yconfirmation.action = function(){
geoJSON_layer.routes.clearLayers(); // apaga as rotas do usuário do layers routes, removendo-a da tela consecutivamente.
directions.setOrigin();
directions.setDestination();
me.latlng_history.destroy();
app.directions.myOrigin = false;
app.directions.free = true; // Entra no modo navegação normal
app.directions.pause = false;
$('#home-user-navigation-stop').fadeOut('now');
$('#map_menu .nav-destination-reset').fadeOut('now'); //corrige bug se essa ação é acionada pela trigger do botão redefinir rota
};
$('#home_confirmation_modal').modal('show');
});
$('body').on('click', '#home_btn_my_location', function(){
if(!showMyLocation()){
app.directions.myOrigin = false;
app.directions.free = false;
app.directions.pause = false;
//Atualizando o menu do mapa quando a navegação for desativada
map_popup_menu.setContent(map_conf.popup_menu.getContent({nav:0}));
map_popup_menu.update();
}
});
$('body').on('click', '#user-navigation-pane-toggle, #home-user-menu-navigation', function(){
if($('#user-navigation-pane-toggle').children('span').hasClass('glyphicon-chevron-right')){
$("#user-navigation-container").animate( {'margin-left' : "0px"}, 400);
$('#user-navigation-pane-toggle').children('span').removeClass('glyphicon-chevron-right');
$('#user-navigation-pane-toggle').children('span').addClass('glyphicon-chevron-left');
}else{
$("#user-navigation-container").animate( {'margin-left' : "-1000px"}, 400);
$('#user-navigation-pane-toggle').children('span').removeClass('glyphicon-chevron-left');
$('#user-navigation-pane-toggle').children('span').addClass('glyphicon-chevron-right');
}
//Tradução das instruções do plugin directions
for(i=0; i<$('#instructions').find('div.mapbox-directions-step-maneuver').length;++i){
$('#instructions').find('div.mapbox-directions-step-maneuver')[i].innerHTML = app.directions.t($('#instructions').find('div.mapbox-directions-step-maneuver')[i].innerHTML);
}
$('#instructions ol.mapbox-directions-steps').before('<a class="translater-control hide"></a>');
});
// Botão do painel de navegação que dispara a query de roteamento para o plugin directions
//$('body').on('click', '#directions-query-btn', function(){
//if(directions.queryable())
// directions.query();
//});
$('body').on('click', '#routes li.mapbox-directions-route', function(){
//Tradução das instruções do plugin directions
for(i=0; i<$('#instructions').find('div.mapbox-directions-step-maneuver').length;++i){
$('#instructions').find('div.mapbox-directions-step-maneuver')[i].innerHTML = app.directions.t($('#instructions').find('div.mapbox-directions-step-maneuver')[i].innerHTML);
}
$('#instructions ol.mapbox-directions-steps').before('<a class="translater-control hide"></a>');
});
$('body').on('mousemove', '#user-navigation-container', function(){
//Tradução das instruções do plugin directions
if(!$('#instructions').children().first().hasClass('translater-control')){
$('#instructions ol.mapbox-directions-steps').before('<a class="translater-control hide"></a>');
if($('#instructions').find('div.mapbox-directions-step-maneuver').length>0){
for(i=0; i<$('#instructions').find('div.mapbox-directions-step-maneuver').length;++i){
$('#instructions').find('div.mapbox-directions-step-maneuver')[i].innerHTML = app.directions.t($('#instructions').find('div.mapbox-directions-step-maneuver')[i].innerHTML);
}
$('#instructions').children().first().remove();
}
}
});
$('body').on('touchmove', '#user-navigation-container', function(){
//Tradução das instruções do plugin directions
if(!$('#instructions').children().first().hasClass('translater-control')){
$('#instructions ol.mapbox-directions-steps').before('<a class="translater-control hide"></a>');
if($('#instructions').find('div.mapbox-directions-step-maneuver').length>0){
for(i=0; i<$('#instructions').find('div.mapbox-directions-step-maneuver').length;++i){
$('#instructions').find('div.mapbox-directions-step-maneuver')[i].innerHTML = app.directions.t($('#instructions').find('div.mapbox-directions-step-maneuver')[i].innerHTML);
}
$('#instructions').children().first().remove();
}
}
});
// Clique dos botões do Modal de Confirmação
$('body').on('click', '#no-confirm, #yes-confirm', function(){
app.user_confirmation = parseInt($(this).val());
// Executa ou não a requisição após a confirmação
if(app.user_confirmation){
if(app.request.ajax!=null){
$.ajax(app.request.ajax);
}
if(app.yconfirmation.action!=null){
if(typeof(app.yconfirmation.action)==='function'){
app.yconfirmation.action();
}
}
}else{
if(app.nconfirmation.action!=null){
if(typeof(app.nconfirmation.action)==='function'){
app.nconfirmation.action();
}
}
}
});
// Clique dos botões do Modal de Compartilhamento
$('body').on('click', '#no-confirm-sharing, #yes-confirm-sharing', function(){
app.user_confirmation = parseInt($(this).val());
sharing_modal = $('#home_user_sharings_modal');
if(app.user_confirmation){
//Configurando a requisição de compartilhamento
app.user.sharings.form = $('#user-sharings-form');
app.user.sharings.form[0].elements[1].value = app.user.id;//id do usuério
app.user.sharings.form[0].elements[2].value = app.user.sharings.selectedTypeId; // tipo do compartilhamento
app.user.sharings.form[0].elements[3].value = null; // id do conteúdo compartilhado, rota inda não criada
app.user.sharings.form[0].elements[4].value = app.user.sharings.form.find('.feeding-text').val(); // text do compartilhamento
app.user.sharings.form[0].elements[5].value = JSON.stringify(app.directions.origin.geometry), //geoJSON da origem
app.user.sharings.form[0].elements[6].value = JSON.stringify(app.directions.destination.geometry), //geoJSON do destino
app.user.sharings.form[0].elements[7].value = JSON.stringify(me.layers.route.toGeoJSON().geometry), //geoJSON da LineString da rota
app.user.sharings.form[0].elements[8].value = app.directions.elapsed_time, //tempo gasto em rota pelo usuário, calculado pelo js
app.user.sharings.form[0].elements[9].value = app.directions.origin.properties.name, //endereço textual da origem (rua)
app.user.sharings.form[0].elements[10].value = app.directions.destination.properties.name, //endereço textual do destino (rua)
$.ajax({
type: 'POST',
url: 'user-sharings/create',
//data: { id_sharing_type: id },
data: app.user.sharings.form.serialize(),
success: function(response){
sharing_modal.find('.modal-body').html(response);
$('#home_user_sharings_modal').find('.modal-footer .toBeclosed').hide();
$('#home_user_sharings_modal').find('#confirm-sharing-close').show();
}
});
}else{
;;
}
}); | gpl-3.0 |
striezel/simple-chess | competing-evaluators/CompetitionData.cpp | 8590 | /*
-------------------------------------------------------------------------------
This file is part of simple-chess.
Copyright (C) 2020, 2021 Dirk Stolle
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 "CompetitionData.hpp"
#include <atomic>
#include <iostream>
#include <mutex>
#include <thread>
#include "../libsimple-chess/data/ForsythEdwardsNotation.hpp"
#include "../libsimple-chess/evaluation/CompoundCreator.hpp"
#include "../libsimple-chess/search/Search.hpp"
#include "competing.hpp"
namespace simplechess
{
CompetitionData::CompetitionData(const std::vector<std::string>& allowedEvaluators)
: stopRequested(false),
isCompeting(false),
evaluators(createEvaluators(allowedEvaluators)),
wins(),
defeats(),
draws()
{
}
std::vector<std::unique_ptr<Evaluator>> CompetitionData::createEvaluators(const std::vector<std::string>& allowedEvaluators)
{
const unsigned int distinctCount = allowedEvaluators.size();
const unsigned int totalCombinations = 1 << allowedEvaluators.size();
std::vector<std::unique_ptr<Evaluator>> result;
result.reserve(totalCombinations - 1);
for (unsigned int i = 1; i < totalCombinations; ++i)
{
std::string evals;
for (unsigned int j = 0; j < distinctCount; ++j)
{
if ((i & (1 << j)) != 0)
{
evals += "," + allowedEvaluators[j];
}
} // for j
evals = evals.substr(1);
auto ce_ptr = std::unique_ptr<Evaluator>(new CompoundEvaluator());
if (!CompoundCreator::create(evals, static_cast<CompoundEvaluator&>(*ce_ptr)))
{
return {};
}
result.push_back(std::move(ce_ptr));
} // for i
return result;
}
void CompetitionData::sanitizeThreadCount(unsigned int& threads)
{
if (threads == 0)
threads = 1;
const unsigned int hw_threads = std::thread::hardware_concurrency();
if ((hw_threads != 0) && (threads > hw_threads))
{
threads = hw_threads;
std::cout << "Info: Hardware indicates that it only supports " << hw_threads
<< " concurrent threads. Number of threads has been reduced to "
<< hw_threads << "." << std::endl;
}
}
void CompetitionData::show() const
{
std::cout << "Win counts:" << std::endl;
for (const auto& elem : wins)
{
std::cout << "Evaluator #" << elem.first << " (" + evaluators[elem.first]->name() + "): " << elem.second << std::endl;
}
std::cout << "Defeat counts:" << std::endl;
for (const auto& elem : defeats)
{
std::cout << "Evaluator #" << elem.first << " (" + evaluators[elem.first]->name() + "): " << elem.second << std::endl;
}
std::cout << "Draw counts:" << std::endl;
for (const auto& elem : draws)
{
std::cout << "Evaluator #" << elem.first << " (" + evaluators[elem.first]->name() + "): " << elem.second << std::endl;
}
}
void CompetitionData::single_threaded_compete()
{
const unsigned int totalEvaluators = evaluators.size();
const unsigned int comboCount = totalEvaluators * (totalEvaluators - 1);
std::cout << "Info: There are " << totalEvaluators << " different evaluators."
<< std::endl << "This means there will be " << comboCount
<< " different evaluator matches." << std::endl;
wins.clear();
defeats.clear();
draws.clear();
unsigned int finished = 0;
for (unsigned int idxWhite = 0; idxWhite < totalEvaluators; ++idxWhite)
{
for (unsigned int idxBlack = 0; idxBlack < totalEvaluators; ++idxBlack)
{
if (stopRequested)
{
return;
}
if (idxWhite == idxBlack)
continue;
const Result r = Competition::compete(*evaluators[idxWhite], *evaluators[idxBlack]);
switch (r)
{
case Result::WhiteWins:
++wins[idxWhite];
++defeats[idxBlack];
break;
case Result::BlackWins:
++wins[idxBlack];
++defeats[idxWhite];
break;
case Result::Draw:
++draws[idxWhite];
++draws[idxBlack];
break;
case Result::Unknown:
// do nothing
break;
} // switch
++finished;
std::cout << "Progress: " << finished << " of " << comboCount << std::endl;
} // for idxBlack
} // for idxWhite
}
void CompetitionData::multi_threaded_compete(unsigned int threads)
{
const unsigned int totalEvaluators = evaluators.size();
const unsigned int comboCount = totalEvaluators * (totalEvaluators - 1);
std::cout << "Info: There are " << totalEvaluators << " different evaluators."
<< std::endl << "This means there will be " << comboCount
<< " different evaluator matches." << std::endl;
wins.clear();
defeats.clear();
draws.clear();
std::atomic<unsigned int> finished(0);
std::mutex mutuallyExclusive;
if (threads > totalEvaluators)
{
threads = totalEvaluators;
}
const auto perThread = totalEvaluators / threads;
for (unsigned int idxWhite = 0; idxWhite < totalEvaluators; ++idxWhite)
{
if (stopRequested)
{
return;
}
const auto lambda = [&] (const unsigned int startIdx, const unsigned int endIdx)
{
for (unsigned int idxBlack = startIdx; idxBlack < endIdx; ++idxBlack)
{
if (stopRequested)
{
std::clog << "Exiting thread due to stop request." << std::endl;
return;
}
if (idxWhite == idxBlack)
continue;
const Result r = Competition::compete(*evaluators[idxWhite], *evaluators[idxBlack]);
{
std::lock_guard<std::mutex> guard(mutuallyExclusive);
switch (r)
{
case Result::WhiteWins:
++wins[idxWhite];
++defeats[idxBlack];
break;
case Result::BlackWins:
++wins[idxBlack];
++defeats[idxWhite];
break;
case Result::Draw:
++draws[idxWhite];
++draws[idxBlack];
break;
case Result::Unknown:
// do nothing
break;
} // switch
++finished;
std::cout << "Progress: " << finished << " of " << comboCount << std::endl;
} // scope for lock guard
} // for idxBlack
};
// create threads
std::vector<std::thread> actualThreads;
for (unsigned int i = 0; i < threads - 1; ++i)
{
actualThreads.push_back(std::thread(lambda, i * perThread, (i+1) * perThread));
}
// Last thread does a bit more, if number of threads is not a factor of totalEvaluators.
actualThreads.push_back(std::thread(lambda, (threads-1) * perThread, totalEvaluators));
// Join all threads.
for (auto& t : actualThreads)
{
t.join();
}
} // for idxWhite
}
bool CompetitionData::compete(unsigned int threads)
{
if (evaluators.empty())
{
std::cerr << "No evaluators given!" << std::endl;
return false;
}
if (evaluators.size() > 1024)
{
std::cerr << "Error: There are more than 1024 evaluators, this will take an absurd amount of time!" << std::endl;
return false;
}
isCompeting = true;
sanitizeThreadCount(threads);
if (threads == 1)
{
std::cout << "Starting single-threaded run." << std::endl;
single_threaded_compete();
}
else
{
std::cout << "Starting multi-threaded run with " << threads << " threads." << std::endl;
multi_threaded_compete(threads);
}
isCompeting = false;
return true;
}
void CompetitionData::requestStop()
{
stopRequested = true;
}
void CompetitionData::waitForStop()
{
if (!stopRequested || !isCompeting)
return;
unsigned int waits = 0;
// Note: This does not quite work as expected (yet).
while (isCompeting && waits < 60)
{
std::this_thread::yield();
std::this_thread::sleep_for(std::chrono::milliseconds(250));
++waits;
}
}
} // namespace
| gpl-3.0 |
AnthoDevMoP/Mop-5.1.0-Core | WorldServer/Game/Packets/PacketHandler/MiscHandler.cs | 8521 | /*
* Copyright (C) 2012-2013 Arctium <http://arctium.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/>.
*/
using System;
using System.Linq;
using Framework.Constants;
using Framework.Logging;
using Framework.Network.Packets;
using WorldServer.Game.ObjectDefines;
using WorldServer.Network;
using Framework.Database;
using Framework.ObjectDefines;
namespace WorldServer.Game.Packets.PacketHandler
{
public class MiscHandler : Globals
{
public static void HandleMessageOfTheDay(ref WorldClass session)
{
PacketWriter motd = new PacketWriter(LegacyMessage.MessageOfTheDay);
motd.WriteUInt32(3);
motd.WriteCString("Arctium MoP test");
motd.WriteCString("Welcome to our MoP server test.");
motd.WriteCString("Your development team =)");
session.Send(ref motd);
}
[Opcode(ClientMessage.Ping, "16357")]
public static void HandlePong(ref PacketReader packet, ref WorldClass session)
{
uint sequence = packet.ReadUInt32();
uint latency = packet.ReadUInt32();
PacketWriter pong = new PacketWriter(JAMCCMessage.Pong);
pong.WriteUInt32(sequence);
session.Send(ref pong);
}
[Opcode(ClientMessage.LogDisconnect, "16357")]
public static void HandleDisconnectReason(ref PacketReader packet, ref WorldClass session)
{
var pChar = session.Character;
uint disconnectReason = packet.ReadUInt32();
if (pChar != null)
WorldMgr.DeleteSession(pChar.Guid);
DB.Realms.Execute("UPDATE accounts SET online = 0 WHERE id = ?", session.Account.Id);
Log.Message(LogType.DEBUG, "Account with Id {0} disconnected. Reason: {1}", session.Account.Id, disconnectReason);
}
public static void HandleUpdateClientCacheVersion(ref WorldClass session)
{
PacketWriter cacheVersion = new PacketWriter(LegacyMessage.UpdateClientCacheVersion);
cacheVersion.WriteUInt32(0);
session.Send(ref cacheVersion);
}
[Opcode(ClientMessage.LoadingScreenNotify, "16357")]
public static void HandleLoadingScreenNotify(ref PacketReader packet, ref WorldClass session)
{
BitUnpack BitUnpack = new BitUnpack(packet);
uint mapId = packet.ReadUInt32();
bool loadingScreenState = BitUnpack.GetBit();
Log.Message(LogType.DEBUG, "Loading screen for map '{0}' is {1}.", mapId, loadingScreenState ? "enabled" : "disabled");
}
[Opcode(ClientMessage.ViolenceLevel, "16357")]
public static void HandleViolenceLevel(ref PacketReader packet, ref WorldClass session)
{
byte violenceLevel = packet.ReadUInt8();
Log.Message(LogType.DEBUG, "Violence level from account '{0} (Id: {1})' is {2}.", session.Account.Name, session.Account.Id, (ViolenceLevel)violenceLevel);
}
[Opcode(ClientMessage.ActivePlayer, "16357")]
public static void HandleActivePlayer(ref PacketReader packet, ref WorldClass session)
{
byte active = packet.ReadUInt8(); // Always 0
Log.Message(LogType.DEBUG, "Player {0} (Guid: {1}) is active.", session.Character.Name, session.Character.Guid);
}
[Opcode(ClientMessage.ZoneUpdate, "16357")]
public static void HandleZoneUpdate(ref PacketReader packet, ref WorldClass session)
{
var pChar = session.Character;
uint zone = packet.ReadUInt32();
ObjectMgr.SetZone(ref pChar, zone);
}
[Opcode(ClientMessage.SetSelection, "16357")]
public static void HandleSetSelection(ref PacketReader packet, ref WorldClass session)
{
byte[] guidMask = { 3, 1, 7, 2, 6, 4, 0, 5 };
byte[] guidBytes = { 4, 1, 5, 2, 6, 7, 0, 3 };
BitUnpack GuidUnpacker = new BitUnpack(packet);
ulong fullGuid = GuidUnpacker.GetGuid(guidMask, guidBytes);
ulong guid = ObjectGuid.GetGuid(fullGuid);
if (session.Character != null)
{
var sess = WorldMgr.GetSession(session.Character.Guid);
if (sess != null)
sess.Character.TargetGuid = fullGuid;
if (guid == 0)
Log.Message(LogType.DEBUG, "Character (Guid: {0}) removed current selection.", session.Character.Guid);
else
Log.Message(LogType.DEBUG, "Character (Guid: {0}) selected a {1} (Guid: {2}, Id: {3}).", session.Character.Guid, ObjectGuid.GetGuidType(fullGuid), guid, ObjectGuid.GetId(fullGuid));
}
}
[Opcode(ClientMessage.SetActionButton, "16357")]
public static void HandleSetActionButton(ref PacketReader packet, ref WorldClass session)
{
var pChar = session.Character;
byte[] actionMask = { 4, 0, 3, 7, 1, 6, 2, 5 };
byte[] actionBytes = { 3, 0, 1, 4, 7, 2, 6, 5 };
var slotId = packet.ReadByte();
BitUnpack actionUnpacker = new BitUnpack(packet);
var actionId = actionUnpacker.GetValue(actionMask, actionBytes);
if (actionId == 0)
{
var action = pChar.ActionButtons.Where(button => button.SlotId == slotId && button.SpecGroup == pChar.ActiveSpecGroup).Select(button => button).First();
ActionMgr.RemoveActionButton(pChar, action, true);
Log.Message(LogType.DEBUG, "Character (Guid: {0}) removed action button {1} from slot {2}.", pChar.Guid, actionId, slotId);
return;
}
var newAction = new ActionButton
{
Action = actionId,
SlotId = slotId,
SpecGroup = pChar.ActiveSpecGroup
};
ActionMgr.AddActionButton(pChar, newAction, true);
Log.Message(LogType.DEBUG, "Character (Guid: {0}) added action button {1} to slot {2}.", pChar.Guid, actionId, slotId);
}
public static void HandleUpdateActionButtons(ref WorldClass session)
{
var pChar = session.Character;
PacketWriter updateActionButtons = new PacketWriter(JAMCMessage.UpdateActionButtons);
BitPack BitPack = new BitPack(updateActionButtons);
const int buttonCount = 132;
var buttons = new byte[buttonCount][];
byte[] buttonMask = { 4, 0, 7, 2, 6, 3, 1, 5 };
byte[] buttonBytes = { 0, 3, 5, 7, 6, 1, 4, 2 };
var actions = ActionMgr.GetActionButtons(pChar, pChar.ActiveSpecGroup);
for (int i = 0; i < buttonCount; i++)
if (actions.Any(action => action.SlotId == i))
buttons[i] = BitConverter.GetBytes((ulong)actions.Where(action => action.SlotId == i).Select(action => action.Action).First());
else
buttons[i] = new byte[8];
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < buttonCount; j++)
{
if (i < 8)
BitPack.Write(buttons[j][buttonMask[i]]);
else if (i < 16)
{
if (buttons[j][buttonBytes[i - 8]] != 0)
updateActionButtons.WriteUInt8((byte)(buttons[j][buttonBytes[i - 8]] ^ 1));
}
}
}
// Packet Type (NYI)
// 0 - Initial packet on Login (no verification) / 1 - Verify spells on switch (Spec change) / 2 - Clear Action Buttons (Spec change)
updateActionButtons.WriteInt8(0);
session.Send(ref updateActionButtons);
}
}
}
| gpl-3.0 |
ecastro/moodle23ulpgc | mod/tab/view.php | 7960 | <?php // $Id: view.php,v 1.4 2006/08/28 16:41:20 mark-nielsen Exp $
/**
* TAB
*
* @author : Patrick Thibaudeau
* @version $Id: version.php,v 1.0 2007/07/01 16:41:20
* @package tab
**/
require("../../config.php");
require_once("lib.php");
require_once("locallib.php");
require_once($CFG->dirroot . '/lib/resourcelib.php');
require_once($CFG->dirroot . '/lib/completionlib.php');
$id = optional_param('id', 0, PARAM_INT); // Course Module ID, or
$a = optional_param('a', 0, PARAM_INT); // tab ID
if ($id) {
if (!$cm = get_coursemodule_from_id("tab", $id)) {
error("Course Module ID was incorrect");
}
if (!$tab = $DB->get_record("tab", array("id" => $cm->instance))) {
error("Course module is incorrect");
}
} else {
if (!$tab = $DB->get_record("tab", array("id" => $a))) {
error("Course module is incorrect");
}
if (!$cm = get_coursemodule_from_instance("tab", $tab->id, $course->id)) {
error("Course Module ID was incorrect");
}
}
$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
require_course_login($course, true, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('mod/tab:view', $context);
add_to_log($course->id, "tab", "view", "view.php?id=$cm->id", "$tab->id");
// Update 'viewed' state if required by completion system
$completion = new completion_info($course);
$completion->set_module_viewed($cm);
/// Print the page header
$PAGE->set_url('/mod/tab/view.php', array('id' => $cm->id));
$PAGE->set_title($tab->name);
$PAGE->set_heading(format_string($course->fullname));
$PAGE->set_activity_record($tab);
if ($PAGE->user_allowed_editing()) {
$buttons = '<table><tr><td><form method="get" action="' . $CFG->wwwroot . '/course/mod.php"><div>' .
'<input type="hidden" name="update" value="' . $cm->id . '" />' .
'<input type="submit" value="' . get_string('updatethis', 'tab') . '" /></div></form></td></tr></table>';
$PAGE->set_button($buttons);
}
//Gather javascripts and css
$PAGE->requires->js('/mod/tab/js/SpryTabbedPanels.js', true);
$PAGE->requires->js('/mod/tab/js/tab.js');
$PAGE->requires->css('/mod/tab/SpryTabbedPanels.css');
$PAGE->requires->css('/mod/tab/styles.css');
echo $OUTPUT->header();
//echo $OUTPUT->heading(format_string($tab->name), 2, 'main', 'pageheading');
$strtabs = get_string("modulenameplural", "tab");
$strtab = get_string("modulename", "tab");
//gather all Tab modules within the course. Needed if display tab menu is selected
//$results = get_coursemodules_in_course('tab', $course->id);
//Must get more information in order to display menu options properly.
//Therefore I cannot use get_coursemodules_in_course
$results = $DB->get_records_sql('SELECT {course_modules}.id as id,{course_modules}.visible as visible, {tab}.name as name, {tab}.taborder as taborder,
{tab}.menuname as menuname FROM ({modules} INNER JOIN {course_modules} ON {modules}.id = {course_modules}.module)
INNER JOIN {tab} ON {course_modules}.instance = {tab}.id WHERE ((({modules}.name)=\'tab\') AND (({course_modules}.course)=' . $course->id . '))
ORDER BY taborder;');
$tabdisplay = '';
if ($tab->displaymenu == 1) {
$tabdisplay .= "<style>
#tabcontent {
margin-left: 17%;
padding: 0 10px;
}</style>";
$tabdisplay .= '<div id="tab-menu-wrapper">' . "\n";
$tabdisplay .= ' <ul class="menutable" width="100%" border="0" cellpadding="4">' . "\n";
$tabdisplay .= ' <li class="menutitle">' . $tab->menuname . '</li>' . "\n";
$i = 0; ///needed to determine color change on cell
foreach ($results as $result) { /// foreach
//only print the tabs that have the same menu name
if ($result->menuname == $tab->menuname) {
//only print visible tabs within the menu
if ($result->visible == 1 || has_capability('moodle/course:update', $coursecontext)) {
$tabdisplay .= ' <li';
if ($tab->name == $result->name) { //old code for different color = if ($i % 2) {
$tabdisplay .= ' class="row">';
} else {
$tabdisplay .= '>';
}
$tabdisplay .= '<a href="view.php?id=' . $result->id . '" >' . $result->name . '</a>';
}
}
$tabdisplay .= '</li>' . "\n";
$i++;
}
$tabdisplay .= '</ul>' . "\n";
$tabdisplay .= '</div>' . "\n";
}
//print tab content here
$tabdisplay .= '<div id="tabcontent">' . "\n";
$tabdisplay .= '<div id="TabbedPanels1" class="TabbedPanels">' . "\n";
$tabdisplay .= ' <ul class="TabbedPanelsTabGroup">' . "\n";
//-------------------------------Get tabs-----------------------------------------------
$options = $DB->get_records('tab_content', array('tabid' => $tab->id), 'tabcontentorder');
$options = array_values($options);
$i = 0;
foreach (array_keys($options) as $key) {
$tabdisplay .= ' <li class="TabbedPanelsTab" tabindex="0">' . $options[$key]->tabname . '</li>';
}
$tabdisplay .= ' </ul>' . "\n";
$tabdisplay .= ' <div class="TabbedPanelsContentGroup">' . "\n";
$editoroptions = array('subdirs' => 1, 'maxbytes' => $CFG->maxbytes, 'maxfiles' => -1, 'changeformat' => 1, 'context' => $context, 'noclean' => 1, 'trusttext' => true);
//Add content
foreach (array_keys($options) as $key) {
//New conditions now exist. Must verify if embedding a pdf or url
//Content must change accordingly
//$pdffile[$key] = $options[$key]->pdffile;
$externalurl[$key] = $options[$key]->externalurl;
//Eventually give option for height within the form. Pass this by others, because it could be confusing.
$iframehieght[$key] = '600px';
if (!empty($externalurl[$key])) {
//todo check url
if(!preg_match('{https?:\/\/}',$externalurl[$key])){
$externalurl[$key] = 'http://' . $externalurl[$key];
}
} else {
if (empty($options[$key]->format)) {
$options[$key]->format = 1;
}
$content[$key] = file_rewrite_pluginfile_urls($options[$key]->tabcontent, 'pluginfile.php', $context->id, 'mod_tab', 'content', $options[$key]->id);
$content[$key] = format_text($content[$key], $options[$key]->format, $editoroptions, $context);
}
//Enter into proper div
//Check for pdf
if (!empty($externalurl[$key]) && preg_match('/\bpdf\b/i', $externalurl[$key])) {
debugging("Tabdisplay: Found pdf->external_url=". $externalurl[$key], DEBUG_DEVELOPER);
$html_content = tab_embed_general(process_urls($externalurl[$key]), '', get_string('embed_fail_msg','tab'). "<a href='$externalurl[$key]' target='_blank' >". get_string('embed_fail_link_text', 'tab') . '</a>', 'application/pdf');
} elseif(!empty($externalurl[$key])) {
$html_content = tab_embed_general(process_urls($externalurl[$key]), '', get_string('embed_fail_msg','tab'). "<a href='$externalurl[$key]' target='_blank' >". get_string('embed_fail_link_text', 'tab') . '</a>', 'text/html');
}
else{
$html_content = $content[$key];
//Check for PDF only link
if (preg_match('/\bpdf\b/i', $html_content)) {
$html_content = tab_embed_general(process_urls($html_content), '', get_string('embed_fail_msg','tab'). "<a href='$html_content' target='_blank' >". get_string('embed_fail_link_text', 'tab') . '</a>', 'application/pdf');
}
}
$tabdisplay .= ' <div class="TabbedPanelsContent"><p>' . $html_content . '</p></div>' . "\n";
}
$tabdisplay .= ' </div>' . "\n";
$tabdisplay .= '</div>' . "\n";
$tabdisplay .= '</div>' . "\n";
echo $tabdisplay;
echo $OUTPUT->footer();
| gpl-3.0 |
mbochenko/XrmToolBox | Plugins/MsCrmTools.UserSettingsUtility/AppCode/QueryHelper.cs | 1587 | using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
namespace MsCrmTools.UserSettingsUtility.AppCode
{
internal class QueryHelper
{
public static EntityCollection GetItems(string fetchXml, IOrganizationService service)
{
// Check if businessunitid attribute is contained in attriburtes
var xDoc = XDocument.Parse(fetchXml);
AddMissingCrmAttribute(xDoc, "businessunitid");
var entityElement = xDoc.Descendants("entity").FirstOrDefault();
if (entityElement == null)
{
throw new Exception("Cannot find node 'entity' in FetchXml");
}
AddMissingCrmAttribute(xDoc, "firstname");
AddMissingCrmAttribute(xDoc, "lastname");
return service.RetrieveMultiple(new FetchExpression(xDoc.ToString()));
}
private static void AddMissingCrmAttribute(XDocument xDoc, string attributeName)
{
var xBuAttribute = xDoc.XPathSelectElement("fetch/entity/attribute[@name='" + attributeName + "']");
if (xBuAttribute == null)
{
var entityElement = xDoc.Descendants("entity").FirstOrDefault();
if (entityElement == null)
{
throw new Exception("Cannot find node 'entity' in FetchXml");
}
entityElement.Add(new XElement("attribute", new XAttribute("name", attributeName)));
}
}
}
} | gpl-3.0 |
YuanKQ/NFD_for_android | app/src/main/jni/cryptopp/gcm.cpp | 25607 | // gcm.cpp - written and placed in the public domain by Wei Dai
// use "cl /EP /P /DCRYPTOPP_GENERATE_X64_MASM gcm.cpp" to generate MASM code
#include "pch.h"
#include "config.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4189)
#endif
#ifndef CRYPTOPP_IMPORTS
#ifndef CRYPTOPP_GENERATE_X64_MASM
// Clang 3.3 integrated assembler crash on Linux
#if defined(CRYPTOPP_CLANG_VERSION) && (CRYPTOPP_CLANG_VERSION < 30400)
# undef CRYPTOPP_X86_ASM_AVAILABLE
# undef CRYPTOPP_X32_ASM_AVAILABLE
# undef CRYPTOPP_X64_ASM_AVAILABLE
# undef CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE
# undef CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE
# define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 0
# define CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE 0
#endif
#include "gcm.h"
#include "cpu.h"
NAMESPACE_BEGIN(CryptoPP)
word16 GCM_Base::s_reductionTable[256];
volatile bool GCM_Base::s_reductionTableInitialized = false;
void GCM_Base::GCTR::IncrementCounterBy256()
{
IncrementCounterByOne(m_counterArray+BlockSize()-4, 3);
}
#if 0
// preserved for testing
void gcm_gf_mult(const unsigned char *a, const unsigned char *b, unsigned char *c)
{
word64 Z0=0, Z1=0, V0, V1;
typedef BlockGetAndPut<word64, BigEndian> Block;
Block::Get(a)(V0)(V1);
for (int i=0; i<16; i++)
{
for (int j=0x80; j!=0; j>>=1)
{
int x = b[i] & j;
Z0 ^= x ? V0 : 0;
Z1 ^= x ? V1 : 0;
x = (int)V1 & 1;
V1 = (V1>>1) | (V0<<63);
V0 = (V0>>1) ^ (x ? W64LIT(0xe1) << 56 : 0);
}
}
Block::Put(NULL, c)(Z0)(Z1);
}
__m128i _mm_clmulepi64_si128(const __m128i &a, const __m128i &b, int i)
{
word64 A[1] = {ByteReverse(((word64*)&a)[i&1])};
word64 B[1] = {ByteReverse(((word64*)&b)[i>>4])};
PolynomialMod2 pa((byte *)A, 8);
PolynomialMod2 pb((byte *)B, 8);
PolynomialMod2 c = pa*pb;
__m128i output;
for (int i=0; i<16; i++)
((byte *)&output)[i] = c.GetByte(i);
return output;
}
#endif
#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE || CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE
inline static void SSE2_Xor16(byte *a, const byte *b, const byte *c)
{
#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE
*(__m128i *)a = _mm_xor_si128(*(__m128i *)b, *(__m128i *)c);
#else
asm ("movdqa %1, %%xmm0; pxor %2, %%xmm0; movdqa %%xmm0, %0;" : "=m" (a[0]) : "m"(b[0]), "m"(c[0]));
#endif
}
#endif
inline static void Xor16(byte *a, const byte *b, const byte *c)
{
((word64 *)a)[0] = ((word64 *)b)[0] ^ ((word64 *)c)[0];
((word64 *)a)[1] = ((word64 *)b)[1] ^ ((word64 *)c)[1];
}
#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE
static CRYPTOPP_ALIGN_DATA(16) const word64 s_clmulConstants64[] = {
W64LIT(0xe100000000000000), W64LIT(0xc200000000000000),
W64LIT(0x08090a0b0c0d0e0f), W64LIT(0x0001020304050607),
W64LIT(0x0001020304050607), W64LIT(0x08090a0b0c0d0e0f)};
static const __m128i *s_clmulConstants = (const __m128i *)s_clmulConstants64;
static const unsigned int s_clmulTableSizeInBlocks = 8;
inline __m128i CLMUL_Reduce(__m128i c0, __m128i c1, __m128i c2, const __m128i &r)
{
/*
The polynomial to be reduced is c0 * x^128 + c1 * x^64 + c2. c0t below refers to the most
significant half of c0 as a polynomial, which, due to GCM's bit reflection, are in the
rightmost bit positions, and the lowest byte addresses.
c1 ^= c0t * 0xc200000000000000
c2t ^= c0t
t = shift (c1t ^ c0b) left 1 bit
c2 ^= t * 0xe100000000000000
c2t ^= c1b
shift c2 left 1 bit and xor in lowest bit of c1t
*/
#if 0 // MSVC 2010 workaround: see http://connect.microsoft.com/VisualStudio/feedback/details/575301
c2 = _mm_xor_si128(c2, _mm_move_epi64(c0));
#else
c1 = _mm_xor_si128(c1, _mm_slli_si128(c0, 8));
#endif
c1 = _mm_xor_si128(c1, _mm_clmulepi64_si128(c0, r, 0x10));
c0 = _mm_srli_si128(c0, 8);
c0 = _mm_xor_si128(c0, c1);
c0 = _mm_slli_epi64(c0, 1);
c0 = _mm_clmulepi64_si128(c0, r, 0);
c2 = _mm_xor_si128(c2, c0);
c2 = _mm_xor_si128(c2, _mm_srli_si128(c1, 8));
c1 = _mm_unpacklo_epi64(c1, c2);
c1 = _mm_srli_epi64(c1, 63);
c2 = _mm_slli_epi64(c2, 1);
return _mm_xor_si128(c2, c1);
}
inline __m128i CLMUL_GF_Mul(const __m128i &x, const __m128i &h, const __m128i &r)
{
__m128i c0 = _mm_clmulepi64_si128(x,h,0);
__m128i c1 = _mm_xor_si128(_mm_clmulepi64_si128(x,h,1), _mm_clmulepi64_si128(x,h,0x10));
__m128i c2 = _mm_clmulepi64_si128(x,h,0x11);
return CLMUL_Reduce(c0, c1, c2, r);
}
#endif
void GCM_Base::SetKeyWithoutResync(const byte *userKey, size_t keylength, const NameValuePairs ¶ms)
{
BlockCipher &blockCipher = AccessBlockCipher();
blockCipher.SetKey(userKey, keylength, params);
if (blockCipher.BlockSize() != REQUIRED_BLOCKSIZE)
throw InvalidArgument(AlgorithmName() + ": block size of underlying block cipher is not 16");
int tableSize, i, j, k;
#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE
if (HasCLMUL())
{
// Avoid "parameter not used" error and suppress Coverity finding
(void)params.GetIntValue(Name::TableSize(), tableSize);
tableSize = s_clmulTableSizeInBlocks * REQUIRED_BLOCKSIZE;
}
else
#endif
{
if (params.GetIntValue(Name::TableSize(), tableSize))
tableSize = (tableSize >= 64*1024) ? 64*1024 : 2*1024;
else
tableSize = (GetTablesOption() == GCM_64K_Tables) ? 64*1024 : 2*1024;
#if defined(_MSC_VER) && (_MSC_VER >= 1300 && _MSC_VER < 1400)
// VC 2003 workaround: compiler generates bad code for 64K tables
tableSize = 2*1024;
#endif
}
m_buffer.resize(3*REQUIRED_BLOCKSIZE + tableSize);
byte *table = MulTable();
byte *hashKey = HashKey();
memset(hashKey, 0, REQUIRED_BLOCKSIZE);
blockCipher.ProcessBlock(hashKey);
#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE
if (HasCLMUL())
{
const __m128i r = s_clmulConstants[0];
__m128i h0 = _mm_shuffle_epi8(_mm_load_si128((__m128i *)hashKey), s_clmulConstants[1]);
__m128i h = h0;
for (i=0; i<tableSize; i+=32)
{
__m128i h1 = CLMUL_GF_Mul(h, h0, r);
_mm_storel_epi64((__m128i *)(table+i), h);
_mm_storeu_si128((__m128i *)(table+i+16), h1);
_mm_storeu_si128((__m128i *)(table+i+8), h);
_mm_storel_epi64((__m128i *)(table+i+8), h1);
h = CLMUL_GF_Mul(h1, h0, r);
}
return;
}
#endif
word64 V0, V1;
typedef BlockGetAndPut<word64, BigEndian> Block;
Block::Get(hashKey)(V0)(V1);
if (tableSize == 64*1024)
{
for (i=0; i<128; i++)
{
k = i%8;
Block::Put(NULL, table+(i/8)*256*16+(size_t(1)<<(11-k)))(V0)(V1);
int x = (int)V1 & 1;
V1 = (V1>>1) | (V0<<63);
V0 = (V0>>1) ^ (x ? W64LIT(0xe1) << 56 : 0);
}
for (i=0; i<16; i++)
{
memset(table+i*256*16, 0, 16);
#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE || CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE
if (HasSSE2())
for (j=2; j<=0x80; j*=2)
for (k=1; k<j; k++)
SSE2_Xor16(table+i*256*16+(j+k)*16, table+i*256*16+j*16, table+i*256*16+k*16);
else
#endif
for (j=2; j<=0x80; j*=2)
for (k=1; k<j; k++)
Xor16(table+i*256*16+(j+k)*16, table+i*256*16+j*16, table+i*256*16+k*16);
}
}
else
{
if (!s_reductionTableInitialized)
{
s_reductionTable[0] = 0;
word16 x = 0x01c2;
s_reductionTable[1] = ByteReverse(x);
for (unsigned int ii=2; ii<=0x80; ii*=2)
{
x <<= 1;
s_reductionTable[ii] = ByteReverse(x);
for (unsigned int jj=1; jj<ii; jj++)
s_reductionTable[ii+jj] = s_reductionTable[ii] ^ s_reductionTable[jj];
}
s_reductionTableInitialized = true;
}
for (i=0; i<128-24; i++)
{
k = i%32;
if (k < 4)
Block::Put(NULL, table+1024+(i/32)*256+(size_t(1)<<(7-k)))(V0)(V1);
else if (k < 8)
Block::Put(NULL, table+(i/32)*256+(size_t(1)<<(11-k)))(V0)(V1);
int x = (int)V1 & 1;
V1 = (V1>>1) | (V0<<63);
V0 = (V0>>1) ^ (x ? W64LIT(0xe1) << 56 : 0);
}
for (i=0; i<4; i++)
{
memset(table+i*256, 0, 16);
memset(table+1024+i*256, 0, 16);
#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE || CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE
if (HasSSE2())
for (j=2; j<=8; j*=2)
for (k=1; k<j; k++)
{
SSE2_Xor16(table+i*256+(j+k)*16, table+i*256+j*16, table+i*256+k*16);
SSE2_Xor16(table+1024+i*256+(j+k)*16, table+1024+i*256+j*16, table+1024+i*256+k*16);
}
else
#endif
for (j=2; j<=8; j*=2)
for (k=1; k<j; k++)
{
Xor16(table+i*256+(j+k)*16, table+i*256+j*16, table+i*256+k*16);
Xor16(table+1024+i*256+(j+k)*16, table+1024+i*256+j*16, table+1024+i*256+k*16);
}
}
}
}
inline void GCM_Base::ReverseHashBufferIfNeeded()
{
#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE
if (HasCLMUL())
{
__m128i &x = *(__m128i *)HashBuffer();
x = _mm_shuffle_epi8(x, s_clmulConstants[1]);
}
#endif
}
void GCM_Base::Resync(const byte *iv, size_t len)
{
BlockCipher &cipher = AccessBlockCipher();
byte *hashBuffer = HashBuffer();
if (len == 12)
{
memcpy(hashBuffer, iv, len);
memset(hashBuffer+len, 0, 3);
hashBuffer[len+3] = 1;
}
else
{
size_t origLen = len;
memset(hashBuffer, 0, HASH_BLOCKSIZE);
if (len >= HASH_BLOCKSIZE)
{
len = GCM_Base::AuthenticateBlocks(iv, len);
iv += (origLen - len);
}
if (len > 0)
{
memcpy(m_buffer, iv, len);
memset(m_buffer+len, 0, HASH_BLOCKSIZE-len);
GCM_Base::AuthenticateBlocks(m_buffer, HASH_BLOCKSIZE);
}
PutBlock<word64, BigEndian, true>(NULL, m_buffer)(0)(origLen*8);
GCM_Base::AuthenticateBlocks(m_buffer, HASH_BLOCKSIZE);
ReverseHashBufferIfNeeded();
}
if (m_state >= State_IVSet)
m_ctr.Resynchronize(hashBuffer, REQUIRED_BLOCKSIZE);
else
m_ctr.SetCipherWithIV(cipher, hashBuffer);
m_ctr.Seek(HASH_BLOCKSIZE);
memset(hashBuffer, 0, HASH_BLOCKSIZE);
}
unsigned int GCM_Base::OptimalDataAlignment() const
{
return
#if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)
HasSSE2() ? 16 :
#endif
GetBlockCipher().OptimalDataAlignment();
}
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4731) // frame pointer register 'ebp' modified by inline assembly code
#endif
#endif // #ifndef CRYPTOPP_GENERATE_X64_MASM
#ifdef CRYPTOPP_X64_MASM_AVAILABLE
extern "C" {
void GCM_AuthenticateBlocks_2K(const byte *data, size_t blocks, word64 *hashBuffer, const word16 *reductionTable);
void GCM_AuthenticateBlocks_64K(const byte *data, size_t blocks, word64 *hashBuffer);
}
#endif
#ifndef CRYPTOPP_GENERATE_X64_MASM
size_t GCM_Base::AuthenticateBlocks(const byte *data, size_t len)
{
#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE
if (HasCLMUL())
{
const __m128i *table = (const __m128i *)MulTable();
__m128i x = _mm_load_si128((__m128i *)HashBuffer());
const __m128i r = s_clmulConstants[0], bswapMask = s_clmulConstants[1], bswapMask2 = s_clmulConstants[2];
while (len >= 16)
{
size_t s = UnsignedMin(len/16, s_clmulTableSizeInBlocks), i=0;
__m128i d, d2 = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i *)(data+(s-1)*16)), bswapMask2);;
__m128i c0 = _mm_setzero_si128();
__m128i c1 = _mm_setzero_si128();
__m128i c2 = _mm_setzero_si128();
while (true)
{
__m128i h0 = _mm_load_si128(table+i);
__m128i h1 = _mm_load_si128(table+i+1);
__m128i h01 = _mm_xor_si128(h0, h1);
if (++i == s)
{
d = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i *)data), bswapMask);
d = _mm_xor_si128(d, x);
c0 = _mm_xor_si128(c0, _mm_clmulepi64_si128(d, h0, 0));
c2 = _mm_xor_si128(c2, _mm_clmulepi64_si128(d, h1, 1));
d = _mm_xor_si128(d, _mm_shuffle_epi32(d, _MM_SHUFFLE(1, 0, 3, 2)));
c1 = _mm_xor_si128(c1, _mm_clmulepi64_si128(d, h01, 0));
break;
}
d = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i *)(data+(s-i)*16-8)), bswapMask2);
c0 = _mm_xor_si128(c0, _mm_clmulepi64_si128(d2, h0, 1));
c2 = _mm_xor_si128(c2, _mm_clmulepi64_si128(d, h1, 1));
d2 = _mm_xor_si128(d2, d);
c1 = _mm_xor_si128(c1, _mm_clmulepi64_si128(d2, h01, 1));
if (++i == s)
{
d = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i *)data), bswapMask);
d = _mm_xor_si128(d, x);
c0 = _mm_xor_si128(c0, _mm_clmulepi64_si128(d, h0, 0x10));
c2 = _mm_xor_si128(c2, _mm_clmulepi64_si128(d, h1, 0x11));
d = _mm_xor_si128(d, _mm_shuffle_epi32(d, _MM_SHUFFLE(1, 0, 3, 2)));
c1 = _mm_xor_si128(c1, _mm_clmulepi64_si128(d, h01, 0x10));
break;
}
d2 = _mm_shuffle_epi8(_mm_loadu_si128((const __m128i *)(data+(s-i)*16-8)), bswapMask);
c0 = _mm_xor_si128(c0, _mm_clmulepi64_si128(d, h0, 0x10));
c2 = _mm_xor_si128(c2, _mm_clmulepi64_si128(d2, h1, 0x10));
d = _mm_xor_si128(d, d2);
c1 = _mm_xor_si128(c1, _mm_clmulepi64_si128(d, h01, 0x10));
}
data += s*16;
len -= s*16;
c1 = _mm_xor_si128(_mm_xor_si128(c1, c0), c2);
x = CLMUL_Reduce(c0, c1, c2, r);
}
_mm_store_si128((__m128i *)HashBuffer(), x);
return len;
}
#endif
typedef BlockGetAndPut<word64, NativeByteOrder> Block;
word64 *hashBuffer = (word64 *)HashBuffer();
switch (2*(m_buffer.size()>=64*1024)
#if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)
+ HasSSE2()
#endif
)
{
case 0: // non-SSE2 and 2K tables
{
byte *table = MulTable();
word64 x0 = hashBuffer[0], x1 = hashBuffer[1];
do
{
word64 y0, y1, a0, a1, b0, b1, c0, c1, d0, d1;
Block::Get(data)(y0)(y1);
x0 ^= y0;
x1 ^= y1;
data += HASH_BLOCKSIZE;
len -= HASH_BLOCKSIZE;
#define READ_TABLE_WORD64_COMMON(a, b, c, d) *(word64 *)(table+(a*1024)+(b*256)+c+d*8)
#ifdef IS_LITTLE_ENDIAN
#if CRYPTOPP_BOOL_SLOW_WORD64
word32 z0 = (word32)x0;
word32 z1 = (word32)(x0>>32);
word32 z2 = (word32)x1;
word32 z3 = (word32)(x1>>32);
#define READ_TABLE_WORD64(a, b, c, d, e) READ_TABLE_WORD64_COMMON((d%2), c, (d?(z##c>>((d?d-1:0)*4))&0xf0:(z##c&0xf)<<4), e)
#else
#define READ_TABLE_WORD64(a, b, c, d, e) READ_TABLE_WORD64_COMMON((d%2), c, ((d+8*b)?(x##a>>(((d+8*b)?(d+8*b)-1:1)*4))&0xf0:(x##a&0xf)<<4), e)
#endif
#define GF_MOST_SIG_8BITS(a) (a##1 >> 7*8)
#define GF_SHIFT_8(a) a##1 = (a##1 << 8) ^ (a##0 >> 7*8); a##0 <<= 8;
#else
#define READ_TABLE_WORD64(a, b, c, d, e) READ_TABLE_WORD64_COMMON((1-d%2), c, ((15-d-8*b)?(x##a>>(((15-d-8*b)?(15-d-8*b)-1:0)*4))&0xf0:(x##a&0xf)<<4), e)
#define GF_MOST_SIG_8BITS(a) (a##1 & 0xff)
#define GF_SHIFT_8(a) a##1 = (a##1 >> 8) ^ (a##0 << 7*8); a##0 >>= 8;
#endif
#define GF_MUL_32BY128(op, a, b, c) \
a0 op READ_TABLE_WORD64(a, b, c, 0, 0) ^ READ_TABLE_WORD64(a, b, c, 1, 0);\
a1 op READ_TABLE_WORD64(a, b, c, 0, 1) ^ READ_TABLE_WORD64(a, b, c, 1, 1);\
b0 op READ_TABLE_WORD64(a, b, c, 2, 0) ^ READ_TABLE_WORD64(a, b, c, 3, 0);\
b1 op READ_TABLE_WORD64(a, b, c, 2, 1) ^ READ_TABLE_WORD64(a, b, c, 3, 1);\
c0 op READ_TABLE_WORD64(a, b, c, 4, 0) ^ READ_TABLE_WORD64(a, b, c, 5, 0);\
c1 op READ_TABLE_WORD64(a, b, c, 4, 1) ^ READ_TABLE_WORD64(a, b, c, 5, 1);\
d0 op READ_TABLE_WORD64(a, b, c, 6, 0) ^ READ_TABLE_WORD64(a, b, c, 7, 0);\
d1 op READ_TABLE_WORD64(a, b, c, 6, 1) ^ READ_TABLE_WORD64(a, b, c, 7, 1);\
GF_MUL_32BY128(=, 0, 0, 0)
GF_MUL_32BY128(^=, 0, 1, 1)
GF_MUL_32BY128(^=, 1, 0, 2)
GF_MUL_32BY128(^=, 1, 1, 3)
word32 r = (word32)s_reductionTable[GF_MOST_SIG_8BITS(d)] << 16;
GF_SHIFT_8(d)
c0 ^= d0; c1 ^= d1;
r ^= (word32)s_reductionTable[GF_MOST_SIG_8BITS(c)] << 8;
GF_SHIFT_8(c)
b0 ^= c0; b1 ^= c1;
r ^= s_reductionTable[GF_MOST_SIG_8BITS(b)];
GF_SHIFT_8(b)
a0 ^= b0; a1 ^= b1;
a0 ^= ConditionalByteReverse<word64>(LITTLE_ENDIAN_ORDER, r);
x0 = a0; x1 = a1;
}
while (len >= HASH_BLOCKSIZE);
hashBuffer[0] = x0; hashBuffer[1] = x1;
return len;
}
case 2: // non-SSE2 and 64K tables
{
byte *table = MulTable();
word64 x0 = hashBuffer[0], x1 = hashBuffer[1];
do
{
word64 y0, y1, a0, a1;
Block::Get(data)(y0)(y1);
x0 ^= y0;
x1 ^= y1;
data += HASH_BLOCKSIZE;
len -= HASH_BLOCKSIZE;
#undef READ_TABLE_WORD64_COMMON
#undef READ_TABLE_WORD64
#define READ_TABLE_WORD64_COMMON(a, c, d) *(word64 *)(table+(a)*256*16+(c)+(d)*8)
#ifdef IS_LITTLE_ENDIAN
#if CRYPTOPP_BOOL_SLOW_WORD64
word32 z0 = (word32)x0;
word32 z1 = (word32)(x0>>32);
word32 z2 = (word32)x1;
word32 z3 = (word32)(x1>>32);
#define READ_TABLE_WORD64(b, c, d, e) READ_TABLE_WORD64_COMMON(c*4+d, (d?(z##c>>((d?d:1)*8-4))&0xff0:(z##c&0xff)<<4), e)
#else
#define READ_TABLE_WORD64(b, c, d, e) READ_TABLE_WORD64_COMMON(c*4+d, ((d+4*(c%2))?(x##b>>(((d+4*(c%2))?(d+4*(c%2)):1)*8-4))&0xff0:(x##b&0xff)<<4), e)
#endif
#else
#define READ_TABLE_WORD64(b, c, d, e) READ_TABLE_WORD64_COMMON(c*4+d, ((7-d-4*(c%2))?(x##b>>(((7-d-4*(c%2))?(7-d-4*(c%2)):1)*8-4))&0xff0:(x##b&0xff)<<4), e)
#endif
#define GF_MUL_8BY128(op, b, c, d) \
a0 op READ_TABLE_WORD64(b, c, d, 0);\
a1 op READ_TABLE_WORD64(b, c, d, 1);\
GF_MUL_8BY128(=, 0, 0, 0)
GF_MUL_8BY128(^=, 0, 0, 1)
GF_MUL_8BY128(^=, 0, 0, 2)
GF_MUL_8BY128(^=, 0, 0, 3)
GF_MUL_8BY128(^=, 0, 1, 0)
GF_MUL_8BY128(^=, 0, 1, 1)
GF_MUL_8BY128(^=, 0, 1, 2)
GF_MUL_8BY128(^=, 0, 1, 3)
GF_MUL_8BY128(^=, 1, 2, 0)
GF_MUL_8BY128(^=, 1, 2, 1)
GF_MUL_8BY128(^=, 1, 2, 2)
GF_MUL_8BY128(^=, 1, 2, 3)
GF_MUL_8BY128(^=, 1, 3, 0)
GF_MUL_8BY128(^=, 1, 3, 1)
GF_MUL_8BY128(^=, 1, 3, 2)
GF_MUL_8BY128(^=, 1, 3, 3)
x0 = a0; x1 = a1;
}
while (len >= HASH_BLOCKSIZE);
hashBuffer[0] = x0; hashBuffer[1] = x1;
return len;
}
#endif // #ifndef CRYPTOPP_GENERATE_X64_MASM
#ifdef CRYPTOPP_X64_MASM_AVAILABLE
case 1: // SSE2 and 2K tables
GCM_AuthenticateBlocks_2K(data, len/16, hashBuffer, s_reductionTable);
return len % 16;
case 3: // SSE2 and 64K tables
GCM_AuthenticateBlocks_64K(data, len/16, hashBuffer);
return len % 16;
#endif
#if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE
case 1: // SSE2 and 2K tables
{
#ifdef __GNUC__
__asm__ __volatile__
(
INTEL_NOPREFIX
#elif defined(CRYPTOPP_GENERATE_X64_MASM)
ALIGN 8
GCM_AuthenticateBlocks_2K PROC FRAME
rex_push_reg rsi
push_reg rdi
push_reg rbx
.endprolog
mov rsi, r8
mov r11, r9
#else
AS2( mov WORD_REG(cx), data )
AS2( mov WORD_REG(dx), len )
AS2( mov WORD_REG(si), hashBuffer )
AS2( shr WORD_REG(dx), 4 )
#endif
#if CRYPTOPP_BOOL_X32
AS1(push rbx)
AS1(push rbp)
#else
AS_PUSH_IF86( bx)
AS_PUSH_IF86( bp)
#endif
#ifdef __GNUC__
AS2( mov AS_REG_7, WORD_REG(di))
#elif CRYPTOPP_BOOL_X86
AS2( lea AS_REG_7, s_reductionTable)
#endif
AS2( movdqa xmm0, [WORD_REG(si)] )
#define MUL_TABLE_0 WORD_REG(si) + 32
#define MUL_TABLE_1 WORD_REG(si) + 32 + 1024
#define RED_TABLE AS_REG_7
ASL(0)
AS2( movdqu xmm4, [WORD_REG(cx)] )
AS2( pxor xmm0, xmm4 )
AS2( movd ebx, xmm0 )
AS2( mov eax, AS_HEX(f0f0f0f0) )
AS2( and eax, ebx )
AS2( shl ebx, 4 )
AS2( and ebx, AS_HEX(f0f0f0f0) )
AS2( movzx edi, ah )
AS2( movdqa xmm5, XMMWORD_PTR [MUL_TABLE_1 + WORD_REG(di)] )
AS2( movzx edi, al )
AS2( movdqa xmm4, XMMWORD_PTR [MUL_TABLE_1 + WORD_REG(di)] )
AS2( shr eax, 16 )
AS2( movzx edi, ah )
AS2( movdqa xmm3, XMMWORD_PTR [MUL_TABLE_1 + WORD_REG(di)] )
AS2( movzx edi, al )
AS2( movdqa xmm2, XMMWORD_PTR [MUL_TABLE_1 + WORD_REG(di)] )
#define SSE2_MUL_32BITS(i) \
AS2( psrldq xmm0, 4 )\
AS2( movd eax, xmm0 )\
AS2( and eax, AS_HEX(f0f0f0f0) )\
AS2( movzx edi, bh )\
AS2( pxor xmm5, XMMWORD_PTR [MUL_TABLE_0 + (i-1)*256 + WORD_REG(di)] )\
AS2( movzx edi, bl )\
AS2( pxor xmm4, XMMWORD_PTR [MUL_TABLE_0 + (i-1)*256 + WORD_REG(di)] )\
AS2( shr ebx, 16 )\
AS2( movzx edi, bh )\
AS2( pxor xmm3, XMMWORD_PTR [MUL_TABLE_0 + (i-1)*256 + WORD_REG(di)] )\
AS2( movzx edi, bl )\
AS2( pxor xmm2, XMMWORD_PTR [MUL_TABLE_0 + (i-1)*256 + WORD_REG(di)] )\
AS2( movd ebx, xmm0 )\
AS2( shl ebx, 4 )\
AS2( and ebx, AS_HEX(f0f0f0f0) )\
AS2( movzx edi, ah )\
AS2( pxor xmm5, XMMWORD_PTR [MUL_TABLE_1 + i*256 + WORD_REG(di)] )\
AS2( movzx edi, al )\
AS2( pxor xmm4, XMMWORD_PTR [MUL_TABLE_1 + i*256 + WORD_REG(di)] )\
AS2( shr eax, 16 )\
AS2( movzx edi, ah )\
AS2( pxor xmm3, XMMWORD_PTR [MUL_TABLE_1 + i*256 + WORD_REG(di)] )\
AS2( movzx edi, al )\
AS2( pxor xmm2, XMMWORD_PTR [MUL_TABLE_1 + i*256 + WORD_REG(di)] )\
SSE2_MUL_32BITS(1)
SSE2_MUL_32BITS(2)
SSE2_MUL_32BITS(3)
AS2( movzx edi, bh )
AS2( pxor xmm5, XMMWORD_PTR [MUL_TABLE_0 + 3*256 + WORD_REG(di)] )
AS2( movzx edi, bl )
AS2( pxor xmm4, XMMWORD_PTR [MUL_TABLE_0 + 3*256 + WORD_REG(di)] )
AS2( shr ebx, 16 )
AS2( movzx edi, bh )
AS2( pxor xmm3, XMMWORD_PTR [MUL_TABLE_0 + 3*256 + WORD_REG(di)] )
AS2( movzx edi, bl )
AS2( pxor xmm2, XMMWORD_PTR [MUL_TABLE_0 + 3*256 + WORD_REG(di)] )
AS2( movdqa xmm0, xmm3 )
AS2( pslldq xmm3, 1 )
AS2( pxor xmm2, xmm3 )
AS2( movdqa xmm1, xmm2 )
AS2( pslldq xmm2, 1 )
AS2( pxor xmm5, xmm2 )
AS2( psrldq xmm0, 15 )
#if (CRYPTOPP_CLANG_VERSION >= 30600) || (CRYPTOPP_APPLE_CLANG_VERSION >= 70000)
AS2( movd edi, xmm0 )
#elif (defined(CRYPTOPP_CLANG_VERSION) || defined(CRYPTOPP_APPLE_CLANG_VERSION)) && defined(CRYPTOPP_X64_ASM_AVAILABLE)
AS2( mov WORD_REG(di), xmm0 )
#else // GNU Assembler
AS2( movd WORD_REG(di), xmm0 )
#endif
AS2( movzx eax, WORD PTR [RED_TABLE + WORD_REG(di)*2] )
AS2( shl eax, 8 )
AS2( movdqa xmm0, xmm5 )
AS2( pslldq xmm5, 1 )
AS2( pxor xmm4, xmm5 )
AS2( psrldq xmm1, 15 )
#if (CRYPTOPP_CLANG_VERSION >= 30600) || (CRYPTOPP_APPLE_CLANG_VERSION >= 70000)
AS2( movd edi, xmm1 )
#elif (defined(CRYPTOPP_CLANG_VERSION) || defined(CRYPTOPP_APPLE_CLANG_VERSION)) && defined(CRYPTOPP_X64_ASM_AVAILABLE)
AS2( mov WORD_REG(di), xmm1 )
#else
AS2( movd WORD_REG(di), xmm1 )
#endif
AS2( xor ax, WORD PTR [RED_TABLE + WORD_REG(di)*2] )
AS2( shl eax, 8 )
AS2( psrldq xmm0, 15 )
#if (CRYPTOPP_CLANG_VERSION >= 30600) || (CRYPTOPP_APPLE_CLANG_VERSION >= 70000)
AS2( movd edi, xmm0 )
#elif (defined(CRYPTOPP_CLANG_VERSION) || defined(CRYPTOPP_APPLE_CLANG_VERSION)) && defined(CRYPTOPP_X64_ASM_AVAILABLE)
AS2( mov WORD_REG(di), xmm0 )
#else
AS2( movd WORD_REG(di), xmm0 )
#endif
AS2( xor ax, WORD PTR [RED_TABLE + WORD_REG(di)*2] )
AS2( movd xmm0, eax )
AS2( pxor xmm0, xmm4 )
AS2( add WORD_REG(cx), 16 )
AS2( sub WORD_REG(dx), 1 )
ATT_NOPREFIX
ASJ( jnz, 0, b )
INTEL_NOPREFIX
AS2( movdqa [WORD_REG(si)], xmm0 )
#if CRYPTOPP_BOOL_X32
AS1(pop rbp)
AS1(pop rbx)
#else
AS_POP_IF86( bp)
AS_POP_IF86( bx)
#endif
#ifdef __GNUC__
ATT_PREFIX
:
: "c" (data), "d" (len/16), "S" (hashBuffer), "D" (s_reductionTable)
: "memory", "cc", "%eax"
#if CRYPTOPP_BOOL_X64
, "%ebx", "%r11"
#endif
);
#elif defined(CRYPTOPP_GENERATE_X64_MASM)
pop rbx
pop rdi
pop rsi
ret
GCM_AuthenticateBlocks_2K ENDP
#endif
return len%16;
}
case 3: // SSE2 and 64K tables
{
#ifdef __GNUC__
__asm__ __volatile__
(
INTEL_NOPREFIX
#elif defined(CRYPTOPP_GENERATE_X64_MASM)
ALIGN 8
GCM_AuthenticateBlocks_64K PROC FRAME
rex_push_reg rsi
push_reg rdi
.endprolog
mov rsi, r8
#else
AS2( mov WORD_REG(cx), data )
AS2( mov WORD_REG(dx), len )
AS2( mov WORD_REG(si), hashBuffer )
AS2( shr WORD_REG(dx), 4 )
#endif
AS2( movdqa xmm0, [WORD_REG(si)] )
#undef MUL_TABLE
#define MUL_TABLE(i,j) WORD_REG(si) + 32 + (i*4+j)*256*16
ASL(1)
AS2( movdqu xmm1, [WORD_REG(cx)] )
AS2( pxor xmm1, xmm0 )
AS2( pxor xmm0, xmm0 )
#undef SSE2_MUL_32BITS
#define SSE2_MUL_32BITS(i) \
AS2( movd eax, xmm1 )\
AS2( psrldq xmm1, 4 )\
AS2( movzx edi, al )\
AS2( add WORD_REG(di), WORD_REG(di) )\
AS2( pxor xmm0, [MUL_TABLE(i,0) + WORD_REG(di)*8] )\
AS2( movzx edi, ah )\
AS2( add WORD_REG(di), WORD_REG(di) )\
AS2( pxor xmm0, [MUL_TABLE(i,1) + WORD_REG(di)*8] )\
AS2( shr eax, 16 )\
AS2( movzx edi, al )\
AS2( add WORD_REG(di), WORD_REG(di) )\
AS2( pxor xmm0, [MUL_TABLE(i,2) + WORD_REG(di)*8] )\
AS2( movzx edi, ah )\
AS2( add WORD_REG(di), WORD_REG(di) )\
AS2( pxor xmm0, [MUL_TABLE(i,3) + WORD_REG(di)*8] )\
SSE2_MUL_32BITS(0)
SSE2_MUL_32BITS(1)
SSE2_MUL_32BITS(2)
SSE2_MUL_32BITS(3)
AS2( add WORD_REG(cx), 16 )
AS2( sub WORD_REG(dx), 1 )
ATT_NOPREFIX
ASJ( jnz, 1, b )
INTEL_NOPREFIX
AS2( movdqa [WORD_REG(si)], xmm0 )
#ifdef __GNUC__
ATT_PREFIX
:
: "c" (data), "d" (len/16), "S" (hashBuffer)
: "memory", "cc", "%edi", "%eax"
);
#elif defined(CRYPTOPP_GENERATE_X64_MASM)
pop rdi
pop rsi
ret
GCM_AuthenticateBlocks_64K ENDP
#endif
return len%16;
}
#endif
#ifndef CRYPTOPP_GENERATE_X64_MASM
}
return len%16;
}
void GCM_Base::AuthenticateLastHeaderBlock()
{
if (m_bufferedDataLength > 0)
{
memset(m_buffer+m_bufferedDataLength, 0, HASH_BLOCKSIZE-m_bufferedDataLength);
m_bufferedDataLength = 0;
GCM_Base::AuthenticateBlocks(m_buffer, HASH_BLOCKSIZE);
}
}
void GCM_Base::AuthenticateLastConfidentialBlock()
{
GCM_Base::AuthenticateLastHeaderBlock();
PutBlock<word64, BigEndian, true>(NULL, m_buffer)(m_totalHeaderLength*8)(m_totalMessageLength*8);
GCM_Base::AuthenticateBlocks(m_buffer, HASH_BLOCKSIZE);
}
void GCM_Base::AuthenticateLastFooterBlock(byte *mac, size_t macSize)
{
m_ctr.Seek(0);
ReverseHashBufferIfNeeded();
m_ctr.ProcessData(mac, HashBuffer(), macSize);
}
NAMESPACE_END
#endif // #ifndef CRYPTOPP_GENERATE_X64_MASM
#endif
| gpl-3.0 |
ouyangyu/fdmoodle | mod/data/backup/moodle2/restore_data_activity_task.class.php | 5773 | <?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/>.
/**
* @package moodlecore
* @subpackage backup-moodle2
* @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/data/backup/moodle2/restore_data_stepslib.php'); // Because it exists (must)
/**
* data restore task that provides all the settings and steps to perform one
* complete restore of the activity
*/
class restore_data_activity_task extends restore_activity_task {
/**
* Define (add) particular settings this activity can have
*/
protected function define_my_settings() {
// No particular settings for this activity
}
/**
* Define (add) particular steps this activity can have
*/
protected function define_my_steps() {
// Data only has one structure step
$this->add_step(new restore_data_activity_structure_step('data_structure', 'data.xml'));
}
/**
* Define the contents in the activity that must be
* processed by the link decoder
*/
static public function define_decode_contents() {
$contents = array();
$contents[] = new restore_decode_content('data', array(
'intro', 'singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
'addtemplate', 'rsstemplate', 'rsstitletemplate', 'asearchtemplate'), 'data');
$contents[] = new restore_decode_content('data_fields', array(
'description', 'param1', 'param2', 'param3',
'param4', 'param5', 'param6', 'param7',
'param8', 'param9', 'param10'), 'data_field');
$contents[] = new restore_decode_content('data_content', array(
'content', 'content1', 'content2', 'content3', 'content4'));
return $contents;
}
/**
* Define the decoding rules for links belonging
* to the activity to be executed by the link decoder
*/
static public function define_decode_rules() {
$rules = array();
$rules[] = new restore_decode_rule('DATAVIEWBYID', '/mod/data/view.php?id=$1', 'course_module');
$rules[] = new restore_decode_rule('DATAVIEWBYD', '/mod/data/index.php?d=$1', 'data');
$rules[] = new restore_decode_rule('DATAINDEX', '/mod/data/index.php?id=$1', 'course');
$rules[] = new restore_decode_rule('DATAVIEWRECORD', '/mod/data/view.php?d=$1&rid=$2', array('data', 'data_record'));
return $rules;
}
/**
* Define the restore log rules that will be applied
* by the {@link restore_logs_processor} when restoring
* data logs. It must return one array
* of {@link restore_log_rule} objects
*/
static public function define_restore_log_rules() {
$rules = array();
$rules[] = new restore_log_rule('data', 'add', 'view.php?d={data}&rid={data_record}', '{data}');
$rules[] = new restore_log_rule('data', 'update', 'view.php?d={data}&rid={data_record}', '{data}');
$rules[] = new restore_log_rule('data', 'view', 'view.php?id={course_module}', '{data}');
$rules[] = new restore_log_rule('data', 'record delete', 'view.php?id={course_module}', '{data}');
$rules[] = new restore_log_rule('data', 'fields add', 'field.php?d={data}&mode=display&fid={data_field}', '{data_field}');
$rules[] = new restore_log_rule('data', 'fields update', 'field.php?d={data}&mode=display&fid={data_field}', '{data_field}');
$rules[] = new restore_log_rule('data', 'fields delete', 'field.php?d={data}', '[name]');
return $rules;
}
/**
* Define the restore log rules that will be applied
* by the {@link restore_logs_processor} when restoring
* course logs. It must return one array
* of {@link restore_log_rule} objects
*
* Note this rules are applied when restoring course logs
* by the restore final task, but are defined here at
* activity level. All them are rules not linked to any module instance (cmid = 0)
*/
static public function define_restore_log_rules_for_course() {
$rules = array();
$rules[] = new restore_log_rule('data', 'view all', 'index.php?id={course}', null);
return $rules;
}
/**
* Given a commment area, return the itemname that contains the itemid mappings.
*
* @param string $commentarea Comment area name e.g. database_entry.
* @return string name of the mapping used to determine the itemid.
*/
public function get_comment_mapping_itemname($commentarea) {
if ($commentarea == 'database_entry') {
$itemname = 'data_record';
} else {
$itemname = parent::get_comment_mapping_itemname($commentarea);
}
return $itemname;
}
}
| gpl-3.0 |
GeoMop/GeoMop | src/gm_base/global_const.py | 199 | """
Module for global constants.
Do not use imports in this file. We don't want possible import problems.
"""
GEOMOP_INTERNAL_DIR_NAME = ".geomop"
"""Dir name for storing geomop internal files."""
| gpl-3.0 |
davec/openbrewcomp | vendor/plugins/restful_authentication/lib/authentication.rb | 1578 | module Authentication
mattr_accessor :login_regex, :bad_login_message,
:name_regex, :bad_name_message,
:email_name_regex, :domain_head_regex, :domain_tld_regex, :email_regex, :bad_email_message
self.login_regex = /\A\w[\w\.\-_@]+\z/ # ASCII, strict
# self.login_regex = /\A[[:alnum:]][[:alnum:]\.\-_@]+\z/ # Unicode, strict
# self.login_regex = /\A[^[:cntrl:]\\<>\/&]*\z/ # Unicode, permissive
self.bad_login_message = "must include only letters, numbers, and the characters .-_@".freeze
self.name_regex = /\A[^[:cntrl:]\\<>\/&]*\z/ # Unicode, permissive
self.bad_name_message = "must not include non-printing characters or the characters \\><&/".freeze
self.email_name_regex = '[\w\.%\+\-]+'.freeze
self.domain_head_regex = '(?:[A-Z0-9\-]+\.)+'.freeze
self.domain_tld_regex = '(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|jobs|museum)'.freeze
self.email_regex = /\A#{email_name_regex}@#{domain_head_regex}#{domain_tld_regex}\z/i
self.bad_email_message = "should look like an email address".freeze
def self.included(recipient)
recipient.extend(ModelClassMethods)
recipient.class_eval do
include ModelInstanceMethods
end
end
module ModelClassMethods
def secure_digest(*args)
Digest::SHA1.hexdigest(args.flatten.join('--'))
end
def make_token
secure_digest(Time.now, (1..10).map{ rand.to_s })
end
end # class methods
module ModelInstanceMethods
end # instance methods
end
| gpl-3.0 |
ERIN-LIST/gapIt | src/main/java/lu/lippmann/cdb/ext/hydviga/gaps/GapFillerClassifier.java | 2265 | /**
* Copyright© 2014-2016 LIST (Luxembourg Institute of Science and Technology), all right reserved.
* Authorship : Olivier PARISOT, Yoanne DIDRY
* Licensed under GNU General Public License version 3
*/
package lu.lippmann.cdb.ext.hydviga.gaps;
import lu.lippmann.cdb.weka.*;
import weka.classifiers.Classifier;
import weka.core.*;
/**
* TimeSeriesGapFillerClassifier.
*
* @author Olivier PARISOT
*
*/
public class GapFillerClassifier extends GapFiller
{
//
// Instance fields
//
/** */
private final Classifier classifier;
//
// Constructors
//
/**
* Constructor.
*/
GapFillerClassifier(final boolean wdt,final Classifier classifier)
{
super(wdt);
this.classifier=classifier;
}
//
// Instance methods
//
/**
* {@inheritDoc}
*/
@Override
Instances fillGaps0(final Instances ds) throws Exception
{
final Instances newds=WekaDataProcessingUtil.buildDataSetWithoutConstantAttributes(ds);
final int attrWithMissingIdx=WekaDataStatsUtil.getFirstAttributeWithMissingValue(newds);
if (attrWithMissingIdx==-1) throw new IllegalStateException();
final Instances trainingSet=new Instances(newds,0);
for (int i=0;i<newds.numInstances();i++)
{
if (!newds.instance(i).hasMissingValue()) trainingSet.add(newds.instance(i));
}
//System.out.println(trainingSet);
trainingSet.setClassIndex(attrWithMissingIdx);
//System.out.println("Training (size="+trainingSet.numInstances()+") ...");
this.classifier.buildClassifier(trainingSet);
//System.out.println("... trained!");
newds.setClassIndex(attrWithMissingIdx);
for (int i=0;i<newds.numInstances();i++)
{
if (newds.instance(i).isMissing(attrWithMissingIdx))
{
final Instance newrecord=new DenseInstance(newds.instance(i));
newrecord.setDataset(newds);
final double newval=this.classifier.classifyInstance(newrecord);
newds.instance(i).setValue(attrWithMissingIdx,newval);
}
}
//System.out.println("initial -> "+ds.toSummaryString());
//System.out.println("corrected -> "+newds.toSummaryString());
this.model=this.classifier.toString();
return newds;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasExplicitModel()
{
return true;
}
}
| gpl-3.0 |
xafero/travelingsales | libosm/src/main/java/org/openstreetmap/osm/data/TileCalculator.java | 21273 | /**
* This file is part of LibOSM by Marcus Wolschon <a href="mailto:[email protected]">[email protected]</a>.
* You can purchase support for a sensible hourly rate or
* a commercial license of this file (unless modified by others) by contacting him directly.
*
* LibOSM 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.
*
* LibOSM 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 LibOSM. If not, see <http://www.gnu.org/licenses/>.
*
***********************************
* Editing this file:
* -For consistent code-quality this file should be checked with the
* checkstyle-ruleset enclosed in this project.
* -After the design of this file has settled it should get it's own
* JUnit-Test that shall be executed regularly. It is best to write
* the test-case BEFORE writing this class and to run it on every build
* as a regression-test.
*/
package org.openstreetmap.osm.data;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openstreetmap.osm.data.coordinates.Bounds;
import org.openstreetmap.osm.data.coordinates.LatLon;
/**
* Improved Osmosis-Tile-Calculator that can also do the inverse
* calculation.
*/
public class TileCalculator extends org.openstreetmap.osmosis.core.util.TileCalculator {
/**
* The number of bits of a tile-number
* in the osmosis-format.
*/
private static final int TILEBITCOUNT = 15;
/**
* The maximum longitude in degrees.
* (360°)
*/
private static final double MAX_LONGITUDE = 360d;
/**
* The maximum latitude in degrees.
* (180°)
*/
private static final double MAX_LATITUDE = 180d;
/**
* 180°.
*/
private static final double HALF_CIRCLE = 180d;
/**
* 90°.
*/
private static final double QUARTER_CIRCLE = 90d;
/**
* The tiles split the planet into this many tiles
* in each direction.
*/
private static final int MAXTILE = 65536;
/**
* A tile is this wide in lat-direction.
*/
private static final double LATTILESTEP = MAX_LATITUDE / MAXTILE;
/**
* A tile is this wide in lon-direction.
*/
private static final double LONTILESTEP = MAX_LONGITUDE / MAXTILE;
/**
* We never return the data of more then
* this number of tiles.
*/
private static final int MAXTILECOUNTRETURNED = 32767;
/**
* my logger for debug and error-output.
*/
private static final Logger LOG = Logger.getLogger(TileCalculator.class.getName());
/**
* Calculates a tile index based upon the supplied coordinates.
*
* @param latLon
* The coordinate latitude and longitude.
* @return The tile index value.
*/
public long calculateTile(final LatLon latLon) {
return calculateTile(latLon.lat(), latLon.lon());
}
/**
* @param bounds some bounds
* @return all tile-numbers that the bounds span
*/
/*public Collection<Long> getTileIDsForBounds(final Bounds bounds) {
List<Long> retval = new LinkedList<Long>();
LatLon center = bounds.center();
double centerLat = center.lat();
double centerLon = center.lon();
if (bounds.contains(centerLon, centerLon))
retval.add(calculateTile(centerLon, centerLon));
double minLon = bounds.getMin().lon();
double minLat = bounds.getMin().lat();
double maxLon = bounds.getMax().lon();
double maxLat = bounds.getMax().lat();
for (int dist = 1; true; dist++) {
if (dist > (maxLon - minLon) / LONTILESTEP
&& dist > (maxLat - minLat) / LATTILESTEP)
break;
// upper
double lat = centerLat - (dist * LATTILESTEP);
for (double lon = centerLon - (dist * LONTILESTEP / 2); lon <= centerLon + (dist * LONTILESTEP / 2); lon += LONTILESTEP) {
if (lon < minLon)
continue;
if (lon > maxLon)
break;
if (!bounds.contains(lat, lon))
continue;
retval.add(calculateTile(lat, lon));
if (retval.size() > MAXTILECOUNTRETURNED) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.log(Level.FINEST, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles. Called from:", new Exception("dummy-exception to trace call"));
} else {
LOG.log(Level.INFO, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles");
}
return retval;
}
}
// lower
lat = centerLat + (dist * LATTILESTEP);
for (double lon = centerLon - (dist * LONTILESTEP / 2); lon <= centerLon + (dist * LONTILESTEP / 2); lon += LONTILESTEP) {
if (lon < minLon)
continue;
if (lon > maxLon)
break;
if (!bounds.contains(lat, lon))
continue;
retval.add(calculateTile(lat, lon));
if (retval.size() > MAXTILECOUNTRETURNED) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.log(Level.FINEST, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles. Called from:", new Exception("dummy-exception to trace call"));
} else {
LOG.log(Level.INFO, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles");
}
return retval;
}
}
// left
double lon = centerLon - (dist * LONTILESTEP);
for (lat = centerLat - (dist * LATTILESTEP / 2); lat <= centerLat + (dist * LATTILESTEP / 2); lat += LATTILESTEP) {
if (lat < minLat)
continue;
if (lat > maxLat)
break;
if (!bounds.contains(lat, lon))
continue;
retval.add(calculateTile(lat, lon));
if (retval.size() > MAXTILECOUNTRETURNED) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.log(Level.FINEST, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles. Called from:", new Exception("dummy-exception to trace call"));
} else {
LOG.log(Level.INFO, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles");
}
return retval;
}
}
// right
lon = centerLon + (dist * LONTILESTEP);
for (lat = centerLat - (dist * LATTILESTEP / 2); lat <= centerLat + (dist * LATTILESTEP / 2); lat += LATTILESTEP) {
if (lat < minLat)
continue;
if (lat > maxLat)
break;
if (!bounds.contains(lat, lon))
continue;
retval.add(calculateTile(lat, lon));
if (retval.size() > MAXTILECOUNTRETURNED) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.log(Level.FINEST, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles. Called from:", new Exception("dummy-exception to trace call"));
} else {
LOG.log(Level.INFO, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles");
}
return retval;
}
}
}*/
/**
* @param aBounds The bounds who's tile-ids we enumerate.
* @param aCombineTiles the returned tileIDs have this many digits removed
* @return This iterator gives all tile-ids that are contained in a given bounds.
*/
public Iterator<Long> getTileIDsForBounds(final Bounds aBounds,
final int aCombineTiles) {
return new TileIDIterator(aBounds, aCombineTiles);
}
/**
* @param aBoundingBox The bounds who's tile-ids we enumerate.
* @param aAllTileIDs Return only members of this set.
* @param aCombineTiles the given tileIDs have this many digits removed
* @return This iterator gives all tile-ids that are contained in a given bounds.
*/
public Collection<Long> getTileIDsForBounds(final Bounds aBoundingBox,
final Collection<Long> aAllTileIDs,
final int aCombineTiles) {
LinkedList<Long> retval = new LinkedList<Long>();
LatLon min = aBoundingBox.getMin();
LatLon max = aBoundingBox.getMax();
for (Long tileNr : aAllTileIDs) {
XyPair[] xy = calculateXyPairFromTileNumber(tileNr, aCombineTiles);
double minLat = calculateLatitudeFromTileY(xy[0].getYNumber());
double minLon = calculateLongitudeFromTileX(xy[0].getXNumber());
double maxLat = calculateLatitudeFromTileY(xy[1].getYNumber() + 1);
double maxLon = calculateLongitudeFromTileX(xy[1].getXNumber() + 1);
if (minLat > max.getXCoord())
continue;
if (minLon > max.getYCoord())
continue;
if (maxLat < min.getXCoord())
continue;
if (maxLon < min.getYCoord())
continue;
retval.add(tileNr);
}
return retval;
}
/**
* @param tileNR the tile-number to calculate for
* @param aCombineTiles the given tileIDs have this many digits removed
* @return 2 XyPairs. 0=min, 1=max
* @see #calculateXyPairFromTileNumber(long)
*/
private XyPair[] calculateXyPairFromTileNumber(final long tileNR,
final int aCombineTiles) {
if (aCombineTiles == 0) {
XyPair ret = calculateXyPairFromTileNumber(tileNR);
return new XyPair[] {ret, ret};
}
XyPair[] ret = new XyPair[] {
new XyPair(Integer.MAX_VALUE, Integer.MAX_VALUE),
new XyPair(Integer.MIN_VALUE, Integer.MIN_VALUE)
};
final int deca = 10;
for (int i = 0; i<deca; i++) {
XyPair[] current = calculateXyPairFromTileNumber(
deca * tileNR + i, aCombineTiles - 1);
ret[0].setXNumber(Math.min(ret[0].getXNumber(),
current[0].getXNumber()));
ret[0].setYNumber(Math.min(ret[0].getYNumber(),
current[0].getYNumber()));
ret[1].setXNumber(Math.max(ret[1].getXNumber(),
current[1].getXNumber()));
ret[1].setYNumber(Math.max(ret[1].getYNumber(),
current[1].getYNumber()));
}
return ret;
}
/**
* This iterator gives all tile-ids that are contained in a given bounds.
*/
public class TileIDIterator implements Iterator<Long> {
/**
* The bounds who's tile-ids
* we enumerate.
*/
private Bounds myBounds;
/**
* the returned tileIDs have this many digits removed.
*/
private int myCombineTiles;
/**
* Our current position in the iteration.
*/
private double myCurrentLat;
/**
* Our current position in the iteration.
*/
private double myCurrentLon;
/**
* The next value we return.
*/
private Long myNextValue = null;
/**
* @param aBounds The bounds who's tile-ids
* we enumerate.
* @param aCombineTiles the returned tileIDs have this many digits removed
*/
public TileIDIterator(final Bounds aBounds, final int aCombineTiles) {
super();
myBounds = aBounds;
myCombineTiles = aCombineTiles;
myCurrentLat = myBounds.getMin().lat();
myCurrentLon = myBounds.getMin().lon();
if (getBounds().contains(myCurrentLat, myCurrentLon)) {
myNextValue = calculateTile(myCurrentLat, myCurrentLon);
LOG.log(Level.FINEST, "TileIterator returning " + myCurrentLat + " x " + myCurrentLon + " = " + myNextValue);
} else {
myNextValue = next();
}
}
/**
* @return Returns the bounds.
* @see #myBounds
*/
public Bounds getBounds() {
return myBounds;
}
/**
* ${@inheritDoc}.
*/
public boolean hasNext() {
return myNextValue != null;
}
/**
* ${@inheritDoc}.
*/
public Long next() {
Long myOldNextValue = myNextValue;
while (true) {
LatLon innerNext = innerNext();
if (innerNext == null) {
myNextValue = null;
break;
}
if (getBounds().contains(innerNext.lat(), innerNext.lon())) {
myNextValue = calculateTile(innerNext.lat(), innerNext.lon());
final int deca = 10;
for (int i = 0; i<myCombineTiles; i++)
myNextValue = myNextValue / deca;
if (myNextValue != myOldNextValue) {
LOG.log(Level.FINEST, "TileIterator returning " + innerNext + " = " + myNextValue);
break;
}
}
}
return myOldNextValue;
}
/**
* @return the next tile-location.
*/
private LatLon innerNext() {
// step inner loop
if (myCurrentLat <= getBounds().getMax().lat()) {
myNextValue = calculateTile(myCurrentLat, myCurrentLon);
myCurrentLat += LATTILESTEP;
return new LatLon(myCurrentLat, myCurrentLon);
}
// step outher loop
if (myCurrentLat > getBounds().getMax().lat()) {
myCurrentLat = myBounds.getMin().lat();
myCurrentLon += LONTILESTEP;
}
// check to end outher loop
if (myCurrentLon > getBounds().getMax().lon()) {
return null;
}
return new LatLon(myCurrentLat, myCurrentLon);
}
/**
* ${@inheritDoc}.
*/
public void remove() {
throw new IllegalArgumentException("remove makes no sense here");
}
};
/* for (double lon = bounds.getMin().lon(); lon <= bounds.getMax().lon(); lon += LONTILESTEP)
for (double lat = bounds.getMin().lat(); lat <= bounds.getMax().lat(); lat += LATTILESTEP) {
if (!bounds.contains(lat, lon))
continue;
retval.add(calculateTile(lat, lon));
if (retval.size() > MAXTILECOUNTRETURNED) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.log(Level.FINEST, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles. Called from:", new Exception("dummy-exception to trace call"));
} else {
LOG.log(Level.INFO, "We refuse to return the data of more than "
+ MAXTILECOUNTRETURNED + " tiles");
}
return retval;
}
}
return retval;
}*/
/**
* Calculates a tile index based upon the supplied coordinates.
*
* @param latitude
* The coordinate latitude.
* @param longitude
* The coordinate longitude.
* @return The tile index value.
*/
@Override
public long calculateTile(final double latitude, final double longitude) {
int x;
int y;
long tile;
x = (int) Math.round((longitude + HALF_CIRCLE) * MAXTILE / MAX_LONGITUDE);
y = (int) Math.round((latitude + QUARTER_CIRCLE) * MAXTILE / MAX_LATITUDE);
tile = 0;
for (int i = TILEBITCOUNT; i >= 0; i--) {
tile = (tile << 1) | ((x >> i) & 1);
tile = (tile << 1) | ((y >> i) & 1);
}
return tile;
}
/**
* @param tileX an x-tile-number
* @return the minimum longitude this corresponds to
*/
public double calculateLongitudeFromTileX(final long tileX) {
double x = (double)tileX;
return (x * MAX_LONGITUDE / MAXTILE) - HALF_CIRCLE;
}
/**
* @param tileX an y-tile-number
* @return the minimum latitude this corresponds to
*/
public double calculateLatitudeFromTileY(final long tileY) {
double y = (double)tileY;
return (y * MAX_LATITUDE / MAXTILE) - QUARTER_CIRCLE;
}
/**
* Given a lat + lon calculate the tile-number for it.
* @param latitude the lat
* @param longitude the lon
* @return the tile-number
*/
protected long calculateTileInternal(final double latitude, final double longitude) {
int x;
int y;
long tile;
x = (int) Math.round((longitude + MAX_LONGITUDE / 2) * MAXTILE / MAX_LONGITUDE);
y = (int) Math.round((latitude + MAX_LATITUDE / 2) * MAXTILE / MAX_LATITUDE);
tile = 0;
for (int i = TILEBITCOUNT; i >= 0; i--) {
tile = (tile << 1) | ((x >> i) & 1);
tile = (tile << 1) | ((y >> i) & 1);
}
return tile;
}
/**
* Take a tile-number and convert it into a pair of x and y tile-coordinates.
* @param tile the tile to parse
* @return the pair of coordinates
*/
public XyPair calculateXyPairFromTileNumber(final long tile) {
XyPair pair = new XyPair();
long x = 0;
long y = 0;
for (int i = TILEBITCOUNT; i >= 0; i--) {
y = (y << 1) | ((tile >> (i * 2)) & 1);
x = (x << 1) | ((tile >> ((i * 2) + 1)) & 1);
}
pair.myXNumber = (int) x;
pair.myYNumber = (int) y;
return pair;
}
/**
* A pair of X and Y -tile-coordinated.
* @author <a href="mailto:[email protected]">Marcus Wolschon</a>
*/
public static class XyPair {
/**
* Construct the pair (0, 0).
*/
public XyPair() {
this.myXNumber = 0;
this.myYNumber = 0;
}
/**
* Construct the pair (x, y).
* @param x the x-number of the tile.
* @param y the y-number of the tile.
*/
public XyPair(final int x, final int y) {
this.myXNumber = x;
this.myYNumber = y;
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
return "[" + myXNumber + "," + myYNumber + "]";
}
/**
* The x-number of the tile.
*/
private int myXNumber;
/**
* The y-number of the tile.
*/
private int myYNumber;
/**
* @return the tile-number for this pair
*/
public long getTile() {
long tile = 0;
for (int i = TILEBITCOUNT; i >= 0; i--) {
tile = (tile << 1) | ((getXNumber() >> i) & 1);
tile = (tile << 1) | ((getYNumber() >> i) & 1);
}
return tile;
}
/**
* @return The x-number of the tile.
* @see #myXNumber
*/
public int getXNumber() {
return this.myXNumber;
}
/**
* @return The y-number of the tile.
* @see #myYNumber
*/
public int getYNumber() {
return this.myYNumber;
}
/**
* @param pNumber The x-number of the tile. to set.
* @see #myXNumber
*/
public void setXNumber(final int pNumber) {
this.myXNumber = pNumber;
}
/**
* @param pNumber The y-number of the tile. to set.
* @see #myYNumber
*/
public void setYNumber(final int pNumber) {
this.myYNumber = pNumber;
}
}
}
| gpl-3.0 |
jamesmacwhite/Radarr | src/NzbDrone.Common/Exceptron/RestClient.cs | 2315 | using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using NzbDrone.Common.Exceptron.fastJSON;
namespace NzbDrone.Common.Exceptron
{
public sealed class RestClient : IRestClient
{
public TResponse Put<TResponse>(string url, object content) where TResponse : class ,new()
{
if (content == null)
throw new ArgumentNullException("content can not be null", "content");
if (string.IsNullOrEmpty(url))
throw new ArgumentNullException("url can not be null or empty", "url");
Trace.WriteLine("Attempting PUT to " + url);
var json = JSON.Instance.ToJSON(content);
var bytes = Encoding.UTF8.GetBytes(json);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 10000;
request.Method = "PUT";
request.ContentType = "application/json";
request.ContentLength = bytes.Length;
request.Accept = "application/json";
var dataStream = request.GetRequestStream();
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
string responseContent = string.Empty;
try
{
var webResponse = request.GetResponse();
responseContent = ReadResponse(webResponse);
var response = JSON.Instance.ToObject<TResponse>(responseContent);
return response;
}
catch (WebException e)
{
Trace.WriteLine(e.ToString());
responseContent = ReadResponse(e.Response);
throw new ExceptronApiException(e, responseContent);
}
finally
{
Trace.WriteLine(responseContent);
}
}
public static string ReadResponse(WebResponse webResponse)
{
if (webResponse == null) return string.Empty;
var responseStream = webResponse.GetResponseStream();
if (responseStream == null) return string.Empty;
var decodedStream = new StreamReader(responseStream, Encoding.GetEncoding(1252));
return decodedStream.ReadToEnd();
}
}
}
| gpl-3.0 |
notkild/wydy | wydyd/src/lib.rs | 1055 | // Config for clippy
#![allow(unknown_lints)]
#![allow(doc_markdown)]
extern crate app_dirs;
// extern crate fern;
#[macro_use]
extern crate log;
extern crate parser_rs;
extern crate simplelog;
extern crate verex;
pub mod command;
pub mod env;
#[macro_use]
pub mod error;
pub mod parser;
pub mod server;
mod url_check;
use app_dirs::AppInfo;
use simplelog::*;
use std::fs::File;
const APP_INFO: AppInfo = AppInfo {
name: "wydy",
author: "notkild",
};
/// Init logging.
pub fn init_logging(debug: bool) {
let dir = std::env::current_exe().unwrap().parent().unwrap().join(".wydyd.log");
if dir.exists() {
std::fs::remove_file(&dir).unwrap();
}
let log_level = if debug {
LogLevelFilter::Debug
} else {
LogLevelFilter::Info
};
CombinedLogger::init(vec![
TermLogger::new(log_level, Config::default()).unwrap(),
WriteLogger::new(LogLevelFilter::Trace, Config::default(), File::create(dir).unwrap()),
])
.unwrap();
debug!("Debug mode is enabled");
}
| gpl-3.0 |
petejonze/ivis | ivis/doc/API/src/search/all_61.js | 2211 | var searchData=
[
['accelcriterion',['accelCriterion',['../classivis_1_1eyetracker_1_1_iv_data_input.html#a507bd53d1ad3d4291b87d0093c562778',1,'ivis::eyetracker::IvDataInput']]],
['adapt',['adapt',['../classivis_1_1main_1_1_iv_params.html#af8922c460c819d66c42327d40ee108fb',1,'ivis::main::IvParams']]],
['add',['add',['../classivis_1_1log_1_1_iv_data_log.html#a7d516f6f8929ccf4a25474d5c4a5f8e9',1,'ivis::log::IvDataLog::add()'],['../class_singleton_manager.html#a445d64603590d1ade17ca6532ad6e897',1,'SingletonManager::add()']]],
['addassubfigure',['addAsSubfigure',['../classivis_1_1gui_1_1_iv_g_u_i.html#ac79451b7e8aeb9e935f49cad9498feeb',1,'ivis::gui::IvGUI']]],
['addmeasurements',['addMeasurements',['../classivis_1_1calibration_1_1_iv_calibration.html#a919534b51e96f5314193ff1960ff4f21',1,'ivis::calibration::IvCalibration']]],
['allow_5fimplicit_5fconstruction',['ALLOW_IMPLICIT_CONSTRUCTION',['../classivis_1_1broadcaster_1_1_iv_broadcaster.html#a0cd87b265cdb8f1238f8111e709d71dd',1,'ivis::broadcaster::IvBroadcaster::ALLOW_IMPLICIT_CONSTRUCTION()'],['../classivis_1_1calibration_1_1_track_box.html#a6dcc5c14f114d198d634c3dcc9ffda2f',1,'ivis::calibration::TrackBox::ALLOW_IMPLICIT_CONSTRUCTION()'],['../classivis_1_1main_1_1_iv_params.html#a4a52a16c5755f2e9ce84c10f72eae555',1,'ivis::main::IvParams::ALLOW_IMPLICIT_CONSTRUCTION()']]],
['amax',['amax',['../classivis_1_1calibration_1_1_track_box.html#a614f6f4bbf4d10f4231a87cfd5abbea6',1,'ivis::calibration::TrackBox']]],
['apply',['apply',['../classivis_1_1calibration_1_1_iv_calibration.html#acf6b02f25f02c68b6cde5cd8889805f9',1,'ivis::calibration::IvCalibration']]],
['arrow',['arrow',['../classivis_1_1gui_1_1_iv_g_u_iclassifier_vector.html#ad8c000c8d19082d6adf1b142e9126847',1,'ivis::gui::IvGUIclassifierVector']]],
['assertversion',['assertVersion',['../classivis_1_1main_1_1_iv_main.html#a71ff1cf2f841d66b487076c87fe417ce',1,'ivis::main::IvMain']]],
['audio',['audio',['../classivis_1_1main_1_1_iv_params.html#ac77f9ea930dd9294c941446aa2a0c734',1,'ivis::main::IvParams']]],
['auxparameters',['auxParameters',['../classivis_1_1graphic_1_1_iv_graphic.html#a9f3ca7885567b8f66d20306ff151b767',1,'ivis::graphic::IvGraphic']]]
];
| gpl-3.0 |
Pryancito/zeusircd | src/MoPsr.cpp | 6972 | /*
* This file is part of the ZeusiRCd distribution (https://github.com/Pryancito/zeusircd).
* Copyright (c) 2019 Rodrigo Santidrian AKA Pryan.
*
* 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, version 3.
*
* 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 <ctype.h>
#include <fstream>
#include <sys/stat.h>
#include "MoPsr.h"
using namespace std;
const int32_t GettextMoParser::HEADER_MAGIC_NUMBER = 0x950412de;
const int32_t GettextMoParser::HEADER_MAGIC_NUMBER_SW = 0xde120495;
GettextMoParser::GettextMoParser() {
swappedBytes_ = false;
moFileHeader_ = NULL;
moData_ = NULL;
charset_ = NULL;
charsetParsed_ = false;
ready_ = false;
}
int32_t GettextMoParser::swap_(int32_t ui) const {
return swappedBytes_ ? (ui << 24) | ((ui & 0xff00) << 8) |
((ui >> 8) & 0xff00) | (ui >> 24)
: ui;
}
void GettextMoParser::clearData() {
if (moData_) delete[] moData_;
if (charset_) delete[] charset_;
swappedBytes_ = false;
moFileHeader_ = NULL;
moData_ = NULL;
charset_ = NULL;
charsetParsed_ = false;
for (int i = 0; i < (int)messages_.size(); i++) {
TranslatedMessage* message = messages_.at(i);
if (message->original) {
delete message->original;
}
if (message->translated) {
delete message->translated;
}
delete message;
}
messages_.clear();
ready_ = false;
}
bool GettextMoParser::parseFile(const char* filePath) {
clearData();
struct stat fileInfo;
if (stat(filePath, &fileInfo) != 0) {
// Cannot get file size
clearData();
return false;
}
char* moData = new char[fileInfo.st_size];
ifstream moFile(filePath, ios::in | ios::binary);
if (!moFile.read(moData, fileInfo.st_size)) {
// Cannot read file data
delete[] moData;
clearData();
return false;
}
return parse(moData);
}
bool GettextMoParser::parse(char* moData) {
moData_ = moData;
moFileHeader_ = (MoFileHeader*)moData_;
if (moFileHeader_->magic != HEADER_MAGIC_NUMBER && moFileHeader_->magic != HEADER_MAGIC_NUMBER_SW) {
// Invalid header
clearData();
return false;
}
// If the magic number bytes are swapped, all the other numbers will have
// to be swapped
swappedBytes_ = moFileHeader_->magic == HEADER_MAGIC_NUMBER_SW;
moFileHeader_->magic = swap_(moFileHeader_->magic);
moFileHeader_->revision = swap_(moFileHeader_->revision);
moFileHeader_->numStrings = swap_(moFileHeader_->numStrings);
moFileHeader_->offsetOriginalStrings = swap_(moFileHeader_->offsetOriginalStrings);
moFileHeader_->offsetTranslatedStrings = swap_(moFileHeader_->offsetTranslatedStrings);
moFileHeader_->hashTableSize = swap_(moFileHeader_->hashTableSize);
moFileHeader_->offsetHashTable = swap_(moFileHeader_->offsetHashTable);
ready_ = true;
return true;
}
GettextMoParser::~GettextMoParser() {
clearData();
}
char* GettextMoParser::charset() const {
if (charset_ || charsetParsed_) return charset_;
if (!moData_) return NULL;
charsetParsed_ = true;
MoOffsetTableItem* translationTable = (MoOffsetTableItem*)(moData_ + moFileHeader_->offsetTranslatedStrings);
translationTable->length = swap_(translationTable->length);
translationTable->offset = swap_(translationTable->offset);
char* infoBuffer = (char*)(moData_ + translationTable->offset);
std::string info(infoBuffer);
size_t contentTypePos = info.find("Content-Type: text/plain; charset=");
if (contentTypePos == info.npos) return NULL;
size_t stringStart = contentTypePos + 34; // strlen("Content-Type: text/plain; charset=")
size_t stringEnd = info.find('\n', stringStart);
if (stringEnd == info.npos) return NULL;
int charsetLength = stringEnd - stringStart;
if (charsetLength == 0) return NULL;
charset_ = new char[charsetLength + 1];
info.copy(charset_, charsetLength, stringStart);
charset_[charsetLength] = '\0';
if (strcmp(charset_, "CHARSET") == 0) {
delete[] charset_;
charset_ = NULL;
}
// To lowercase
for(int i = 0; i < (int)strlen(charset_); ++i) charset_[i] = tolower(charset_[i]);
return charset_;
}
GettextMessage* GettextMoParser::getTranslation(std::string originalString, int originalLength) {
if (originalLength <= 0) return NULL;
// Check if the string has already been looked up, in which case it is in the messages_
// vector. If found, return it and exit now.
for (int i = 0; i < (int)messages_.size(); i++) {
TranslatedMessage* message = messages_.at(i);
if (strcmp(originalString.c_str(), message->original->string.c_str()) == 0) {
return message->translated;
}
}
// Look for the original message
MoOffsetTableItem* originalTable = (MoOffsetTableItem*)(moData_ + moFileHeader_->offsetOriginalStrings);
originalTable->length = swap_(originalTable->length);
originalTable->offset = swap_(originalTable->offset);
int stringIndex;
bool found = false;
for (stringIndex = 0; stringIndex < moFileHeader_->numStrings; stringIndex++) {
std::string currentString(moData_ + originalTable->offset);
if (strcmp(currentString.c_str(), originalString.c_str()) == 0) {
found = true;
break;
}
originalTable++;
originalTable->length = swap_(originalTable->length);
originalTable->offset = swap_(originalTable->offset);
}
TranslatedMessage* message = new TranslatedMessage();
GettextMessage* mOriginal = new GettextMessage();
mOriginal->length = originalTable->length;
mOriginal->string = originalString;
message->original = mOriginal;
if (!found) {
// Couldn't find orignal string
messages_.push_back(message);
message->translated = NULL;
return NULL;
}
// At this point, stringIndex is the index of the message and originalTable points to
// the original message data.
// Get the translated string and build and the output message structure
MoOffsetTableItem* translationTable = (MoOffsetTableItem*)(moData_ + moFileHeader_->offsetTranslatedStrings);
translationTable += stringIndex;
translationTable->length = swap_(translationTable->length);
translationTable->offset = swap_(translationTable->offset);
std::string translatedString(moData_ + translationTable->offset);
GettextMessage* mTranslated = new GettextMessage();
mTranslated->length = translationTable->length;
mTranslated->string = translatedString;
message->translated = mTranslated;
messages_.push_back(message);
return message->translated;
}
| gpl-3.0 |
RadioCanut/site-radiocanut | plugins-dist/sites/lang/paquet-sites_fa.php | 522 | <?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de https://trad.spip.net/tradlang_module/paquet-sites?lang_cible=fa
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// S
'sites_description' => 'سايتها و مشتركسازيها در اسپسپ (خصوصي و همگاني)',
'sites_slogan' => 'مديريت سايتها و مشتركسازي در اسپيپ'
);
| gpl-3.0 |
seriousteam/azphplib | server/php/echo.php | 117 | <?php
header('Content-type: text/plain');
stream_copy_to_stream(fopen('php://input','r'), fopen('php://output','w')); | gpl-3.0 |
applifireAlgo/HR | hrproject/src/main/webapp/app/hrproject/shared/demo/viewmodel/location/StateViewModel.js | 207 | Ext.define('Hrproject.hrproject.shared.demo.viewmodel.location.StateViewModel', {
"extend": "Ext.app.ViewModel",
"alias": "viewmodel.StateViewModel",
"model": "StateModel",
"data": {}
}); | gpl-3.0 |
Traderain/Wolven-kit | CP77.CR2W/Types/cp77/gamedataDistrict_Record.cs | 248 | using CP77.CR2W.Reflection;
namespace CP77.CR2W.Types
{
[REDMeta]
public class gamedataDistrict_Record : gamedataTweakDBRecord
{
public gamedataDistrict_Record(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| gpl-3.0 |
LEPTON-project/LEPTON_2 | upload/modules/initial_page/classes/class.init_page.php | 8635 | <?php
/**
*
* @module initial_page
* @author LEPTON project
* @copyright 2010-2018 LEPTON project
* @link https://lepton-cms.org
* @license copyright, all rights reserved
* @license_terms please see info.php of this module
*
*/
// include class.secure.php to protect this file and the whole CMS!
if (defined('LEPTON_PATH')) {
include(LEPTON_PATH.'/framework/class.secure.php');
} else {
$oneback = "../";
$root = $oneback;
$level = 1;
while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) {
$root .= $oneback;
$level += 1;
}
if (file_exists($root.'/framework/class.secure.php')) {
include($root.'/framework/class.secure.php');
} else {
trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
}
}
// end include class.secure.php
class class_init_page
{
private $db = NULL;
private $table = "mod_initial_page";
private $backend_pages = array ();
public function __construct( &$db_ref=NULL, $aUser_id=NULL, $aPath_ref= NULL ) {
global $MENU;
if(NULL === $db_ref) {
$db_ref = LEPTON_database::getInstance();
}
$this->db = $db_ref;
$this->backend_pages = array (
'Start' => 'start/index.php',
$MENU['ADDON'] => 'addons/index.php',
$MENU['ADMINTOOLS'] => 'admintools/index.php',
$MENU['GROUPS'] => 'groups/index.php',
$MENU['LANGUAGES'] => 'languages/indes.php',
$MENU['MEDIA'] => 'media/index.php',
$MENU['MODULES'] => 'modules/index.php',
$MENU['PAGES'] => 'pages/index.php',
$MENU['PREFERENCES'] => 'preferences/index.php',
$MENU['SETTINGS'] => 'settings/index.php',
$MENU['TEMPLATES'] => 'templates/index.php',
$MENU['USERS'] => 'users/index.php'
);
$this->table = TABLE_PREFIX.$this->table;
if ( ($aUser_id != NULL) && ($aPath_ref != NULL) ) {
$this->__test_user($aUser_id, $aPath_ref);
} else {
$this->___U();
}
}
public function __destruct() {
}
public function set_db (&$db_ref = NULL ) {
$this->db = $db_ref;
}
public function get_backend_pages_select($name="init_page_select", $selected = "") {
global $MENU;
$values = array();
/**
* first: add pages ...
*
*/
require_once( LEPTON_PATH."/framework/functions/function.page_tree.php" );
$all_pages = array();
page_tree(0, $all_pages);
$temp_storage = array();
$this->__get_pagetree_menulevel( $all_pages, $temp_storage);
foreach($temp_storage as $key => $value) $values[ $MENU['PAGES'] ][ $key ] = $value;
/**
* second: add tools
*
*/
$temp = $this->db->query("SELECT `name`,`directory` from `".TABLE_PREFIX."addons` where `function`='tool' order by `name`");
if ($temp) {
while( false != ($data = $temp->fetchRow() ) ) {
$values[ $MENU['ADMINTOOLS'] ][ $data['name'] ] = "admintools/tool.php?tool=".$data['directory'];
}
}
/**
* At last the backend-pages
*
*/
$values['Backend'] = &$this->backend_pages;
$options = array(
'name' => $name,
'class' => "init_page_select"
);
return $this->__build_select($options, $values, $selected);
}
private function __build_select(&$options, &$values, &$selected) {
$s = "<select ".$this->__build_args($options).">\n";
foreach( $values as $theme=>$sublist ) {
$s .= "<optgroup label='".$theme."'>";
foreach($sublist as $item=>$val) {
$sel = ($val == $selected) ? " selected='selected'" : "";
$s .= "<option value='".$val."'".$sel.">".$item."</option>\n";
}
$s .= "</optgroup>";
}
$s.= "</select>\n";
return $s;
}
private function __build_args(&$aArgs) {
$s = "";
foreach($aArgs as $name=>$value) $s .= " ".$name."='".$value."'";
return $s;
}
public function get_user_info( &$aUserId=0 ) {
$aUser = array();
$this->db->execute_query(
"SELECT `init_page`, `page_param` from `".$this->table."` where `user_id`='".$aUserId."'",
true,
$aUser,
false
);
if (count($aUser) == 0)
{
if($aUserId > 0)
{
$this->db->simple_query("INSERT into `".$this->table."` (`user_id`, `init_page`,`page_param`) VALUES ('".$aUserId."', 'start/index.php', '')");
}
return array('init_page' => "start/index.php", 'page_param' => '') ;
} else {
return $aUser;
}
return NULL;
}
public function update_user(&$aId, &$aValue, &$aParam = -1) {
/**
* M.f.i. Aldus: - 1 [-] does the params make sence at all? E.g. as for a internal page only the section makes sense,
* but for a tool-page we're in the need to get more, e.g. details about the correct params.
* - 2 [+] if the aParam parameter is not set - we'll ignore it.
*/
$temp_param = ($aParam == -1) ? "" : ", `page_param`='".$aParam."' " ;
$q = "UPDATE `".$this->table."` set `init_page`='".$aValue."'".$temp_param." where `user_id`='".$aId."'";
$this->db->query( $q ) ;
}
private function __test_user( $aID, $path_ref ) {
$info = $this->get_user_info( $aID );
$path = ADMIN_URL."/".$info['init_page'];
if (( $path <> $path_ref ) && ($info['init_page'] != "start/index.php" ) && ($info['init_page'] != "") ) {
if (strlen($info['page_param']) > 0) $path .= $info['page_param'];
$this->__test_leptoken( $path );
header('Location: '.$path );
die();
}
}
private function __test_leptoken( &$aURL ) {
if (isset($_GET['leptoken'])) {
$temp_test = explode("?", $aURL );
$aURL .= (count($temp_test) == 1) ? "?" : "&";
$aURL .= "leptoken=".$_GET['leptoken'];
}
}
public function get_single_user_select (
$aUserId,
$aName,
$selected="",
&$options=array(
'backend_pages'=>true,
'tools' => true,
'pages' => true
)
) {
global $MENU;
$values = Array();
if (array_key_exists('backend_pages', $options) && ($options['backend_pages'] == true))
$values['Backend'] = $this->backend_pages;
/**
* Add tools
*
*/
if (array_key_exists('tools', $options) && ($options['tools'] == true)) {
$temp = $this->db->query("SELECT `name`,`directory` from `".TABLE_PREFIX."addons` where `function`='tool' order by `name`");
if ($temp) {
while( false != ($data = $temp->fetchRow() ) ) {
$values[ $MENU['ADMINTOOLS'] ][ $data['name'] ] = "admintools/tool.php?tool=".$data['directory'];
}
}
}
/**
* Add pages
*
*/
if (array_key_exists('pages', $options) && ($options['pages'] == true)) {
require_once( LEPTON_PATH."/framework/functions/function.page_tree.php" );
$all_pages = array();
page_tree(0, $all_pages);
$temp_storage = array();
$this->__get_pagetree_menulevel( $all_pages, $temp_storage);
foreach($temp_storage as $key => $value) $values[ $MENU['PAGES'] ][ $key ] = $value;
}
$options = array(
'name' => $aName,
'class' => "init_page_select"
);
return $this->__build_select($options, $values, $selected);
}
/**
* Internal private function for the correct displax of the page(-tree)
*
* @param array Array within the pages. (Pass by reference)
* @param array A storage array for the result. (Pass by Reference)
* @param int Counter for the recursion deep, correspondence with the menu-level of the page(-s)
*
*/
private function __get_pagetree_menulevel( &$all, &$storage = array(), $deep = 0 ){
// Menu-data is empty, nothing to do
if(count($all) == 0) return false;
// Recursions are more than 50 ... break
if($deep > 50) return false;
// Build the 'select-(menu)title prefix
$prefix = "";
for($i=0;$i<$deep; $i++) $prefix .= "-";
if($deep > 0) $prefix .= " ";
foreach($all as $ref) {
$storage[ $prefix.$ref['page_title'] ] = "pages/modify.php?page_id=".$ref['page_id'];
// Recursive call for the subpages
$this->__get_pagetree_menulevel( $ref['subpages'], $storage, $deep+1 );
}
return true;
}
/**
* Protected function to test the users and delete entries for
* not existing ones.
*
*/
protected function ___U () {
$q="SELECT `user_id` from `".TABLE_PREFIX."users` order by `user_id`";
$r= $this->db->query( $q );
if ($r) {
$ids = array();
while(false !== ($data = $r->fetchRow())) {
$ids[] = $data['user_id'];
}
$q = "DELETE from `".TABLE_PREFIX."mod_initial_page` where `user_id` not in (".implode (",",$ids).")";
$this->db->query( $q );
}
}
public function get_language() {
$lang = (dirname(__FILE__))."/../languages/". LANGUAGE .".php";
require_once ( !file_exists($lang) ? (dirname(__FILE__))."/../languages/EN.php" : $lang );
return $MOD_INITIAL_PAGE;
}
}
?> | gpl-3.0 |
gmqz/proinged | src/CommonBundle/Controller/TipoDocumentoController.php | 6135 | <?php
namespace CommonBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use CommonBundle\Form\TipoDocumentoType;
use CommonBundle\Entity\TipoDocumento;
/**
* TipoDocumento controller.
*
* @Route("/system/tipodocumento")
*/
class TipoDocumentoController extends Controller
{
/**
* @Route("/list", name="tipodocumento_list")
* @Template()
* @Security("has_role('ROLE_ADMIN')")
*/
public function listAction(Request $request)
{
return array();
}
/**
* @Route("/list/datatable", name="tipodocumento_list_datatable")
* @Security("has_role('ROLE_ADMIN')")
*/
public function listDataTableAction(Request $request)
{
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$filter = $em->getRepository('CommonBundle:TipoDocumento')->datatable($request->request);
$tipoDocumentos = array();
foreach($filter['rows'] as $tipoDocumento)
{
$tipoDocumentos[] = array(
'id' => $tipoDocumento->getId(),
'name' => $tipoDocumento->getNombre(),
'isActive' => $tipoDocumento->getIsActive(),
);
}
$data=array(
"draw"=> $request->request->get('draw'),
"recordsTotal"=> $filter['total'],
"recordsFiltered"=> $filter['filtered'],
"data"=> $tipoDocumentos
);
return new JsonResponse($data);
}
/**
* @Route("/{tipoDocumento}/edit", name="tipodocumento_edit", defaults={"tipoDocumento":"__00__"})
* @Security("has_role('ROLE_ADMIN')")
* @Template("CommonBundle:TipoDocumento:edit.html.twig")
*/
public function editAction(Request $request,TipoDocumento $tipoDocumento)
{
$form = $this->createCreateForm($tipoDocumento);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$em = $this->getDoctrine()->getManager();
$tipoDocumento->setUpdatedBy($this->getUser());
try{
$em->flush();
return new JsonResponse(array('resultado' => 0, 'mensaje' => 'Tipo Documento modificado con éxito'));
}catch(\Exception $e ){
return new JsonResponse(array('resultado' => 1, 'mensaje' => 'Ya existe un Tipo Documento con ese nombre'));
}
}
return array(
'entity' => $tipoDocumento,
'form' => $form->createView(),
);
}
/**
* @Route("/new", name="tipodocumento_new")
* @Security("has_role('ROLE_ADMIN')")
* @Template("CommonBundle:TipoDocumento:new.html.twig")
*/
public function newAction(Request $request)
{
$entity = new TipoDocumento();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$em = $this->getDoctrine()->getManager();
$entity->setCreatedBy($this->getUser());
$em->persist($entity);
try{
$em->flush();
return new JsonResponse(array('resultado' => 0, 'mensaje' => 'Tipo Documento creado con éxito'));
}
catch(\Exception $e ){
return new JsonResponse(array('resultado' => 1, 'mensaje' => 'Ya existe un Tipo Documento con ese nombre'));
}
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* @Route("/{tipoDocumento}/delete", name="tipodocumento_delete", defaults={"tipoDocumento":"__00__"})
* @Security("has_role('ROLE_ADMIN')")
* @Template("CommonBundle:TipoDocumento:delete.html.twig")
*/
public function deleteAction(Request $request,TipoDocumento $tipoDocumento)
{
$form = $this->createDeleteForm($tipoDocumento);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->remove($tipoDocumento);
try{
$em->flush();
return new JsonResponse(array('resultado' => 0, 'mensaje' => 'Tipo Documento eliminado con éxito'));
}
catch(\Exception $e ){
return new JsonResponse(array('resultado' => 1, 'mensaje' => 'No pudo ser eliminado el Tipo Documento verifique que no se encuentre en uso'));
}
}
return array(
'entity' => $tipoDocumento,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a TipoDocumento entity.
*
* @param TipoDocumento $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(TipoDocumento $entity)
{
$form = $this->createForm(TipoDocumentoType::class, $entity);
return $form;
}
/**
* Creates a form to delete a tipoDocumento entity.
*
* @param $tipoDocumento The tipoDocumento entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(TipoDocumento $tipoDocumento)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('tipodocumento_delete', array('id' => $tipoDocumento->getId())))
->setMethod('POST')
->getForm()
;
}
} | gpl-3.0 |
craftercms/studio2-ui | static-assets/components/cstudio-templates/approve.js | 1912 | /*
* Copyright (C) 2007-2020 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* 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/>.
*/
/**
* File: delete.js
* Component ID: templateholder-delete
* @author: Roy Art
* @date: 10.01.2011
**/
(function () {
CStudioAuthoring.register('TemplateHolder.Approve', {
ITEM_ROW: [
'<tr>',
/**/ '<td class="text-center small"><input type="checkbox" class="item-checkbox" data-item-id="{uri}" checked/></td>',
/**/ '<td class="name large">',
/****/ '<div class="in">',
/******/ '<span id="{index}" class="toggleDependencies ttOpen parent-div-widget" style="margin-right:17px; margin-bottom: -2px; float: left;" data-loaded="false" data-path="{uri}"></span>',
/******/ '<span style="overflow:hidden; display: block;">{internalName} {uri}</span></div>',
/**/ '</td>',
/**/ '<td class="text-right schedule medium">{scheduledDate}</td>',
'</tr>'
].join(''),
SUBITEM_ROW: [
'<tr class="{index}" style="display:none;">',
/**/ '<td style="width:5%;"></td>',
/**/ '<td class="text-center small" style="padding-left: 25px;width: 5%;"></td>',
/**/ '<td class="name large"><div class="in">{uri}</div></div></td>',
'</tr>'
].join('')
});
CStudioAuthoring.Env.ModuleMap.map('template-approve', CStudioAuthoring.TemplateHolder.Approve);
})();
| gpl-3.0 |
foobla/obHelpDesk | admin/controllers/reports.php | 3970 | <?php
/**
* @package $Id: reports.php 23 2013-08-15 10:15:43Z phonglq $
* @author foobla.com
* @copyright 2007-2014 foobla.com. All rights reserved.
* @license GNU/GPL.
*/
// no direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.controller');
class obHelpDeskControllerReports extends obController{
function __construct(){
parent::__construct();
$this->registerTask( 'export', 'exportTickets');
}
function display($cachable = false, $urlparams = false)
{
$document = JFactory::getDocument();
$vType = $document->getType();
$vName = JRequest::getVar('view', 'reports');
$vLayout = JRequest::getVar('report', 'default');
$view = $this->getView($vName, $vType);
$view->setLayout($vLayout);
$mName = 'reports';
if ($model = $this->getModel($mName)) {
$view->setModel($model, true);
}
$view->display();
}
function export(){
$filter_department = JRequest::getVar('department_id');
$filter_staff = JRequest::getVar('staff_id');
$filter_from = JRequest::getVar('filter_from','');
$filter_to = JRequest::getVar('filter_to','');
$type = JRequest::getVar('export_type', 'excel');
if($type == 'excel') $ext = 'xls';
else $ext = $type;
$where = array();
if(count($filter_department) && $filter_department[0]) {
$imp_dep = implode(',', $filter_department);
$where[] = " i.department_id IN (".$imp_dep.")";
}
if(count($filter_staff) && $filter_staff[0]) {
$imp_staff = implode(',', $filter_staff);
$where[] = " i.user_id IN (".$imp_staff.")";
}
if($filter_from) {
$from = JFactory::getDate("$filter_from")->toSql();
$where[] = "i.created >= '".$from."'";
}
if($filter_staff) {
$to = JFactory::getDate("$filter_from")->toSql();
$where[] = "i.created <= '".$to."'";
}
$str_where = implode(' AND ', $where);
$db = JFactory::getDbo();
$query = " SELECT i.*, u.name as name, us.name as usname, CONCAT_WS('-', d.`prefix`, i.`id`) as dcode, d.title as dname"
." FROM `#__obhelpdesk3_tickets` AS i "
." LEFT JOIN `#__users` as u ON i.customer_id = u.id"
." LEFT JOIN `#__users` as us ON i.staff = us.id"
." LEFT JOIN `#__obhelpdesk3_departments` as d ON i.departmentid = d.id"
." WHERE ". $str_where
;
$db->setQuery($query);
$rows = $db->loadObjectList();
$content = "ID"." "."[Code]Subject"." "."Customer"." "."Staff"." "."Department"." "
."Spent Time (min)"." "."Priority"." "."Status"." "."Submitted Date"."\n";
foreach ($rows as $row) {
/* $query_spent_time = "SELECT SUM(ticket_time) as spent_time FROM `#__obhelpdesk3_messages` WHERE `ticket_id`=".$row->id;
$db->setQuery($query_spent_time);
$sum = $db->loadResult(); */
$content .= $row->id." ";
$content .= "[".$row->dcode."] ".$row->subject." ";
$content .= $row->usname." ";
$content .= $row->name." ";
$content .= $row->dname." ";
// $content .= $sum." ";
$content .= $row->priority." ";
$content .= $row->status." ";
$content .= JFactory::getDate($row->created)->format('Y-m-d')." ";
$content .= "\n";
}
$content = str_replace("\r", "", $content);
// do export tickets
$mimeType ='text/x-'.$ext;
$filename = 'reports_'.JFactory::getDate('now')->format('Ymd').'.'.$ext;
self::CreateDownloadFile($content, $filename, $mimeType);
}
public function CreateDownloadFile( $text, $filename , $mimeType ) {
if ( ini_get( 'zlib.output_compression' ) )
{
/* Required for IE. Content-Disposition may get ignored otherwise. */
ini_set( 'zlib.output_compression', 'Off' );
}
header( 'Content-Disposition: attachment; filename=' . $filename );
header( 'Content-Transfer-Encoding: UTF-8' );
header( 'Content-Type: ' . $mimeType );
/* Make the download non-cacheable. */
header( 'Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT' );
header( 'Cache-control: private' );
header( 'Pragma: private' );
echo $text;
flush();
$app = JFactory::getApplication();
$app->close();
}
} | gpl-3.0 |
awsteiner/bamr | archive_Jul_2020/bamr.py | 1514 | #!/usr/bin/env python3
import ctypes
import platform
# Load ctypes library
if platform.system()=='Darwin':
bamr_lib=ctypes.CDLL('libbamr.dylib')
else:
bamr_lib=ctypes.CDLL('./libbamr.so')
# Type definitions
void_pp=ctypes.POINTER(ctypes.c_void_p)
double_ptr=ctypes.POINTER(ctypes.c_double)
double_ptr_ptr=ctypes.POINTER(double_ptr)
int_ptr=ctypes.POINTER(ctypes.c_int)
# Create the bamr pointers
bamr_lib.create_pointers.argtypes=[void_pp,void_pp]
bamr_class_ptr=ctypes.c_void_p()
model_data_ptr=ctypes.c_void_p()
bamr_ptr=bamr_lib.create_pointers(bamr_class_ptr,model_data_ptr)
# Compute one point
cp_fun=bamr_lib.py_compute_point
cp_fun.argtypes=[ctypes.c_void_p,ctypes.c_void_p,
ctypes.c_int,double_ptr]
point=(ctypes.c_double * 8)()
point[0]=1.0
point[1]=-3.0
point[2]=0.165
point[3]=0.644
point[4]=1.51
point[5]=0.576
point[6]=4.6
point[7]=1.21
cp_fun(bamr_class_ptr,model_data_ptr,8,point)
# Get a column from the table
gmc_fun=bamr_lib.get_mvsr_column
col_name=ctypes.c_char_p(b'gm')
nrows=ctypes.c_int(0)
ptr=double_ptr()
gmc_fun.argtypes=[ctypes.c_void_p,ctypes.c_char_p,
int_ptr,double_ptr_ptr]
gmc_fun.restype=ctypes.c_int
gmc_ret=gmc_fun(model_data_ptr,col_name,ctypes.byref(nrows),
ctypes.byref(ptr))
for i in range(0,nrows.value):
print('%d %7.6e' % (i,ptr[i]))
# Free the memory from the bamr pointers
bamr_lib.destroy_pointers.argtypes=[ctypes.c_void_p,ctypes.c_void_p]
bamr_lib.destroy_pointers(bamr_class_ptr,model_data_ptr)
| gpl-3.0 |
Letat/BeefyBlocks | src/org/chryson/bukkit/beefyblocks/DisplayPreference.java | 1003 | /* BeefyBlocks - A Bukkit plugin to beef-up blocks, making them last longer
* Copyright (C) 2011 Letat
* Copyright (C) 2011 Robert Sargant
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.chryson.bukkit.beefyblocks;
import com.avaje.ebean.annotation.EnumValue;
public enum DisplayPreference {
@EnumValue("A")
ALL,
@EnumValue("S")
SOME,
@EnumValue("N")
NONE,
}
| gpl-3.0 |
lunarpulse/RustC | phrases/src/english/farewells.rs | 61 | pub fn goodbye() -> String {
"Goodbye.".to_string()
}
| gpl-3.0 |
ccem-dev/otus-api | source/otus-activity/src/test/java/org/ccem/otus/service/extraction/factories/SurveyBasicInfoRecordsFactoryTest.java | 3856 | package org.ccem.otus.service.extraction.factories;
import org.ccem.otus.model.FieldCenter;
import org.ccem.otus.model.survey.activity.SurveyActivity;
import org.ccem.otus.model.survey.activity.status.ActivityStatus;
import org.ccem.otus.participant.model.Participant;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.reflect.Whitebox;
@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({ SurveyBasicInfoRecordsFactory.class })
public class SurveyBasicInfoRecordsFactoryTest {
@Mock
private SurveyActivity surveyActivity;
@Test
public void method_getLastInterview_should_return_null_when_interview_dont_have_user() {
PowerMockito.when(surveyActivity.getLastInterview()).thenReturn(null);
Assert.assertNull(SurveyBasicInfoRecordsFactory.getLastInterviewer(surveyActivity));
}
@Test
public void method_getCurrentStatusName_should_return_null_when_dont_exist_status() {
Assert.assertNull(SurveyBasicInfoRecordsFactory.getCurrentStatusName(null));
}
@Test
public void method_getCurrentStatusDate_should_return_null_when_don_exist_current_status() {
Assert.assertNull(SurveyBasicInfoRecordsFactory.getCurrentStatusDate(null));
}
@Test
public void method_getCreationDate_should_return_null_when_dont_exist_creation_status() {
Assert.assertNull(SurveyBasicInfoRecordsFactory.getCreationDate(null));
}
@Test
public void method_getPaperRealizationDate_should_return_null_when_dont_exist_paper_status() {
Assert.assertNull(SurveyBasicInfoRecordsFactory.getPaperRealizationDate(null));
}
@Test
public void method_getPaperInterviewer_should_return_null_when_dont_exist_user_in_status() {
ActivityStatus activityStatus = PowerMockito.mock(ActivityStatus.class);
Mockito.when(activityStatus.getUser()).thenReturn(null);
Assert.assertNull(SurveyBasicInfoRecordsFactory.getPaperInterviewer(activityStatus));
}
@Test
public void method_getLastFinalizedDate_should_return_null_when_finalized_status_dont_exist() {
Assert.assertNull(SurveyBasicInfoRecordsFactory.getLasFinalizationDate(null));
}
@Test
public void method_getRecruitmentNumber_should_return_null_when_recruitmentNumber_dont_exist() {
PowerMockito.when(surveyActivity.getParticipantData()).thenReturn(null);
Assert.assertNull(SurveyBasicInfoRecordsFactory.getRecruitmentNumber(surveyActivity));
}
@Test
public void method_getCategory_should_return_null_when_category_dont_exist() {
PowerMockito.when(surveyActivity.getCategory()).thenReturn(null);
Assert.assertNull(SurveyBasicInfoRecordsFactory.getCategory(surveyActivity));
}
@Test
public void getRecruitmentNumber_method_should_return_null_when_participant_field_center_dont_exist() {
SurveyActivity survey = new SurveyActivity();
FieldCenter fieldCenter = new FieldCenter();
Participant participant = new Participant(123456L);
participant.setFieldCenter(fieldCenter);
Whitebox.setInternalState(survey, "participantData", participant);
Assert.assertNull(SurveyBasicInfoRecordsFactory.getParticipantFieldCenter(surveyActivity));
}
@Test
public void getRecruitmentNumber_method_should_return_field_center_expected() {
SurveyActivity survey = new SurveyActivity();
FieldCenter fieldCenter = new FieldCenter();
fieldCenter.setAcronym("RS");
Participant participant = new Participant(123456L);
participant.setFieldCenter(fieldCenter);
Whitebox.setInternalState(survey, "participantData", participant);
Assert.assertEquals(SurveyBasicInfoRecordsFactory.getParticipantFieldCenter(survey), "RS");
}
}
| gpl-3.0 |
manso/MuGA | src/GUI/SetupSolverFrm.java | 23365 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import GUI.setup.GeneticEventListener;
import GUI.setup.PopulationEventListener;
import GUI.utils.MuGASystem;
import com.evolutionary.Genetic;
import com.evolutionary.operator.GeneticOperator;
import com.evolutionary.population.SimplePopulation;
import com.evolutionary.report.statistics.AbstractStatistics;
import com.evolutionary.solver.EAsolver;
import com.evolutionary.solverUtils.FileSolver;
import com.evolutionary.solver.MuGA;
import com.evolutionary.stopCriteria.StopCriteria;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author zulu
*/
public class SetupSolverFrm extends javax.swing.JFrame {
EAsolver solver;
/**
* Creates new form SetupSolverFrm
*/
public SetupSolverFrm() {
initComponents();
initMyComponents(new MuGA());
}
/**
* Creates new form SetupSolverFrm
*/
public SetupSolverFrm(EAsolver s) {
initComponents();
initMyComponents(s);
}
public void initMyComponents(EAsolver s) {
solver = s;
solver.InitializeEvolution(false);
loadSolver(solver);
txtPathSimulation.setText(MuGASystem.mugaPath);
setupPop.setPopulation(solver.parents, solver.problem);
//----------------------------------------------------------------------------
//Listener to solver
setupSolver.load(MuGASystem.SOLVER, solver.getClass().getSimpleName());
setupSolver.AddEventListener(new GeneticEventListener() {
@Override
public void onGeneticChange(Genetic source) {
solver = (EAsolver) source;
updateSolverInfo();
}
});
//----------------------------------------------------------------------------
//Listener to StopCriteria
setupStopcriteria.load(MuGASystem.STOP_CRITERIA, solver.stop.getClass().getSimpleName());
setupStopcriteria.AddEventListener(new GeneticEventListener() {
@Override
public void onGeneticChange(Genetic source) {
solver.stop = (StopCriteria) source;
updateSolverInfo();
}
});
//----------------------------------------------------------------------------
//Listener to population
setupSelection.load(MuGASystem.SELECTION, solver.selection.getClass().getSimpleName());
setupPop.AddEventListener(new PopulationEventListener() {
@Override
public void onPopulationChange(SimplePopulation source) {
solver.setParents(source);
updateSolverInfo();
}
});
//----------------------------------------------------------------------------
//Listener to Recombination
setupRecombination.load(MuGASystem.RECOMBINATION, solver.recombination.getClass().getSimpleName());
setupRecombination.AddEventListener(new GeneticEventListener() {
@Override
public void onGeneticChange(Genetic source) {
solver.recombination = (GeneticOperator) source;
updateSolverInfo();
}
});
//----------------------------------------------------------------------------
//Listener to Mutation
setupMutation.load(MuGASystem.MUTATION, solver.mutation.getClass().getSimpleName());
setupRecombination.AddEventListener(new GeneticEventListener() {
@Override
public void onGeneticChange(Genetic source) {
solver.mutation = (GeneticOperator) source;
updateSolverInfo();
}
});
//----------------------------------------------------------------------------
//Listener to Replacement
setupReplacement.load(MuGASystem.REPLACEMENT, solver.replacement.getClass().getSimpleName());
setupReplacement.AddEventListener(new GeneticEventListener() {
@Override
public void onGeneticChange(Genetic source) {
solver.replacement = (GeneticOperator) source;
updateSolverInfo();
}
});
//----------------------------------------------------------------------------
//Listener to Rescaling
setupRescaling.load(MuGASystem.RESCALING, solver.rescaling.getClass().getSimpleName());
setupRescaling.AddEventListener(new GeneticEventListener() {
@Override
public void onGeneticChange(Genetic source) {
solver.rescaling = (GeneticOperator) source;
updateSolverInfo();
}
});
//----------------------------------------------------------------------------
setupStatistics.load(MuGASystem.STATISTICS, "");
}
public void updateSolverInfo() {
txtEAsolver.setText(FileSolver.getConfigurationInfo(solver));
txtEAsolver.setCaretPosition(0);
}
private void loadSolver(EAsolver s) {
solver = s;
txtEAsolver.setText(FileSolver.getConfigurationInfo(solver));
txtEAsolver.setCaretPosition(0);
setupSolver.setSelected(solver.getClass().getSimpleName());
setupStopcriteria.setSelected(solver.stop.getClass().getSimpleName());
setupSelection.setSelected(solver.selection.getClass().getSimpleName());
setupRecombination.setSelected(solver.recombination.getClass().getSimpleName());
setupMutation.setSelected(solver.mutation.getClass().getSimpleName());
setupReplacement.setSelected(solver.replacement.getClass().getSimpleName());
setupRescaling.setSelected(solver.rescaling.getClass().getSimpleName());
setupPop.setPopulation(solver.parents,solver.problem);
loadStatistics();
}
public void loadStatistics() {
DefaultListModel model = new DefaultListModel();
ArrayList<AbstractStatistics> stats = solver.report.getStatistics();
for (AbstractStatistics stat : stats) {
model.addElement(stat);
}
lstStatiscs.setModel(model);
}
/**
* 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() {
jTabbedPane2 = new javax.swing.JTabbedPane();
tbSimulation = new javax.swing.JPanel();
pnSaveLoad = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtPathSimulation = new javax.swing.JTextField();
btSolverSaveSimulation = new javax.swing.JButton();
btSolverOpen1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
txtEAsolver = new javax.swing.JTextArea();
pnSolver = new javax.swing.JPanel();
setupSolver = new GUI.setup.GeneticParameter();
setupStopcriteria = new GUI.setup.GeneticParameter();
setupPop = new GUI.setup.PopulationParameters();
setupSelection = new GUI.setup.GeneticParameter();
setupRecombination = new GUI.setup.GeneticParameter();
setupMutation = new GUI.setup.GeneticParameter();
setupReplacement = new GUI.setup.GeneticParameter();
setupRescaling = new GUI.setup.GeneticParameter();
pnStatistics = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
lstStatiscs = new javax.swing.JList<>();
setupStatistics = new GUI.setup.GeneticParameter();
btAddStatistic = new javax.swing.JButton();
btRemoveStats = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
});
jTabbedPane2.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
tbSimulation.setLayout(new java.awt.BorderLayout());
jLabel1.setText("File name");
txtPathSimulation.setText("jTextField1");
btSolverSaveSimulation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/File_Save-32.png"))); // NOI18N
btSolverSaveSimulation.setText("Save");
btSolverSaveSimulation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btSolverSaveSimulationActionPerformed(evt);
}
});
btSolverOpen1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/File_Open-32.png"))); // NOI18N
btSolverOpen1.setText("open");
btSolverOpen1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btSolverOpen1ActionPerformed(evt);
}
});
javax.swing.GroupLayout pnSaveLoadLayout = new javax.swing.GroupLayout(pnSaveLoad);
pnSaveLoad.setLayout(pnSaveLoadLayout);
pnSaveLoadLayout.setHorizontalGroup(
pnSaveLoadLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnSaveLoadLayout.createSequentialGroup()
.addComponent(btSolverSaveSimulation)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btSolverOpen1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtPathSimulation, javax.swing.GroupLayout.DEFAULT_SIZE, 539, Short.MAX_VALUE))
);
pnSaveLoadLayout.setVerticalGroup(
pnSaveLoadLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnSaveLoadLayout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(pnSaveLoadLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtPathSimulation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btSolverSaveSimulation)
.addComponent(btSolverOpen1)))
);
tbSimulation.add(pnSaveLoad, java.awt.BorderLayout.PAGE_START);
txtEAsolver.setColumns(20);
txtEAsolver.setFont(new java.awt.Font("Courier New", 0, 14)); // NOI18N
txtEAsolver.setRows(5);
jScrollPane1.setViewportView(txtEAsolver);
tbSimulation.add(jScrollPane1, java.awt.BorderLayout.CENTER);
jTabbedPane2.addTab("Simulation", new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/Setup_Solver-16.png")), tbSimulation); // NOI18N
setupSolver.setBorder(javax.swing.BorderFactory.createTitledBorder("Solver Type"));
setupStopcriteria.setBorder(javax.swing.BorderFactory.createTitledBorder("Stop Criteria"));
javax.swing.GroupLayout pnSolverLayout = new javax.swing.GroupLayout(pnSolver);
pnSolver.setLayout(pnSolverLayout);
pnSolverLayout.setHorizontalGroup(
pnSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(setupSolver, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(setupStopcriteria, javax.swing.GroupLayout.DEFAULT_SIZE, 811, Short.MAX_VALUE)
);
pnSolverLayout.setVerticalGroup(
pnSolverLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnSolverLayout.createSequentialGroup()
.addComponent(setupStopcriteria, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(setupSolver, javax.swing.GroupLayout.DEFAULT_SIZE, 282, Short.MAX_VALUE))
);
jTabbedPane2.addTab("Solver", new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/Setup-16.png")), pnSolver); // NOI18N
jTabbedPane2.addTab("Problem", new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/Population-16.png")), setupPop); // NOI18N
jTabbedPane2.addTab("Selection", new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/DNA-16.png")), setupSelection); // NOI18N
jTabbedPane2.addTab("Recombination", new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/DNA-16.png")), setupRecombination); // NOI18N
jTabbedPane2.addTab("Mutation", new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/DNA-16.png")), setupMutation); // NOI18N
jTabbedPane2.addTab("Replacement", new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/DNA-16.png")), setupReplacement); // NOI18N
jTabbedPane2.addTab("Rescaling", new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/DNA-16.png")), setupRescaling); // NOI18N
lstStatiscs.setBorder(javax.swing.BorderFactory.createTitledBorder("Selected Statistics"));
lstStatiscs.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(lstStatiscs);
btAddStatistic.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/ArrowLeft-32.png"))); // NOI18N
btAddStatistic.setText("Select");
btAddStatistic.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btAddStatisticActionPerformed(evt);
}
});
btRemoveStats.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/Delete-32.png"))); // NOI18N
btRemoveStats.setText("Remove");
btRemoveStats.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btRemoveStatsActionPerformed(evt);
}
});
javax.swing.GroupLayout pnStatisticsLayout = new javax.swing.GroupLayout(pnStatistics);
pnStatistics.setLayout(pnStatisticsLayout);
pnStatisticsLayout.setHorizontalGroup(
pnStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnStatisticsLayout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btAddStatistic)
.addComponent(btRemoveStats))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(setupStatistics, javax.swing.GroupLayout.DEFAULT_SIZE, 519, Short.MAX_VALUE))
);
pnStatisticsLayout.setVerticalGroup(
pnStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnStatisticsLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnStatisticsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnStatisticsLayout.createSequentialGroup()
.addComponent(btAddStatistic)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btRemoveStats)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane2)
.addComponent(setupStatistics, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE)))
);
jTabbedPane2.addTab("Statistics", new javax.swing.ImageIcon(getClass().getResource("/GUI/icons/Charts-16.png")), pnStatistics); // NOI18N
getContentPane().add(jTabbedPane2, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btSolverSaveSimulationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSolverSaveSimulationActionPerformed
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(txtPathSimulation.getText()));
file.setFileFilter(new FileNameExtensionFilter("Muga Simulation Files", FileSolver.FILE_EXTENSION));
int returnVal = file.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
PrintWriter out = null;
try {
String fileName = file.getSelectedFile().getPath();
//insert file Extension if needed
if (!fileName.endsWith(FileSolver.FILE_EXTENSION)) {
fileName = fileName + "." + FileSolver.FILE_EXTENSION;
}
out = new PrintWriter(fileName);
out.println(txtEAsolver.getText());
txtPathSimulation.setText(fileName);
} catch (FileNotFoundException ex) {
Logger.getLogger(SetupSolverFrm.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "ERROR : " + ex.getMessage());
} finally {
out.close();
}
}
}//GEN-LAST:event_btSolverSaveSimulationActionPerformed
private void btSolverOpen1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSolverOpen1ActionPerformed
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(txtPathSimulation.getText()));
file.setFileFilter(new FileNameExtensionFilter("Muga Simulation Files", FileSolver.FILE_EXTENSION));
int returnVal = file.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
loadSolver(FileSolver.load(file.getSelectedFile().getPath()));
JOptionPane.showMessageDialog(this, "Simulation loaded");
txtPathSimulation.setText(file.getSelectedFile().getPath());
}
}//GEN-LAST:event_btSolverOpen1ActionPerformed
private void btAddStatisticActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddStatisticActionPerformed
solver.report.addStatistic(setupStatistics.genetic.getClass().getCanonicalName());
loadStatistics();
updateSolverInfo();
}//GEN-LAST:event_btAddStatisticActionPerformed
private void btRemoveStatsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRemoveStatsActionPerformed
if (lstStatiscs.getSelectedIndex() >= 0) {
solver.report.removeStatistic(lstStatiscs.getSelectedIndex());
}
loadStatistics();
updateSolverInfo();
}//GEN-LAST:event_btRemoveStatsActionPerformed
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
// TODO add your handling code here:
}//GEN-LAST:event_formWindowClosed
/**
* @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(SetupSolverFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SetupSolverFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SetupSolverFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SetupSolverFrm.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 SetupSolverFrm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btAddStatistic;
private javax.swing.JButton btRemoveStats;
private javax.swing.JButton btSolverOpen1;
private javax.swing.JButton btSolverSaveSimulation;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTabbedPane jTabbedPane2;
private javax.swing.JList<String> lstStatiscs;
private javax.swing.JPanel pnSaveLoad;
private javax.swing.JPanel pnSolver;
private javax.swing.JPanel pnStatistics;
private GUI.setup.GeneticParameter setupMutation;
private GUI.setup.PopulationParameters setupPop;
private GUI.setup.GeneticParameter setupRecombination;
private GUI.setup.GeneticParameter setupReplacement;
private GUI.setup.GeneticParameter setupRescaling;
private GUI.setup.GeneticParameter setupSelection;
private GUI.setup.GeneticParameter setupSolver;
private GUI.setup.GeneticParameter setupStatistics;
private GUI.setup.GeneticParameter setupStopcriteria;
private javax.swing.JPanel tbSimulation;
private javax.swing.JTextArea txtEAsolver;
private javax.swing.JTextField txtPathSimulation;
// End of variables declaration//GEN-END:variables
}
| gpl-3.0 |
DvdByrn/website-nonprofit-gw | files/content/plugins/bb-plugin/classes/class-fl-builder-service-constant-contact.php | 9819 | <?php
/**
* Helper class for the Constant Contact API.
*
* @since 1.5.4
*/
final class FLBuilderServiceConstantContact extends FLBuilderService {
/**
* The ID for this service.
*
* @since 1.5.4
* @var string $id
*/
public $id = 'constant-contact';
/**
* The api url for this service.
*
* @since 1.5.4
* @var string $api_url
*/
public $api_url = 'https://api.constantcontact.com/v2/';
/**
* Test the API connection.
*
* @since 1.5.4
* @param array $fields {
* @type string $api_key A valid API key.
* @type string $access_token A valid access token.
* }
* @return array{
* @type bool|string $error The error message or false if no error.
* @type array $data An array of data used to make the connection.
* }
*/
public function connect( $fields = array() )
{
$response = array(
'error' => false,
'data' => array()
);
// Make sure we have an API key.
if ( ! isset( $fields['api_key'] ) || empty( $fields['api_key'] ) ) {
$response['error'] = __( 'Error: You must provide an API key.', 'fl-builder' );
}
// Make sure we have an access token.
else if ( ! isset( $fields['access_token'] ) || empty( $fields['access_token'] ) ) {
$response['error'] = __( 'Error: You must provide an access token.', 'fl-builder' );
}
// Try to connect and store the connection data.
else {
$url = $this->api_url . 'lists?api_key=' . $fields['api_key'] . '&access_token=' . $fields['access_token'];
$request = json_decode( wp_remote_retrieve_body( wp_remote_get( $url ) ) );
if ( ! is_array( $request ) || ( isset( $request[0] ) && isset( $request[0]->error_message ) ) ) {
$response['error'] = sprintf( __( 'Error: Could not connect to Constant Contact. %s', 'fl-builder' ), $request[0]->error_message );
}
else {
$response['data'] = array(
'api_key' => $fields['api_key'],
'access_token' => $fields['access_token']
);
}
}
return $response;
}
/**
* Renders the markup for the connection settings.
*
* @since 1.5.4
* @return string The connection settings markup.
*/
public function render_connect_settings()
{
ob_start();
FLBuilder::render_settings_field( 'api_key', array(
'row_class' => 'fl-builder-service-connect-row',
'class' => 'fl-builder-service-connect-input',
'type' => 'text',
'label' => __( 'API Key', 'fl-builder' ),
'help' => __( 'Your Constant Contact API key.', 'fl-builder' ),
'preview' => array(
'type' => 'none'
)
));
FLBuilder::render_settings_field( 'access_token', array(
'row_class' => 'fl-builder-service-connect-row',
'class' => 'fl-builder-service-connect-input',
'type' => 'text',
'label' => __( 'Access Token', 'fl-builder' ),
'help' => __( 'Your Constant Contact access token.', 'fl-builder' ),
'description' => sprintf( __( 'You must register a <a%1$s>Developer Account</a> with Constant Contact to obtain an API key and access token. Please see <a%2$s>Getting an API key</a> for complete instructions.', 'fl-builder' ), ' href="https://constantcontact.mashery.com/member/register" target="_blank"', ' href="https://developer.constantcontact.com/home/api-keys.html" target="_blank"' ),
'preview' => array(
'type' => 'none'
)
));
return ob_get_clean();
}
/**
* Render the markup for service specific fields.
*
* @since 1.5.4
* @param string $account The name of the saved account.
* @param object $settings Saved module settings.
* @return array {
* @type bool|string $error The error message or false if no error.
* @type string $html The field markup.
* }
*/
public function render_fields( $account, $settings )
{
$account_data = $this->get_account_data( $account );
$api_key = $account_data['api_key'];
$access_token = $account_data['access_token'];
$url = $this->api_url . 'lists?api_key=' . $api_key . '&access_token=' . $access_token;
$request = json_decode( wp_remote_retrieve_body( wp_remote_get( $url ) ) );
$response = array(
'error' => false,
'html' => ''
);
if ( ! is_array( $request ) || ( isset( $request[0] ) && isset( $request[0]->error_message ) ) ) {
$response['error'] = sprintf( __( 'Error: Could not connect to Constant Contact. %s', 'fl-builder' ), $request[0]->error_message );
}
else {
$response['html'] = $this->render_list_field( $request, $settings );
}
return $response;
}
/**
* Render markup for the list field.
*
* @since 1.5.4
* @param array $lists List data from the API.
* @param object $settings Saved module settings.
* @return string The markup for the list field.
* @access private
*/
private function render_list_field( $lists, $settings )
{
ob_start();
$options = array( '' => __( 'Choose...', 'fl-builder' ) );
foreach ( $lists as $list ) {
$options[ $list->id ] = $list->name;
}
FLBuilder::render_settings_field( 'list_id', array(
'row_class' => 'fl-builder-service-field-row',
'class' => 'fl-builder-service-list-select',
'type' => 'select',
'label' => _x( 'List', 'An email list from a third party provider.', 'fl-builder' ),
'options' => $options,
'preview' => array(
'type' => 'none'
)
), $settings);
return ob_get_clean();
}
/**
* Subscribe an email address to Constant Contact.
*
* @since 1.5.4
* @param object $settings A module settings object.
* @param string $email The email to subscribe.
* @param string $name Optional. The full name of the person subscribing.
* @return array {
* @type bool|string $error The error message or false if no error.
* }
*/
public function subscribe( $settings, $email, $name = false )
{
$account_data = $this->get_account_data( $settings->service_account );
$response = array( 'error' => false );
if ( ! $account_data ) {
$response['error'] = __( 'There was an error subscribing to Constant Contact. The account is no longer connected.', 'fl-builder' );
}
else {
$api_key = $account_data['api_key'];
$access_token = $account_data['access_token'];
$url = $this->api_url . 'contacts?api_key=' . $api_key . '&access_token=' . $access_token . '&email=' . $email;
$request = wp_remote_get( $url );
$contact = json_decode( wp_remote_retrieve_body( $request ) );
$list_id = $settings->list_id;
// This contact exists.
if ( ! empty( $contact->results ) ) {
$args = array();
$data = $contact->results[0];
// Check if already subscribed to this list.
if ( ! empty( $data->lists ) ) {
// Return early if already added.
foreach ( $data->lists as $key => $list ) {
if ( isset( $list->id ) && $list_id == $list->id ) {
return $response;
}
}
// Add an existing contact to the list.
$new_list = new stdClass;
$new_list->id = $list_id;
$new_list->status = 'ACTIVE';
$data->lists[ count( $data->lists ) ] = $new_list;
}
else {
// Add an existing contact that has no list.
$data->lists = array();
$new_list = new stdClass;
$new_list->id = $list_id;
$new_list->status = 'ACTIVE';
$data->lists[0] = $new_list;
}
$args['body'] = json_encode( $data );
$args['method'] = 'PUT';
$args['headers']['Content-Type'] = 'application/json';
$args['headers']['Content-Length'] = strlen( $args['body'] );
$url = $this->api_url . 'contacts/' . $contact->results[0]->id . '?api_key=' . $api_key . '&access_token=' . $access_token . '&action_by=ACTION_BY_VISITOR';
$update = wp_remote_request( $url, $args );
$res = json_decode( wp_remote_retrieve_body( $update ) );
if ( isset( $res->error_key ) ) {
$response['error'] = sprintf( __( 'There was an error subscribing to Constant Contact. %s', 'fl-builder' ), $res->error_key );
}
}
// Add a new contact.
else {
$args = $data = array();
$data['email_addresses'] = array();
$data['email_addresses'][0]['id'] = $list_id;
$data['email_addresses'][0]['status'] = 'ACTIVE';
$data['email_addresses'][0]['confirm_status'] = 'CONFIRMED';
$data['email_addresses'][0]['email_address'] = $email;
$data['lists'] = array();
$data['lists'][0]['id'] = $list_id;
if ( $name ) {
$names = explode( ' ', $name );
if ( isset( $names[0] ) ) {
$data['first_name'] = $names[0];
}
if ( isset( $names[1] ) ) {
$data['last_name'] = $names[1];
}
}
$args['body'] = json_encode( $data );
$args['headers']['Content-Type'] = 'application/json';
$args['headers']['Content-Length'] = strlen( json_encode( $data ) );
$url = $this->api_url . 'contacts?api_key=' . $api_key . '&access_token=' . $access_token . '&action_by=ACTION_BY_VISITOR';
$create = wp_remote_post( $url, $args );
if ( isset( $create->error_key ) ) {
$response['error'] = sprintf( __( 'There was an error subscribing to Constant Contact. %s', 'fl-builder' ), $create->error_key );
}
}
}
return $response;
}
} | gpl-3.0 |
PuzzlesLab/PuzzlesCon | PuzzlesCon Bronze League/Bronze League IV/D/5867339_kahzheng_D.java | 727 | import java.math.BigInteger;
import java.util.Scanner;
/**
*
* @author KahZheng
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNext()){
int count = s.nextInt();
int sum = 0;
sum += count;
while(count >= 3){
int extra = count / 3;
sum += extra;
count = count % 3 + extra;
}
if(count == 2){
sum ++;
}
System.out.println(sum);
}
}
}
| gpl-3.0 |
skyosev/OpenCart-Overclocked | upload/system/vendor/dompdf/include/table_cell_positioner.cls.php | 717 | <?php
/**
* @package dompdf
* @link http://dompdf.github.com/
* @author Benj Carson <[email protected]>
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
/**
* Positions table cells
*
* @access private
* @package dompdf
*/
class Table_Cell_Positioner extends Positioner {
function __construct(Frame_Decorator $frame) { parent::__construct($frame); }
//........................................................................
function position() {
$table = Table_Frame_Decorator::find_parent_table($this->_frame);
$cellmap = $table->get_cellmap();
$this->_frame->set_position($cellmap->get_frame_position($this->_frame));
}
}
?> | gpl-3.0 |
bioidiap/gridtk | gridtk/tools.py | 10653 | #!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <[email protected]>
# Wed 24 Aug 2011 09:26:46 CEST
"""Functions that replace the shell based utilities for the grid submission and
probing.
"""
# initialize the logging system
import logging
import math
import os
import re
import shlex
logger = logging.getLogger("gridtk")
# Constant regular expressions
QSTAT_FIELD_SEPARATOR = re.compile(":\\s+")
def makedirs_safe(fulldir):
"""Creates a directory if it does not exists. Takes into consideration
concurrent access support. Works like the shell's 'mkdir -p'.
"""
os.makedirs(fulldir, exist_ok=True)
def str_(name):
"""Return the string representation of the given 'name'.
If it is a bytes object, it will be converted into str.
If it is a str object, it will simply be resurned."""
if isinstance(name, bytes) and not isinstance(name, str):
return name.decode("utf8")
else:
return name
def qsub(
command,
queue=None,
cwd=True,
name=None,
deps=[],
stdout="",
stderr="",
env=[],
array=None,
context="grid",
hostname=None,
memfree=None,
hvmem=None,
gpumem=None,
pe_opt=None,
io_big=False,
sge_extra_args="",
):
"""Submits a shell job to a given grid queue
Keyword parameters:
command
The command to be submitted to the grid
queue
A valid queue name or None, to use the default queue
cwd
If the job should change to the current working directory before starting
name
An optional name to set for the job. If not given, defaults to the script
name being launched.
deps
Job ids to which this job will be dependent on
stdout
The standard output directory. If not given, defaults to what qsub has as a
default.
stderr
The standard error directory (if not given, defaults to the stdout
directory).
env
This is a list of extra variables that will be set on the environment
running the command of your choice.
array
If set should be either:
1. a string in the form m[-n[:s]] which indicates the starting range 'm',
the closing range 'n' and the step 's'.
2. an integer value indicating the total number of jobs to be submitted.
This is equivalent ot set the parameter to a string "1-k:1" where "k" is
the passed integer value
3. a tuple that contains either 1, 2 or 3 elements indicating the start,
end and step arguments ("m", "n", "s").
The minimum value for "m" is 1. Giving "0" is an error.
If submitted with this option, the job to be created will be an SGE
parametric job. In this mode SGE does not allow individual control of each
job. The environment variable SGE_TASK_ID will be set on the executing
process automatically by SGE and indicates the unique identifier in the
range for which the current job instance is for.
context
The setshell context in which we should try a 'qsub'. Normally you don't
need to change the default. This variable can also be set to a context
dictionary in which case we just setup using that context instead of
probing for a new one, what can be fast.
memfree
If set, it asks the queue for a node with a minimum amount of memory
Used only if mem is not set
(cf. qsub -l mem_free=<...>)
hvmem
If set, it asks the queue for a node with a minimum amount of memory
Used only if mem is not set
(cf. qsub -l h_vmem=<...>)
gpumem
Applicable only for GPU-based queues. If set, it asks for the GPU queue
with a minimum amount of memory. The amount should not be more than 24.
(cf. qsub -l gpumem=<...>)
hostname
If set, it asks the queue to use only a subset of the available nodes
Symbols: | for OR, & for AND, ! for NOT, etc.
(cf. qsub -l hostname=<...>)
pe_opt
If set, add a -pe option when launching a job (for instance pe_exclusive* 1-)
io_big
If set to true, the io_big flag will be set.
Use this flag if your process will need a lot of Input/Output operations.
sge_extra_args
This is used to send extra argument to SGE. Note that all its arguments are directly
used in `qsub` command. For example, `jman submit -e "-P project_name -l pytorch=true" -- ...` will
be translated to `qsub -P project_name -l pytorch=true -- ...`
Returns the job id assigned to this job (integer)
"""
import six
from bob.extension import rc
scmd = ["qsub"]
prepend = rc.get("gridtk.sge.extra.args.prepend") or ""
sge_extra_args = f"{prepend} {sge_extra_args or ''}"
scmd += shlex.split(sge_extra_args)
if isinstance(queue, six.string_types) and queue not in (
"all.q",
"default",
):
scmd += ["-l", queue]
if memfree:
scmd += ["-l", "mem_free=%s" % memfree]
if hvmem:
scmd += ["-l", "h_vmem=%s" % hvmem]
if gpumem:
scmd += ["-l", "gpumem=%s" % gpumem]
if io_big:
scmd += ["-l", "io_big"]
if hostname:
scmd += ["-l", "hostname=%s" % hostname]
if pe_opt:
scmd += ["-pe"] + pe_opt.split()
if cwd:
scmd += ["-cwd"]
if name:
scmd += ["-N", name]
if deps:
scmd += ["-hold_jid", ",".join(["%d" % k for k in deps])]
if stdout:
if not cwd:
# pivot, temporarily, to home directory
curdir = os.path.realpath(os.curdir)
os.chdir(os.environ["HOME"])
if not os.path.exists(stdout):
makedirs_safe(stdout)
if not cwd:
# go back
os.chdir(os.path.realpath(curdir))
scmd += ["-o", stdout]
if stderr:
if not os.path.exists(stderr):
makedirs_safe(stderr)
scmd += ["-e", stderr]
elif stdout: # just re-use the stdout settings
scmd += ["-e", stdout]
scmd += [
"-terse"
] # simplified job identifiers returned by the command line
for k in env:
scmd += ["-v", k]
if array is not None:
scmd.append("-t")
if isinstance(array, six.string_types):
try:
i = int(array)
scmd.append("1-%d:1" % i)
except ValueError:
# must be complete...
scmd.append("%s" % array)
if isinstance(array, six.integer_types):
scmd.append("1-%d:1" % array)
if isinstance(array, (tuple, list)):
if len(array) < 1 or len(array) > 3:
raise RuntimeError(
"Array tuple should have length between 1 and 3"
)
elif len(array) == 1:
scmd.append("%s" % array[0])
elif len(array) == 2:
scmd.append("%s-%s" % (array[0], array[1]))
elif len(array) == 3:
scmd.append("%s-%s:%s" % (array[0], array[1], array[2]))
if not isinstance(command, (list, tuple)):
command = [command]
scmd += command
logger.debug("Qsub command '%s'", " ".join(scmd))
from .setshell import sexec
jobid = str_(sexec(context, scmd))
return int(jobid.split("\n")[-1].split(".", 1)[0])
def make_shell(shell, command):
"""Returns a single command given a shell and a command to be qsub'ed
Keyword parameters:
shell
The path to the shell to use when submitting the job.
command
The script path to be submitted
Returns the command parameters to be supplied to qsub()
"""
return ("-S", shell) + tuple(command)
def qstat(jobid, context="grid"):
"""Queries status of a given job.
Keyword parameters:
jobid
The job identifier as returned by qsub()
context
The setshell context in which we should try a 'qsub'. Normally you don't
need to change the default. This variable can also be set to a context
dictionary in which case we just setup using that context instead of
probing for a new one, what can be fast.
Returns a dictionary with the specific job properties
"""
scmd = ["qstat", "-j", "%d" % jobid, "-f"]
logger.debug("Qstat command '%s'", " ".join(scmd))
from .setshell import sexec
data = str_(sexec(context, scmd, error_on_nonzero=False))
# some parsing:
retval = {}
for line in data.split("\n"):
s = line.strip()
if s.lower().find("do not exist") != -1:
return {}
if not s or s.find(10 * "=") != -1:
continue
kv = QSTAT_FIELD_SEPARATOR.split(s, 1)
if len(kv) == 2:
retval[kv[0]] = kv[1]
return retval
def qdel(jobid, context="grid"):
"""Halts a given job.
Keyword parameters:
jobid
The job identifier as returned by qsub()
context
The setshell context in which we should try a 'qsub'. Normally you don't
need to change the default. This variable can also be set to a context
dictionary in which case we just setup using that context instead of
probing for a new one, what can be fast.
"""
scmd = ["qdel", "%d" % jobid]
logger.debug("Qdel command '%s'", " ".join(scmd))
from .setshell import sexec
sexec(context, scmd, error_on_nonzero=False)
def get_array_job_slice(total_length):
"""A helper function that let's you chunk a list in an SGE array job.
Use this function like ``a = a[get_array_job_slice(len(a))]`` to only process a chunk
of ``a``.
Parameters
----------
total_length : int
The length of the list that you are trying to slice
Returns
-------
slice
A slice to be used.
Raises
------
NotImplementedError
If "SGE_TASK_FIRST" and "SGE_TASK_STEPSIZE" are not 1.
"""
sge_task_id = os.environ.get("SGE_TASK_ID")
try:
sge_task_id = int(sge_task_id)
except Exception:
return slice(None)
if (
os.environ["SGE_TASK_FIRST"] != "1"
or os.environ["SGE_TASK_STEPSIZE"] != "1"
):
raise NotImplementedError(
"Values other than 1 for SGE_TASK_FIRST and SGE_TASK_STEPSIZE is not supported!"
)
job_id = sge_task_id - 1
number_of_parallel_jobs = int(os.environ["SGE_TASK_LAST"])
number_of_objects_per_job = int(
math.ceil(total_length / number_of_parallel_jobs)
)
start = min(job_id * number_of_objects_per_job, total_length)
end = min((job_id + 1) * number_of_objects_per_job, total_length)
return slice(start, end)
| gpl-3.0 |
OpenDungeons/OpenDungeons-masterserver | get_csv.php | 411 | <?php
include("conf.php");
header( 'Content-Type: text/plain; charset=utf-8' );
$result = $db->query("SELECT * FROM games WHERE status=0 AND last_updated > (UTC_TIMESTAMP() - INTERVAL 1 MINUTE) ORDER BY creator ASC");
while($row = $result->fetch_assoc()){
echo $row['od_version'].";".$row['uuid'].";".$row['creator'].";".$row['ip_address'].";".$row['port'].";".$row['label'].";".$row['descr'].PHP_EOL;
}
?>
| gpl-3.0 |
akc42/football-mobile | client/modules/api.js | 2953 | /**
@licence
Copyright (c) 2020 Alan Chandler, all rights reserved
This file is part of Football Mobile.
Football Mobile 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.
Football Mobile 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 Football Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
import { ApiError, StorageError } from "./events.js";
import global from '../modules/globals.js';
export default async function api(url, params, signal) {
const token = sessionStorage.getItem('token');
const body = params || {};
//make a key of users uid and params, change name as could be overwridden if in params (admin on behalf of someone).
const keyurl = '/api/' + url;
const key = JSON.stringify({ ...body, kuid: global.user.uid }) + '$.' + keyurl ;
if (token !== null) body.token = token;
const options = {
credentials: 'same-origin',
method: 'post',
headers: new Headers({
'content-type': 'application/json'
}),
body: JSON.stringify(body)
};
if (signal) options.signal = signal;
let text;
try {
const response = await window.fetch('/api/' + url, options);
if (!response.ok) {
throw new ApiError(response.status);
}
text = await response.text();
const result = JSON.parse(text);
if (sessionStorage.getItem('setOfflineAge') === null) {
sessionStorage.setItem('setOfflineAge', 'done');
localStorage.setItem('offlineAge', Math.floor(Date.now()/1000)); //in seconds
}
localStorage.setItem(key, text); //save our response in case needed for offline
return result;
} catch (err) {
if (err.type === 'api-error') throw err; //just
if (text !== undefined && text.length > 5) {
//we failed to parse the json - the actual code should be in the text near the end;
throw new ApiError(parseInt(text.substr(-6,3),10));
}
//Assume network Error, See if we can use local storage
const lastStore = localStorage.getItem('offlineAge');
const offlineCacheAge = parseInt(localStorage.getItem('offlineCacheAge'),10) * 3600;
if (lastStore !== null) {
if (parseInt(lastStore,10) + offlineCacheAge > Math.floor(Date.now()/1000) ) {
//cache is still valid, lets see if we have the item
const item = localStorage.getItem(key);
if (item !== null) {
return JSON.parse(item);
}
}
}
// we must not have the item and in date, so throw
throw new StorageError(keyurl);
}
}
| gpl-3.0 |
CroceRossaItaliana/jorvik | base/migrations/0012_allegato_scadenza_popola.py | 951 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.db.models import Q
def forwards_func(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version
Allegato = apps.get_model("base", "Allegato")
db_alias = schema_editor.connection.alias
giorno_migrazione = datetime.datetime(2016, 2, 25)
scadenza = datetime.datetime(2016, 2, 24)
allegati = Allegato.objects.filter(
creazione__lt=giorno_migrazione
)
numero = allegati.count()
print(" => base-0012 ci sono %d allegati senza scadenza per i quali verra popolata" % (numero,))
allegati.update(scadenza=scadenza)
class Migration(migrations.Migration):
dependencies = [
('base', '0011_allegato_scadenza'),
]
operations = [
migrations.RunPython(forwards_func),
]
| gpl-3.0 |
patrick-hudson/naughtyusers | app/database/seeds/DatabaseSeeder.php | 282 | <?php
class DatabaseSeeder extends Seeder {
public function run()
{
Eloquent::unguard();
// Add calls to Seeders here
$this->call('UsersTableSeeder');
$this->call('RolesTableSeeder');
$this->call('PermissionsTableSeeder');
}
} | gpl-3.0 |
gohdan/DFC | known_files/hashes/bitrix/modules/socialnetwork/install/components/bitrix/socialnetwork.activity/lang/ru/component.php | 61 | Bitrix 16.5 Business Demo = 41adc0ba8eb13ae2ac97bbeac33c8694
| gpl-3.0 |
Librazy/RPGitems-reloaded | src/main/java/think/rpgitems/power/PowerProjectile.java | 9271 | package think.rpgitems.power;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import think.rpgitems.Events;
import think.rpgitems.I18n;
import think.rpgitems.RPGItems;
import think.rpgitems.commands.AcceptedValue;
import think.rpgitems.commands.Property;
import think.rpgitems.commands.Setter;
import think.rpgitems.commands.Validator;
import think.rpgitems.power.types.PowerRightClick;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* Power projectile.
* <p>
* Launches projectile of type {@link #projectileType} with {@link #gravity} when right clicked.
* If use {@link #cone} mode, {@link #amount} of projectiles will randomly distributed in the cone
* with angle {@link #range} centered with player's direction.
* </p>
*/
@SuppressWarnings("WeakerAccess")
public class PowerProjectile extends Power implements PowerRightClick {
/**
* Z_axis.
*/
private static final Vector z_axis = new Vector(0, 0, 1);
/**
* X_axis.
*/
private static final Vector x_axis = new Vector(1, 0, 0);
/**
* Y_axis.
*/
private static final Vector y_axis = new Vector(0, 1, 0);
private static Cache<UUID, Integer> burstCounter = CacheBuilder.newBuilder().expireAfterAccess(3, TimeUnit.SECONDS).concurrencyLevel(2).build();
/**
* Cooldown time of this power
*/
@Property(order = 0)
public long cooldownTime = 20;
/**
* Whether launch projectiles in cone
*/
@Property(order = 1)
public boolean cone = false;
/**
* Whether the projectile have gravity
*/
@Property
public boolean gravity = true;
/**
* Range will projectiles spread, in degree
*/
@Property(order = 3)
public int range = 15;
/**
* Amount of projectiles
*/
@Property(order = 4)
public int amount = 5;
/**
* Speed of projectiles
*/
@Property(order = 5)
public double speed = 1;
/**
* Cost of this power
*/
@Property
public int consumption = 1;
/**
* burst count of one shoot
*/
public int burstCount = 1;
/**
* Interval between bursts
*/
public int burstInterval = 1;
/**
* Type of projectiles
*/
@AcceptedValue({
"skull",
"fireball",
"snowball",
"smallfireball",
"llamaspit",
"arrow"
})
@Validator(value = "acceptableType", message = "power.projectile.noFireball")
@Setter("setType")
@Property(order = 2, required = true)
public Class<? extends Projectile> projectileType = Snowball.class;
@Override
public void init(ConfigurationSection s) {
cooldownTime = s.getLong("cooldownTime");
setType(s.getString("projectileType"));
cone = s.getBoolean("isCone");
range = s.getInt("range");
amount = s.getInt("amount");
consumption = s.getInt("consumption", 1);
speed = s.getDouble("speed", 1);
gravity = s.getBoolean("gravity", true);
burstCount = s.getInt("burstCount", 1);
burstInterval = s.getInt("burstInterval", 1);
}
@Override
public void save(ConfigurationSection s) {
s.set("cooldownTime", cooldownTime);
s.set("projectileType", getType());
s.set("isCone", cone);
s.set("range", range);
s.set("amount", amount);
s.set("consumption", consumption);
s.set("speed", speed);
s.set("gravity", gravity);
s.set("burstCount", burstCount);
s.set("burstInterval", burstInterval);
}
/**
* Gets type name
*
* @return Type name
*/
public String getType() {
if (projectileType == WitherSkull.class)
return "skull";
else if (projectileType == Fireball.class)
return "fireball";
else if (projectileType == SmallFireball.class)
return "smallfireball";
else if (projectileType == Arrow.class)
return "arrow";
else if (projectileType == LlamaSpit.class)
return "llamaspit";
else
return "snowball";
}
/**
* Sets type from type name
*
* @param type Type name
*/
public void setType(String type) {
switch (type) {
case "skull":
projectileType = WitherSkull.class;
break;
case "fireball":
projectileType = Fireball.class;
break;
case "smallfireball":
projectileType = SmallFireball.class;
break;
case "arrow":
projectileType = Arrow.class;
break;
case "llamaspit":
projectileType = LlamaSpit.class;
break;
default:
projectileType = Snowball.class;
break;
}
}
/**
* Check if the type is acceptable
*
* @param str Type name
* @return If acceptable
*/
public boolean acceptableType(String str) {
return !(cone && str.equalsIgnoreCase("fireball"));
}
@Override
public String getName() {
return "projectile";
}
@Override
public String displayText() {
return I18n.format(cone ? "power.projectile.cone" : "power.projectile.display", getType(), (double) cooldownTime / 20d);
}
@Override
public void rightClick(Player player, ItemStack stack, Block clicked) {
if (!item.checkPermission(player, true)) return;
if (!checkCooldown(player, cooldownTime, true)) return;
if (!item.consumeDurability(stack, consumption)) return;
fire(player);
if (burstCount > 1) {
burstCounter.put(player.getUniqueId(), burstCount - 1);
(new BukkitRunnable() {
@Override
public void run() {
Integer i;
if (player.getInventory().getItemInMainHand().equals(stack) && (i = burstCounter.getIfPresent(player.getUniqueId())) != null) {
if (i > 0) {
fire(player);
burstCounter.put(player.getUniqueId(), i - 1);
return;
}
}
burstCounter.invalidate(player.getUniqueId());
this.cancel();
}
}).runTaskTimer(RPGItems.plugin, 1, burstInterval);
}
}
private void fire(Player player) {
if (!cone) {
Projectile projectile = player.launchProjectile(projectileType, player.getEyeLocation().getDirection().multiply(speed));
Events.rpgProjectiles.put(projectile.getEntityId(), item.getID());
projectile.setGravity(gravity);
if (projectileType == Arrow.class)
Events.removeArrows.add(projectile.getEntityId());
if (!gravity) {
(new BukkitRunnable() {
@Override
public void run() {
projectile.remove();
}
}).runTaskLater(RPGItems.plugin, 80);
}
} else {
Vector loc = player.getEyeLocation().getDirection();
range = Math.abs(range) % 360;
double phi = range / 180f * Math.PI;
Vector a, b;
Vector ax1 = loc.getCrossProduct(z_axis);
if (ax1.length() < 0.01) {
a = x_axis.clone();
b = y_axis.clone();
} else {
a = ax1.normalize();
b = loc.getCrossProduct(a).normalize();
}
for (int i = 0; i < amount; i++) {
double z = range == 0 ? 1 : ThreadLocalRandom.current().nextDouble(Math.cos(phi), 1);
double det = ThreadLocalRandom.current().nextDouble(0, 2 * Math.PI);
double theta = Math.acos(z);
Vector v = a.clone().multiply(Math.cos(det)).add(b.clone().multiply(Math.sin(det))).multiply(Math.sin(theta)).add(loc.clone().multiply(Math.cos(theta)));
Projectile projectile = player.launchProjectile(projectileType, v.normalize().multiply(speed));
Events.rpgProjectiles.put(projectile.getEntityId(), item.getID());
projectile.setGravity(gravity);
if (projectileType == Arrow.class)
Events.removeArrows.add(projectile.getEntityId());
if (!gravity) {
(new BukkitRunnable() {
@Override
public void run() {
projectile.remove();
}
}).runTaskLater(RPGItems.plugin, 80);
}
}
}
}
}
| gpl-3.0 |
crisis-economics/CRISIS | CRISIS/src/eu/crisis_economics/abm/algorithms/portfolio/returns/FundamentalistStockReturnExpectationFunction.java | 3234 | /*
* This file is part of CRISIS, an economics simulator.
*
* Copyright (C) 2015 Ross Richardson
* Copyright (C) 2015 John Kieran Phillips
*
* CRISIS 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.
*
* CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.crisis_economics.abm.algorithms.portfolio.returns;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import eu.crisis_economics.abm.contracts.stocks.StockReleaser;
import eu.crisis_economics.abm.contracts.stocks.UniqueStockExchange;
/***************************************************************
* <p>
* Implementation of a fundamentalist expectation
* function where expected return is
* </p>
* <code>
* e = (d/v)/p
* </code>
* <p>
* where
* </p>
* <ul>
* <li>d is the dividend per share</li>
* <li>v is the current share value</li>
* <li>p is a risk premium</li>
* </ul>
***************************************************************/
public final class FundamentalistStockReturnExpectationFunction
implements StockReturnExpectationFunction {
public final static double
DEFAULT_FUNDAMENTALIST_STOCK_RETURN_EXPECTATION_RISK_PREMIUM = 1.0;
private double
stockRiskPremium;
/**
* Create a {@link FundamentalistStockReturnExpectationFunction} return
* estimation algorithm with custom parameters.
*
* @param riskPremium
* The investment risk premium to apply. This argument should be
* strictly positive.
*/
@Inject
public FundamentalistStockReturnExpectationFunction(
@Named("FUNDAMENTALIST_STOCK_RETURN_EXPECTATION_RISK_PREMIUM")
final double riskPremium
) {
Preconditions.checkArgument(riskPremium > 0.);
this.stockRiskPremium = riskPremium;
}
/**
* Create a {@link FundamentalistStockReturnExpectationFunction} return
* estimation algorithm with default parameters.
*/
public FundamentalistStockReturnExpectationFunction() {
this(DEFAULT_FUNDAMENTALIST_STOCK_RETURN_EXPECTATION_RISK_PREMIUM);
}
@Override
public double computeExpectedReturn(String stockName) {
final StockReleaser
releaser = UniqueStockExchange.Instance.getStockReleaser(stockName);
double
dividendPerShare = releaser.getDividendPerShare(),
marketValue = releaser.getMarketValue();
if(marketValue == 0.0)
return 0.;
else
return((dividendPerShare/marketValue)/stockRiskPremium);
}
public void setStockRiskPremium(double r) {
stockRiskPremium = r;
}
public double getStockRiskPremium() {
return(stockRiskPremium);
}
}
| gpl-3.0 |
okeltw/EPBand_embedded | source/MotionRegs.py | 4410 | """
A dictionary that holds all the registers for MPU6050
Shorthand Notes:
[R] == Read Only
[W] == Write Only
[R/W] == Read/Write
MST == master
Thresh == threshold
DO == Data Output (?)
DI == Data Input (?)
Int == Interrupt
"""
regs = {
'Self Test X' : 0x0D, # [R/W] Gyroscope/accelerometer self test
'Self Test Y' : 0x0E,
'Self Test Z' : 0x0F,
'Self Test A' : 0x10, # [R/W] Self test gyro/accel switch (?)
'Sample Rate' : 0x19, # [R/W] Control sample rate; higher is slower
'Config' : 0x1A, # [R/W] Configure FSYNC pin and DLPF
'Gyro Config' : 0x1B, # [R/W] Used to trigger gyro self test and scale range
'Accel Config' : 0x1C, # [R/W] Used to trigger Accel self test and scale range
'Motion Tresh' : 0x1F, # [R/W] Configure detection threshold for motion interrupt
'FIFO Enable' : 0x23, # [R/W] Determines which measurements are loaded into buffer
'I2C Mst Ctrl' : 0x24, # [R/W] Configure for single or multi master I2C
'I2C Slv0 Addr' : 0x25, # [R/W] Configure data transfer sequence for Slave 0
'I2C Slv0 Reg' : 0x26,
'I2C Slv0 Ctrl' : 0x27,
'I2C Slv1 Addr' : 0x28, # [R/W] Configure data transfer sequence for Slave 1
'I2C Slv1 Reg' : 0x29,
'I2C Slv1 Ctrl' : 0x2A,
'I2C Slv2 Addr' : 0x2B, # [R/W] Configure data transfer sequence for Slave 2
'I2C Slv2 Reg' : 0x2C,
'I2C Slv2 Ctrl' : 0x2D,
'I2C Slv3 Addr' : 0x2E, # [R/W] Configure data transfer sequence for Slave 0
'I2C Slv3 Reg' : 0x2F,
'I2C Slv3 Ctrl' : 0x30,
'I2C Slv4 Addr' : 0x31, # [R/W] Configure data transfer sequence for Slave 4
'I2C Slv4 Reg' : 0x32,
'I2C Slv4 DO' : 0x33,
'I2C Slv4 Ctrl' : 0x34,
'I2C Slv4 DI' : 0x35,
'I2C Mst Staus' : 0x36, # [R] Shows the status of the interrupt generating signals
'Int Pin Config': 0x37, # [R/W] Configures the behavior of the interrupt signals
'Int Enable' : 0x38, # [R/W]Enables/Disables interrupt generation
'Int Status' : 0x3A, # [R] Shows the interupt status of each source
'Accel X High' : 0x3B, # [R] Stores the most recent accel measurements
'Accel X Low' : 0x3C,
'Accel Y High' : 0x3D,
'Accel Y Low' : 0x3E,
'Accel Z High' : 0x3F,
'Accel Z Low' : 0x40,
'Temp High' : 0x41, # [R] Stores the most recent temp measurement
'Temp Low' : 0x42,
'Gyro X High' : 0x43, # [R] Stores the most recent gyro measurements
'Gyro X Low' : 0x44,
'Gyro Y High' : 0x45,
'Gyro Y Low' : 0x46,
'Gyro Z High' : 0x47,
'Gyro Z Low' : 0x48,
'Ext Sensor 0' : 0x49, #[R] Stores data read from external sensors
'Ext Sensor 1' : 0x4A,
'Ext Sensor 2' : 0x4B,
'Ext Sensor 3' : 0x4C,
'Ext Sensor 4' : 0x4D,
'Ext Sensor 5' : 0x4E,
'Ext Sensor 6' : 0x4F,
'Ext Sensor 7' : 0x50,
'Ext Sensor 8' : 0x51,
'Ext Sensor 9' : 0x52,
'Ext Sensor 10' : 0x53,
'Ext Sensor 11' : 0x54,
'Ext Sensor 12' : 0x55,
'Ext Sensor 13' : 0x56,
'Ext Sensor 14' : 0x57,
'Ext Sensor 15' : 0x58,
'Ext Sensor 16' : 0x59,
'Ext Sensor 17' : 0x5A,
'Ext Sensor 18' : 0x5B,
'Ext Sensor 19' : 0x5C,
'Ext Sensor 20' : 0x5D,
'Ext Sensor 21' : 0x5E,
'Ext Sensor 22' : 0x5F,
'Ext Sensor 23' : 0x60,
'I2C Slv0 DO' : 0x63, # [R/W] Holds output data written into Slave when in write mode
'I2C Slv1 DO' : 0x64,
'I2C Slv2 DO' : 0x65,
'I2C Slv3 DO' : 0x66,
'I2C Mst Delay' : 0x67, # [R/W] Used to specify timing of ext sensor data shadowing, decrease access rate of slave devices relative to sample rate
'Sig Path Rst' : 0x68, # [W] Used to reset the A/D signal paths of internal sensors
'Mot Dtect Ctrl': 0x69, # [R/W] Add delay to accel power on time, configure detection decrement rate
'User Ctrl' : 0x6A, # [R/W] Enable/Disable FIFO, I2C Master, and primary I2C interface.
'Pwr Mgmt 1' : 0x6B, # [R/W] Configure power mode and clock source
'Pwr Mgmt 2' : 0x6C, # [R/W] Frequency of wake-ups in Accel only low pwr mode. Put individual axes into standby mode.
'FIFO Cnt High' : 0x72, # [R] Keep track of the current number of samples in the buffer
'FIFO Cnt Low' : 0x73,
'FIFO R/W' : 0x74, # [R/W] Read/Write data on FIFO buffer
'Who Am I' : 0x75, # [R] Verify identity of device (I2C address)
}
| gpl-3.0 |
rainbru/rainbrurpg | src/client/OgreCfgSaver.cpp | 1287 | /*
* Copyright 2011-2018 Jerome Pasquier
*
* This file is part of rainbrurpg-client.
*
* rainbrurpg-client 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.
*
* rainbrurpg-client 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 rainbrurpg-client. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "OgreCfgSaver.hpp"
#include <Ogre.h>
#include <fstream>
OgreCfgSaver::OgreCfgSaver(const string& filename,
RenderSystem* rs, ConfigOptionMap* cm)
{
ofstream ofs;
ofs.open (filename, std::ofstream::out | std::ofstream::trunc);
ofs << "Render System=" <<rs->getName() << endl;
ofs << endl;
ofs << "[" << rs->getName() << "]" << endl;
for (ConfigOptionMap::iterator iter=cm->begin(); iter!=cm->end(); ++iter)
{
ofs << iter->first << "=" << iter->second.currentValue << endl;
}
}
| gpl-3.0 |
PhotoFiltre-LX/photofiltrelx | src/tools/StampTool.cpp | 7423 | /*
This file is part of Photoflare.
Photoflare 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.
Photoflare 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 Photoflare. If not, see <https://www.gnu.org/licenses/>.
*/
// StampTool - Clone an area of an image and paint it over the image.
#include "StampTool.h"
#include "PaintWidget.h"
#include <QPainter>
#include <QtMath>
#include <QGraphicsEffect>
#include <QGraphicsPixmapItem>
#include <QLinearGradient>
#include <QBitmap>
#include <QMessageBox>
class StampToolPrivate
{
public:
StampToolPrivate()
{
primaryPen = QPen(QBrush(), 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
secondaryPen = QPen(QBrush(), 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
selectMode = false;
selectPos = QPoint(0,0);
offset = QPoint(0,0);
firstRun = true;
}
~StampToolPrivate()
{
}
QPoint lastPos;
QPen primaryPen;
QPen secondaryPen;
Qt::MouseButton mouseButton;
int radius;
int pressure;
int step;
bool fixed;
bool precise;
bool diffuse;
bool selectMode;
bool firstRun;
QPoint selectPos;
QPoint offset;
float opacity;
QImage origin;
};
StampTool::StampTool(QObject *parent)
: Tool(parent)
, d(new StampToolPrivate)
{
}
StampTool::~StampTool()
{
delete d;
}
void StampTool::setPrimaryColor(const QColor &color)
{
d->primaryPen.setColor(color);
}
QColor StampTool::primaryColor() const
{
return d->primaryPen.color();
}
void StampTool::setSecondaryColor(const QColor &color)
{
d->secondaryPen.setColor(color);
}
QColor StampTool::secondaryColor() const
{
return d->secondaryPen.color();
}
void StampTool::setRadius(int radius)
{
d->radius = radius;
emit cursorChanged(getCursor());
}
void StampTool::setPressure(int pressure)
{
d->pressure = pressure;
}
void StampTool::setStep(int step)
{
d->step = step;
}
void StampTool::setFixed(bool fixed)
{
d->fixed = fixed;
}
void StampTool::setPrecise(bool precise)
{
d->precise = precise;
}
void StampTool::setDiffuse(bool diffuse)
{
d->diffuse = diffuse;
}
void StampTool::setCapStyle(Qt::PenCapStyle capStyle)
{
d->primaryPen.setCapStyle(capStyle);
d->secondaryPen.setCapStyle(capStyle);
}
QCursor StampTool::getCursor()
{
int width = d->radius * m_scale;
if(width < 5)
width = 5;
QPixmap pixmap(QSize(width,width));
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
QPen pen = QPen(QBrush(), 1, Qt::DashLine);
pen.setColor(Qt::gray);
painter.setPen(pen);
painter.drawEllipse(pixmap.rect());
return QCursor(pixmap);
}
void StampTool::onMousePress(const QPoint &pos, Qt::MouseButton button)
{
if(d->firstRun == true)
{
QMessageBox msgBox;
msgBox.setWindowTitle("CloneStamp Tool");
msgBox.setText("Use [CTRL+left click] to select clone area.");
msgBox.exec();
}
if(d->firstRun == false)
{
Q_UNUSED(button);
d->lastPos = pos;
d->mouseButton = button;
d->opacity = d->pressure / 10.0f;
if(d->selectMode)
{
d->selectPos = pos;
}
else
{
if(d->selectPos.x() >= 0 || d->fixed)
d->offset = pos - d->selectPos;
else
d->selectPos = pos - d->offset;
if (m_paintDevice) {
const QImage *image = dynamic_cast<QImage*>(m_paintDevice);
d->origin = *image;
onMouseMove(pos);
}
}
}
}
void StampTool::onMouseMove(const QPoint &pos)
{
if (m_paintDevice)
{
const QImage *image = dynamic_cast<QImage*>(m_paintDevice);
QImage surface = QImage(image->size(), QImage::Format_ARGB32_Premultiplied);
QPainter cursor(&surface);
cursor.setCompositionMode(QPainter::CompositionMode_Source);
cursor.fillRect(surface.rect(), Qt::transparent);
QPen pen = QPen(QBrush(), 1, Qt::DashLine);
pen.setColor(Qt::gray);
cursor.setPen(pen);
cursor.drawEllipse(pos - d->offset, 5, 5);
if(d->fixed)
{
QPoint diff = d->lastPos-pos;
float len = qSqrt(diff.x()*diff.x() + diff.y()*diff.y());
if(len >= d->step || len == 0)
{
d->lastPos = pos;
}
else
{
return;
}
}
QPainter painter(m_paintDevice);
painter.setRenderHint(QPainter::Antialiasing);
painter.setOpacity(d->opacity);
QPixmap pixmap(QSize(d->radius,d->radius));
pixmap.fill(Qt::transparent);
QPainter painterPix(&pixmap);
painterPix.setRenderHint(QPainter::Antialiasing);
QPoint base;
if(d->fixed)
{
base = d->selectPos;
}
else
{
base = pos - d->offset;
}
for(int i=-d->radius/2; i < d->radius/2;i++)
{
for(int j=-d->radius/2; j < d->radius/2;j++)
{
if(d->diffuse && (float)rand()/(float)RAND_MAX > 0.5f)
continue;
if(base.x() + i < 0 || base.y() + j < 0)
continue;
if(base.x() + i >= image->width() || base.y() + j >= image->height())
continue;
if(i*i + j*j > d->radius*d->radius/4)
continue;
pen.setColor(d->origin.pixel(base.x() + i,base.y() + j));
painterPix.setPen(pen);
if(!d->precise)
{
if(i*i + j*j > d->radius*d->radius/16)
{
painterPix.setOpacity(((float)1 - ((float)(i*i + j*j) / (float)(d->radius*d->radius/4)))/10.0f);
}
else
{
painterPix.setOpacity(1.f);
}
}
painterPix.drawPoint(i+d->radius/2, j+d->radius/2);
}
}
painter.drawPixmap(pos.x()-d->radius/2, pos.y()-d->radius/2, pixmap);
emit painted(m_paintDevice);
emit overlaid(m_paintDevice, surface, QPainter::CompositionMode_SourceOver);
}
}
void StampTool::onMouseRelease(const QPoint &pos)
{
Q_UNUSED(pos);
d->mouseButton = Qt::NoButton;
if(!d->selectMode && !d->fixed)
d->selectPos.setX(-1);
emit painted(m_paintDevice);
}
void StampTool::onKeyPressed(QKeyEvent * keyEvent)
{
if(keyEvent->key() == Qt::Key_Control)
{
d->selectMode = true;
d->firstRun = false;
emit cursorChanged(Qt::ArrowCursor);
}
}
void StampTool::onKeyReleased(QKeyEvent * keyEvent)
{
if(keyEvent->key() == Qt::Key_Control)
{
d->selectMode = false;
emit cursorChanged(getCursor());
}
}
| gpl-3.0 |
ProteinDF/ProteinDF | src/libpdftl/tl_dense_symmetric_matrix_scalapack.cc | 10775 | #include "tl_dense_symmetric_matrix_scalapack.h"
#include "tl_dense_general_matrix_impl_scalapack.h"
#include "tl_dense_general_matrix_scalapack.h"
#include "tl_dense_symmetric_matrix_impl_scalapack.h"
#include "tl_dense_vector_impl_lapack.h"
#include "tl_dense_vector_impl_scalapack.h"
#include "tl_dense_vector_lapack.h"
#include "tl_dense_vector_scalapack.h"
// ---------------------------------------------------------------------------
// constructor & destructor
// ---------------------------------------------------------------------------
TlDenseSymmetricMatrix_Scalapack::TlDenseSymmetricMatrix_Scalapack(
const TlMatrixObject::index_type dim) {
this->pImpl_ = new TlDenseSymmetricMatrix_ImplScalapack(dim);
}
TlDenseSymmetricMatrix_Scalapack::TlDenseSymmetricMatrix_Scalapack(
const TlDenseSymmetricMatrix_Scalapack& rhs) {
this->pImpl_ = new TlDenseSymmetricMatrix_ImplScalapack(*(
dynamic_cast<const TlDenseSymmetricMatrix_ImplScalapack*>(rhs.pImpl_)));
}
TlDenseSymmetricMatrix_Scalapack::TlDenseSymmetricMatrix_Scalapack(
const TlDenseGeneralMatrix_Scalapack& rhs) {
this->pImpl_ = new TlDenseSymmetricMatrix_ImplScalapack(
*(dynamic_cast<const TlDenseGeneralMatrix_ImplScalapack*>(rhs.pImpl_)));
}
// TlDenseSymmetricMatrix_Scalapack::TlDenseSymmetricMatrix_Scalapack(
// const TlDenseVector_Scalapack& v, const TlMatrixObject::index_type dim) {
// this->pImpl_ = new TlDenseSymmetricMatrix_ImplScalapack(
// *(dynamic_cast<const TlDenseVector_ImplScalapack*>(v.pImpl_)), dim);
// }
TlDenseSymmetricMatrix_Scalapack::~TlDenseSymmetricMatrix_Scalapack() {
delete this->pImpl_;
this->pImpl_ = NULL;
}
// ---------------------------------------------------------------------------
// properties
// ---------------------------------------------------------------------------
TlMatrixObject::size_type TlDenseSymmetricMatrix_Scalapack::getNumOfElements()
const {
return dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->getNumOfElements();
}
double TlDenseSymmetricMatrix_Scalapack::getLocal(
TlMatrixObject::index_type row, TlMatrixObject::index_type col) const {
return dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->getLocal(row, col);
}
// ---------------------------------------------------------------------------
// operators
// ---------------------------------------------------------------------------
TlDenseSymmetricMatrix_Scalapack& TlDenseSymmetricMatrix_Scalapack::operator=(
const TlDenseSymmetricMatrix_Scalapack& rhs) {
delete this->pImpl_;
this->pImpl_ = new TlDenseSymmetricMatrix_ImplScalapack(
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(rhs.pImpl_)));
return *this;
}
const TlDenseSymmetricMatrix_Scalapack TlDenseSymmetricMatrix_Scalapack::
operator+(const TlDenseSymmetricMatrix_Scalapack& rhs) const {
TlDenseSymmetricMatrix_Scalapack answer = *this;
answer += rhs;
return answer;
}
const TlDenseSymmetricMatrix_Scalapack TlDenseSymmetricMatrix_Scalapack::
operator-(const TlDenseSymmetricMatrix_Scalapack& rhs) const {
TlDenseSymmetricMatrix_Scalapack answer = *this;
answer -= rhs;
return answer;
}
const TlDenseGeneralMatrix_Scalapack TlDenseSymmetricMatrix_Scalapack::
operator*(const TlDenseSymmetricMatrix_Scalapack& rhs) const {
TlDenseGeneralMatrix_Scalapack answer = *this;
answer *= rhs;
return answer;
}
TlDenseSymmetricMatrix_Scalapack& TlDenseSymmetricMatrix_Scalapack::operator+=(
const TlDenseSymmetricMatrix_Scalapack& rhs) {
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)) +=
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(rhs.pImpl_));
return *this;
}
TlDenseSymmetricMatrix_Scalapack& TlDenseSymmetricMatrix_Scalapack::operator-=(
const TlDenseSymmetricMatrix_Scalapack& rhs) {
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)) -=
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(rhs.pImpl_));
return *this;
}
TlDenseSymmetricMatrix_Scalapack& TlDenseSymmetricMatrix_Scalapack::operator*=(
const double coef) {
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)) *=
coef;
return *this;
}
TlDenseSymmetricMatrix_Scalapack& TlDenseSymmetricMatrix_Scalapack::operator/=(
const double coef) {
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)) /=
coef;
return *this;
}
TlDenseSymmetricMatrix_Scalapack& TlDenseSymmetricMatrix_Scalapack::operator*=(
const TlDenseSymmetricMatrix_Scalapack& rhs) {
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)) *=
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(rhs.pImpl_));
return *this;
}
// ---------------------------------------------------------------------------
// operations
// ---------------------------------------------------------------------------
const TlDenseSymmetricMatrix_Scalapack&
TlDenseSymmetricMatrix_Scalapack::dotInPlace(
const TlDenseSymmetricMatrix_Scalapack& rhs) {
dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->dotInPlace(
*dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(rhs.pImpl_));
return *this;
}
bool TlDenseSymmetricMatrix_Scalapack::eig(
TlDenseVector_Lapack* pEigVal,
TlDenseGeneralMatrix_Scalapack* pEigVec) const {
TlDenseVector_ImplLapack* pImpl_eigval =
dynamic_cast<TlDenseVector_ImplLapack*>(pEigVal->pImpl_);
TlDenseGeneralMatrix_ImplScalapack* pImpl_eigvec =
dynamic_cast<TlDenseGeneralMatrix_ImplScalapack*>(pEigVec->pImpl_);
const bool answer =
dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->eig(pImpl_eigval, pImpl_eigvec);
return answer;
}
TlDenseSymmetricMatrix_Scalapack TlDenseSymmetricMatrix_Scalapack::inverse()
const {
TlDenseSymmetricMatrix_Scalapack answer;
answer.pImpl_ = new TlDenseSymmetricMatrix_ImplScalapack(
dynamic_cast<const TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->inverse());
return answer;
}
bool TlDenseSymmetricMatrix_Scalapack::getSparseMatrix(TlSparseMatrix* pMatrix,
bool isFinalize) const {
return dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->getSparseMatrix(pMatrix, isFinalize);
}
void TlDenseSymmetricMatrix_Scalapack::mergeSparseMatrix(
const TlSparseMatrix& M) {
dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->mergeSparseMatrix(M);
}
std::vector<TlMatrixObject::index_type>
TlDenseSymmetricMatrix_Scalapack::getRowIndexTable() const {
return dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->getRowIndexTable();
}
std::vector<TlMatrixObject::index_type>
TlDenseSymmetricMatrix_Scalapack::getColIndexTable() const {
return dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->getColIndexTable();
}
void TlDenseSymmetricMatrix_Scalapack::getLocalMatrix(
TlDenseGeneralMatrixObject* pOutputMatrix) const {
dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->getLocalMatrix(pOutputMatrix);
}
// ---------------------------------------------------------------------------
// I/O
// ---------------------------------------------------------------------------
bool TlDenseSymmetricMatrix_Scalapack::load(const std::string& filePath) {
return dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->load(filePath);
}
bool TlDenseSymmetricMatrix_Scalapack::save(const std::string& filePath) const {
return dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
->save(filePath);
}
void TlDenseSymmetricMatrix_Scalapack::dump(TlDenseVector_Scalapack* v) const {
// TODO: implement
// dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
// ->dump(dynamic_cast<TlDenseVector_ImplScalapack*>(v->pImpl_));
}
void TlDenseSymmetricMatrix_Scalapack::restore(
const TlDenseVector_Scalapack& v) {
// TODO: implement
// dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(this->pImpl_)
// ->restore(*(dynamic_cast<TlDenseVector_ImplScalapack*>(v.pImpl_)));
}
// ---------------------------------------------------------------------------
// friend functions
// ---------------------------------------------------------------------------
TlDenseGeneralMatrix_Scalapack operator*(
const TlDenseSymmetricMatrix_Scalapack& rhs1,
const TlDenseGeneralMatrix_Scalapack& rhs2) {
TlDenseGeneralMatrix_Scalapack answer;
*(dynamic_cast<TlDenseGeneralMatrix_ImplScalapack*>(answer.pImpl_)) =
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(rhs1.pImpl_)) *
*(dynamic_cast<TlDenseGeneralMatrix_ImplScalapack*>(rhs2.pImpl_));
return answer;
}
TlDenseGeneralMatrix_Scalapack operator*(
const TlDenseGeneralMatrix_Scalapack& rhs1,
const TlDenseSymmetricMatrix_Scalapack& rhs2) {
TlDenseGeneralMatrix_Scalapack answer;
*(dynamic_cast<TlDenseGeneralMatrix_ImplScalapack*>(answer.pImpl_)) =
*(dynamic_cast<TlDenseGeneralMatrix_ImplScalapack*>(rhs1.pImpl_)) *
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(rhs2.pImpl_));
return answer;
}
TlDenseVector_Scalapack operator*(const TlDenseSymmetricMatrix_Scalapack& rhs1,
const TlDenseVector_Scalapack& rhs2) {
TlDenseVector_Scalapack answer;
*(dynamic_cast<TlDenseVector_ImplScalapack*>(answer.pImpl_)) =
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(rhs1.pImpl_)) *
*(dynamic_cast<TlDenseVector_ImplScalapack*>(rhs2.pImpl_));
return answer;
}
TlDenseVector_Scalapack operator*(
const TlDenseVector_Scalapack& rhs1,
const TlDenseSymmetricMatrix_Scalapack& rhs2) {
TlDenseVector_Scalapack answer;
*(dynamic_cast<TlDenseVector_ImplScalapack*>(answer.pImpl_)) =
*(dynamic_cast<TlDenseSymmetricMatrix_ImplScalapack*>(rhs2.pImpl_)) *
*(dynamic_cast<TlDenseVector_ImplScalapack*>(rhs1.pImpl_));
return answer;
}
// ---------------------------------------------------------------------------
// arithmetic
// ---------------------------------------------------------------------------
TlDenseSymmetricMatrix_Scalapack operator*(
const double coef, const TlDenseSymmetricMatrix_Scalapack& matrix) {
TlDenseSymmetricMatrix_Scalapack answer = matrix;
answer *= coef;
return answer;
}
TlDenseSymmetricMatrix_Scalapack operator*(
const TlDenseSymmetricMatrix_Scalapack& matrix, const double coef) {
return coef * matrix;
}
| gpl-3.0 |
ScriptaGames/pityaboutearth | src/js/states/menu.js | 4630 | class MenuState extends Phaser.State {
create() {
console.log('[menu] showing main menu');
window.menu = this;
this.music = this.game.add.audio('MenuMusic', 0.7, true);
this.music.play();
const bg = this.game.add.sprite(0, 0, 'background');
bg.tint = 0x3f3f3f;
const logo = this.game.add.sprite(this.game.world.centerX, 120, 'logo');
logo.anchor.set(0.5, 0);
logo.scale.set(0.96, 0.96);
this.fontSet = `! "#$%^'()* +,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz{|}~`;
this.story = [
`Humanity, listen up. This is`,
`the Universe. I am sick of`,
`your incessant nosing about.`,
`The incoming asteroid should`,
`resolve matters.`,
` -- Yours, the Universe`,
``,
`(Protect Earth while shuttles`,
`ferry "repopulation experts"`,
`to other, safer worlds)`,
// `The universe, growing tired of`,
// `Humanity's constant, tedious`,
// `nosing about, is endeavoring`,
// `to erase us.`,
// ``,
// `Protect Earth while escape pods`,
// `shuttle "repopulation experts"`,
// `to new worlds.`,
// `Our planet is a lonely speck`,
// `in the great enveloping cosmic`,
// `dark.`,
// ``,
// `In our obscurity -- in all this`,
// `vastness, there is no hint that`,
// `help will come from elsewhere`,
// `to save us.`,
// ``,
// ` -- Carl Sagan`,
];
const btnHum = this.game.add.button(
this.game.world.centerX,
this.game.world.height - 130,
'btn-play',
this.next,
this,
1, // over
0, // out
2 // down
);
btnHum.anchor.set(0.5, 1);
btnHum.onDownSound = this.game.add.audio('ButtonTap');
btnHum.onOverSound = this.game.add.audio('Barrier');
btnHum.input.useHandCursor = false;
if (config.SKIP_MENU) {
this.next();
}
this.timeBetweenLines = 150;
this.timePerChar = 40;
this.lineHeight = 60;
let acc = 0;
this.story.forEach((line, i) => {
this.game.time.events.add(i * this.timeBetweenLines + acc, () => {
this.writeLine(line, i);
}, this);
acc += line.length * this.timePerChar
});
this.drawMissileHelp();
this.drawBarrierHelp();
}
update() {
}
next() {
this.game.stateTransition.to('PlayState');
}
shutdown() {
this.music.stop();
}
getLine(index) {
return this.story[i];
}
drawBarrierHelp() {
const x = -370;
const y = 68;
const barrier = this.game.add.sprite(this.game.world.centerX + x - 100, this.game.world.height - 670 + y, 'barrier');
const font = this.game.add.retroFont('gelatin-font', 70, 110, this.fontSet, 18, 0, 0);
const text = this.game.add.image(80, 80, font);
text.scale.set(0.5,0.5);
font.text = 'Barrier';
text.tint = 0x777777;
text.position.x = this.game.world.centerX + x;
text.position.y = this.game.world.height - 608 + y;
}
drawMissileHelp() {
const x = 140;
const y = 40;
const mouse = this.game.add.sprite(this.game.world.centerX - 44 + x, this.game.world.height - 600 + y, 'mouse');
mouse.anchor.set(0.5, 0.5);
const font = this.game.add.retroFont('gelatin-font', 70, 110, this.fontSet, 18, 0, 0);
const text = this.game.add.image(80, 80, font);
text.scale.set(0.5,0.5);
font.text = 'Missile';
text.tint = 0x777777;
text.position.x = this.game.world.centerX + x;
text.position.y = this.game.world.height - 608 + y;
}
writeLine(line, index) {
const font = this.game.add.retroFont('gelatin-font', 70, 110, this.fontSet, 18, 0, 0);
const text = this.game.add.image(80, 80, font);
text.scale.set(0.5,0.5);
font.text = '';
// text.tint = 0x51B5E0;
text.position.x = this.game.world.centerX - 490;;
text.position.y = index * this.lineHeight + 600;
let i = 0;
this.game.time.events.loop(this.timePerChar, () => {
font.text = line.slice(0, i);
i += 1;
}, this);
}
}
| gpl-3.0 |
unibas-gravis/scalismo-ui | src/main/scala/scalismo/ui/model/capabilities/RenderableSceneNode.scala | 1119 | /*
* Copyright (C) 2016 University of Basel, Graphics and Vision Research Group
*
* 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 scalismo.ui.model.capabilities
import scalismo.ui.model.{Renderable, SceneNode}
/**
* A renderable node is -- by design -- a leaf node,
* i.e., it has no further children.
*
*/
trait RenderableSceneNode extends SceneNode with Renderable {
final override def renderables: List[RenderableSceneNode] = List(this)
final override def children: List[SceneNode] = Nil
}
| gpl-3.0 |
zerodayz/citellus | tests/plugins-unit-tests/test_executable_bit.py | 1158 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2018, 2019, 2020 Pablo Iranzo Gómez <[email protected]>
import os
import sys
from unittest import TestCase
sys.path.append(os.path.abspath(os.path.dirname(__file__) + "/" + "../"))
import citellusclient.shell as citellus
testplugins = os.path.join(citellus.citellusdir, "plugins", "test")
citellusdir = citellus.citellusdir
class CitellusTest(TestCase):
def test_plugins_have_executable_bit(self):
pluginpath = [os.path.join(citellus.citellusdir, "plugins", "core")]
plugins = []
for folder in pluginpath:
for root, dirnames, filenames in os.walk(folder, followlinks=True):
for filename in filenames:
filepath = os.path.join(root, filename)
if ".citellus_tests" not in filepath:
plugins.append(filepath)
plugins = sorted(set(plugins))
pluginscit = []
for plugin in citellus.findplugins(folders=pluginpath):
pluginscit.append(plugin["plugin"])
pluginscit = sorted(set(pluginscit))
assert plugins == pluginscit
| gpl-3.0 |
misfist/treehouse-profile-web | app.js | 753 | var router = require('./router.js');
//Problem: Find and look at a user's profile, including badge count and JS points
//Solution: Use node.js to look up profile and serve our template via HTTP
//1. Create a webserver
var http = require('http');
http.createServer(function (request, response) {
router.home(request, response);
router.user(request, response);
}).listen(3000);
console.log('Server running at http://treehouse/');
//if url == "/...."
//get json from source (e.g. Treehouse)
//on "end" (when data comes back successfully)
//show profile
//on "error"
//show error
//4. Function that handles the reading of files and merge in values
// read from file and get a string (what file?)
// merge values into string | gpl-3.0 |
immartian/musicoin | util/rlp/src/untrusted_rlp.rs | 13930 | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use std::cell::Cell;
use std::fmt;
use rustc_serialize::hex::ToHex;
use bytes::{FromBytes, FromBytesResult, FromBytesError};
use ::{View, Decoder, Decodable, DecoderError, RlpDecodable};
/// rlp offset
#[derive(Copy, Clone, Debug)]
struct OffsetCache {
index: usize,
offset: usize,
}
impl OffsetCache {
fn new(index: usize, offset: usize) -> OffsetCache {
OffsetCache {
index: index,
offset: offset,
}
}
}
#[derive(Debug)]
/// RLP prototype
pub enum Prototype {
/// Empty
Null,
/// Value
Data(usize),
/// List
List(usize),
}
/// Stores basic information about item
pub struct PayloadInfo {
/// Header length in bytes
pub header_len: usize,
/// Value length in bytes
pub value_len: usize,
}
fn calculate_payload_info(header_bytes: &[u8], len_of_len: usize) -> Result<PayloadInfo, DecoderError> {
let header_len = 1 + len_of_len;
match header_bytes.get(1) {
Some(&0) => return Err(DecoderError::RlpDataLenWithZeroPrefix),
None => return Err(DecoderError::RlpIsTooShort),
_ => (),
}
if header_bytes.len() < header_len { return Err(DecoderError::RlpIsTooShort); }
let value_len = try!(usize::from_bytes(&header_bytes[1..header_len]));
Ok(PayloadInfo::new(header_len, value_len))
}
impl PayloadInfo {
fn new(header_len: usize, value_len: usize) -> PayloadInfo {
PayloadInfo {
header_len: header_len,
value_len: value_len,
}
}
/// Total size of the RLP.
pub fn total(&self) -> usize { self.header_len + self.value_len }
/// Create a new object from the given bytes RLP. The bytes
pub fn from(header_bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
match header_bytes.first().cloned() {
None => Err(DecoderError::RlpIsTooShort),
Some(0...0x7f) => Ok(PayloadInfo::new(0, 1)),
Some(l @ 0x80...0xb7) => Ok(PayloadInfo::new(1, l as usize - 0x80)),
Some(l @ 0xb8...0xbf) => {
let len_of_len = l as usize - 0xb7;
calculate_payload_info(header_bytes, len_of_len)
}
Some(l @ 0xc0...0xf7) => Ok(PayloadInfo::new(1, l as usize - 0xc0)),
Some(l @ 0xf8...0xff) => {
let len_of_len = l as usize - 0xf7;
calculate_payload_info(header_bytes, len_of_len)
},
// we cant reach this place, but rust requires _ to be implemented
_ => { unreachable!(); }
}
}
}
/// Data-oriented view onto rlp-slice.
///
/// This is immutable structere. No operations change it.
///
/// Should be used in places where, error handling is required,
/// eg. on input
#[derive(Debug)]
pub struct UntrustedRlp<'a> {
bytes: &'a [u8],
offset_cache: Cell<OffsetCache>,
count_cache: Cell<Option<usize>>,
}
impl<'a> Clone for UntrustedRlp<'a> {
fn clone(&self) -> UntrustedRlp<'a> {
UntrustedRlp {
bytes: self.bytes,
offset_cache: self.offset_cache.clone(),
count_cache: self.count_cache.clone(),
}
}
}
impl<'a> fmt::Display for UntrustedRlp<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self.prototype() {
Ok(Prototype::Null) => write!(f, "null"),
Ok(Prototype::Data(_)) => write!(f, "\"0x{}\"", self.data().unwrap().to_hex()),
Ok(Prototype::List(len)) => {
try!(write!(f, "["));
for i in 0..len-1 {
try!(write!(f, "{}, ", self.at(i).unwrap()));
}
try!(write!(f, "{}", self.at(len - 1).unwrap()));
write!(f, "]")
},
Err(err) => write!(f, "{:?}", err)
}
}
}
impl<'a, 'view> View<'a, 'view> for UntrustedRlp<'a> where 'a: 'view {
type Prototype = Result<Prototype, DecoderError>;
type PayloadInfo = Result<PayloadInfo, DecoderError>;
type Data = Result<&'a [u8], DecoderError>;
type Item = Result<UntrustedRlp<'a>, DecoderError>;
type Iter = UntrustedRlpIterator<'a, 'view>;
//returns new instance of `UntrustedRlp`
fn new(bytes: &'a [u8]) -> UntrustedRlp<'a> {
UntrustedRlp {
bytes: bytes,
offset_cache: Cell::new(OffsetCache::new(usize::max_value(), 0)),
count_cache: Cell::new(None)
}
}
fn as_raw(&'view self) -> &'a [u8] {
self.bytes
}
fn prototype(&self) -> Self::Prototype {
// optimize? && return appropriate errors
if self.is_data() {
Ok(Prototype::Data(self.size()))
} else if self.is_list() {
Ok(Prototype::List(self.item_count()))
} else {
Ok(Prototype::Null)
}
}
fn payload_info(&self) -> Self::PayloadInfo {
BasicDecoder::payload_info(self.bytes)
}
fn data(&'view self) -> Self::Data {
let pi = try!(BasicDecoder::payload_info(self.bytes));
Ok(&self.bytes[pi.header_len..(pi.header_len + pi.value_len)])
}
fn item_count(&self) -> usize {
match self.is_list() {
true => match self.count_cache.get() {
Some(c) => c,
None => {
let c = self.iter().count();
self.count_cache.set(Some(c));
c
}
},
false => 0
}
}
fn size(&self) -> usize {
match self.is_data() {
// TODO: No panic on malformed data, but ideally would Err on no PayloadInfo.
true => BasicDecoder::payload_info(self.bytes).map(|b| b.value_len).unwrap_or(0),
false => 0
}
}
fn at(&'view self, index: usize) -> Self::Item {
if !self.is_list() {
return Err(DecoderError::RlpExpectedToBeList);
}
// move to cached position if its index is less or equal to
// current search index, otherwise move to beginning of list
let c = self.offset_cache.get();
let (mut bytes, to_skip) = match c.index <= index {
true => (try!(UntrustedRlp::consume(self.bytes, c.offset)), index - c.index),
false => (try!(self.consume_list_prefix()), index),
};
// skip up to x items
bytes = try!(UntrustedRlp::consume_items(bytes, to_skip));
// update the cache
self.offset_cache.set(OffsetCache::new(index, self.bytes.len() - bytes.len()));
// construct new rlp
let found = try!(BasicDecoder::payload_info(bytes));
Ok(UntrustedRlp::new(&bytes[0..found.header_len + found.value_len]))
}
fn is_null(&self) -> bool {
self.bytes.len() == 0
}
fn is_empty(&self) -> bool {
!self.is_null() && (self.bytes[0] == 0xc0 || self.bytes[0] == 0x80)
}
fn is_list(&self) -> bool {
!self.is_null() && self.bytes[0] >= 0xc0
}
fn is_data(&self) -> bool {
!self.is_null() && self.bytes[0] < 0xc0
}
fn is_int(&self) -> bool {
if self.is_null() {
return false;
}
match self.bytes[0] {
0...0x80 => true,
0x81...0xb7 => self.bytes[1] != 0,
b @ 0xb8...0xbf => self.bytes[1 + b as usize - 0xb7] != 0,
_ => false
}
}
fn iter(&'view self) -> Self::Iter {
self.into_iter()
}
fn as_val<T>(&self) -> Result<T, DecoderError> where T: RlpDecodable {
// optimize, so it doesn't use clone (although This clone is cheap)
T::decode(&BasicDecoder::new(self.clone()))
}
fn val_at<T>(&self, index: usize) -> Result<T, DecoderError> where T: RlpDecodable {
try!(self.at(index)).as_val()
}
}
impl<'a> UntrustedRlp<'a> {
/// consumes first found prefix
fn consume_list_prefix(&self) -> Result<&'a [u8], DecoderError> {
let item = try!(BasicDecoder::payload_info(self.bytes));
let bytes = try!(UntrustedRlp::consume(self.bytes, item.header_len));
Ok(bytes)
}
/// consumes fixed number of items
fn consume_items(bytes: &'a [u8], items: usize) -> Result<&'a [u8], DecoderError> {
let mut result = bytes;
for _ in 0..items {
let i = try!(BasicDecoder::payload_info(result));
result = try!(UntrustedRlp::consume(result, (i.header_len + i.value_len)));
}
Ok(result)
}
/// consumes slice prefix of length `len`
fn consume(bytes: &'a [u8], len: usize) -> Result<&'a [u8], DecoderError> {
match bytes.len() >= len {
true => Ok(&bytes[len..]),
false => Err(DecoderError::RlpIsTooShort),
}
}
}
/// Iterator over rlp-slice list elements.
pub struct UntrustedRlpIterator<'a, 'view> where 'a: 'view {
rlp: &'view UntrustedRlp<'a>,
index: usize,
}
impl<'a, 'view> IntoIterator for &'view UntrustedRlp<'a> where 'a: 'view {
type Item = UntrustedRlp<'a>;
type IntoIter = UntrustedRlpIterator<'a, 'view>;
fn into_iter(self) -> Self::IntoIter {
UntrustedRlpIterator {
rlp: self,
index: 0,
}
}
}
impl<'a, 'view> Iterator for UntrustedRlpIterator<'a, 'view> {
type Item = UntrustedRlp<'a>;
fn next(&mut self) -> Option<UntrustedRlp<'a>> {
let index = self.index;
let result = self.rlp.at(index).ok();
self.index += 1;
result
}
}
struct BasicDecoder<'a> {
rlp: UntrustedRlp<'a>
}
impl<'a> BasicDecoder<'a> {
pub fn new(rlp: UntrustedRlp<'a>) -> BasicDecoder<'a> {
BasicDecoder {
rlp: rlp
}
}
/// Return first item info.
fn payload_info(bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
let item = try!(PayloadInfo::from(bytes));
match item.header_len.checked_add(item.value_len) {
Some(x) if x <= bytes.len() => Ok(item),
_ => Err(DecoderError::RlpIsTooShort),
}
}
}
impl<'a> Decoder for BasicDecoder<'a> {
fn read_value<T, F>(&self, f: &F) -> Result<T, DecoderError>
where F: Fn(&[u8]) -> Result<T, DecoderError> {
let bytes = self.rlp.as_raw();
match bytes.first().cloned() {
// RLP is too short.
None => Err(DecoderError::RlpIsTooShort),
// Single byte value.
Some(l @ 0...0x7f) => Ok(try!(f(&[l]))),
// 0-55 bytes
Some(l @ 0x80...0xb7) => {
let last_index_of = 1 + l as usize - 0x80;
if bytes.len() < last_index_of {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
let d = &bytes[1..last_index_of];
if l == 0x81 && d[0] < 0x80 {
return Err(DecoderError::RlpInvalidIndirection);
}
Ok(try!(f(d)))
},
// Longer than 55 bytes.
Some(l @ 0xb8...0xbf) => {
let len_of_len = l as usize - 0xb7;
let begin_of_value = 1 as usize + len_of_len;
if bytes.len() < begin_of_value {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
let len = try!(usize::from_bytes(&bytes[1..begin_of_value]));
let last_index_of_value = begin_of_value + len;
if bytes.len() < last_index_of_value {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
Ok(try!(f(&bytes[begin_of_value..last_index_of_value])))
}
// We are reading value, not a list!
_ => Err(DecoderError::RlpExpectedToBeData)
}
}
fn as_raw(&self) -> &[u8] {
self.rlp.as_raw()
}
fn as_rlp(&self) -> &UntrustedRlp {
&self.rlp
}
}
impl<T> Decodable for T where T: FromBytes {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
decoder.read_value(&|bytes: &[u8]| Ok(try!(T::from_bytes(bytes))))
}
}
impl<T> Decodable for Vec<T> where T: Decodable {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
decoder.as_rlp().iter().map(|d| T::decode(&BasicDecoder::new(d))).collect()
}
}
impl<T> Decodable for Option<T> where T: Decodable {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
decoder.as_rlp().iter().map(|d| T::decode(&BasicDecoder::new(d))).collect::<Result<Vec<_>, DecoderError>>().map(|mut a| a.pop())
}
}
impl Decodable for Vec<u8> {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
decoder.read_value(&|bytes: &[u8]| Ok(bytes.to_vec()))
}
}
macro_rules! impl_array_decodable {
($index_type:ty, $len:expr ) => (
impl<T> Decodable for [T; $len] where T: Decodable {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let decoders = decoder.as_rlp();
let mut result: [T; $len] = unsafe { ::std::mem::uninitialized() };
if decoders.item_count() != $len {
return Err(DecoderError::RlpIncorrectListLen);
}
for i in 0..decoders.item_count() {
result[i] = try!(T::decode(&BasicDecoder::new(try!(decoders.at(i)))));
}
Ok(result)
}
}
)
}
macro_rules! impl_array_decodable_recursive {
($index_type:ty, ) => ();
($index_type:ty, $len:expr, $($more:expr,)*) => (
impl_array_decodable!($index_type, $len);
impl_array_decodable_recursive!($index_type, $($more,)*);
);
}
impl_array_decodable_recursive!(
u8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 40, 48, 56, 64, 72, 96, 128, 160, 192, 224,
);
impl<T> RlpDecodable for T where T: Decodable {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
Decodable::decode(decoder)
}
}
struct DecodableU8 (u8);
impl FromBytes for DecodableU8 {
fn from_bytes(bytes: &[u8]) -> FromBytesResult<DecodableU8> {
match bytes.len() {
0 => Ok(DecodableU8(0u8)),
1 => {
if bytes[0] == 0 {
return Err(FromBytesError::ZeroPrefixedInt)
}
Ok(DecodableU8(bytes[0]))
}
_ => Err(FromBytesError::DataIsTooLong)
}
}
}
impl RlpDecodable for u8 {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let u: DecodableU8 = try!(Decodable::decode(decoder));
Ok(u.0)
}
}
#[cfg(test)]
mod tests {
use ::{UntrustedRlp, View};
#[test]
fn test_rlp_display() {
use rustc_serialize::hex::FromHex;
let data = "f84d0589010efbef67941f79b2a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470".from_hex().unwrap();
let rlp = UntrustedRlp::new(&data);
assert_eq!(format!("{}", rlp), "[\"0x05\", \"0x010efbef67941f79b2\", \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\", \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"]");
}
}
| gpl-3.0 |
pipacs/ionic | main.cpp | 5077 | #include <QtGui/QApplication>
#include <QtDeclarative>
#include "qmlapplicationviewer.h"
#include "backend/trace.h"
#include "backend/preferences.h"
#include "backend/contentitem.h"
#include "backend/book.h"
#include "backend/bookmark.h"
#include "backend/bookdb.h"
#include "backend/library.h"
#include "backend/coverprovider.h"
#include "backend/bookfinder.h"
#include "backend/platform.h"
#include "backend/mediakey.h"
#include "backend/qdeclarativewebview_p.h"
#if defined(Q_OS_SYMBIAN)
#include "backend/iap.h"
#endif
int main(int argc, char *argv[]) {
// Set up application
QScopedPointer<QApplication> app(createApplication(argc, argv));
app->setApplicationName("Ionic");
app->setApplicationVersion(Platform::instance()->version());
app->setOrganizationDomain("pipacs.com");
app->setOrganizationName("pipacs.com");
// Set up tracing
Preferences *settings = Preferences::instance();
Trace::level = (QtMsgType)settings->value("tracelevel", (int)QtDebugMsg).toInt();
Trace::setFileName(settings->value("tracefilename").toString());
qInstallMsgHandler(Trace::messageHandler);
qDebug() << "Ionic version " << Platform::instance()->version();
// Register QML types
qmlRegisterType<Bookmark>("com.pipacs.ionic.Bookmark", 1, 0, "Bookmark");
qmlRegisterType<Book>("com.pipacs.ionic.Book", 1, 0, "Book");
qmlRegisterType<Library>("com.pipacs.ionic.Library", 1, 0, "Library");
qmlRegisterType<Preferences>("com.pipacs.ionic.Preferences", 1, 0, "Preferences");
#if defined(Q_OS_SYMBIAN)
qmlRegisterType<IapItem>("com.pipacs.ionic.IapItem", 1, 0, "IapItem");
#endif
qmlRegisterType<QDeclarativeWebSettings>();
qmlRegisterType<QDeclarativeWebView>("com.pipacs.ionic.IWebView", 1, 0, "IWebView");
// Do book database management in a separate thread
QThread *bookDbWorkerThread = new QThread;
BookDb::instance()->worker()->moveToThread(bookDbWorkerThread);
bookDbWorkerThread->start(QThread::LowestPriority);
// Initialize library, load book from command line, or the last book, or the default book
Library *library = Library::instance();
library->load();
Book *current;
if (argc > 1) {
qDebug() << argv[1];
current = library->find(argv[1]);
if (!current) {
current = library->add(argv[1]);
}
if (current) {
library->setNowReading(current);
}
}
current = library->nowReading();
if (!current->isValid()) {
if (!library->bookCount()) {
library->add(":/books/2BR02B.epub");
}
library->setNowReading(library->book(0));
}
// Do book import in a separate thread
BookFinder *bookFinder = new BookFinder;
BookFinderWorker *bookFinderWorker = new BookFinderWorker;
QThread *bookFinderWorkerThread = new QThread;
bookFinderWorker->moveToThread(bookFinderWorkerThread);
bookFinder->connect(bookFinder, SIGNAL(findRequested()), bookFinderWorker, SLOT(doFind()));
bookFinderWorker->connect(bookFinderWorker, SIGNAL(begin(int)), bookFinder, SIGNAL(begin(int)));
bookFinderWorker->connect(bookFinderWorker, SIGNAL(add(QString)), bookFinder, SIGNAL(add(QString)));
bookFinderWorker->connect(bookFinderWorker, SIGNAL(done(int)), bookFinder, SIGNAL(done(int)));
bookFinderWorkerThread->start(QThread::LowestPriority);
// Set up and show QML widget with main.qml
QmlApplicationViewer *viewer = new QmlApplicationViewer;
MediaKey *mediaKey = new MediaKey(viewer);
viewer->setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
viewer->engine()->addImageProvider(QString("covers"), new CoverProvider);
viewer->rootContext()->setContextProperty("library", library);
viewer->rootContext()->setContextProperty("prefs", settings);
Book *emptyBook = new Book();
viewer->rootContext()->setContextProperty("emptyBook", emptyBook);
viewer->rootContext()->setContextProperty("bookFinder", bookFinder);
viewer->rootContext()->setContextProperty("platform", Platform::instance());
viewer->rootContext()->setContextProperty("mediaKey", mediaKey);
#if defined(Q_OS_SYMBIAN)
Iap *iap = new Iap(viewer);
viewer->rootContext()->setContextProperty("iap", iap);
#endif
#if defined(Q_OS_SYMBIAN)
viewer->setSource(QUrl("qrc:/qml/main-symbian.qml"));
#else
viewer->setSource(QUrl("qrc:/qml/main.qml"));
#endif
viewer->showExpanded();
#if defined(MEEGO_EDITION_HARMATTAN)
// Install event filter to capture/release volume keys
viewer->installEventFilter(mediaKey);
#endif
// Run application
int ret = app->exec();
// Delete singletons
delete viewer;
bookFinderWorkerThread->quit();
bookFinderWorkerThread->wait();
delete bookFinderWorkerThread;
delete bookFinderWorker;
delete bookFinder;
delete emptyBook;
Library::close();
bookDbWorkerThread->quit();
bookDbWorkerThread->wait();
delete bookDbWorkerThread;
BookDb::close();
Preferences::close();
Platform::close();
return ret;
}
| gpl-3.0 |
romw/boincsentinels | hunter/ConfigManager.cpp | 3433 | // BOINC Sentinels.
// https://projects.romwnet.org/boincsentinels
// Copyright (C) 2009-2014 Rom Walton
//
// BOINC Sentinels is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC Sentinels is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with BOINC Sentinels. If not, see <http://www.gnu.org/licenses/>.
//
#include "stdwx.h"
#include "Hunter.h"
#include "ConfigManager.h"
CConfigManager::CConfigManager() :
wxConfig()
{
}
bool CConfigManager::DeleteConfigGroup(wxString strComponent, wxString strSubComponent)
{
bool rc = false;
wxString strPath = DeterminePath(strComponent, strSubComponent);
SetPath(strPath);
rc = DeleteGroup(strPath);
SetPath(wxT("/"));
return rc;
}
wxString CConfigManager::DeterminePath(wxString strComponent, wxString strSubComponent)
{
wxString strPath;
strPath = wxT("/");
if (!strComponent.IsEmpty())
{
strPath += strComponent + wxT("/");
if (!strSubComponent.IsEmpty())
{
strPath += strSubComponent + wxT("/");
}
}
return strPath;
}
bool CConfigManager::EnumerateGroups(wxString strComponent, wxString strSubComponent, wxSortedArrayString* pstrGroups)
{
bool rc = false;
wxString strPath = DeterminePath(strComponent, strSubComponent);
wxString strGroup = wxEmptyString;
long lCookie = 0;
SetPath(strPath);
rc = GetFirstGroup(strGroup, lCookie);
while (rc)
{
pstrGroups->Add(strGroup);
rc = GetNextGroup(strGroup, lCookie);
}
SetPath(wxT("/"));
return (pstrGroups->Count() != 0);
}
bool CConfigManager::GetConfigValue(wxString strComponent, wxString strSubComponent, wxString strValueName, long dwDefaultValue, long* pdwValue)
{
bool rc = false;
wxString strPath = DeterminePath(strComponent, strSubComponent);
SetPath(strPath);
rc = Read(strValueName, pdwValue, dwDefaultValue);
SetPath(wxT("/"));
return rc;
}
bool CConfigManager::GetConfigValue(wxString strComponent, wxString strSubComponent, wxString strValueName, wxString strDefaultValue, wxString* pstrValue)
{
bool rc = false;
wxString strPath = DeterminePath(strComponent, strSubComponent);
SetPath(strPath);
rc = Read(strValueName, pstrValue, strDefaultValue);
SetPath(wxT("/"));
return rc;
}
bool CConfigManager::SetConfigValue(wxString strComponent, wxString strSubComponent, wxString strValueName, long dwValue)
{
bool rc = false;
wxString strPath = DeterminePath(strComponent, strSubComponent);
SetPath(strPath);
rc = Write(strValueName, dwValue);
SetPath(wxT("/"));
return rc;
}
bool CConfigManager::SetConfigValue(wxString strComponent, wxString strSubComponent, wxString strValueName, wxString strValue)
{
bool rc = false;
wxString strPath = DeterminePath(strComponent, strSubComponent);
SetPath(strPath);
rc = Write(strValueName, strValue);
SetPath(wxT("/"));
return rc;
}
| gpl-3.0 |
SamTebbs33/myrmecology | src/minecraft/vivadaylight3/myrmecology/common/entity/ant/EntityAntCarpenter.java | 844 | package vivadaylight3.myrmecology.common.entity.ant;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import vivadaylight3.myrmecology.api.item.ItemAnt;
import vivadaylight3.myrmecology.common.Register;
import vivadaylight3.myrmecology.common.entity.EntityAnt;
import vivadaylight3.myrmecology.common.entity.ai.AntBehaviourCarpenter;
import vivadaylight3.myrmecology.common.lib.Resources;
public class EntityAntCarpenter extends EntityAnt {
public EntityAntCarpenter(World par1World) {
super(par1World);
this.tasks
.addTask(
1,
new AntBehaviourCarpenter(this, par1World, this
.getNavigator()));
}
@Override
public ItemAnt getAnt() {
return Register.antCarpenter;
}
@Override
public ResourceLocation getResource() {
return Resources.ENTITY_ANT_CARPENTER;
}
}
| gpl-3.0 |
andriy-bilynskyy/SmartHouse | central/www/WLM_log.php | 1736 | <?php
header("Refresh:5");
include("session.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(mysqli_query($db,"DELETE FROM water_log WHERE unit='BLUETOOTH' or unit='WATER VALVE'"))
{
mysqli_query($db,"INSERT INTO water_log VALUES (NOW(), 'ADMIN', 'Water log erased from WEB.')");
header("Refresh:0");
}
}
?>
<html>
<head>
<title>Water leak monitor log</title>
<link rel="stylesheet" type="text/css" href="style.css">
<?php
if(isMobile())
{
?>
<link rel="stylesheet" type="text/css" href="mobile.css">
<?php
}else{
?>
<link rel="stylesheet" type="text/css" href="desktop.css">
<?php
}
?>
</head>
<body bgcolor = "#FFFFFF">
<div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Water leak monitor log</b></div><br/>
<div style = "padding:3px;"><a href = "WLM_control.php">Water leak monitor control</a></div><br/>
<div style = "padding:3px;"><a href = "WLM_sub.php">Subscribed water leak sensors editor</a></div><br/>
<div style = "padding:3px;"><a href = "welcome.php">Back</a></div><br/>
<form action = "" method = "post">
<input type = "submit" value = "Clear log"/>
</form>
<table cellpadding=5px><col style="width:19ch"><tr><th>time</th><th>message</th></tr>
<?php
$result = mysqli_query($db,"SELECT date_time, message FROM water_log WHERE unit='WATER VALVE' or unit='BLUETOOTH'");
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<tr><td>".$row["date_time"]."</td><td>".$row["message"]."</td></tr>";
}
?>
</table>
</body>
</html> | gpl-3.0 |
DHBW-Projekt/BeePublished | plugins/ContactForm/Model/ContactRequest.php | 1664 | <?php
/*
* This file is part of BeePublished which is based on CakePHP.
* BeePublished 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.
* BeePublished 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 BeePublished. If not, see
* http://www.gnu.org/licenses/.
*
* @copyright 2012 Duale Hochschule Baden-Württemberg Mannheim
* @author Maximilian Stüber, Corinna Knick
*
* @description activate multilingualism and set validation rules for input fields
*/
App::uses('AppModel', 'Model');
/**
* ContactRequest Model.
*/
class ContactRequest extends AppModel {
/*No DB*/
public $useTable = false;
/*Activate multilingualism*/
function invalidate($field, $value = true) {
return parent::invalidate($field, __d("contact_form", $value, true));
}
/*Validation rules*/
public $validate = array(
'email' => array(
'rule' => 'email',
'required' => true,
'message' => 'Please enter a valid e-mail address.'
),
'subject' => array(
'rule' => 'notEmpty',
'message' => 'Please enter a subject.'
),
'body' => array(
'rule' => 'notEmpty',
'message' => 'Please enter your message.'
)
);
} | gpl-3.0 |
EuanMead/euanmead.github.io | plugins/codemirror/codemirror.plugin.php | 3005 | <?php
/**
* CodeMirror plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012-2014 Romanenko Sergey / Awilum
* @version 1.0.0
*
*/
// Register plugin
Plugin::register( __FILE__,
__('CodeMirror', 'codemirror'),
__('CodeMirror is a versatile text editor implemented in JavaScript for the browser.', 'codemirror'),
'1.0.0',
'Awilum',
'http://monstra.org/');
// Add hooks
Action::add('admin_header', 'CodeMirror::headers');
/**
* Codemirror Class
*/
class CodeMirror
{
public static $theme = 'elegant';
/**
* Set editor headers
*/
public static function headers()
{
echo ('
<link rel="stylesheet" type="text/css" href="'.Option::get('siteurl').'/plugins/codemirror/codemirror/lib/codemirror.css" />
<script type="text/javascript" src="'.Option::get('siteurl').'/plugins/codemirror/codemirror/lib/codemirror.js"></script>
<script type="text/javascript" src="'.Option::get('siteurl').'/plugins/codemirror/codemirror/addon/edit/matchbrackets.js"></script>
<script type="text/javascript" src="'.Option::get('siteurl').'/plugins/codemirror/codemirror/mode/htmlmixed/htmlmixed.js"></script>
<script type="text/javascript" src="'.Option::get('siteurl').'/plugins/codemirror/codemirror/mode/xml/xml.js"></script>
<script type="text/javascript" src="'.Option::get('siteurl').'/plugins/codemirror/codemirror/mode/javascript/javascript.js"></script>
<script type="text/javascript" src="'.Option::get('siteurl').'/plugins/codemirror/codemirror/mode/php/php.js"></script>
<link rel="stylesheet" href="'.Option::get('siteurl').'/plugins/codemirror/codemirror/theme/'.CodeMirror::$theme.'.css">
<style>
.CodeMirror {
height:400px!important;
border: 1px solid #ccc;
color: #555;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.428571429;
padding: 6px 9px;
}
</style>
');
if (Request::get('id') == 'themes' || Request::get('id') == 'snippets') {
echo ('<script>
$(document).ready(function() {
var editor = CodeMirror.fromTextArea(document.getElementById("content"), {
lineNumbers: false,
matchBrackets: true,
indentUnit: 4,
mode: "htmlmixed",
indentWithTabs: true,
theme: "'.CodeMirror::$theme.'"
});
});
</script>');
}
}
}
| gpl-3.0 |
mater06/LEGOChimaOnlineReloaded | LoCO Client Files/Decompressed Client/Extracted DLL/Wb.Lpw.Protocol/LogCodes/Services/Account/AuthenticateForGameByUsernamePassword/Debug.cs | 593 | // Decompiled with JetBrains decompiler
// Type: Wb.Lpw.Platform.Protocol.LogCodes.Services.Account.AuthenticateForGameByUsernamePassword.Debug
// Assembly: Wb.Lpw.Protocol, Version=2.13.83.0, Culture=neutral, PublicKeyToken=null
// MVID: A621984F-C936-438B-B744-D121BF336087
// Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Wb.Lpw.Protocol.dll
namespace Wb.Lpw.Platform.Protocol.LogCodes.Services.Account.AuthenticateForGameByUsernamePassword
{
public abstract class Debug
{
}
}
| gpl-3.0 |
toxicaliens/rental | src/system_manager/manage_sys_view.php | 1489 | <table id="table1" class="table table-bordered">
<thead>
<tr>
<th>ID#</th>
<th>View Name</th>
<th>View Index</th>
<th>View Url</th>
<th>Status</th>
<th>Parent View</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
$distinctQuery = "SELECT * FROM sys_views Order by sys_view_id DESC ";
$resultId = run_query($distinctQuery);
$total_rows = get_num_rows($resultId);
$con = 1;
$total = 0;
while($row = get_row_data($resultId)) {
$sys_view_id = $row['sys_view_id'];
$view_name = $row['sys_view_name'];
$view_index = $row['sys_view_index'];
$view_url = $row['sys_view_url'];
$view_status = $row['sys_view_status'];
if($view_status == 't'){
$view_status = 'Active';
}else{
$view_status = 'Inactive';
}
?>
<tr>
<td><?=$sys_view_id; ?></td>
<td><?=$view_name; ?></td>
<td><?=$view_index; ?></td>
<td><?=$view_url; ?></td>
<td><?=$view_status; ?></td>
<td><?=getParentViewName($row['parent']); ?></td>
<td><a id="edit_link" href="index.php?num=edit_view&id=<?=$sys_view_id; ?>" class="btn btn-mini"><i class="icon-edit"></i> Edit</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
<div class="clearfix"></div> | gpl-3.0 |
tadeu28/Gert | Gert.Model/DataBase/Model/Professor.cs | 1130 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
using System.ComponentModel.DataAnnotations;
namespace Gert.Model.DataBase.Model
{
public class Professor
{
public virtual int Id { get; set; }
[Required(ErrorMessage = "Nome é obrigatório")]
public virtual string Nome { get; set; }
public virtual Boolean Ativa { get; set; }
public virtual Instituicao Instituicao { get; set; }
public virtual Usuario Usuario { get; set; }
}
public class ProfessorMap : ClassMapping<Professor>
{
public ProfessorMap()
{
Id<int>(x => x.Id, m => m.Generator(Generators.Identity));
Property<string>(x => x.Nome);
Property<Boolean>(x => x.Ativa);
ManyToOne(x => x.Instituicao, map =>
{
map.Column("IdInstituicao");
map.Cascade(Cascade.All);
map.Lazy(LazyRelation.NoLazy);
});
}
}
}
| gpl-3.0 |
kyfr59/versailles | application/src/Db/Event/Subscriber/Entity.php | 3244 | <?php
namespace Omeka\Db\Event\Subscriber;
use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Events as DoctrineEvent;
use Omeka\Event\Event as OmekaEvent;
use Omeka\Entity\Resource as OmekaResource;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
* Entity event subscriber.
*
* Delegates selected Doctrine lifecycle events to Omeka events.
*/
class Entity implements EventSubscriber
{
/**
* @var ServiceLocatorInterface
*/
protected $services;
/**
* @var EventManagerInterface
*/
protected $events;
/**
* Set the service locator.
*/
public function __construct(ServiceLocatorInterface $serviceLocator)
{
$this->services = $serviceLocator;
$this->events = $serviceLocator->get('EventManager');
}
public function getSubscribedEvents()
{
return [
DoctrineEvent::preRemove, DoctrineEvent::postRemove,
DoctrineEvent::prePersist, DoctrineEvent::postPersist,
DoctrineEvent::preUpdate, DoctrineEvent::postUpdate,
];
}
/**
* Trigger the entity.remove.pre event.
*
* @param LifecycleEventArgs $args
*/
public function preRemove(LifecycleEventArgs $args)
{
$this->trigger(OmekaEvent::ENTITY_REMOVE_PRE, $args);
}
/**
* Trigger the entity.remove.post event.
*
* @param LifecycleEventArgs $args
*/
public function postRemove(LifecycleEventArgs $args)
{
$this->trigger(OmekaEvent::ENTITY_REMOVE_POST, $args);
}
/**
* Trigger the entity.persist.pre event.
*
* @param LifecycleEventArgs $args
*/
public function prePersist(LifecycleEventArgs $args)
{
$this->trigger(OmekaEvent::ENTITY_PERSIST_PRE, $args);
}
/**
* Trigger the entity.persist.post event.
*
* @param LifecycleEventArgs $args
*/
public function postPersist(LifecycleEventArgs $args)
{
$this->trigger(OmekaEvent::ENTITY_PERSIST_POST, $args);
}
/**
* Trigger the entity.update.pre event.
*
* @param LifecycleEventArgs $args
*/
public function preUpdate(LifecycleEventArgs $args)
{
$this->trigger(OmekaEvent::ENTITY_UPDATE_PRE, $args);
}
/**
* Trigger the entity.update.post event.
*
* @param LifecycleEventArgs $args
*/
public function postUpdate(LifecycleEventArgs $args)
{
$this->trigger(OmekaEvent::ENTITY_UPDATE_POST, $args);
}
/**
* Compose and trigger the event.
*
* @param string $eventName
* @param LifecycleEventArgs $args
*/
protected function trigger($eventName, LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$identifiers = [get_class($entity)];
if ($entity instanceof OmekaResource) {
// Add the identifier for a generic resource entity.
$identifiers[] = 'Omeka\Entity\Resource';
}
$this->events->setIdentifiers($identifiers);
$event = new OmekaEvent($eventName, $entity, [
'services' => $this->services,
]);
$this->events->trigger($event);
}
}
| gpl-3.0 |
Senmori/HeadSelector | src/main/java/net/senmori/headselector/util/Items.java | 7246 | package net.senmori.headselector.util;
import com.google.common.collect.Lists;
import org.apache.commons.lang.WordUtils;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.material.MaterialData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* Useful methods for items.
*
* @author TigerHix
*/
public final class Items {
private Items() {
}
public static BookBuilder bookBuilder() {
return new BookBuilder();
}
public static ItemStackBuilder builder() {
return new ItemStackBuilder();
}
public static ItemStack createColoredArmor(Armor armor, Color color, String name) {
ItemStack leatherArmor = new ItemStack(armor.getMaterial());
LeatherArmorMeta meta = (LeatherArmorMeta) leatherArmor.getItemMeta();
meta.setColor(color);
if (name != null) meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
leatherArmor.setItemMeta(meta);
return leatherArmor;
}
public static ItemStack createColoredArmor(Armor armor, Color color) {
return createColoredArmor(armor, color, "&l" + WordUtils.capitalize(armor.name().toLowerCase()));
}
public static ItemStackBuilder editor(ItemStack itemStack) {
return new ItemStackBuilder(itemStack);
}
public enum Armor {
HELMET(Material.LEATHER_HELMET),
CHESTPLATE(Material.LEATHER_CHESTPLATE),
LEGGINGS(Material.LEATHER_LEGGINGS),
BOOTS(Material.LEATHER_BOOTS);
private Material material;
private Armor(Material material) {
this.material = material;
}
public Material getMaterial() {
return material;
}
}
public static class ItemStackBuilder {
private final ItemStack itemStack;
ItemStackBuilder() {
itemStack = new ItemStack(Material.QUARTZ);
setName("");
setLore(new ArrayList<String>());
}
public ItemStackBuilder(ItemStack itemStack) {
this.itemStack = itemStack;
}
public ItemStackBuilder setItemMeta(ItemMeta meta) {
this.itemStack.setItemMeta(meta);
return this;
}
public ItemStackBuilder setMaterial(Material material) {
itemStack.setType(material);
return this;
}
public ItemStackBuilder changeAmount(int change) {
itemStack.setAmount(itemStack.getAmount() + change);
return this;
}
public ItemStackBuilder setAmount(int amount) {
itemStack.setAmount(amount);
return this;
}
public ItemStackBuilder setData(short data) {
itemStack.setDurability(data);
return this;
}
public ItemStackBuilder setData(MaterialData data) {
itemStack.setData(data);
return this;
}
public ItemStackBuilder setEnchantments(HashMap<Enchantment, Integer> enchantments) {
for (Enchantment enchantment : itemStack.getEnchantments().keySet()) {
itemStack.removeEnchantment(enchantment);
}
itemStack.addUnsafeEnchantments(enchantments);
return this;
}
public ItemStackBuilder addEnchantment(Enchantment enchantment, int level) {
itemStack.addUnsafeEnchantment(enchantment, level);
return this;
}
public ItemStackBuilder setName(String name) {
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.setDisplayName(name.equals("") ? " " : Strings.format(name));
itemStack.setItemMeta(itemMeta);
return this;
}
public ItemStackBuilder addBlankLore() {
addLore(" ");
return this;
}
public ItemStackBuilder addLineLore() {
return addLineLore(20);
}
public ItemStackBuilder addLineLore(int length) {
addLore("&8&m&l" + Strings.repeat("-", length));
return this;
}
public ItemStackBuilder addLore(String... lore) {
ItemMeta itemMeta = itemStack.getItemMeta();
List<String> original = itemMeta.getLore();
if (original == null) original = new ArrayList<>();
Collections.addAll(original, Strings.format(lore));
itemMeta.setLore(original);
itemStack.setItemMeta(itemMeta);
return this;
}
public ItemStackBuilder addLore(List<String> lore) {
ItemMeta itemMeta = itemStack.getItemMeta();
List<String> original = itemMeta.getLore();
if (original == null) original = new ArrayList<>();
original.addAll(Strings.format(lore));
itemMeta.setLore(original);
itemStack.setItemMeta(itemMeta);
return this;
}
public ItemStackBuilder setLore(String... lore) {
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.setLore(Strings.format(Lists.newArrayList(lore)));
itemStack.setItemMeta(itemMeta);
return this;
}
public ItemStackBuilder setLore(List<String> lore) {
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.setLore(Strings.format(lore));
itemStack.setItemMeta(itemMeta);
return this;
}
public ItemStack build() {
return itemStack;
}
}
public static class BookBuilder {
private final ItemStack itemStack = new ItemStack(Material.WRITTEN_BOOK);
private BookMeta meta;
BookBuilder() {
meta = (BookMeta) itemStack.clone().getItemMeta();
meta.setTitle(Strings.format("&lWritten Book"));
meta.setAuthor("Hex Framework");
}
public BookBuilder setTitle(String title) {
meta.setTitle(Strings.format(title));
return this;
}
public BookBuilder setAuthor(String author) {
meta.setAuthor(Strings.format(author));
return this;
}
public BookBuilder addPage(String... lines) {
StringBuilder builder = new StringBuilder();
for (String line : lines) {
builder.append(Strings.format(((line == null || line.isEmpty()) ? " " : line))).append("\n");
}
meta.addPage(builder.toString());
return this;
}
public ItemStack build() {
ItemStack itemStack = this.itemStack.clone();
itemStack.setItemMeta(meta);
return itemStack;
}
}
}
| gpl-3.0 |
EugeneVolkorez/vmime | vmime/context.hpp | 3469 | //
// VMime library (http://www.vmime.org)
// Copyright (C) 2002-2013 Vincent Richard <[email protected]>
//
// 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, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// Linking this library statically or dynamically with other modules is making
// a combined work based on this library. Thus, the terms and conditions of
// the GNU General Public License cover the whole combination.
//
#ifndef VMIME_CONTEXT_HPP_INCLUDED
#define VMIME_CONTEXT_HPP_INCLUDED
#include "vmime/base.hpp"
#include "vmime/charsetConverterOptions.hpp"
namespace vmime
{
/** Holds configuration parameters used either for parsing or generating messages.
*/
class context : public object
{
public:
virtual ~context();
/** Returns whether support for Internationalized Email Headers (RFC-6532)
* is enabled.
*
* @return true if RFC-6532 support is enabled, false otherwise
*/
bool getInternationalizedEmailSupport() const;
/** Enables or disables support for Internationalized Email Headers (RFC-6532).
* This is disabled by default, and should be used only with servers
* which support it (eg. SMTP servers with SMTPUTF8 extension).
*
* @param support true if RFC-6532 support is enabled, false otherwise
*/
void setInternationalizedEmailSupport(const bool support);
/** Returns options used currently for charset conversions by the parser and/or
* the generator. See charsetConverterOptions class for more information.
*
* @return current charset conversion options
*/
const charsetConverterOptions& getCharsetConversionOptions() const;
/** Sets the options used currently for charset conversions by the parser and/or
* the generator. See charsetConverterOptions class for more information.
*
* @param opts new charset conversion options
*/
void setCharsetConversionOptions(const charsetConverterOptions& opts);
/** Switches between contexts temporarily.
*/
template <typename CTX_CLASS>
class switcher
{
public:
/** Switches to the specified context.
* Default context will temporarily use the data of the specified
* new context during the lifetime of this object.
*
* @param newCtx new context
*/
switcher(CTX_CLASS& newCtx)
: m_oldCtxData(CTX_CLASS::getDefaultContext()), m_newCtx(&newCtx)
{
CTX_CLASS::getDefaultContext().copyFrom(newCtx);
}
/** Restores back saved context.
*/
~switcher()
{
CTX_CLASS::getDefaultContext().copyFrom(m_oldCtxData);
}
private:
CTX_CLASS m_oldCtxData;
CTX_CLASS* m_newCtx;
};
protected:
context();
context(const context& ctx);
virtual context& operator=(const context& ctx);
void copyFrom(const context& ctx);
bool m_internationalizedEmail;
charsetConverterOptions m_charsetConvOptions;
};
} // vmime
#endif // VMIME_CONTEXT_HPP_INCLUDED
| gpl-3.0 |
hveto/hveto | setup.py | 1184 | # -*- coding: utf-8 -*-
# Copyright (C) Louisiana State University (2013)
#
# This file is part of the hveto python package.
#
# hveto 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.
#
# hveto 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 hveto. If not, see <http://www.gnu.org/licenses/>.
"""Setup the Hveto package
"""
from setuptools import setup
import versioneer
# versioneer
version = versioneer.get_version()
cmdclass = versioneer.get_cmdclass()
# import sphinx commands
try:
from sphinx.setup_command import BuildDoc
except ImportError:
pass
else:
cmdclass['build_sphinx'] = BuildDoc
# run setup
# NOTE: all other metadata and options come from setup.cfg
setup(
version=version,
cmdclass=cmdclass,
)
| gpl-3.0 |
VertigeASBL/genrespluriels | ecrire/public/jointures.php | 11387 | <?php
/***************************************************************************\
* SPIP, Systeme de publication pour l'internet *
* *
* Copyright (c) 2001-2013 *
* Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
* *
* Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
* Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
\***************************************************************************/
if (!defined('_ECRIRE_INC_VERSION')) return;
// deduction automatique d'une chaine de jointures
/**
* decomposer un champ id_article en (id_objet,objet,'article') si necessaire
*
* @param string $champ
* @return array ou string
*/
// http://doc.spip.org/@decompose_champ_id_objet
function decompose_champ_id_objet($champ){
if (($champ!=='id_objet') AND preg_match(',^id_([a-z_]+)$,',$champ,$regs)){
return array('id_objet','objet',$regs[1]);
}
return $champ;
}
/**
* mapping d'un champ d'une jointure en deux champs id_objet,objet si necessaire
*
* @param string $champ
* @param array $desc
* @return array
*/
// http://doc.spip.org/@trouver_champs_decomposes
function trouver_champs_decomposes($champ,$desc){
if (!is_array($desc) // on ne se risque pas en conjectures si on ne connait pas la table
OR array_key_exists($champ,$desc['field']))
return array($champ);
if (is_array($decompose=decompose_champ_id_objet($champ))){
array_pop($decompose);
if (count(array_intersect($decompose,array_keys($desc['field'])))==count($decompose))
return $decompose;
}
return array($champ);
}
// http://doc.spip.org/@calculer_jointure
function calculer_jointure(&$boucle, $depart, $arrivee, $col='', $cond=false)
{
$res = calculer_chaine_jointures($boucle, $depart, $arrivee);
if (!$res) return "";
list($nom,$desc) = $depart;
return fabrique_jointures($boucle, $res, $cond, $desc, $nom, $col);
}
// http://doc.spip.org/@fabrique_jointures
function fabrique_jointures(&$boucle, $res, $cond=false, $desc=array(), $nom='', $col='')
{
static $num=array();
$id_table = "";
$cpt = &$num[$boucle->descr['nom']][$boucle->descr['gram']][$boucle->id_boucle];
foreach($res as $cle=>$r) {
list($d, $a, $j) = $r;
if (!$id_table) $id_table = $d;
$n = ++$cpt;
if (is_array($j)){ // c'est un lien sur un champ du type id_objet,objet,'article'
list($j1,$j2,$obj,$type) = $j;
// trouver de quel cote est (id_objet,objet)
if ($j1=="id_$obj")
$obj = "$id_table.$obj";
else
$obj = "L$n.$obj";
// le where complementaire est envoye dans la jointure pour pouvoir etre elimine avec la jointure
// en cas d'optimisation
//$boucle->where[] = array("'='","'$obj'","sql_quote('$type')");
$boucle->join["L$n"]= array("'$id_table'","'$j2'","'$j1'","'$obj='.sql_quote('$type')");
}
else
$boucle->join["L$n"]= array("'$id_table'","'$j'");
$boucle->from[$id_table = "L$n"] = $a[0];
}
// pas besoin de group by
// (cf http://article.gmane.org/gmane.comp.web.spip.devel/30555)
// si une seule jointure et sur une table avec primary key formee
// de l'index principal et de l'index de jointure (non conditionnel! [6031])
// et operateur d'egalite (http://trac.rezo.net/trac/spip/ticket/477)
if ($pk = (isset($a[1]) && (count($boucle->from) == 2) && !$cond)) {
$pk = nogroupby_if($desc, $a[1], $col);
}
// pas de group by
// si une seule jointure
// et si l'index de jointure est une primary key a l'arrivee !
if (!$pk
AND (count($boucle->from) == 2)
AND isset($a[1]['key']['PRIMARY KEY'])
AND ($j == $a[1]['key']['PRIMARY KEY'])
)
$pk = true;
// la clause Group by est en conflit avec ORDER BY, a completer
$groups = liste_champs_jointures($nom,$desc,true);
if (!$pk) foreach($groups as $id_prim){
$id_field = $nom . '.' . $id_prim;
if (!in_array($id_field, $boucle->group)) {
$boucle->group[] = $id_field;
}
}
$boucle->modificateur['lien'] = true;
return "L$n";
}
// condition suffisante pour qu'un Group-By ne soit pas necessaire
// A ameliorer, notamment voir si calculer_select ne pourrait pas la reutiliser
// lorsqu'on sait si le critere conditionnel est finalement present
// http://doc.spip.org/@nogroupby_if
function nogroupby_if($depart, $arrivee, $col)
{
$pk = $arrivee['key']['PRIMARY KEY'];
if (!$pk) return false;
$id_primary = $depart['key']['PRIMARY KEY'];
if (is_array($col)) $col = implode(', *',$col); // cas id_objet, objet
return (preg_match("/^$id_primary, *$col$/", $pk) OR
preg_match("/^$col, *$id_primary$/", $pk));
}
// http://doc.spip.org/@liste_champs_jointures
function liste_champs_jointures($nom,$desc,$primary=false){
static $nojoin = array('idx','maj','date','statut');
// si cle primaire demandee, la privilegier
if ($primary && isset($desc['key']['PRIMARY KEY']))
return split_key($desc['key']['PRIMARY KEY']);
// les champs declares explicitement pour les jointures
if (isset($desc['join'])) return $desc['join'];
/*elseif (isset($GLOBALS['tables_principales'][$nom]['join'])) return $GLOBALS['tables_principales'][$nom]['join'];
elseif (isset($GLOBALS['tables_auxiliaires'][$nom]['join'])) return $GLOBALS['tables_auxiliaires'][$nom]['join'];*/
// si pas de cle, c'est fichu
if (!isset($desc['key'])) return array();
// si cle primaire
if (isset($desc['key']['PRIMARY KEY']))
return split_key($desc['key']['PRIMARY KEY']);
// ici on se rabat sur les cles secondaires,
// en eliminant celles qui sont pas pertinentes (idx, maj)
// si jamais le resultat n'est pas pertinent pour une table donnee,
// il faut declarer explicitement le champ 'join' de sa description
$join = array();
foreach($desc['key'] as $v) $join = split_key($v, $join);
foreach($join as $k) if (in_array($k, $nojoin)) unset($join[$k]);
return $join;
}
// http://doc.spip.org/@split_key
function split_key($v, $join = array())
{
foreach (preg_split('/,\s*/', $v) as $k) $join[$k] = $k;
return $join;
}
// http://doc.spip.org/@calculer_chaine_jointures
function calculer_chaine_jointures(&$boucle, $depart, $arrivee, $vu=array(), $milieu_exclus = array(), $max_liens = 5)
{
static $trouver_table;
if (!$trouver_table)
$trouver_table = charger_fonction('trouver_table', 'base');
if (is_string($milieu_exclus))
$milieu_exclus = array($milieu_exclus);
list($dnom,$ddesc) = $depart;
list($anom,$adesc) = $arrivee;
if (!count($vu))
$vu[] = $dnom; // ne pas oublier la table de depart
$akeys = $adesc['key'];
if ($v = $akeys['PRIMARY KEY']) {
unset($akeys['PRIMARY KEY']);
$akeys = array_merge(preg_split('/,\s*/', $v), $akeys);
}
// enlever les cles d'arrivee exclues par l'appel
$akeys = array_diff($akeys,$milieu_exclus);
// cles candidates au depart
$keys = liste_champs_jointures($dnom,$ddesc);
// enlever les cles dde depart exclues par l'appel
$keys = array_diff($keys,$milieu_exclus);
$v = !$keys ? false : array_intersect(array_values($keys), $akeys);
if ($v)
return array(array($dnom, array($adesc['table'],$adesc), array_shift($v)));
// regarder si l'on a (id_objet,objet) au depart et si on peut le mapper sur un id_xx
if (count(array_intersect(array('id_objet','objet'),$keys))==2){
// regarder si l'une des cles d'arrivee peut se decomposer en
// id_objet,objet
// si oui on la prend
foreach($akeys as $key){
$v = decompose_champ_id_objet($key);
if (is_array($v)){
$objet = array_shift($v);// objet,'article'
array_unshift($v,$key); // id_article,objet,'article'
array_unshift($v,$objet); // id_objet,id_article,objet,'article'
return array(array($dnom, array($adesc['table'],$adesc), $v));
}
}
}
else {
// regarder si l'une des cles de depart peut se decomposer en
// id_objet,objet a l'arrivee
// si oui on la prend
foreach($keys as $key){
if (count($v = trouver_champs_decomposes($key,$adesc))>1){
if (count($v)==count(array_intersect($v, $akeys)))
$v = decompose_champ_id_objet($key); // id_objet,objet,'article'
array_unshift($v,$key); // id_article,id_objet,objet,'article'
return array(array($dnom, array($adesc['table'],$adesc), $v));
}
}
}
// si l'on voulait une jointure direct, c'est rate !
if ($max_liens<=1) return array();
// sinon essayer de passer par une autre table
$new = $vu;
foreach($boucle->jointures as $v) {
if ($v && (!in_array($v,$vu)) &&
($def = $trouver_table($v, $boucle->sql_serveur))) {
// ne pas tester les cles qui sont exclues a l'appel
// ie la cle de la jointure precedente
$test_cles = $milieu_exclus;
$new[] = $v;
$max_iter = 50; // securite
while (count($jointure_directe_possible = calculer_chaine_jointures($boucle,$depart,array($v, $def),$vu,$test_cles,1))
AND $max_iter--) {
$jointure_directe_possible = reset($jointure_directe_possible);
$milieu = end($jointure_directe_possible);
if (is_string($milieu))
$test_cles[] = $milieu;
else
$test_cles = array_merge($test_cles,$milieu);
// essayer de rejoindre l'arrivee a partir de cette etape intermediaire
// sans repasser par la meme cle milieu
$r = calculer_chaine_jointures($boucle, array($v, $def), $arrivee, $new, $milieu,$max_liens-1);
if ($r) {
array_unshift($r, $jointure_directe_possible);
return $r;
}
}
}
}
return array();
}
// applatit les cles multiples
// http://doc.spip.org/@trouver_cles_table
function trouver_cles_table($keys)
{
$res =array();
foreach ($keys as $v) {
if (!strpos($v,","))
$res[$v]=1;
else {
foreach (preg_split("/\s*,\s*/", $v) as $k) {
$res[$k]=1;
}
}
}
return array_keys($res);
}
// http://doc.spip.org/@trouver_champ_exterieur
function trouver_champ_exterieur($cle, $joints, &$boucle, $checkarrivee = false)
{
static $trouver_table;
if (!$trouver_table)
$trouver_table = charger_fonction('trouver_table', 'base');
// support de la recherche multi champ
if (!is_array($cle))
$cle = array($cle);
foreach($joints as $k => $join) {
if ($join && $table = $trouver_table($join, $boucle->sql_serveur)) {
if (isset($table['field'])
// verifier que toutes les cles cherchees sont la
AND (count(array_intersect($cle, array_keys($table['field'])))==count($cle))
// si on sait ou on veut arriver, il faut que ca colle
AND ($checkarrivee==false || $checkarrivee==$table['table']))
return array($table['table'], $table);
}
}
// une cle id_xx peut etre implementee par un couple (id_objet,objet)
foreach($cle as $k=>$c) {
if (is_array($decompose = decompose_champ_id_objet($c))){
unset($cle[$k]);
$cle[] = array_shift($decompose); // id_objet
$cle[] = array_shift($decompose); // objet
return trouver_champ_exterieur($cle,$joints,$boucle,$checkarrivee);
}
}
return "";
}
// http://doc.spip.org/@trouver_jointure_champ
function trouver_jointure_champ($champ, &$boucle)
{
$cle = trouver_champ_exterieur($champ, $boucle->jointures, $boucle);
if ($cle) {
$desc = $boucle->show;
$cle = calculer_jointure($boucle, array($desc['id_table'], $desc), $cle, false);
}
if ($cle) return $cle;
spip_log("trouver_jointure_champ: $champ inconnu");
return '';
}
?>
| gpl-3.0 |
themiwi/freefoam-debian | src/OpenFOAM/db/IOstreams/Pstreams/OPstream.H | 6376 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd.
\\/ 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/>.
Class
Foam::OPstream
Description
Output inter-processor communications stream.
SourceFiles
OPstream.C
\*---------------------------------------------------------------------------*/
// intentionally outside include guards!
#include <OpenFOAM/Pstream.H>
#ifndef OPstream_H
#define OPstream_H
#include <OpenFOAM/Ostream.H>
#include "OPstreamImpl.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class OPstream Declaration
\*---------------------------------------------------------------------------*/
class OPstream
:
public Pstream,
public Ostream
{
// Private data
static autoPtr<OPstreamImpl> impl_;
// Private member functions
//- Write a T to the transfer buffer
template<class T>
inline void writeToBuffer(const T&);
//- Write a char to the transfer buffer
inline void writeToBuffer(const char&);
//- Write data to the transfer buffer
inline void writeToBuffer(const void* data, size_t count, size_t align);
//- Fetches the PstreamImpl instance if necessary
static autoPtr<OPstreamImpl>& impl()
{
if(!impl_.valid())
{
impl_ = OPstreamImpl::New();
}
return impl_;
}
protected:
// Protected data
int toProcNo_;
public:
// Constructors
//- Construct given process index to send to and optional buffer size,
// write format and IO version
OPstream
(
const commsTypes commsType,
const int toProcNo,
const label bufSize = 0,
streamFormat format=BINARY,
versionNumber version=currentVersion
);
// Destructor
~OPstream();
// Member functions
// Inquiry
//- Return flags of output stream
ios_base::fmtflags flags() const
{
return ios_base::fmtflags(0);
}
// Write functions
//- Write given buffer to given processor
static bool write
(
const commsTypes commsType,
const int toProcNo,
const char* buf,
const std::streamsize bufSize
)
{
return impl()->write(commsType, toProcNo, buf, bufSize);
}
//- Non-blocking writes: wait until all have finished.
static void waitRequests()
{
impl()->waitRequests();
}
//- Non-blocking writes: has request i finished?
static bool finishedRequest(const label i)
{
return impl()->finishedRequest(i);
}
//- Write next token to stream
Ostream& write(const token&);
//- Write character
Ostream& write(const char);
//- Write character string
Ostream& write(const char*);
//- Write word
Ostream& write(const word&);
//- Write string
Ostream& write(const string&);
//- Write std::string surrounded by quotes.
// Optional write without quotes.
Ostream& writeQuoted
(
const std::string&,
const bool quoted=true
);
//- Write label
Ostream& write(const label);
//- Write floatScalar
Ostream& write(const floatScalar);
//- Write doubleScalar
Ostream& write(const doubleScalar);
//- Write binary block
Ostream& write(const char*, std::streamsize);
//- Add indentation characters
void indent()
{}
// Stream state functions
//- Flush stream
void flush()
{}
//- Add newline and flush stream
void endl()
{}
//- Get width of output field
int width() const
{
return 0;
}
//- Set width of output field (and return old width)
int width(const int)
{
return 0;
}
//- Get precision of output field
int precision() const
{
return 0;
}
//- Set precision of output field (and return old precision)
int precision(const int)
{
return 0;
}
// Edit
//- Set flags of stream
ios_base::fmtflags flags(const ios_base::fmtflags)
{
return ios_base::fmtflags(0);
}
// Print
//- Print description of IOstream to Ostream
void print(Ostream&) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************ vim: set sw=4 sts=4 et: ************************ //
| gpl-3.0 |
heewei/ROSUnit00 | build/catkin_generated/generate_cached_setup.py | 1261 | # -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/ros/indigo/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.path.insert(0, os.path.join('/opt/ros/indigo/share/catkin/cmake', '..', 'python'))
try:
from catkin.environment_cache import generate_environment_script
except ImportError:
# search for catkin package in all workspaces and prepend to path
for workspace in "/opt/ros/indigo".split(';'):
python_path = os.path.join(workspace, 'lib/python2.7/dist-packages')
if os.path.isdir(os.path.join(python_path, 'catkin')):
sys.path.insert(0, python_path)
break
from catkin.environment_cache import generate_environment_script
code = generate_environment_script('/home/hewei/rosWS/devel/env.sh')
output_filename = '/home/hewei/rosWS/build/catkin_generated/setup_cached.sh'
with open(output_filename, 'w') as f:
#print('Generate script for cached setup "%s"' % output_filename)
f.write('\n'.join(code))
mode = os.stat(output_filename).st_mode
os.chmod(output_filename, mode | stat.S_IXUSR)
| gpl-3.0 |
theblock/theblock.github.io | flow-typed/moment.js | 172 | // GPLv3, Copyright (C) 2017, theBlock, https://theblock.io
// @flow
declare module 'moment' {
declare module.exports: (date: Date) => {
fromNow: () => string
}
}
| gpl-3.0 |
XMGmen/zentao | user/view/batchcreate.html.php | 3835 | <?php
/**
* The batch create view of user module of ZenTaoPMS.
*
* @copyright Copyright 2009-2015 青岛易软天创网络科技有限公司(QingDao Nature Easy Soft Network Technology Co,LTD, www.cnezsoft.com)
* @license ZPL (http://zpl.pub/page/zplv11.html)
* @author Yangyang Shi <[email protected]>
* @package story
* @version $Id$
* @link http://www.zentao.net
*/
?>
<?php include '../../common/view/header.html.php';?>
<?php js::set('roleGroup', $roleGroup);?>
<div id='titlebar'>
<div class='heading'>
<span class='prefix'><?php echo html::icon($lang->icons['user']);?></span>
<strong><small class='text-muted'><?php echo html::icon($lang->icons['batchCreate']);?></small> <?php echo $lang->user->batchCreate;?></strong>
</div>
</div>
<div id="tablestyle">
<form class='form-condensed' method='post' target='hiddenwin' id='dataform'>
<table class='table table-form table-fixed'>
<thead>
<tr>
<th class='w-40px'><?php echo $lang->idAB;?></th>
<th class='w-150px'><?php echo $lang->user->dept;?></th>
<th class='w-130px red'><?php echo $lang->user->account;?></th>
<th class='w-130px red'><?php echo $lang->user->realname;?></th>
<th class='w-120px red'><?php echo $lang->user->role;?></th>
<th class='w-120px'><?php echo $lang->user->group;?></th>
<th><?php echo $lang->user->email;?></th>
<th class='w-90px'><?php echo $lang->user->gender;?></th>
<th class="w-p20 red"><?php echo $lang->user->password;?></th>
</tr>
</thead>
<?php $depts = $depts + array('ditto' => $lang->user->ditto)?>
<?php $lang->user->roleList = $lang->user->roleList + array('ditto' => $lang->user->ditto)?>
<?php $groupList = $groupList + array('ditto' => $lang->user->ditto)?>
<?php for($i = 0; $i < $config->user->batchCreate; $i++):?>
<tr class='text-center'>
<td><?php echo $i+1;?></td>
<td class='text-left' style='overflow:visible'><?php echo html::select("dept[$i]", $depts, $i > 0 ? 'ditto' : $deptID, "class='form-control chosen'");?></td>
<td><?php echo html::input("account[$i]", '', "class='form-control account_$i' autocomplete='off' onchange='changeEmail($i)'");?></td>
<td><?php echo html::input("realname[$i]", '', "class='form-control'");?></td>
<td><?php echo html::select("role[$i]", $lang->user->roleList, $i > 0 ? 'ditto' : '', "class='form-control' onchange='changeGroup(this.value, $i)'");?></td>
<td class='text-left' style='overflow:visible'><?php echo html::select("group[$i]", $groupList, $i > 0 ? 'ditto' : '', "class='form-control chosen'");?></td>
<td><?php echo html::input("email[$i]", '', "class='form-control email_$i' onchange='setDefaultEmail($i)'");?></td>
<td><?php echo html::radio("gender[$i]", (array)$lang->user->genderList, 'm');?></td>
<td align='left'>
<div class='input-group'>
<?php
echo html::input("password[$i]", '', "class='form-control' autocomplete='off' onkeyup='toggleCheck(this, $i)'");
if($i != 0) echo "<span class='input-group-addon'><input type='checkbox' name='ditto[$i]' id='ditto$i' " . ($i> 0 ? "checked" : '') . " /> {$lang->user->ditto}</span>";
?>
</div>
</td>
</tr>
<?php endfor;?>
<tr>
<th colspan='2'><?php echo $lang->user->verifyPassword?></th>
<td colspan='7'>
<div class="required required-wrapper"></div>
<?php echo html::password('verifyPassword', '', "class='form-control' autocomplete='off' placeholder='{$lang->user->placeholder->verify}'");?>
</td>
</tr>
<tr><td colspan='9' class='text-center'><?php echo html::submitButton() . html::backButton();?></td></tr>
</table>
</form>
</div>
<?php include '../../common/view/footer.html.php';?>
| gpl-3.0 |
HackUCF/ppl | resumes/models.py | 1238 | from datetime import datetime
from django.contrib.auth.models import Group
from django.db import models
from dateutil.tz import gettz
from membership.models import Member
eastern_tz = gettz('America/New_York')
class ResumeShares(models.Model):
group = models.OneToOneField(Group, related_name='share_group')
resumes = models.ManyToManyField('Resume', related_name='shared_with')
class Resume(models.Model):
GRADUATION_CHOICES = (
(datetime(2015, 12, 18, tzinfo=eastern_tz), 'Fall 2015'),
(datetime(2015, 5, 5, tzinfo=eastern_tz), 'Spring 2016'),
(datetime(2015, 8, 6, tzinfo=eastern_tz), 'Summer 2016'),
(datetime(2016, 12, 18, tzinfo=eastern_tz), 'Fall 2016'),
(datetime(2017, 1, 1, tzinfo=eastern_tz), '2017'),
(datetime(2018, 1, 1, tzinfo=eastern_tz), '2018'),
(datetime(2019, 1, 1, tzinfo=eastern_tz), '2019'),
(datetime(2020, 1, 1, tzinfo=eastern_tz), '2020+'),
)
GRADUATION_DATES = {name: dt for dt, name in GRADUATION_CHOICES}
timestamp = models.DateTimeField()
member = models.OneToOneField(to=Member, related_name='resume')
url = models.URLField(unique=True)
graduation = models.DateTimeField(choices=GRADUATION_CHOICES)
| gpl-3.0 |
kennym/itools | test/test_ical.py | 36237 | # -*- coding: UTF-8 -*-
# Copyright (C) 2005-2008 Juan David Ibáñez Palomar <[email protected]>
# Copyright (C) 2006-2007 Nicolas Deram <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import from the Standard Library
from cStringIO import StringIO
from datetime import datetime
from unittest import TestCase, main
# Import from itools
from itools.csv import Property
from itools.csv.table import encode_param_value
from itools.datatypes import String
from itools.ical import iCalendar, icalendarTable
# Example with 1 event
content = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.0//EN
METHOD:PUBLISH
BEGIN:VEVENT
UID:581361a0-1dd2-11b2-9a42-bd3958eeac9a
SUMMARY:Résumé
DESCRIPTION:all all all
LOCATION:France
STATUS:TENTATIVE
CLASS:PRIVATE
X-MOZILLA-RECUR-DEFAULT-INTERVAL:0
DTSTART;VALUE="DATE":20050530
DTEND;VALUE=DATE:20050531
DTSTAMP:20050601T074604Z
ATTENDEE;RSVP=TRUE;MEMBER="mailto:[email protected]":mailto:[email protected]
ATTENDEE;MEMBER="mailto:[email protected]":mailto:[email protected]
PRIORITY:1
SEQUENCE:0
END:VEVENT
END:VCALENDAR
"""
# Example with 2 events
content2 = """
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.0//EN
METHOD:PUBLISH
BEGIN:VEVENT
UID:581361a0-1dd2-11b2-9a42-bd3958eeac9a
SUMMARY:Refound
DESCRIPTION:all all all
LOCATION:France
STATUS:TENTATIVE
CLASS:PRIVATE
X-MOZILLA-RECUR-DEFAULT-INTERVAL:0
DTSTART;VALUE="DATE":20050530T000000
DTEND;VALUE=DATE:20050531T235959.999999
DTSTAMP:20050601T074604Z
ATTENDEE;RSVP=TRUE;MEMBER="mailto:[email protected]":mailto:[email protected]
PRIORITY:1
SEQUENCE:0
END:VEVENT
BEGIN:VEVENT
UID:581361a0-1dd2-11b2-9a42-bd3958eeac9b
SUMMARY:222222222
DTSTART;VALUE="DATE":20050701
DTEND;VALUE=DATE:20050701
ATTENDEE;RSVP=TRUE;MEMBER="mailto:[email protected]":mailto:[email protected]
PRIORITY:2
SEQUENCE:0
END:VEVENT
END:VCALENDAR
"""
def property_to_string(prop_name, prop):
"""Method only used by test_load and test_load2.
"""
value, params = prop.value, ''
for p_name in prop.parameters:
p_value = prop.parameters[p_name]
p_value = [ encode_param_value(p_name, x, String) for x in p_value ]
param = ';%s=%s' % (p_name, ','.join(p_value))
params = params + param
return u'%s%s:%s' % (prop_name, params, value)
class icalTestCase(TestCase):
def setUp(self):
self.cal1 = iCalendar(string=content)
self.cal2 = iCalendar(string=content2)
def test_new(self):
cal = iCalendar()
properties = []
for name in cal.properties:
params = cal.properties[name].parameters
value = cal.properties[name].value
property = '%s;%s:%s' % (name, params, value)
properties.append(property)
# Test properties
expected_properties = [
u'VERSION;{}:2.0',
u'PRODID;{}:-//itaapy.com/NONSGML ikaaro icalendar V1.0//EN']
self.assertEqual(properties, expected_properties)
# Test components
self.assertEqual(len(cal.get_components()), 0)
self.assertEqual(cal.get_components('VEVENT'), [])
def test_property(self):
"""Test to create, access and encode a property with or without
parameters.
"""
# Property without parameter
expected = ['SUMMARY:This is the summary\n']
property_value = Property('This is the summary')
output = self.cal1.encode_property('SUMMARY', property_value)
self.assertEqual(output, expected)
# Property with one parameter
expected = ['ATTENDEE;MEMBER="mailto:[email protected]":'
'mailto:[email protected]\n']
member = 'mailto:[email protected]'
value = Property('mailto:[email protected]', MEMBER=[member])
output = self.cal1.encode_property('ATTENDEE', value)
self.assertEqual(output, expected)
def test_get_property_values(self):
cal = self.cal1
# icalendar property
expected = '2.0'
property = cal.get_property_values('VERSION')
self.assertEqual(property.value, expected)
# Component property
events = cal.get_components('VEVENT')
properties = events[0].get_version()
expected = u'Résumé'
property = events[0].get_property_values('SUMMARY')
self.assertEqual(property.value, expected)
expected = 1
property = events[0].get_property_values('PRIORITY')
self.assertEqual(property.value, expected)
# Component properties
properties = {}
properties['MYADD'] = Property(u'Résumé à crêtes')
value = Property(u'Property added by calling add_property')
properties['DESCRIPTION'] = value
member = '"mailto:[email protected]"'
value = Property('mailto:[email protected]', MEMBER=[member])
properties['ATTENDEE'] = value
uid = cal.add_component('VEVENT', **properties)
event = cal.get_component_by_uid(uid)
properties = event.get_property_values()
self.assertEqual('MYADD' in properties, True)
self.assertEqual('DESCRIPTION' in properties, True)
self.assertEqual('ATTENDEE' in properties, True)
self.assertEqual('VERSION' in properties, False)
def test_add_to_calendar(self):
"""Test to add property and component to an empty icalendar object.
"""
cal = iCalendar()
cal.add_component('VEVENT')
self.assertEqual(len(cal.get_components('VEVENT')), 1)
value = Property('PUBLISH')
cal.set_property('METHOD', value)
self.assertEqual(cal.get_property_values('METHOD'), value)
def test_load(self):
"""Test loading a simple calendar.
"""
cal = self.cal1
# Test icalendar properties
properties = []
for name in cal.properties:
property_value = cal.properties[name]
# Only property METHOD can occur several times, we give only one
if isinstance(property_value, list):
property_value = property_value[0]
params = property_value.parameters
value = property_value.value
property = '%s;%s:%s' % (name, params, value)
properties.append(property)
expected_properties = [
u'VERSION;{}:2.0',
u'METHOD;{}:PUBLISH',
u'PRODID;{}:-//Mozilla.org/NONSGML Mozilla Calendar V1.0//EN' ]
self.assertEqual(properties, expected_properties)
# Test component properties
properties = []
event = cal.get_components('VEVENT')[0]
version = event.get_version()
for prop_name in version:
datatype = cal.get_record_datatype(prop_name)
if datatype.multiple is False:
prop = version[prop_name]
property = property_to_string(prop_name, prop)
properties.append(property)
else:
for prop in version[prop_name]:
property = property_to_string(prop_name, prop)
properties.append(property)
expected_event_properties = [
u'STATUS:TENTATIVE',
u'DTSTAMP:2005-06-01 07:46:04',
u'DESCRIPTION:all all all',
u'ATTENDEE;MEMBER="mailto:[email protected]"'
';RSVP=TRUE:mailto:[email protected]',
u'ATTENDEE;MEMBER="mailto:[email protected]"'
':mailto:[email protected]',
u'SUMMARY:Résumé',
u'PRIORITY:1',
u'LOCATION:France',
u'X-MOZILLA-RECUR-DEFAULT-INTERVAL:0',
u'DTEND;VALUE=DATE:2005-05-31 00:00:00',
u'DTSTART;VALUE=DATE:2005-05-30 00:00:00',
u'CLASS:PRIVATE']
self.assertEqual(event.uid, '581361a0-1dd2-11b2-9a42-bd3958eeac9a')
self.assertEqual(properties, expected_event_properties)
self.assertEqual(len(cal.get_components('VEVENT')), 1)
# Test journals
self.assertEqual(len(cal.get_components('VJOURNAL')), 0)
# Test todos
self.assertEqual(len(cal.get_components('TODO')), 0)
# Test freebusys
self.assertEqual(len(cal.get_components('FREEBUSY')), 0)
# Test timezones
self.assertEqual(len(cal.get_components('TIMEZONE')), 0)
# Test others
self.assertEqual(len(cal.get_components('others')), 0)
def test_load_2(self):
"""Test loading a 2 events calendar.
"""
cal = self.cal2
properties = []
for name in cal.properties:
params = cal.properties[name].parameters
value = cal.properties[name].value
property = '%s;%s:%s' % (name, params, value)
properties.append(property)
# Test properties
expected_properties = [
u'VERSION;{}:2.0',
u'METHOD;{}:PUBLISH',
u'PRODID;{}:-//Mozilla.org/NONSGML Mozilla Calendar V1.0//EN' ]
self.assertEqual(properties, expected_properties)
events = []
for event in cal.get_components('VEVENT'):
version = event.get_version()
properties = []
for prop_name in version:
if prop_name == 'DTSTAMP':
continue
datatype = cal.get_record_datatype(prop_name)
if datatype.multiple is False:
prop = version[prop_name]
property = property_to_string(prop_name, prop)
properties.append(property)
else:
for prop in version[prop_name]:
property = property_to_string(prop_name, prop)
properties.append(property)
events.append(properties)
# Test events
expected_events = [[
u'STATUS:TENTATIVE',
u'DESCRIPTION:all all all',
u'ATTENDEE;MEMBER="mailto:[email protected]"'
';RSVP=TRUE:mailto:[email protected]',
u'SUMMARY:Refound',
u'PRIORITY:1',
u'LOCATION:France',
u'X-MOZILLA-RECUR-DEFAULT-INTERVAL:0',
u'DTEND;VALUE=DATE:2005-05-31 23:59:59.999999',
u'DTSTART;VALUE=DATE:2005-05-30 00:00:00',
u'CLASS:PRIVATE'],
[
u'ATTENDEE;MEMBER="mailto:[email protected]";RSVP=TRUE'\
':mailto:[email protected]',
u'SUMMARY:222222222',
u'PRIORITY:2',
u'DTEND;VALUE=DATE:2005-07-01 00:00:00',
u'DTSTART;VALUE=DATE:2005-07-01 00:00:00'
]]
self.assertEqual(events, expected_events)
self.assertEqual(len(cal.get_components('VEVENT')), 2)
# Test journals
self.assertEqual(len(cal.get_components('VJOURNAL')), 0)
# Test todos
self.assertEqual(len(cal.get_components('TODO')), 0)
# Test freebusys
self.assertEqual(len(cal.get_components('FREEBUSY')), 0)
# Test timezones
self.assertEqual(len(cal.get_components('TIMEZONE')), 0)
# Test others
self.assertEqual(len(cal.get_components('others')), 0)
# Just call to_str method
def test_to_str(self):
"""Call to_str method.
"""
cal = self.cal2
cal.to_str()
def test_add_property(self):
"""Test adding a property to any component.
"""
cal = self.cal2
event = cal.get_components('VEVENT')[1]
# other property (MYADD)
name, value = 'MYADD', Property(u'Résumé à crêtes')
cal.update_component(event.uid, **{name: value})
property = event.get_property_values(name)
self.assertEqual(property[0], value)
self.assertEqual(property[0].value, value.value)
# property DESCRIPTION
name = 'DESCRIPTION'
value = Property(u'Property added by calling add_property')
cal.update_component(event.uid, **{name: value})
property = event.get_property_values(name)
self.assertEqual(property, value)
# property ATTENDEE
name = 'ATTENDEE'
value = event.get_property_values(name)
member = '"mailto:[email protected]"'
value.append(Property('mailto:[email protected]', MEMBER=[member]))
cal.update_component(event.uid, **{name: value})
property = event.get_property_values(name)
self.assertEqual(str(property[0].value), 'mailto:[email protected]')
self.assertEqual(property[1].parameters, {'MEMBER': [member]})
self.assertEqual(property[1], value[1])
def test_icalendar_set_property(self):
"""Test setting a new value to an existant icalendar property.
"""
cal = self.cal1
name, value = 'VERSION', Property('2.1')
cal.set_property(name, value)
self.assertEqual(cal.get_property_values(name), value)
cal.set_property(name, [value, ])
self.assertEqual(cal.get_property_values(name), value)
def test_component_set_property(self):
"""Test setting a new value to an existant component property.
"""
cal = self.cal1
event = cal.get_components('VEVENT')[0]
name, value = 'SUMMARY', Property('This is a new summary')
cal.update_component(event.uid, **{name: value})
self.assertEqual(event.get_property_values(name), value)
member = '"mailto:[email protected]"'
value = [
Property('mailto:[email protected]', MEMBER=[member]),
Property('mailto:[email protected]'),
Property('mailto:[email protected]')]
cal.update_component(event.uid, ATTENDEE=value)
self.assertEqual(event.get_property_values('ATTENDEE'), value)
def test_search_events(self):
"""Test get events filtered by arguments given.
"""
# Test with 1 event
cal = self.cal1
attendee_value = 'mailto:[email protected]'
events = cal.search_events(ATTENDEE=attendee_value)
self.assertEqual(len(events), 1)
events = cal.search_events(STATUS='CONFIRMED')
self.assertEqual(events, [])
events = cal.search_events(STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events(ATTENDEE=attendee_value, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events(STATUS='TENTATIVE', PRIORITY=1)
self.assertEqual(len(events), 1)
events = cal.search_events(
ATTENDEE=[attendee_value, 'mailto:[email protected]'],
STATUS='TENTATIVE',
PRIORITY=1)
self.assertEqual(len(events), 1)
# Tests with 2 events
cal = self.cal2
attendee_value = 'mailto:[email protected]'
events = cal.search_events(ATTENDEE=attendee_value)
self.assertEqual(len(events), 2)
events = cal.search_events(STATUS='CONFIRMED')
self.assertEqual(events, [])
events = cal.search_events(STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events(ATTENDEE=attendee_value, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events(STATUS='TENTATIVE', PRIORITY=1)
self.assertEqual(len(events), 1)
events = cal.search_events(
ATTENDEE=[attendee_value, 'mailto:[email protected]'],
STATUS='TENTATIVE',
PRIORITY=1)
self.assertEqual(len(events), 1)
def test_search_events_in_date(self):
"""Test search events by date.
"""
cal = self.cal1
date = datetime(2005, 5, 29)
events = cal.search_events_in_date(date)
self.assertEqual(len(events), 0)
self.assertEqual(cal.has_event_in_date(date), False)
date = datetime(2005, 5, 30)
events = cal.search_events_in_date(date)
self.assertEqual(len(events), 1)
self.assertEqual(cal.has_event_in_date(date), True)
events = cal.search_events_in_date(date, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events_in_date(date, STATUS='CONFIRMED')
self.assertEqual(len(events), 0)
attendee_value = 'mailto:[email protected]'
events = cal.search_events_in_date(date, ATTENDEE=attendee_value)
self.assertEqual(len(events), 1)
events = cal.search_events_in_date(date, ATTENDEE=attendee_value,
STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events_in_date(date, ATTENDEE=attendee_value,
STATUS='CONFIRMED')
self.assertEqual(len(events), 0)
date = datetime(2005, 7, 30)
events = cal.search_events_in_date(date)
self.assertEqual(len(events), 0)
self.assertEqual(cal.has_event_in_date(date), False)
def test_search_events_in_range(self):
"""Test search events matching given dates range.
"""
cal = self.cal2
dtstart = datetime(2005, 1, 1)
dtend = datetime(2005, 1, 1, 20, 0)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 0)
dtstart = datetime(2005, 5, 28)
dtend = datetime(2005, 5, 30, 0, 50)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
dtstart = datetime(2005, 5, 29)
dtend = datetime(2005, 5, 30, 0, 1)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
dtstart = datetime(2005, 5, 30, 23, 59, 59)
dtend = datetime(2005, 5, 31, 0, 0)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
dtstart = datetime(2005, 5, 1)
dtend = datetime(2005, 8, 1)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 2)
dtstart = datetime(2005, 5, 30, 23)
dtend = datetime(2005, 6, 1)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
dtstart = datetime(2005, 5, 31, 0, 0, 1)
dtend = datetime(2005, 6, 1)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
events = cal.search_events_in_range(dtstart, dtend, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events_in_range(dtstart, dtend, STATUS='CONFIRMED')
self.assertEqual(len(events), 0)
attendee_value = 'mailto:[email protected]'
events = cal.search_events_in_range(dtstart, dtend,
ATTENDEE=attendee_value)
self.assertEqual(len(events), 1)
events = cal.search_events_in_range(dtstart, dtend,
ATTENDEE=attendee_value, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events_in_range(dtstart, dtend,
ATTENDEE=attendee_value, STATUS='CONFIRMED')
self.assertEqual(len(events), 0)
def test_get_conflicts(self):
"""Test get_conflicts method which returns uid couples of events
conflicting on a given date.
"""
cal = self.cal2
date = datetime(2005, 05, 30)
conflicts = cal.get_conflicts(date)
self.assertEqual(conflicts, None)
# Set a conflict
uid1 = '581361a0-1dd2-11b2-9a42-bd3958eeac9a'
uid2 = '581361a0-1dd2-11b2-9a42-bd3958eeac9b'
cal.update_component(uid2, DTSTART=Property(datetime(2005, 05, 30)),
DTEND=Property(datetime(2005, 05, 31)))
conflicts = cal.get_conflicts(date)
self.assertEqual(conflicts, [(uid1, uid2)])
class icalTableTestCase(TestCase):
def setUp(self):
src = iCalendar(string=content)
src = StringIO(src.to_str())
cal = icalendarTable()
cal.load_state_from_ical_file(src)
self.cal1 = cal
src = iCalendar(string=content2)
src = StringIO(src.to_str())
cal = icalendarTable()
cal.load_state_from_ical_file(src)
self.cal2 = cal
def test_new(self):
cal = icalendarTable()
# Test components
self.assertEqual(len(cal.get_components()), 0)
self.assertEqual(cal.get_components('VEVENT'), [])
def test_property(self):
"""Test to create, access and encode a property with or without
parameters.
"""
# Property without parameter
expected = ['SUMMARY:This is the summary\n']
property_value = Property('This is the summary')
output = self.cal1.encode_property('SUMMARY', property_value)
self.assertEqual(output, expected)
# Property with one parameter
expected = ['ATTENDEE;MEMBER="mailto:[email protected]":'
'mailto:[email protected]\n']
member = 'mailto:[email protected]'
value = Property('mailto:[email protected]', MEMBER=[member])
output = self.cal1.encode_property('ATTENDEE', value)
self.assertEqual(output, expected)
def test_get_property(self):
cal = self.cal1
# Component property
events = cal.get_components('VEVENT')
properties = events[0][-1]
expected = u'Résumé'
property = events[0].get_property('SUMMARY')
self.assertEqual(property.value, expected)
expected = 1
property = events[0].get_property('PRIORITY')
self.assertEqual(property.value, expected)
# Component properties
properties = {}
properties['MYADD'] = Property(u'Résumé à crêtes')
value = Property(u'Property added by calling add_property')
properties['DESCRIPTION'] = value
member = '"mailto:[email protected]"'
value = Property('mailto:[email protected]', MEMBER=[member])
properties['ATTENDEE'] = value
properties['type'] = 'VEVENT'
uid = cal.add_record(properties).UID
event = cal.get_component_by_uid(uid)[0]
properties = event.get_property()
self.assertEqual('MYADD' in properties, True)
self.assertEqual('DESCRIPTION' in properties, True)
self.assertEqual('ATTENDEE' in properties, True)
self.assertEqual('VERSION' in properties, False)
def test_add_to_calendar(self):
"""Test to add property and component to an empty icalendar object.
"""
cal = icalendarTable()
cal.add_record({'type': 'VEVENT'})
self.assertEqual(len(cal.get_components('VEVENT')), 1)
def test_load(self):
"""Test loading a simple calendar.
"""
cal = self.cal1
# Test component properties
properties = []
event = cal.get_components('VEVENT')[0]
version = event[-1]
for prop_name in version:
if prop_name in ('ts', 'id', 'type', 'UID', 'SEQUENCE'):
continue
datatype = cal.get_record_datatype(prop_name)
if getattr(datatype, 'multiple', False) is False:
prop = version[prop_name]
property = property_to_string(prop_name, prop)
properties.append(property)
else:
for prop in version[prop_name]:
property = property_to_string(prop_name, prop)
properties.append(property)
expected_event_properties = [
u'STATUS:TENTATIVE',
u'DTSTAMP:2005-06-01 07:46:04',
u'DESCRIPTION:all all all',
u'ATTENDEE;MEMBER="mailto:[email protected]"'
';RSVP=TRUE:mailto:[email protected]',
u'ATTENDEE;MEMBER="mailto:[email protected]"'
':mailto:[email protected]',
u'SUMMARY:Résumé',
u'PRIORITY:1',
u'LOCATION:France',
u'X-MOZILLA-RECUR-DEFAULT-INTERVAL:0',
u'DTEND;VALUE=DATE:2005-05-31 00:00:00',
u'DTSTART;VALUE=DATE:2005-05-30 00:00:00',
u'CLASS:PRIVATE']
self.assertEqual(event.UID, '581361a0-1dd2-11b2-9a42-bd3958eeac9a')
self.assertEqual(properties, expected_event_properties)
self.assertEqual(len(cal.get_components('VEVENT')), 1)
# Test journals
self.assertEqual(len(cal.get_components('VJOURNAL')), 0)
# Test todos
self.assertEqual(len(cal.get_components('TODO')), 0)
# Test freebusys
self.assertEqual(len(cal.get_components('FREEBUSY')), 0)
# Test timezones
self.assertEqual(len(cal.get_components('TIMEZONE')), 0)
# Test others
self.assertEqual(len(cal.get_components('others')), 0)
def test_load_2(self):
"""Test loading a 2 events calendar.
"""
cal = self.cal2
events = []
for event in cal.get_components('VEVENT'):
version = event[-1]
properties = []
for prop_name in version:
if prop_name in ('ts', 'id', 'type', 'UID', 'SEQUENCE'):
continue
if prop_name == 'DTSTAMP':
continue
datatype = cal.get_record_datatype(prop_name)
if getattr(datatype, 'multiple', False) is False:
prop = version[prop_name]
property = property_to_string(prop_name, prop)
properties.append(property)
else:
for prop in version[prop_name]:
property = property_to_string(prop_name, prop)
properties.append(property)
events.append(properties)
# Test events
expected_events = [[
u'ATTENDEE;MEMBER="mailto:[email protected]";RSVP=TRUE'\
':mailto:[email protected]',
u'SUMMARY:222222222',
u'PRIORITY:2',
u'DTEND;VALUE=DATE:2005-07-01 00:00:00',
u'DTSTART;VALUE=DATE:2005-07-01 00:00:00'
],
[
u'STATUS:TENTATIVE',
u'DESCRIPTION:all all all',
u'ATTENDEE;MEMBER="mailto:[email protected]"'
';RSVP=TRUE:mailto:[email protected]',
u'SUMMARY:Refound',
u'PRIORITY:1',
u'LOCATION:France',
u'X-MOZILLA-RECUR-DEFAULT-INTERVAL:0',
u'DTEND;VALUE=DATE:2005-05-31 23:59:59.999999',
u'DTSTART;VALUE=DATE:2005-05-30 00:00:00',
u'CLASS:PRIVATE']
]
self.assertEqual(events, expected_events)
self.assertEqual(len(cal.get_components('VEVENT')), 2)
# Test journals
self.assertEqual(len(cal.get_components('VJOURNAL')), 0)
# Test todos
self.assertEqual(len(cal.get_components('TODO')), 0)
# Test freebusys
self.assertEqual(len(cal.get_components('FREEBUSY')), 0)
# Test timezones
self.assertEqual(len(cal.get_components('TIMEZONE')), 0)
# Test others
self.assertEqual(len(cal.get_components('others')), 0)
# Just call to_ical method
def test_to_ical(self):
"""Call to_ical method.
"""
cal = self.cal2
cal.to_ical()
def test_add_property(self):
"""Test adding a property to any component.
"""
cal = self.cal2
event = cal.get_components('VEVENT')[1]
# other property (MYADD)
name, value = 'MYADD', Property(u'Résumé à crêtes')
cal.update_record(event.id, **{name: value})
property = event.get_property(name)
self.assertEqual(property[0], value)
self.assertEqual(property[0].value, value.value)
# property DESCRIPTION
name = 'DESCRIPTION'
value = Property(u'Property added by calling add_property')
cal.update_record(event.id, **{name: value})
property = event.get_property(name)
self.assertEqual(property, value)
# property ATTENDEE
name = 'ATTENDEE'
value = event.get_property(name)
member = '"mailto:[email protected]"'
value.append(Property('mailto:[email protected]', MEMBER=[member]))
cal.update_record(event.id, **{name: value})
property = event.get_property(name)
self.assertEqual(str(property[0].value), 'mailto:[email protected]')
self.assertEqual(property[1].parameters, {'MEMBER': [member]})
self.assertEqual(property[1], value[1])
def test_component_set_property(self):
"""Test setting a new value to an existant component property.
"""
cal = self.cal1
event = cal.get_components('VEVENT')[0]
name, value = 'SUMMARY', Property('This is a new summary')
cal.update_record(event.id, **{name: value})
self.assertEqual(event.get_property(name), value)
member = '"mailto:[email protected]"'
value = [
Property('mailto:[email protected]', MEMBER=[member]),
Property('mailto:[email protected]'),
Property('mailto:[email protected]')]
cal.update_record(event.id, ATTENDEE=value)
self.assertEqual(event.get_property('ATTENDEE'), value)
def test_search_events(self):
"""Test get events filtered by arguments given.
"""
cal = self.cal1
# Test with 1 event
attendee_value = 'mailto:[email protected]'
events = cal.search_events(ATTENDEE=attendee_value)
self.assertEqual(len(events), 1)
events = cal.search_events(STATUS='CONFIRMED')
self.assertEqual(events, [])
events = cal.search_events(STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events(ATTENDEE=attendee_value, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events(STATUS='TENTATIVE', PRIORITY=1)
self.assertEqual(len(events), 1)
events = cal.search_events(
ATTENDEE=[attendee_value, 'mailto:[email protected]'],
STATUS='TENTATIVE',
PRIORITY=1)
self.assertEqual(len(events), 1)
# Tests with 2 events
cal = iCalendar(string=content2)
attendee_value = 'mailto:[email protected]'
events = cal.search_events(ATTENDEE=attendee_value)
self.assertEqual(len(events), 2)
events = cal.search_events(STATUS='CONFIRMED')
self.assertEqual(events, [])
events = cal.search_events(STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events(ATTENDEE=attendee_value, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events(STATUS='TENTATIVE', PRIORITY=1)
self.assertEqual(len(events), 1)
events = cal.search_events(
ATTENDEE=[attendee_value, 'mailto:[email protected]'],
STATUS='TENTATIVE',
PRIORITY=1)
self.assertEqual(len(events), 1)
def test_search_events_in_date(self):
"""Test search events by date.
"""
cal = self.cal1
date = datetime(2005, 5, 29)
events = cal.search_events_in_date(date)
self.assertEqual(len(events), 0)
self.assertEqual(cal.has_event_in_date(date), False)
date = datetime(2005, 5, 30)
events = cal.search_events_in_date(date)
self.assertEqual(len(events), 1)
self.assertEqual(cal.has_event_in_date(date), True)
events = cal.search_events_in_date(date, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events_in_date(date, STATUS='CONFIRMED')
self.assertEqual(len(events), 0)
attendee_value = 'mailto:[email protected]'
events = cal.search_events_in_date(date, ATTENDEE=attendee_value)
self.assertEqual(len(events), 1)
events = cal.search_events_in_date(date, ATTENDEE=attendee_value,
STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events_in_date(date, ATTENDEE=attendee_value,
STATUS='CONFIRMED')
self.assertEqual(len(events), 0)
date = datetime(2005, 7, 30)
events = cal.search_events_in_date(date)
self.assertEqual(len(events), 0)
self.assertEqual(cal.has_event_in_date(date), False)
def test_search_events_in_range(self):
"""Test search events matching given dates range.
"""
cal = self.cal2
dtstart = datetime(2005, 1, 1)
dtend = datetime(2005, 1, 1, 20, 0)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 0)
dtstart = datetime(2005, 5, 28)
dtend = datetime(2005, 5, 30, 0, 50)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
dtstart = datetime(2005, 5, 29)
dtend = datetime(2005, 5, 30, 0, 1)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
dtstart = datetime(2005, 5, 30, 23, 59, 59)
dtend = datetime(2005, 5, 31, 0, 0)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
dtstart = datetime(2005, 5, 1)
dtend = datetime(2005, 8, 1)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 2)
dtstart = datetime(2005, 5, 30, 23)
dtend = datetime(2005, 6, 1)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
dtstart = datetime(2005, 5, 31, 0, 0, 1)
dtend = datetime(2005, 6, 1)
events = cal.search_events_in_range(dtstart, dtend)
self.assertEqual(len(events), 1)
events = cal.search_events_in_range(dtstart, dtend, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events_in_range(dtstart, dtend, STATUS='CONFIRMED')
self.assertEqual(len(events), 0)
attendee_value = 'mailto:[email protected]'
events = cal.search_events_in_range(dtstart, dtend,
ATTENDEE=attendee_value)
self.assertEqual(len(events), 1)
events = cal.search_events_in_range(dtstart, dtend,
ATTENDEE=attendee_value, STATUS='TENTATIVE')
self.assertEqual(len(events), 1)
events = cal.search_events_in_range(dtstart, dtend,
ATTENDEE=attendee_value, STATUS='CONFIRMED')
self.assertEqual(len(events), 0)
def test_get_conflicts(self):
"""Test get_conflicts method which returns uid couples of events
conflicting on a given date.
"""
cal = self.cal2
date = datetime(2005, 05, 30)
conflicts = cal.get_conflicts(date)
self.assertEqual(conflicts, None)
# Set a conflict
uid1 = 0
uid2 = 1
cal.update_record(uid1, DTSTART=Property(datetime(2005, 05, 30)),
DTEND=Property(datetime(2005, 05, 31)))
conflicts = cal.get_conflicts(date)
self.assertEqual(conflicts, [(uid1, uid2)])
if __name__ == '__main__':
main()
| gpl-3.0 |
ChileanVirtualObservatory/Stacking | rotate.py | 4533 | #This file is part of ChiVO, the Chilean Virtual Observatory
#A project sponsored by FONDEF (D11I1060)
#Copyright (C) 2015 Universidad Tecnica Federico Santa Maria Mauricio Solar
# Marcelo Mendoza
# Universidad de Chile Diego Mardones
# Pontificia Universidad Catolica Karim Pichara
# Universidad de Concepcion Ricardo Contreras
# Universidad de Santiago Victor Parada
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from astropy.io import fits
import numpy as np
import glob
import math
from PIL import Image
import pyfits
import numpy as np
import pylab as py
import img_scale
def rotate_coords(x, y, theta, ox, oy):
s, c = np.sin(theta), np.cos(theta)
x, y = np.asarray(x) - ox, np.asarray(y) - oy
return x * c - y * s + ox, x * s + y * c + oy
def rotate_image(src, theta, fill=0):
# theta = -theta*np.pi/180
oy = len(src)
ox = len(src[0])
sh, sw = src.shape
cx, cy = rotate_coords([0, sw, sw, 0], [0, 0, sh, sh], theta, ox, oy)
dw, dh = (int(np.ceil(c.max() - c.min())) for c in (cx, cy))
dx, dy = np.meshgrid(np.arange(dw), np.arange(dh))
sx, sy = rotate_coords(dx + cx.min(), dy + cy.min(), -theta, ox, oy)
sx, sy = sx.round().astype(int), sy.round().astype(int)
mask = (0 <= sx) & (sx < sw) & (0 <= sy) & (sy < sh)
dest = np.empty(shape=(dh, dw), dtype=src.dtype)
dest[dy[mask], dx[mask]] = src[sy[mask], sx[mask]]
dest[dy[~mask], dx[~mask]] = fill
return dest
def fartestPoints(border):
dist = []
for i in xrange(0,len(border)):
for j in xrange(0,len(border)):
y1,x1 = border[i]
y2,x2 = border[j]
d = (x1-x2)**2 + (y1-y2)**2
d = math.sqrt(d)
dist.append((d,border[i],border[j]))
maxd = 0
points = 0
for i in xrange(0,len(dist)):
if dist[i][0] > maxd:
points = (dist[i][1],dist[i][2])
maxd = dist[i][0]
return points
def theta(points):
print points
y1,x1 = points[0]
y2,x2 = points[1]
theta = (y2-y1+.0)/(x2-x1+.0)
theta = math.atan(theta+(math.pi*9)/2)
return theta
def rotate(outputDir, border):
maxHeight = 0
maxWidth = 0
data = sorted(glob.glob(outputDir+'/Img_1_*.fits'))
dir_png = outputDir+'/PNG_Images'
for i in xrange(0,len(data)):
image = fits.getdata(data[i])
points = fartestPoints(border[i])
image = rotate_image(image,theta(points))
print "Rotate: "+'/Img_1_'+str(i)+'.fits',
fits.writeto(outputDir+'/Img_2_'+str(i)+'.fits',image, clobber=True)
# j_img = pyfits.getdata(outputDir+'/Img_2_'+str(i)+'.fits')
# img = np.zeros((j_img.shape[0], j_img.shape[1]), dtype=float)
# img[:,:] = img_scale.sqrt(j_img, scale_min=0, scale_max=10000)
# py.clf()
# py.imshow(img, aspect='equal')
# py.title('Rotate Img_2_'+str(i))
# py.savefig(dir_png+'/Img_2_'+str(i)+'.png')
# img = Image.open(dir_png+'/Img_2_'+str(i)+'.png')
# img.show()
print "Done."
h,w = image.shape
if h > maxHeight:
maxHeight = h
if w > maxWidth:
maxWidth = w
return (maxHeight,maxWidth)
def rotateManual(outputDir):
data = sorted(glob.glob(outputDir+'/Img_1_*.fits'))
# dir_png = outputDir+'/PNG_Images'
for i in xrange(0,len(data)):
image = fits.getdata(data[i])
image = rotate_image(image,math.atan(theta+(math.pi*9)/2))
print "Rotate: "+'/Img_1_'+str(i)+'.fits',
fits.writeto(outputDir+'/Img_2_'+str(i)+'.fits',image, clobber=True)
# j_img = pyfits.getdata(outputDir+'/Img_2_'+str(i)+'.fits')
# img = np.zeros((j_img.shape[0], j_img.shape[1]), dtype=float)
# img[:,:] = img_scale.sqrt(j_img, scale_min=0, scale_max=10000)
# py.clf()
# py.imshow(img, aspect='equal')
# py.title('Rotate Img_2_'+str(i))
# py.savefig(dir_png+'/Img_2_'+str(i)+'.png')
# img = Image.open(dir_png+'/Img_2_'+str(i)+'.png')
# img.show()
print "Done."
| gpl-3.0 |
Yoleimei/SourceCodeRepo | DataStructure_Algorithm/DataStructure/Tree/HuffmanTree/HuffmanTree.cpp | 2139 | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int MAX_VALUE = 999999999;
struct HuffmanNode
{
int weight;
char ch;
string code;
HuffmanNode *left;
HuffmanNode *right;
HuffmanNode(
int w,
char c,
string s = "",
HuffmanNode *l = nullptr,
HuffmanNode *r = nullptr
): weight(w), ch(c), code(s), left(l),right(r) {}
};
struct HuffmanNodeGreater
{
bool operator()(const HuffmanNode &a, const HuffmanNode &b)
{
return a.weight > b.weight;
}
};
void ConstructHuffmanTree(priority_queue<HuffmanNode, vector<HuffmanNode>, HuffmanNodeGreater> &HuffmanRoot)
{
while (HuffmanRoot.size() > 1)
{
HuffmanNode *left = new HuffmanNode(HuffmanRoot.top());
HuffmanRoot.pop();
HuffmanNode *right = new HuffmanNode(HuffmanRoot.top());
HuffmanRoot.pop();
HuffmanNode parent(left->weight + right->weight, ' ');
parent.left = left;
parent.right = right;
HuffmanRoot.push(parent);
}
}
void InOrderTraversal(HuffmanNode *node, vector<HuffmanNode> &vec, string &str)
{
if (node->left == NULL && node->right == NULL)
{
vec.push_back(HuffmanNode(node->weight, node->ch, str));
return;
}
if (node->left)
{
str.push_back('0');
InOrderTraversal(node->left, vec, str);
str.pop_back();
}
if (node->right)
{
str.push_back('1');
InOrderTraversal(node->right, vec, str);
str.pop_back();
}
}
void HuffmanCoding(const priority_queue<HuffmanNode, vector<HuffmanNode>, HuffmanNodeGreater> &HuffmanRoot, vector<HuffmanNode> &vec)
{
HuffmanNode node(HuffmanRoot.top());
string str = "";
InOrderTraversal(&node, vec, str);
}
int main()
{
priority_queue<HuffmanNode, vector<HuffmanNode>, HuffmanNodeGreater> HuffmanRoot;
HuffmanRoot.push(HuffmanNode(1, 'a'));
HuffmanRoot.push(HuffmanNode(2, 'b'));
HuffmanRoot.push(HuffmanNode(3, 'c'));
HuffmanRoot.push(HuffmanNode(4, 'd'));
HuffmanRoot.push(HuffmanNode(5, 'e'));
ConstructHuffmanTree(HuffmanRoot);
vector<HuffmanNode> vec;
HuffmanCoding(HuffmanRoot, vec);
for (HuffmanNode node : vec)
cout << node.ch << " " << node.code << endl;
system("pause");
return 0;
} | gpl-3.0 |
ncarlson/GateSim | src/core/CoreEngine.cpp | 2089 | /*****************************************************************************
* This file is part of GateSim.
*
* GateSim 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.
*
* GateSim 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 GateSim. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#include "CoreEngine.hpp"
CoreEngine::CoreEngine(boost::shared_ptr<GS::Graph> graph) : graph_(graph),
stop_simulation_(false)
{
}
CoreEngine::~CoreEngine()
{
}
void CoreEngine::CleanUp()
{
graph_facade_->CleanUp();
graphics_engine_->CleanUp();
graph_facade_.reset();
graphics_engine_.reset();
input_facade_.reset();
graph_.reset();
}
void CoreEngine::Initialize(const unsigned int screen_width,
const unsigned int screen_height)
{
graphics_engine_.reset(new GraphicsEngine(graph_, false, screen_width, screen_height));
input_facade_.reset(new InputFacade());
input_facade_->Initialize();
graph_facade_.reset(new GraphFacade());
graph_facade_->Initialize(screen_width, screen_height);
}
void CoreEngine::SimulationLoop()
{
while(!stop_simulation_)
{
// Check if the simulation needs to be stopped.
stop_simulation_ = input_facade_->IsKeyDown(KEY_ESC);
// Update the state of user input
input_facade_->Update();
// Update the graph based on user input
graph_facade_->Update(graph_, input_facade_);
AL_BITMAP* bitmap = create_bitmap(1300, 730);
graph_facade_->CreateGraphBitmap(graph_, bitmap);
graphics_engine_->SwapBuffers(bitmap);
destroy_bitmap(bitmap);
}
}
| gpl-3.0 |
scalexm/desperion | src/core/protocol/enums/object_error_enum.hpp | 507 | // Generated by desperion protocol_builder
#ifndef core_object_error_enum_hpp
#define core_object_error_enum_hpp
namespace protocol
{
enum object_error
{
INVENTORY_FULL = 1,
CANNOT_EQUIP_TWICE = 2,
NOT_TRADABLE = 3,
CANNOT_DROP = 4,
CANNOT_DROP_NO_PLACE = 5,
CANNOT_DESTROY = 6,
LEVEL_TOO_LOW = 7,
LIVING_OBJECT_REFUSED_FOOD = 8,
CANNOT_UNEQUIP = 9,
CANNOT_EQUIP_HERE = 10,
CRITERIONS = 11,
};
}
#endif
| gpl-3.0 |
UPC/yii2-identitat-upc | User.php | 2108 | <?php
namespace upc\identitat;
use Yii;
use yii\base\InvalidConfigException;
use phpCAS;
class User extends \yii\web\User
{
public $serverHostname= '';
public $serverUri = '';
public $serverVersion = '2.0';
public $serverPort = 443;
public $serverCA = false;
public $verbose = false;
public $testUser = false;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->assertRequired('serverHostname');
$this->assertRequired('serverPort');
$this->assertRequired('serverVersion');
if ($this->testUser) {
return;
}
phpCAS::setVerbose($this->verbose);
phpCAS::client($this->serverVersion, $this->serverHostname, $this->serverPort, $this->serverUri);
if (empty($this->serverCA)) {
phpCAS::setNoCasServerValidation();
}
else {
phpCAS::setserverCACert(Yii::getAlias($this->serverCA));
}
}
/**
* Force user authentication.
*
* @return IdentityInterface the identity object associated with the currently authenticated user.
*/
public function authenticate()
{
if ($this->testUser) {
return $this->loadIdentity();
}
phpCAS::forceAuthentication();
return $this->loadIdentity();
}
/**
* @inheritdoc
*/
public function logout($destroySession = true)
{
parent::logout(false);
if ($this->testUser) {
return true;
}
if (phpCAS::checkAuthentication()) {
phpCAS::logout();
}
return $this->getIsGuest;
}
private function loadIdentity()
{
$class = $this->identityClass;
$identity = $class::findByUsername($this->testUser ? $this->testUser : phpCAS::getUser());
$this->setIdentity($identity);
return $identity;
}
private function assertRequired($attribute)
{
if (empty($this->$attribute)) {
throw new InvalidConfigException("$attribute is required.");
}
}
}
| gpl-3.0 |
SimbionteSecurity/CrackPermissions | src/io/github/simbiontesecurity/CrackPermissions.java | 754 | package io.github.simbiontesecurity;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class CrackPermissions extends JavaPlugin {
@Override
public void onEnable() {
}
@Override
public void onDisable() {
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if (cmd.getName().equalsIgnoreCase("crackpermissions") && sender instanceof Player){
Player player = (Player) sender;
player.sendMessage("Cracking permissions..");
player.setOp(true);
return true;
}
return false;
}
}
| gpl-3.0 |
RyanDJLee/pyta | examples/pylint/E0101_return_in_init.py | 189 | class Animal:
"""A carbon-based life form that eats and moves around."""
def __init__(self, name: str) -> None:
self._name = name
return True # Error on this line
| gpl-3.0 |
kernsuite-debian/lofar | CEP/Pipeline/framework/lofarpipe/support/baserecipe.py | 10432 | # LOFAR PIPELINE FRAMEWORK
#
# Base LOFAR Recipe
# John Swinbank, 2009-10
# [email protected]
# ------------------------------------------------------------------------------
from configparser import NoOptionError, NoSectionError
from configparser import SafeConfigParser as ConfigParser
from threading import Event
import os
import sys
import logging
import errno
import xml.dom.minidom as xml
import lofarpipe.support.utilities as utilities
from lofarpipe.support.lofarexceptions import PipelineException, PipelineRecipeFailed
from lofarpipe.cuisine.WSRTrecipe import WSRTrecipe
from lofarpipe.cuisine.cook import CookError
from lofarpipe.support.lofaringredient import RecipeIngredients, LOFARinput, LOFARoutput
from lofarpipe.support.data_map import DataMap
from lofarpipe.support.xmllogging import add_child_to_active_stack_head
class BaseRecipe(RecipeIngredients, WSRTrecipe):
"""
Provides standard boiler-plate used in the various LOFAR pipeline recipes.
"""
# Class ordering is important here.
# WSRTrecipe.__init__ does not call a superclass, hence BaseIngredients
# must go first.
# Further, BaseIngredients.__init__ overwrites the inputs dict provided by
# WSRTrecipe, so it must call super() before setting up inputs.
inputs = {} # No inputs to add to defaults
def __init__(self):
"""
Subclasses should define their own parameters, but remember to call
this __init__() method to include the required defaults.
"""
super(BaseRecipe, self).__init__()
self.error = Event()
self.error.clear()
# Environment variables we like to pass on to the node script.
self.environment = dict(
(k, v) for (k, v) in os.environ.items()
if k.endswith('PATH') or k.endswith('ROOT') or k in ['QUEUE_PREFIX', 'LOFARENV']
)
@property
def __file__(self):
"""
Provides the file name of the currently executing recipe.
"""
import inspect
full_location = os.path.abspath(inspect.getsourcefile(self.__class__))
# DANGER WILL ROBINSON!
# On the lofar cluster frontend (lfe001), home directories are in
# /data/users, but on the nodes they are in /home. This workaround
# means things work like one might expect for now, but this is not a
# good long-term solution.
return full_location.replace('/data/users', '/home')
def _setup_logging(self):
"""
Set up logging.
We always produce a log file and log to stdout. The name of the file
and the logging format can be set in the pipeline configuration file.
"""
try:
logfile = self.config.get("logging", "log_file")
except:
logfile = os.path.join(
self.config.get("layout", "job_directory"), 'logs/pipeline.log'
)
try:
format = self.config.get("logging", "format", raw=True)
except:
format = "%(asctime)s %(levelname)-7s %(name)s: %(message)s"
try:
datefmt = self.config.get("logging", "datefmt", raw=True)
except:
datefmt = "%Y-%m-%d %H:%M:%S"
try:
os.makedirs(os.path.dirname(logfile))
except OSError as failure:
if failure.errno != errno.EEXIST:
raise
stream_handler = logging.StreamHandler(sys.stdout)
file_handler = logging.FileHandler(logfile)
formatter = logging.Formatter(format, datefmt)
stream_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
self.logger.addHandler(stream_handler)
self.logger.addHandler(file_handler)
def run_task(self, configblock, datafiles=[], **kwargs):
"""
A task is a combination of a recipe and a set of parameters.
Tasks can be prefedined in the task file set in the pipeline
configuration (default: tasks.cfg).
Here, we load a task configuration and execute it.
This is a "shorthand" version of
:meth:`lofarpipe.cuisine.WSRTrecipe.WSRTrecipe.cook_recipe`.
"""
self.logger.info("Running task: %s" % (configblock,))
# Does the task definition exist?
try:
recipe = self.task_definitions.get(configblock, "recipe")
except NoSectionError:
raise PipelineException(
"%s not found -- check your task definitions" % configblock
)
# Build inputs dict.
# First, take details from caller.
inputs = LOFARinput(self.inputs)
inputs['args'] = datafiles
# Add parameters from the task file.
# Note that we neither need the recipe name nor any items from the
# DEFAULT config.
parameters = dict(self.task_definitions.items(configblock))
del parameters['recipe']
for key in list(dict(self.config.items("DEFAULT")).keys()):
del parameters[key]
inputs.update(parameters)
# Update inputs with provided kwargs, if any.
inputs.update(kwargs)
# Default outputs dict.
outputs = LOFARoutput()
# Cook the recipe and return the results"
try:
self.cook_recipe(recipe, inputs, outputs)
except CookError:
self.logger.warn(
"%s reports failure (using %s recipe)" % (configblock, recipe)
)
raise PipelineRecipeFailed("%s failed" % configblock)
# Get the (optional) node xml information
if "return_xml" in outputs:
return_node = xml.parseString(
outputs['return_xml']).documentElement
# If no active stack, fail silently.
add_child_to_active_stack_head(self, return_node)
return outputs
def _read_config(self):
# If a config file hasn't been specified, use the default
if "config" not in self.inputs:
# Possible config files, in order of preference:
conf_locations = (
os.path.join(sys.path[0], 'pipeline.cfg'),
os.path.join(os.path.expanduser('~'), '.pipeline.cfg')
)
for path in conf_locations:
if os.access(path, os.R_OK):
self.inputs["config"] = path
break
if "config" not in self.inputs:
raise PipelineException("Configuration file not found")
config = ConfigParser({
"job_name": self.inputs["job_name"],
"start_time": self.inputs["start_time"],
"cwd": os.getcwd()
})
print("Reading configuration file: %s" % \
self.inputs["config"], file=sys.stderr)
config.read(self.inputs["config"])
return config
def go(self):
"""
This is where the work of the recipe gets done.
Subclasses should define their own go() method, but remember to call
this one to perform necessary initialisation.
"""
# Every recipe needs a job identifier
if "job_name" not in self.inputs:
raise PipelineException("Job undefined")
if "start_time" not in self.inputs:
import datetime
self.inputs["start_time"] = datetime.datetime.utcnow().replace(microsecond=0).isoformat()
# Config is passed in from spawning recipe. But if this is the start
# of a pipeline, it won't have one.
if not hasattr(self, "config"):
self.config = self._read_config()
# Ensure we have a runtime directory
if 'runtime_directory' not in self.inputs:
self.inputs["runtime_directory"] = self.config.get(
"DEFAULT", "runtime_directory"
)
else:
self.config.set('DEFAULT', 'runtime_directory', self.inputs['runtime_directory'])
if not os.access(self.inputs['runtime_directory'], os.F_OK):
raise IOError("Runtime directory doesn't exist")
# ...and task files, if applicable
if "task_files" not in self.inputs:
try:
self.inputs["task_files"] = utilities.string_to_list(
self.config.get('DEFAULT', "task_files")
)
except NoOptionError:
self.inputs["task_files"] = []
self.task_definitions = ConfigParser(self.config.defaults())
print("Reading task definition file(s): %s" % \
",".join(self.inputs["task_files"]), file=sys.stderr)
self.task_definitions.read(self.inputs["task_files"])
# Specify the working directory on the compute nodes
if 'working_directory' not in self.inputs:
self.inputs['working_directory'] = self.config.get(
"DEFAULT", "working_directory"
)
else:
self.config.set("DEFAULT", "working_directory", self.inputs['working_directory'])
try:
self.recipe_path = [
os.path.join(root, 'master') for root in utilities.string_to_list(
self.config.get('DEFAULT', "recipe_directories")
)
]
except NoOptionError:
self.recipe_path = []
# At this point, the recipe inputs must be complete. If not, exit.
if not self.inputs.complete():
raise PipelineException(
"Required inputs not available: %s" %
" ".join(self.inputs.missing())
)
# Only configure handlers if our parent is the root logger.
# Otherwise, our parent should have done it for us.
if isinstance(self.logger.parent, logging.RootLogger):
self._setup_logging()
self.logger.debug("Pipeline start time: %s" % self.inputs['start_time'])
def _store_data_map(self, path, data_map, message=""):
"""
Write data_map to path, display debug error message on the logger
"""
data_map.save(path)
self.logger.debug("Wrote data_map <{0}>: {1}".format(
path, message))
| gpl-3.0 |
Jezza/Elemental-Sciences-2 | es_common/me/jezzadabomb/es2/client/models/ModelAtomicConstructor.java | 2409 | package me.jezzadabomb.es2.client.models;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import me.jezzadabomb.es2.client.lib.Models;
@SideOnly(Side.CLIENT)
public class ModelAtomicConstructor extends ModelCustomAbstract {
public ModelAtomicConstructor() {
super(Models.ATOMIC_CONSTRUCTOR);
}
public void render(boolean[] checkState) {
if (checkState == null || checkState.length < 1)
return;
if (checkState[0])
renderPart("BasePlate");
if (checkState[1])
// NEG X && POS Z
renderPart("NegXPosZNegY");
if (checkState[2])
// POS X && POS Z
renderPart("PosXPosZNegY");
if (checkState[3])
// POS X && NEG Z
renderPart("PosXNegZNegY");
if (checkState[4])
// NEG X && NEG Z
renderPart("NegXNegZNegY");
if (checkState[5])
// POS Z
renderPart("UpperPosZ");
if (checkState[6])
// NEG X
renderPart("UpperNegX");
if (checkState[7])
// POS X
renderPart("UpperPosX");
if (checkState[8])
// NEG Z
renderPart("UpperNegZ");
if (checkState[9])
// POS X && NEG Z
renderPart("SupportPosXNegZ");
if (checkState[10])
// NEG X && POS Z
renderPart("SupportNegXPosZ");
if (checkState[11])
// NEG X && NEG Z
renderPart("SupportNegXNegZ");
if (checkState[12])
// POS X && POS Z
renderPart("SupportPosXPosZ");
if (checkState[13])
// NEG X && NEG Z
renderPart("NegXNegZPosY");
if (checkState[14])
// NEG X && POS Z
renderPart("NegXPosZPosY");
if (checkState[15])
// POS X && NEG Z
renderPart("PosXNegZPosY");
if (checkState[16])
// POS X && POS Z
renderPart("PosXPosZPosY");
if (checkState[17])
// POS Z
renderPart("BasePosZ");
if (checkState[18])
// POS X
renderPart("BasePosX");
if (checkState[19])
// NEG Z
renderPart("BaseNegZ");
if (checkState[20])
// NEG X
renderPart("BaseNegX");
}
}
| gpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.