code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
/**
* @file:
* This is an example update script for STAGING environment setup. It should
* be run automatically at the end of the build process.
*
* This update script should be run to enable/disable CSS and JavaScript
* aggregation; enable/disable block and page caching, enable/disable developer
* modules.
*
* TODO:
* - Rename this file to: update.staging.php and copy it to your scripts folder.
* - Always extend and improve this script.
*/
// Save a watchdog entry for the first update script in this phase.
watchdog('us-environment', 'Setup STAGING Environment');
// Disable CSS and JavaScript aggregation.
variable_set('preprocess_css', 0);
variable_set('preprocess_js', 0);
// Enable LESS Developer mode.
// variable_set('less_devel', 1);
// Use the development version of Modernizr.
variable_set('modernizr_build', 'development');
// Do not use any CDN for jQuery and jQuery UI
variable_set('jquery_update_jquery_cdn', 'none');
// Make sure that jQuery version 1.8.x is used on the frontend of the website.
variable_set('jquery_update_jquery_version', '1.8');
// Make sure that jQuery version 1.5.x is used on the admin interface.
variable_set('jquery_update_jquery_admin_version', '1.5');
| EITIorg/eiti | public_html/sites/all/modules/custom/update_scripts/examples/update.staging.php | PHP | gpl-3.0 | 1,227 |
////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// Implementation file
//
// Copyright (c) 2002-2011 IOhannes m zmölnig. forum::für::umläute. IEM. zmoelnig@iem.at
// zmoelnig@iem.kug.ac.at
// For information on usage and redistribution, and for a DISCLAIMER
// * OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS"
//
// this file has been generated...
////////////////////////////////////////////////////////
#include "GEMglFeedbackBuffer.h"
CPPEXTERN_NEW_WITH_TWO_ARGS ( GEMglFeedbackBuffer , t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT);
/////////////////////////////////////////////////////////
//
// GEMglViewport
//
/////////////////////////////////////////////////////////
// Constructor
//
GEMglFeedbackBuffer :: GEMglFeedbackBuffer (t_floatarg arg0=128, t_floatarg arg1=0) :
size(static_cast<GLsizei>(arg0)), type(static_cast<GLenum>(arg1))
{
len=(size>0)?size:128;
buffer = new float[len];
m_inlet[0] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("size"));
m_inlet[1] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("type"));
}
/////////////////////////////////////////////////////////
// Destructor
//
GEMglFeedbackBuffer :: ~GEMglFeedbackBuffer () {
inlet_free(m_inlet[0]);
inlet_free(m_inlet[1]);
}
//////////////////
// extension check
bool GEMglFeedbackBuffer :: isRunnable(void) {
if(GLEW_VERSION_1_1)return true;
error("your system does not support OpenGL-1.1");
return false;
}
/////////////////////////////////////////////////////////
// Render
//
void GEMglFeedbackBuffer :: render(GemState *state) {
glFeedbackBuffer (size, type, buffer);
error("i got data @ %X, but i don't know what to do with it!", buffer);
}
/////////////////////////////////////////////////////////
// Variables
//
void GEMglFeedbackBuffer :: sizeMess (t_float arg1) { // FUN
size = static_cast<GLsizei>(arg1);
if (size>len){
len=size;
delete[]buffer;
buffer = new float[len];
}
setModified();
}
void GEMglFeedbackBuffer :: typeMess (t_float arg1) { // FUN
type = static_cast<GLenum>(arg1);
setModified();
}
/////////////////////////////////////////////////////////
// static member functions
//
void GEMglFeedbackBuffer :: obj_setupCallback(t_class *classPtr) {
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglFeedbackBuffer::sizeMessCallback), gensym("size"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglFeedbackBuffer::typeMessCallback), gensym("type"), A_DEFFLOAT, A_NULL);
}
void GEMglFeedbackBuffer :: sizeMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->sizeMess ( static_cast<t_float>(arg0));
}
void GEMglFeedbackBuffer :: typeMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->typeMess ( static_cast<t_float>(arg0));
}
| rvega/morphasynth | vendors/pd-extended-0.43.4/externals/Gem/src/openGL/GEMglFeedbackBuffer.cpp | C++ | gpl-3.0 | 2,848 |
import fuzzy from 'fuzzy';
import { resolve } from 'redux-simple-promise';
import {
FETCH_POSTS,
FETCH_POST,
FETCH_PAGE,
FETCH_POSTS_CATEGORY,
FETCH_POSTS_TAG
} from '../actions/index';
const INITIAL_STATE = { all: {}, post: {}, page: {}, category: {} };
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case resolve(FETCH_POSTS): {
const data = action.payload.data.entries;
const payload = [];
if (typeof action.meta.term !== 'undefined') {
const options = {
pre: '',
post: '',
extract(el) {
return `${el.title} ${el.tags.map((tag) => `${tag} `)} `;
}
};
const results = fuzzy.filter(action.meta.term, data, options);
results.map((el) => {
if (el.score > 6) {
payload.push(el.original);
}
});
return { ...state, all: payload };
}
data.map((el) => {
if (el.meta.type === 'post') {
payload.push(el);
}
});
return { ...state, all: payload };
}
case resolve(FETCH_POSTS_CATEGORY): {
const data = action.payload.data.entries;
const payload = [];
data.map((el) => {
if (el.meta.categories.includes(action.meta.category)) {
payload.push(el);
}
});
return { ...state, category: payload };
}
case resolve(FETCH_POSTS_TAG): {
const data = action.payload.data.entries;
const payload = [];
data.map((el) => {
if (el.tags.includes(action.meta.tag)) {
payload.push(el);
}
});
return { ...state, category: payload };
}
case resolve(FETCH_POST): {
const data = action.payload.data.entries;
let payload;
data.map((el) => {
if (el.title === action.meta.title) {
payload = el;
}
});
return { ...state, post: payload };
}
case resolve(FETCH_PAGE): {
const data = action.payload.data;
return { ...state, page: data };
}
default:
return state;
}
}
| WDTAnyMore/WDTAnyMore.github.io | react-dev/reducers/reducer_posts.js | JavaScript | gpl-3.0 | 2,110 |
package com.az.gitember.controller.handlers;
import com.az.gitember.controller.DefaultProgressMonitor;
import com.az.gitember.controller.IntegerlDialog;
import com.az.gitember.data.ScmItemDocument;
import com.az.gitember.data.ScmRevisionInformation;
import com.az.gitember.service.Context;
import com.az.gitember.service.SearchService;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.text.MessageFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class IndexEventHandler extends AbstractLongTaskEventHandler implements EventHandler<ActionEvent> {
private final static Logger log = Logger.getLogger(IndexEventHandler.class.getName());
Integer docQty = 0 ;
@Override
public void handle(ActionEvent event) {
IntegerlDialog integerlDialog = new IntegerlDialog("Index repository history " , "Limit revisions to reindex", "Quantiy", 100);
integerlDialog.showAndWait().ifPresent( r -> {
Task<Void> longTask = new Task<Void>() {
@Override
protected Void call() throws Exception {
DefaultProgressMonitor progressMonitor = new DefaultProgressMonitor((t, d) -> {
updateTitle(t);
updateProgress(d, 1.0);
});
List<ScmRevisionInformation> sriList = Context.getGitRepoService().getItemsToIndex(null, r, progressMonitor);
SearchService service = new SearchService( Context.getProjectFolder() );
progressMonitor.beginTask("Indexing ", sriList.size());
int idx = 0;
for (ScmRevisionInformation sri : sriList) {
sri.getAffectedItems().forEach(
i -> {
service.submitItemToReindex(new ScmItemDocument(i));
}
);
idx++;
progressMonitor.update(idx);
docQty = docQty + sri.getAffectedItems().size();
}
service.close();
return null;
}
};
launchLongTask(
longTask,
o -> {
Context.getCurrentProject().setIndexed(true);
Context.saveSettings();
Context.getMain().showResult(
"Indexing", "Was indexed " + docQty + " documents",
Alert.AlertType.INFORMATION);
},
o -> {
log.log(Level.WARNING,
MessageFormat.format("Indexing error", o.getSource().getException()));
Context.getMain().showResult("Indexing", "Cannot index history of changess\n" +
ExceptionUtils.getStackTrace(o.getSource().getException()), Alert.AlertType.ERROR);
o.getSource().getException().printStackTrace();
}
);
} );
}
}
| iazarny/gitember | src/main/java/com/az/gitember/controller/handlers/IndexEventHandler.java | Java | gpl-3.0 | 3,508 |
import os, sys, re, argparse, time, json, logging
import requests
from glob import glob
from urlparse import urlsplit
from getpass import getpass
from mastodon import Mastodon
from markdown import markdown
from html_text import extract_text
from flask import (Flask, render_template, abort,
request, redirect, jsonify)
DEBUG = False # If it ain't broke, don't debug it.
NO_TOOTING = False # Handy during debug: create gist, but don't toot.
RE_HASHTAG = re.compile(u'(?:^|(?<=\s))#(\\w+)')
RE_MENTION = re.compile(u'(?:^|(?<=\s))@(\\w+)@([\\w.]+)')
def get_hashtags(s, ignore=None):
tags = set(
['#'+tag.lower() for tag in RE_HASHTAG.findall(s)])
if ignore:
tags -= get_hashtags(ignore)
return tags
def linkify_hashtags(s, instance):
return RE_HASHTAG.sub(
lambda m:
u"[#{tag}](https://{instance}/tags/{tag})".format(
tag=m.group(1), instance=instance),
s)
def get_mentions(s, ignore=None):
mentions = set(
[u"@{}@{}".format(user,instance)
for user, instance in RE_MENTION.findall(s)])
if ignore:
mentions -= get_mentions(ignore)
return mentions
def linkify_mentions(s):
return RE_MENTION.sub(
lambda m:
u"[@{user}](https://{instance}/@{user})".format(
user=m.group(1), instance=m.group(2)),
s)
def url2toot(masto, url):
u = urlsplit(url)
if not (u.scheme=='https' and u.netloc and u.path):
return None # Don't bother the instance
res = masto.search(url, True)
res = res.get('statuses',[])
return res and res[0] or None
def make_gist(title, body):
return requests.post(
"https://api.github.com/gists",
json={
"description": title,
"public": True,
"files": {
"TOOT.md": {
"content": u"### {}\n\n{}".format(title, body)
}
}
}
).json()['html_url']+"#file-toot-md"
def post(masto, body, instance, title=None,
direction='ltr', in_reply_to=None):
# Markdown more than we need, to [hopefully] discard chopped markup.
summary = extract_text(markdown(body.strip()))[:140]
hashtags = get_hashtags(body, ignore=summary)
mentions = get_mentions(body, ignore=summary)
irt_id = in_reply_to and in_reply_to.get('id') or None
body = linkify_hashtags(linkify_mentions(body), instance)
if direction=='rtl':
body = u"""<div dir="rtl">
{}
</div>""".format(markdown(body))
if in_reply_to:
body = u"""#### In reply to [@{}]({}):
{}""".format(
in_reply_to['account']['username'],
in_reply_to['url'], body)
gist = make_gist(
title or u"A gistodon toot, {} GMT".format(
time.asctime(time.gmtime())),
body+u"""
###### Generated by [Gistodon](https://github.com/thedod/gistodon/#readme).""")
if NO_TOOTING:
return gist
status = u'{}... {}'.format(summary, gist)
if hashtags or mentions:
status += u'\n'+u' '.join(hashtags.union(mentions))
return masto.status_post(
status, spoiler_text=title, in_reply_to_id=irt_id)['url']
def webserver(masto, instance, account):
app = Flask(__name__, static_url_path='')
@app.route('/')
def index():
re = request.args.get('re','')
return render_template('index.html', account=account,
re=re)
@app.route('/toot', methods=['POST'])
def tootit():
if not request.form['markdown'].strip():
return "Nothing to toot"
in_reply_to=request.form.get('re')
if in_reply_to:
in_reply_to = url2toot(masto, in_reply_to)
if not in_reply_to:
abort(500, 'The "in reply to" url is not a toot.')
return redirect(post(
masto, request.form['markdown'], instance,
title=request.form['title'],
in_reply_to=in_reply_to,
direction=request.form['direction']))
@app.route('/re', methods=['GET', 'POST'])
def tootsearch():
return jsonify(url2toot(masto,
request.form.get('q', request.args.get('q',''))))
@app.route('/search', methods=['GET', 'POST'])
def search():
q = request.form.get(
'q', request.args.get('q','')).strip()
if not q:
return jsonify([])
res = masto.search(q, True)
return jsonify(sorted(
[
{
# This trick makes sure both local and external
# accounts get a @hostname suffix.
"value": "@{}@{}".format(
a["username"], urlsplit(a["url"]).netloc),
"title": a.get("display_name")
} for a in res.get('accounts',[])]+ \
[{"value": '#'+a} for a in res.get('hashtags',[])],
key=lambda s: s['value'].lower()))
app.run(host='localhost', port=8008, debug=DEBUG)
def main():
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
parser = argparse.ArgumentParser(
description=("Toot stdin as a gist [markdown is supported],"
" or launch a localhost web interface."))
parser.add_argument('-i', '--instance',
help='Your mastodon instance (e.g. mastodon.social).')
parser.add_argument('-e', '--email',
help='The email address you login to that instance with.')
parser.add_argument('-a', '--app_name', default='Gistodon',
help=('Name for the app (default is Gistodon).'
' Appears below the toot, near the date.'))
parser.add_argument('-w', '--web', action="store_true",
help=("Run as a web server on localhost"
" (toot-specific --title, --re, and --rtl"
" are ignored)."))
parser.add_argument('-t', '--title',
help="Optional: gist's title, and the toot's content warning (CW).")
parser.add_argument('-r', '--re',
help="Optional: url of the toot you're replying to.")
parser.add_argument('--rtl', dest='direction', action='store_const',
const='rtl', default='ltr',
help=("Format the gist as right-to-left text."))
args = parser.parse_args()
instance = args.instance
if instance:
client_cred_filename = '{}.{}.client.secret'.format(args.app_name, args.instance)
else:
candidates = glob('{}.*.client.secret'.format(args.app_name))
assert candidates, "No app/user registered. Please run register.sh first."
client_cred_filename = candidates[0]
instance = client_cred_filename[len(args.app_name)+1:-len('.client.secret')]
email = args.email
if email:
user_cred_filename = '{}.{}.{}.user.secret'.format(
args.app_name, instance, email.replace('@','.'))
else:
candidates = glob('{}.{}.*.user.secret'.format(
args.app_name, instance))
assert len(candidates), \
"No user registered for {} at {}. Please run register.sh first.".format(
args.app_name, instance)
user_cred_filename = candidates[0]
assert \
os.path.exists(client_cred_filename) and \
os.path.exists(user_cred_filename), \
"App/user not registered. Please run register.sh"
logging.info("Connecting to {}...".format(instance))
masto = Mastodon(
client_id = client_cred_filename,
access_token = user_cred_filename,
api_base_url = 'https://'+instance)
if args.web:
account = masto.account_verify_credentials()
webserver(masto, instance, account)
else:
logging.info("Reading markdown from standard input...")
lines = [unicode(l,'utf-8') for l in sys.stdin.readlines()]
assert len(filter(lambda l: l.strip(), lines)), \
"Empty toot."
body = u'\n'.join(lines)
assert not args.title or len(args.title)<=80, "Title exceeds 80 characters"
if args.re:
irt = url2toot(masto, args.re)
assert irt, "not a toot's url: {}".format(args.re)
else:
irt = None
title = args.title
try:
title = unicode(title,'utf-8')
except TypeError:
pass # Either Null, or already unicode(?!?)
logging.info("Posted {}.".format(post(
masto, body, instance,
title=title, direction=args.direction, in_reply_to=irt)))
if __name__=='__main__':
main()
| thedod/gistodon | gistodon.py | Python | gpl-3.0 | 8,763 |
/*******************************************************************************
* Copyright 2012
* FG Language Technologie
* Technische Universitaet Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.jobimtext.api.configuration;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* Configuration class for the database connection
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DatabaseThesaurusConfiguration {
public DatabaseTableConfiguration tables = new DatabaseTableConfiguration();
public String dbUser;
public String dbUrl;
public String dbPassword;
public String jdbcString;
public String similarTermsQuery;
public String similarTermsTopQuery;
public String similarTermsGtScoreQuery;
public String similarTermScoreQuery;
public String similarContextsQuery;
public String similarContextsTopQuery;
public String similarContextsGtScoreQuery;
public String contextTermsScoresQuery;
public String termsCountQuery;
public String contextsCountQuery;
public String termContextsCountQuery;
public String termContextsScoreQuery;
public String batchTermContextsScoreQuery;
public String termContextsScoresQuery;
public String termContextsScoresTopQuery;
public String termContextsScoresGtScoreQuery;
public String sensesQuery;
public String senseCUIsQuery;
public String isasQuery;
@XmlTransient
private HashMap<String, String> tableStringMapping = null;
@XmlTransient
private List<String> tableValuesSorted = null;
public String getSimilarTermsTopQuery(int top) {
return replaceTables(similarTermsTopQuery, "$numberOfEntries",
Integer.toString(top));
}
public String getSimilarTermsGtScoreQuery() {
return replaceTables(similarTermsGtScoreQuery);
}
public String getSimilarContextsQuery() {
return replaceTables(similarContextsQuery);
}
public String getSimilarContextsTopQuery(int top) {
return replaceTables(similarContextsTopQuery, "$numberOfEntries",
Integer.toString(top));
}
public String getSimilarContextsGtScoreQuery() {
return replaceTables(similarContextsGtScoreQuery);
}
public HashMap<String, String> getTableStringMapping() {
return tableStringMapping;
}
public List<String> getTableValuesSorted() {
return tableValuesSorted;
}
public DatabaseTableConfiguration getTables() {
return tables;
}
public void setTables(DatabaseTableConfiguration tables) {
this.tables = tables;
}
public String getDbUser() {
return dbUser;
}
public void setDbUser(String dbUser) {
this.dbUser = dbUser;
}
public String getDbUrl() {
return dbUrl;
}
public void setDbUrl(String dbUrl) {
this.dbUrl = dbUrl;
}
public String getDbPassword() {
return dbPassword;
}
public void setDbPassword(String dbPassword) {
this.dbPassword = dbPassword;
}
public String getJdbcString() {
return jdbcString;
}
public void setJdbcString(String jdbcString) {
this.jdbcString = jdbcString;
}
public void saveAsXml(PrintStream ps) throws JAXBException {
JAXBContext context = JAXBContext
.newInstance(DatabaseThesaurusConfiguration.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(this, ps);
}
public void saveAsXml(File file) throws JAXBException,
FileNotFoundException {
saveAsXml(new PrintStream(file));
}
public static DatabaseThesaurusConfiguration getFromXmlDataReader(Reader reader) throws JAXBException,
InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException,
SecurityException, ClassNotFoundException {
JAXBContext jaxbContext = JAXBContext
.newInstance(DatabaseThesaurusConfiguration.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (DatabaseThesaurusConfiguration) jaxbUnmarshaller
.unmarshal(reader);
}
public static DatabaseThesaurusConfiguration getFromXmlFile(File name) throws IOException, IllegalAccessException,
InstantiationException, JAXBException, NoSuchMethodException, InvocationTargetException,
ClassNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(name));
try {
return getFromXmlDataReader(reader);
} finally {
reader.close();
}
}
public static DatabaseThesaurusConfiguration getFromXmlFile(String name)
throws JAXBException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException,
SecurityException, ClassNotFoundException, IOException {
return getFromXmlFile(new File(name));
}
private String replaceTables(String query, String... replacements) {
if (tableStringMapping == null) {
tableStringMapping = new HashMap<String, String>();
tableValuesSorted = new ArrayList<String>();
for (Field f : tables.getClass().getDeclaredFields()) {
String name = f.getName();
try {
String value = f.get(this.tables).toString();
tableStringMapping.put(name, value);
tableValuesSorted.add(name);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NullPointerException e) {
System.err.println("The table parameter: " + f.toString() + " does not has a value assigned");
}
}
// sort the table names according to their length (longest is first
// element) to avoid replacing parts of table names
Collections.sort(tableValuesSorted, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.length() - o1.length();
}
});
}
String sb = query;
for (String key : tableValuesSorted) {
sb = sb.replace("$" + key, tableStringMapping.get(key));
}
if (replacements.length % 2 != 0) {
throw new IllegalArgumentException(
"the arguemnts should also be modulo two==0: Key1 Value1 Key2 Value2");
}
for (int i = 0; i < replacements.length; i += 2) {
sb = sb.replace(replacements[i], replacements[i + 1]);
}
return sb.toString();
}
public String getSimilarTermsQuery() {
return replaceTables(similarTermsQuery);
}
public String getTermsCountQuery() {
return replaceTables(termsCountQuery);
}
public String getContextsCountQuery() {
return replaceTables(contextsCountQuery);
}
public String getTermContextsCountQuery() {
return replaceTables(termContextsCountQuery);
}
public String getTermContextsScoreQuery() {
return replaceTables(termContextsScoreQuery);
}
/*public String getBatchTermContextsScoreQuery(String inClause) {
return replaceTables(batchTermContextsScoreQuery).replace("[IN-CLAUSE]", inClause);
}*/
public String getBatchTermContextsScoreQuery() {
return replaceTables(batchTermContextsScoreQuery);
}
public String getTermContextsScoresQuery() {
return replaceTables(termContextsScoresQuery);
}
public String getTermContextsScoresTopQuery(int numberOfEntries) {
return replaceTables(termContextsScoresTopQuery, "$numberOfEntries",
Integer.toString(numberOfEntries));
}
public String getTermContextsScoresGtScore() {
return replaceTables(termContextsScoresGtScoreQuery);
}
public String getSensesCUIsQuery() {
return replaceTables(senseCUIsQuery);
}
public String getIsasQuery() {
return replaceTables(isasQuery);
}
public String getSensesQuery() {
return replaceTables(sensesQuery);
}
public String getSimilarTermScoreQuery() {
return replaceTables(similarTermScoreQuery);
}
public String getContextTermsScoresQuery() { return replaceTables(contextTermsScoresQuery); }
}
| timfeu/berkeleycoref-thesaurus | src/main/java/org/jobimtext/api/configuration/DatabaseThesaurusConfiguration.java | Java | gpl-3.0 | 9,826 |
/*
* $Id: WorkReportBusinessHome.java,v 1.5 2004/12/07 15:58:30 eiki Exp $
* Created on Dec 3, 2004
*
* Copyright (C) 2004 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf.
* Use is subject to license terms.
*/
package is.idega.idegaweb.member.isi.block.reports.business;
import com.idega.business.IBOHome;
/**
*
* Last modified: $Date: 2004/12/07 15:58:30 $ by $Author: eiki $
*
* @author <a href="mailto:eiki@idega.com">eiki</a>
* @version $Revision: 1.5 $
*/
public interface WorkReportBusinessHome extends IBOHome {
public WorkReportBusiness create() throws javax.ejb.CreateException, java.rmi.RemoteException;
}
| idega/platform2 | src/is/idega/idegaweb/member/isi/block/reports/business/WorkReportBusinessHome.java | Java | gpl-3.0 | 691 |
"use strict";
var SHOW_DATA = {
"venue_name": "Merriweather Post Pavilion, Columbia, Maryland",
"venue_id": 76,
"show_date": "26th of Jun, 1984",
"sets": [
{"set_title": "1st set",
"encore": false,
"songs": [
{"name": "Casey Jones", "length":"5:59", "trans":"/"},
{"name": "Feel Like A Stranger", "length":"7:32", "trans":"/"},
{"name": "Althea", "length":"8:00", "trans":"/"},
{"name": "Cassidy", "length":"6:08", "trans":"/"},
{"name": "Tennessee Jed", "length":"7:58", "trans":"/"},
{"name": "Looks Like Rain", "length":"6:32", "trans":"/"},
{"name": "Might As Well", "length":"4:47", "trans":"/"},
]},
{"set_title": "2nd set",
"encore": false,
"songs": [
{"name": "China Cat Sunflower", "length":"3:32", "trans":">"},
{"name": "Weir's Segue", "length":"3:53", "trans":">"},
{"name": "I Know You Rider", "length":"5:37", "trans":"/"},
{"name": "Man Smart, Woman Smarter", "length":"6:30", "trans":"/"},
{"name": "He's Gone", "length":"12:02", "trans":">"},
{"name": "Improv", "length":"5:16", "trans":">"},
{"name": "Drums", "length":"9:49", "trans":">"},
{"name": "Space", "length":"10:01", "trans":">"},
{"name": "Don't Need Love", "length":"8:07", "trans":">"},
{"name": "Prelude", "length":"0:47", "trans":">"},
{"name": "Truckin'", "length":"5:11", "trans":">"},
{"name": "Truckin' Jam", "length":"1:21", "trans":">"},
{"name": "Improv", "length":"0:53", "trans":">"},
{"name": "Wang Dang Doodle", "length":"3:24", "trans":">"},
{"name": "Stella Blue", "length":"9:13", "trans":">"},
{"name": "Around & Around", "length":"3:44", "trans":"/"},
{"name": "Good Lovin'", "length":"7:28", "trans":"/"},
]},
{"set_title": "3rd set",
"encore": false,
"songs": [
{"name": "Keep Your Day Job", "length":"4:14", "trans":"/"},
]},
],
};
| maximinus/grateful-dead-songs | gdsongs/static/data/shows/295.js | JavaScript | gpl-3.0 | 1,845 |
package models;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import play.data.validation.Required;
import play.db.jpa.Model;
@Entity
public class UserEvent extends Model {
public static final int TYPE_LOGIN = 1;
public static final int TYPE_LOGOUT = 2;
@Required
public Date eventDate;
@Required
@ManyToOne
public User user;
@Required
public int eventType;
public UserEvent(final Date eventDate, final User user, final int eventType) {
super();
this.eventDate = eventDate;
this.user = user;
this.eventType = eventType;
}
public static List<UserEvent> findByUser(final long userId) {
return find("user =? order by eventDate desc", User.findById(userId)).fetch(100);
}
@Override
public String toString() {
return "UserEvent [eventDate=" + eventDate + ", user=" + user + ", eventType=" + eventType + "]";
}
}
| Thierry36tribus/Jeko | app/models/UserEvent.java | Java | gpl-3.0 | 916 |
#define PI 3.141592f
#include <iostream>
#include <cmath>
#include "circulo.h"
#include <string>
using namespace std;
ostream& operator<<(ostream &Saida, circulo &c1)
{
Saida << "Raio: " << c1.get_raio() << endl;
Saida << "Diâmetro: " << c1.get_raio()*2 << endl;
Saida << "Circunferência: " << c1.get_circunferencia() << endl;
Saida << "Área: " << c1.get_area() << endl;
Saida << "Coordenada X do Centro: " << c1.get_centroX() << endl;
Saida << "Coordenada Y do Centro: " << c1.get_centroY() << endl;
return Saida;
}
istream& operator>>(istream &Entrada, circulo &c1)
{
int x, y, i;
cout << "Digite a Coordenada X do Centro: " << endl;
Entrada >> x;
cout << "Digite a Coordenada Y do Centro: " << endl;
Entrada >> y;
c1.set_centro(x, y);
cout << "Digite o Raio: " << endl;
Entrada >> i;
c1.set_raio(i);
c1.set_rest();
return Entrada;
}
int main (void)
{
circulo c1;
circulo c2;
c1 = circulo(31, 14, 5);
c2 = circulo(30, 13, 8);
c1.imprime_area();
cout << c1;
cout << c2;
if (c2^c1) cout << "Há intersecção" << endl;
else cout << "Não há intersecção" << endl;
if (c2>c1) cout << "A área de c2 é maior do que a área de c1" << endl;
else cout << "A área de c1 é maior do que a área de c2" << endl;
if (c2<c1) cout << "A área de c2 é menor do que a área de c1" << endl;
else cout << "A área de c1 é menor do que a área de c2" << endl;
cin >> c1;
return 0;
}
| kinmax/LAPRO2 | sobrecarga/main.cpp | C++ | gpl-3.0 | 1,419 |
/*******************************************************************************
* Copyright (c) 2010 Torsten Zesch.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* Contributors:
* Torsten Zesch - initial API and implementation
******************************************************************************/
package de.tudarmstadt.ukp.wikipedia.api;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import de.tudarmstadt.ukp.wikipedia.api.exception.WikiTitleParsingException;
/**
* An iterator over category objects.
* @author zesch
*
*/
public class TitleIterator implements Iterator<Title> {
// private final static Logger logger = Logger.getLogger(TitleIterator.class);
private TitleBuffer buffer;
public TitleIterator(Wikipedia wiki, int bufferSize) {
buffer = new TitleBuffer(bufferSize, wiki);
}
public boolean hasNext(){
return buffer.hasNext();
}
public Title next(){
return buffer.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Buffers titles in a list.
*
* @author zesch
*
*/
class TitleBuffer {
private Wikipedia wiki;
private List<String> titleStringBuffer;
private int maxBufferSize; // the number of pages to be buffered after a query to the database.
private int bufferFillSize; // even a 500 slot buffer can be filled with only 5 elements
private int bufferOffset; // the offset in the buffer
private int dataOffset; // the overall offset in the data
public TitleBuffer(int bufferSize, Wikipedia wiki){
this.maxBufferSize = bufferSize;
this.wiki = wiki;
this.titleStringBuffer = new ArrayList<String>();
this.bufferFillSize = 0;
this.bufferOffset = 0;
this.dataOffset = 0;
}
/**
* If there are elements in the buffer left, then return true.
* If the end of the filled buffer is reached, then try to load new buffer.
* @return True, if there are pages left. False otherwise.
*/
public boolean hasNext(){
if (bufferOffset < bufferFillSize) {
return true;
}
else {
return this.fillBuffer();
}
}
/**
*
* @return The next Title or null if no more categories are available.
*/
public Title next(){
// if there are still elements in the buffer, just retrieve the next one
if (bufferOffset < bufferFillSize) {
return this.getBufferElement();
}
// if there are no more elements => try to fill a new buffer
else if (this.fillBuffer()) {
return this.getBufferElement();
}
else {
// if it cannot be filled => return null
return null;
}
}
private Title getBufferElement() {
String titleString = titleStringBuffer.get(bufferOffset);
Title title = null;
try {
title = new Title(titleString);
} catch (WikiTitleParsingException e) {
e.printStackTrace();
}
bufferOffset++;
dataOffset++;
return title;
}
private boolean fillBuffer() {
Session session = this.wiki.__getHibernateSession();
session.beginTransaction();
List returnList = session.createSQLQuery(
"select p.name from PageMapLine as p")
.setFirstResult(dataOffset)
.setMaxResults(maxBufferSize)
.setFetchSize(maxBufferSize)
.list();
session.getTransaction().commit();
// clear the old buffer and all variables regarding the state of the buffer
titleStringBuffer.clear();
bufferOffset = 0;
bufferFillSize = 0;
titleStringBuffer.addAll(returnList);
if (titleStringBuffer.size() > 0) {
bufferFillSize = titleStringBuffer.size();
return true;
}
else {
return false;
}
}
}
}
| fauconnier/LaToe | src/de/tudarmstadt/ukp/wikipedia/api/TitleIterator.java | Java | gpl-3.0 | 4,695 |
/*
* Hyperbox - Virtual Infrastructure Manager
* Copyright (C) 2013 Max Dor
*
* https://apps.kamax.io/hyperbox
*
* 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 io.kamax.hboxd.factory;
import io.kamax.hboxd.core.SingleHostServer;
import io.kamax.hboxd.core._Hyperbox;
public class ModelFactory {
private static _Hyperbox hyperbox;
private ModelFactory() {
throw new RuntimeException("Not allowed");
}
public static _Hyperbox get() {
if (hyperbox == null) {
hyperbox = new SingleHostServer();
}
return hyperbox;
}
}
| hyperbox/server | src/main/java/io/kamax/hboxd/factory/ModelFactory.java | Java | gpl-3.0 | 1,201 |
/* ---------------------------------------------------------------------------
* Programa: lee_lineas
* Entradas: Una serie de líneas de texto
* Salidas: - La línea más larga (si no se introduce ninguna se muestra una cadena vacía)
* - La línea menor lexicográficamente (si no se introduce ninguna se
* muestra la cadena FIN)
* --------------------------------------------------------------------------- */
#include <iostream>
#include <string>
using namespace std;
int main ()
{
const string CENTINELA = "FIN";
string masLarga = ""; // tiene longitud 0
string linea;
cout << "Introduzca una línea (" << CENTINELA << " para acabar): ";
getline (cin, linea);
string menor = linea; // se inicia la menor a la primera línea leída
while (linea != CENTINELA) {
if (linea.length () > masLarga.length ())
masLarga = linea;
if (linea < menor)
menor = linea;
cout << "Introduzca una línea (" << CENTINELA << " para acabar): ";
getline (cin, linea);
}
cout << "Línea más larga: " << masLarga << endl;
cout << "Línea menor lexicográficamente: " << menor << endl;
return 0;
}
| FundamentosProgramacionUJA/Ejercicios | Tema5-Tipos de datos estructurados/lee_lineas.cc | C++ | gpl-3.0 | 1,137 |
package com.m4thg33k.lit.lib;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
public enum EnumBetterFurnaceType implements IStringSerializable {
IRON("Iron",0.5,1,1.25,30000, new ItemStack(Items.iron_ingot,1)),
GOLD("Gold",0.25,1,1.25,40000,new ItemStack(Items.gold_ingot,1)),
DIAMOND("Diamond",0.25,2,1.5,80000, new ItemStack(Items.diamond,1)),
REDSTONE("Redstone",0.125,0,1.25,30000,new ItemStack(Blocks.redstone_block,1)),
LAPIS("Lapis",0.25,3,1.0,20000,new ItemStack(Blocks.lapis_block,1));
protected final String name;
protected final double speedMult;
protected final int numUpgrades;
protected final double fuelEfficiencyMult;
protected final int fuelCap;
protected final ItemStack ingredient;
EnumBetterFurnaceType(String name,double speedMult,int numUpgrades,double fuelEfficiencyMult,int fuelCap,ItemStack ingredient)
{
this.name = name;
this.speedMult = speedMult;
this.numUpgrades = numUpgrades;
this.fuelEfficiencyMult = fuelEfficiencyMult;
this.fuelCap = fuelCap;
this.ingredient = ingredient.copy();
}
@Override
public String getName() {
return this.name.toLowerCase();
}
public String getTypeName()
{
return this.name;
}
public double getSpeedMult() {
return speedMult;
}
public int getNumUpgrades() {
return numUpgrades;
}
public double getFuelEfficiencyMult() {
return fuelEfficiencyMult;
}
public int getFuelCap() {
return fuelCap;
}
public ItemStack getIngredient() {
return ingredient.copy();
}
public String[] getDisplayInfo()
{
return new String[]{""+getSpeedMult(),""+getFuelEfficiencyMult(),""+getNumUpgrades(),""+(Math.floor(100*((0.0+getFuelCap())/(1600*64*getFuelEfficiencyMult())))/100)};
}
}
| M4thG33k/LittleInsignificantThings_1.9 | src/main/java/com/m4thg33k/lit/lib/EnumBetterFurnaceType.java | Java | gpl-3.0 | 1,983 |
import time
import os
import json
import requests
# Plan is to import and to checkout dependencies:
| pi-bot/pibot-pkg | tests/dependencies.py | Python | gpl-3.0 | 100 |
var __v=[
{
"Id": 2257,
"Panel": 1127,
"Name": "刪除 舊 kernel",
"Sort": 0,
"Str": ""
}
] | zuiwuchang/king-document | data/panels/1127.js | JavaScript | gpl-3.0 | 112 |
/*
* gMix open source project - https://svs.informatik.uni-hamburg.de/gmix/
* Copyright (C) 2012 Karl-Peter Fuchs
*
* 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 evaluation.loadGenerator.applicationLevelTraffic.requestReply;
import java.io.IOException;
import evaluation.loadGenerator.ClientTrafficScheduleWriter;
import evaluation.loadGenerator.LoadGenerator;
import evaluation.loadGenerator.scheduler.ScheduleTarget;
import framework.core.util.IOTester;
import framework.core.util.Util;
public class ALRR_BasicWriter implements ScheduleTarget<ApplicationLevelMessage> {
private final boolean IS_DUPLEX;
private ClientTrafficScheduleWriter<ApplicationLevelMessage> owner;
public ALRR_BasicWriter(ClientTrafficScheduleWriter<ApplicationLevelMessage> owner, boolean isDuplex) {
this.owner = owner;
this.IS_DUPLEX = isDuplex;
}
@Override
public void execute(ApplicationLevelMessage message) {
ALRR_ClientWrapper cw = (ALRR_ClientWrapper)owner.getClientWrapper(message.getClientId());
synchronized (cw.outputStream) {
try {
message.setAbsoluteSendTime(System.currentTimeMillis());
byte[] payload = message.createPayloadForRequest();
String stats = "LOAD_GENERATOR: sending request ("
+"client:" +message.getClientId()
+"; transactionId:" +message.getTransactionId()
+"; requestSize: " +message.getRequestSize() +"bytes";
if (message.getReplySize() != Util.NOT_SET)
stats += "; replySize: " +message.getReplySize() +"bytes";
stats += ")";
System.out.println(stats);
if (LoadGenerator.VALIDATE_IO)
IOTester.findInstance(""+message.getClientId()).addSendRecord(payload);
//System.out.println("" +this +": sending (client): " +Util.toHex(payload)); // TODO: remove
cw.outputStream.write(payload);
cw.outputStream.flush();
if (IS_DUPLEX)
ALRR_ClientWrapper.activeTransactions.put(message.getTransactionId(), message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| abeifuss/simgui | src/evaluation/loadGenerator/applicationLevelTraffic/requestReply/ALRR_BasicWriter.java | Java | gpl-3.0 | 2,609 |
from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output
from troposphere.efs import FileSystem, MountTarget
from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet
from create import export_ref, import_ref
from create.network import AclFactory, assoc_nacl_subnet
def efs_setup(template, ops, app_cfn_options, stack_name, stack_setup):
# Variable Declarations
vpc_id=ops.get('vpc_id')
efs_sg = app_cfn_options.network_names['tcpstacks'][stack_name]['sg_name']
efs_acl = app_cfn_options.network_names['tcpstacks'][stack_name]['nacl_name']
# Create EFS FIleSystem
efs_fs=FileSystem(
title='{}{}'.format(ops.app_name, stack_name),
FileSystemTags=Tags(Name='{}-{}'.format(ops.app_name, stack_name))
)
template.add_resource(efs_fs)
export_ref(template, '{}{}{}'.format(ops.app_name,stack_name,"Endpoint"), value=Ref(efs_fs), desc="Endpoint for EFS FileSystem")
# EFS FS Security Groups
efs_security_group=SecurityGroup(
title=efs_sg,
GroupDescription='Allow Access',
VpcId=vpc_id,
Tags=Tags(Name=efs_sg)
)
template.add_resource(efs_security_group)
export_ref(template, efs_sg, value=Ref(efs_sg), desc="Export for EFS Security Group")
# Create Network ACL for EFS Stack
efs_nacl = AclFactory(
template,
name=efs_acl,
vpc_id=ops.vpc_id,
in_networks=[val for key, val in sorted(ops.app_networks.items())],
in_ports=stack_setup['ports'],
out_ports=ops.out_ports,
out_networks=[val for key, val in sorted(ops.app_networks.items())],
ssh_hosts=ops.get("deploy_hosts"),
)
export_ref(
template,
export_name=efs_acl,
value=Ref(efs_acl),
desc="{}{} stack".format("NetACL for", stack_name)
)
# Create Subnets for Mount Targets
for k, v in ops['tcpstacks']['EFS']['networks'].items():
efs_subnet=Subnet(
title='{}{}{}{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]),
AvailabilityZone=k,
CidrBlock=v,
VpcId=vpc_id,
Tags=Tags(Name='{}-{}-{}-{}'.format(ops.app_name, stack_name, "MountTargetSubnet", k.split("-")[-1]))
)
template.add_resource(efs_subnet)
assoc_name = '{}{}{}'.format(stack_name,"AclAssoc",k.split("-")[-1])
assoc_nacl_subnet(template, assoc_name, Ref(efs_acl), Ref(efs_subnet))
efs_mount_target=MountTarget(
title='{}{}{}'.format(ops.app_name, "EFSMountTarget", k.split("-")[-1]),
FileSystemId=Ref(efs_fs),
SecurityGroups=[Ref(efs_security_group)],
SubnetId=Ref(efs_subnet)
)
template.add_resource(efs_mount_target)
| gotropo/gotropo | create/efs.py | Python | gpl-3.0 | 2,807 |
<?php
/*
* Social Widget
*/
class Custom_Search_Widget extends WP_Widget {
function Custom_Search_Widget() {
parent::__construct(
'custom_search', // Base ID
__('Custom Search', 'denta-lite'), // Name
array( 'description' => __( 'Custom Search widget.', 'denta-lite' ), ) // Args
);
}
function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
?>
<form role="search" method="get" id="custom-searchform" class="custom-form-search" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<fieldset>
<input type="submit" class="custom-input-submit" value="" />
<input type="text" value="<?php echo get_search_query(); ?>" name="s" class="custom-input-text" placeholder="Search now..." />
</fieldset>
</form><!--/#custom-searchform .custom-form-search-->
<?php
echo $args['after_widget'];
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'Custom Search', 'denta-lite' );
}
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'denta-lite' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
}
function social_widget_register() {
register_widget( 'Custom_Search_Widget' );
}
add_action( 'widgets_init', 'social_widget_register' );
?> | Codeinwp/dentatheme-lite | includes/custom-widgets.php | PHP | gpl-3.0 | 1,853 |
/*
*** Transformer
*** src/base/transformer.cpp
Copyright T. Youngs 2013-2015
This file is part of uChroma.
uChroma 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.
uChroma 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 uChroma. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/transformer.h"
#include "expression/variable.h"
#include "templates/array.h"
// Constructor
Transformer::Transformer()
{
// Add permanent variable trio to equation
x_ = equation_.createVariable("x", NULL, true);
y_ = equation_.createVariable("y", NULL, true);
z_ = equation_.createVariable("z", NULL, true);
valid_ = false;
}
// Destructor
Transformer::~Transformer()
{
}
// Copy constructor
Transformer::Transformer(const Transformer& source)
{
(*this) = source;
}
// Assignment operator
void Transformer::operator=(const Transformer& source)
{
// Set equation from old expression
setEquation(source.text_);
enabled_ = source.enabled_;
}
// Set whether transform is enabled
void Transformer::setEnabled(bool b)
{
enabled_ = b;
}
// Return whether transform is enabled
bool Transformer::enabled()
{
return enabled_;
}
// Set equation, returning if Tree construction was successful
bool Transformer::setEquation(QString equation)
{
text_ = equation;
valid_ = equation_.generate(equation);
return valid_;
}
// Return text used to generate last equation_
QString Transformer::text()
{
return text_;
}
// Return whether current equation is valid
bool Transformer::valid()
{
return valid_;
}
// Transform single value
double Transformer::transform(double x, double y, double z)
{
// If equation is not valid, just return
if (!valid_)
{
msg.print("Equation is not valid, so returning 0.0.\n");
return 0.0;
}
x_->set(x);
y_->set(y);
z_->set(z);
bool success;
return equation_.execute(success);
}
// Transform whole array, including application of pre/post transform shift
Array<double> Transformer::transformArray(Array<double> sourceX, Array<double> sourceY, double z, int target)
{
// If transform is not enabled, return original array
if (!enabled_) return (target == 0 ? sourceX : sourceY);
// If equation is not valid, just return original array
if (!valid_)
{
msg.print("Equation is not valid, so returning original array.\n");
return (target == 0 ? sourceX : sourceY);
}
if (sourceX.nItems() != sourceY.nItems())
{
msg.print("Error in Transformer::transformArray() - x and y array sizes do not match.\n");
return Array<double>();
}
// Create new array, and create reference to target array
Array<double> newArray(sourceX.nItems());
z_->set(z);
bool success;
// Loop over x points
for (int n=0; n<sourceX.nItems(); ++n)
{
// Set x and y values in equation
x_->set(sourceX[n]);
y_->set(sourceY[n]);
newArray[n] = equation_.execute(success);
if (!success) break;
}
return newArray;
}
| trisyoungs/uchroma | src/base/transformer.cpp | C++ | gpl-3.0 | 3,304 |
# Snap! Configuration Manager
#
# (C) Copyright 2011 Mo Morsi (mo@morsi.org)
#
# 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.
import os
import os.path
import optparse, ConfigParser
import snap
from snap.options import *
from snap.snapshottarget import SnapshotTarget
from snap.exceptions import ArgError
class ConfigOptions:
"""Container holding all the configuration options available
to the Snap system"""
# modes of operation
RESTORE = 0
BACKUP = 1
def __init__(self):
'''initialize configuration'''
# mode of operation
self.mode = None
# mapping of targets to lists of backends to use when backing up / restoring them
self.target_backends = {}
# mapping of targets to lists of entities to include when backing up
self.target_includes = {}
# mapping of targets to lists of entities to exclude when backing up
self.target_excludes = {}
# output log level
# currently supports 'quiet', 'normal', 'verbose', 'debug'
self.log_level = 'normal'
# output format to backup / restore
self.outputformat = 'snapfile'
# location of the snapfile to backup to / restore from
self.snapfile = None
# Encryption/decryption password to use, if left as None, encryption will be disabled
self.encryption_password = None
# hash of key/value pairs of service-specific options
self.service_options = {}
for backend in SnapshotTarget.BACKENDS:
self.target_backends[backend] = False
self.target_includes[backend] = []
self.target_excludes[backend] = []
def log_level_at_least(self, comparison):
return (comparison == 'quiet') or \
(comparison == 'normal' and self.log_level != 'quiet') or \
(comparison == 'verbose' and (self.log_level == 'verbose' or self.log_level == 'debug')) or \
(comparison == 'debug' and self.log_level == 'debug')
class ConfigFile:
"""Represents the snap config file to be read and parsed"""
parser = None
def __init__(self, config_file):
'''
Initialize the config file, specifying its path
@param file - the path to the file to load
'''
# if config file doesn't exist, just ignore
if not os.path.exists(config_file):
if snap.config.options.log_level_at_least("verbose"):
snap.callback.snapcallback.warn("Config file " + config_file + " not found")
else:
self.parser = ConfigParser.ConfigParser()
self.parser.read(config_file)
self.__parse()
def string_to_bool(string):
'''Static helper to convert a string to a boolean value'''
if string == 'True' or string == 'true' or string == '1':
return True
elif string == 'False' or string == 'false' or string == '0':
return False
return None
string_to_bool = staticmethod(string_to_bool)
def string_to_array(string):
'''Static helper to convert a colon deliminated string to an array of strings'''
return string.split(':')
string_to_array = staticmethod(string_to_array)
def __get_bool(self, key, section='main'):
'''
Retreive the indicated boolean value from the config file
@param key - the string key corresponding to the boolean value to retrieve
@param section - the section to retrieve the value from
@returns - the value or False if not found
'''
try:
return ConfigFile.string_to_bool(self.parser.get(section, key))
except:
return None
def __get_string(self, key, section='main'):
'''
Retreive the indicated string value from the config file
@param key - the string key corresponding to the string value to retrieve
@param section - the section to retrieve the value from
@returns - the value or None if not found
'''
try:
return self.parser.get(section, key)
except:
return None
def __get_array(self, section='main'):
'''return array of key/value pairs from the config file section
@param section - the section which to retrieve the key / values from
@returns - the array of key / value pairs or None if not found
'''
try:
return self.parser.items(section)
except:
return None
def __parse(self):
'''parse configuration out of the config file'''
for backend in SnapshotTarget.BACKENDS:
val = self.__get_bool(backend)
if val is not None:
snap.config.options.target_backends[backend] = val
else:
val = self.__get_string(backend)
if val:
snap.config.options.target_backends[backend] = True
val = ConfigFile.string_to_array(val)
for include in val:
if include[0] == '!':
snap.config.options.target_excludes[backend].append(include[1:])
else:
snap.config.options.target_includes[backend].append(include)
else:
val = self.__get_bool('no' + backend)
if val:
snap.config.options.target_backends[backend] = False
of = self.__get_string('outputformat')
sf = self.__get_string('snapfile')
ll = self.__get_string('loglevel')
enp = self.__get_string('encryption_password')
if of != None:
snap.config.options.outputformat = of
if sf != None:
snap.config.options.snapfile = sf
if ll != None:
snap.config.options.log_level = ll
if enp != None:
snap.config.options.encryption_password = enp
services = self.__get_array('services')
if services:
for k, v in services:
snap.config.options.service_options[k] = v
class Config:
"""The configuration manager, used to set and verify snap config values
from the config file and command line. Primary interface to the
Configuration System"""
configoptions = None
parser = None
# read values from the config files and set them in the target ConfigOptions
def read_config(self):
# add conf stored in resources if running from local checkout
CONFIG_FILES.append(os.path.join(os.path.dirname(__file__), "..", "resources", "snap.conf"))
for config_file in CONFIG_FILES:
ConfigFile(config_file)
def parse_cli(self):
'''
parses the command line an set them in the target ConfigOptions
'''
usage = "usage: %prog [options] arg"
self.parser = optparse.OptionParser(usage, version=SNAP_VERSION)
self.parser.add_option('', '--restore', dest='restore', action='store_true', default=False, help='Restore snapshot')
self.parser.add_option('', '--backup', dest='backup', action='store_true', default=False, help='Take snapshot')
self.parser.add_option('-l', '--log-level', dest='log_level', action='store', default="normal", help='Log level (quiet, normal, verbose, debug)')
self.parser.add_option('-o', '--outputformat', dest='outputformat', action='store', default=None, help='Output file format')
self.parser.add_option('-f', '--snapfile', dest='snapfile', action='store', default=None, help='Snapshot file, use - for stdout')
self.parser.add_option('-p', '--password', dest='encryption_password', action='store', default=None, help='Snapshot File Encryption/Decryption Password')
# FIXME how to permit parameter lists for some of these
for backend in SnapshotTarget.BACKENDS:
self.parser.add_option('', '--' + backend, dest=backend, action='store_true', help='Enable ' + backend + ' snapshots/restoration')
self.parser.add_option('', '--no' + backend, dest=backend, action='store_false', help='Disable ' + backend + ' snapshots/restoration')
(options, args) = self.parser.parse_args()
if options.restore != False:
snap.config.options.mode = ConfigOptions.RESTORE
if options.backup != False:
snap.config.options.mode = ConfigOptions.BACKUP
if options.log_level:
snap.config.options.log_level = options.log_level
if options.outputformat != None:
snap.config.options.outputformat = options.outputformat
if options.snapfile != None:
snap.config.options.snapfile = options.snapfile
if options.encryption_password != None:
snap.config.options.encryption_password = options.encryption_password
for backend in SnapshotTarget.BACKENDS:
val = getattr(options, backend)
if val != None:
if type(val) == str:
snap.config.options.target_backends[backend] = True
val = ConfigFile.string_to_array(val)
for include in val:
if include[0] == '!':
snap.config.options.target_excludes[backend].append(include[1:])
else:
snap.config.options.target_includes[backend].append(include)
else:
snap.config.options.target_backends[backend] = val
def verify_integrity(self):
'''
verify the integrity of the current option set
@raises - ArgError if the options are invalid
'''
if snap.config.options.mode == None: # mode not specified
raise snap.exceptions.ArgError("Must specify backup or restore")
if snap.config.options.snapfile == None: # need to specify snapfile location
raise snap.exceptions.ArgError("Must specify snapfile")
# TODO verify output format is one of permitted types
if snap.config.options.outputformat == None: # need to specify output format
raise snap.exceptions.ArgError("Must specify valid output format")
# static shared options
options = ConfigOptions()
| movitto/snap | snap/config.py | Python | gpl-3.0 | 10,759 |
package org.safepod.app.android.exceptions;
/**
* Created by Prajit on 3/7/2016.
*/
public class AppSignatureNotGeneratedException extends Exception {
public AppSignatureNotGeneratedException() {
}
public AppSignatureNotGeneratedException(String detailMessage) {
super(detailMessage);
}
public AppSignatureNotGeneratedException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
public AppSignatureNotGeneratedException(Throwable throwable) {
super(throwable);
}
@Override
public String getMessage() {
return super.getMessage();
}
@Override
public String toString() {
return super.toString();
}
@Override
public Throwable getCause() {
return super.getCause();
}
}
| SafePodOrg/SafePodAndroid | app/src/main/java/org/safepod/app/android/exceptions/AppSignatureNotGeneratedException.java | Java | gpl-3.0 | 818 |
import { Template } from 'meteor/templating';
import { Academy } from '/imports/api/databasedriver.js';
import { Challenges } from '/imports/api/databasedriver.js';
import { Rooms } from '/imports/api/databasedriver.js';
import { Badges } from '/imports/api/databasedriver.js';
import { ROOMS_ACTIVE_ELEMENT_KEY } from '/client/management/rooms/TabRooms.js';
Template.NewRoomInfo.helpers({
badges(){
var badges = Badges.find({}).fetch();
return badges;
},
teamBadge() {
let roomType = "Team";
let roomBadges = Badges.find({'type': roomType }).fetch();
return roomBadges;
}
});
const TABLE_ROOMS_ACTIVE_TEMPLATE_NAME = "TableRoomInfo";
const NEW_ROOM_ACTIVE_TEMPLATE_NAME = "NewRoomInfo";
const EDIT_ROOM_ACTIVE_TEMPLATE_NAME = "EditRoomInfo";
Template.NewRoomInfo.events({
'submit form' (event) {
event.preventDefault();
let data = {};
let roomName = $("#roomName").val();
let roomDecision = $("#roomDecision").val();
let roomDescription = $("#roomDescription").val();
let roomBadge = $("#roomBadge").val();
data =
{
name: roomName,
dailyDecision: roomDecision,
description: roomDescription,
badges: [{ badge: roomBadge }]
};
//Modal.show('roomsInsertModal', this);
Meteor.call("insertRoom", data, function(error, result) {
if (error) {
alert(error);
}
});
$("#addRoom")[0].reset();
Session.set(ROOMS_ACTIVE_ELEMENT_KEY, TABLE_ROOMS_ACTIVE_TEMPLATE_NAME);
},
'click #nopRoom' (event){
event.preventDefault();
Session.set(ROOMS_ACTIVE_ELEMENT_KEY, TABLE_ROOMS_ACTIVE_TEMPLATE_NAME);
}
});
| LandOfKroilon/KroilonApp | client/management/rooms/newRoom/NewRoomInfo.js | JavaScript | gpl-3.0 | 1,694 |
/*
* Copyright 2014-2015 Erik Wilson <erikwilson@magnorum.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.tritania.unicus.command;
/*Start Imports*/
import java.util.Random;
import org.bukkit.permissions.PermissibleBase;
import org.bukkit.entity.Player;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.Location;
import org.tritania.unicus.Unicus;
import org.tritania.unicus.utils.Message;
import org.tritania.unicus.utils.Log;
/*End Imports*/
public class CResource implements CommandExecutor
{
public Unicus un;
private int highest;
public CResource(Unicus un)
{
this.un = un;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
Player player = (Player) sender;
if (player.getWorld().getName().equals("Resource"))
{
Message.info(sender, "You're already in the resource world");
return true;
}
else if (un.land.wipeWorld())
{
Message.info(sender, "Please wait a few moments, the resource world is resetting");
un.land.unloadWorld(un.datalocal);
return true;
}
else if (args.length > 0 && args[0].equals("spawn"))
{
Random rand = new Random();
World world = Bukkit.getWorld("Resource");
Location location = new Location(world, 0, 64.0, 0);
if (world.getHighestBlockYAt(location) > 5)
{
highest = 64;
}
else
{
highest = world.getHighestBlockYAt(location);
}
Location prime = new Location(world, 0, highest, 0);
player.teleport(prime);
}
else
{
Random rand = new Random();
World world = Bukkit.getWorld("Resource");
double x = 40000 * rand.nextDouble();
double z = 40000 * rand.nextDouble();
Location location = new Location(world, x, 64.0, z);
if (world.getHighestBlockYAt(location) > 5)
{
highest = 64;
}
else
{
highest = world.getHighestBlockYAt(location);
}
Location prime = new Location(world, x, highest, z);
player.teleport(prime);
}
Message.info(sender, un.land.timeLeft());
return true;
}
}
| tritania/Unicus | src/main/java/org/tritania/unicus/command/CResource.java | Java | gpl-3.0 | 3,241 |
<?php
/**
* This file is part of PHP_Depend.
*
* PHP Version 5
*
* Copyright (c) 2008-2011, Manuel Pichler <mapi@pdepend.org>.
* 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 Manuel Pichler nor the names of his
* 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.
*
* @category PHP
* @package PHP_Depend
* @subpackage Code
* @author Manuel Pichler <mapi@pdepend.org>
* @copyright 2008-2011 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version SVN: $Id$
* @link http://www.pdepend.org/
* @since 0.9.8
*/
/**
* This node class represents a logical <b>and</b>-expression.
*
* @category PHP
* @package PHP_Depend
* @subpackage Code
* @author Manuel Pichler <mapi@pdepend.org>
* @copyright 2008-2011 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: @package_version@
* @link http://www.pdepend.org/
* @since 0.9.8
*/
class PHP_Depend_Code_ASTLogicalAndExpression extends PHP_Depend_Code_ASTExpression
{
/**
* The type of this class.
*/
const CLAZZ = __CLASS__;
/**
* Accept method of the visitor design pattern. This method will be called
* by a visitor during tree traversal.
*
* @param PHP_Depend_Code_ASTVisitorI $visitor The calling visitor instance.
* @param mixed $data Optional previous calculated data.
*
* @return mixed
* @since 0.9.12
*/
public function accept(PHP_Depend_Code_ASTVisitorI $visitor, $data = null)
{
return $visitor->visitLogicalAndExpression($this, $data);
}
} | matamouros/cintient | lib/PEAR/PHP/Depend/Code/ASTLogicalAndExpression.php | PHP | gpl-3.0 | 3,148 |
/*
* This file is part of NanoUI
*
* Copyright (C) 2016-2018 Guerra24
*
* 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 net.luxvacuos.nanoui.rendering.glfw;
import java.nio.ByteBuffer;
public class Icon {
protected String path;
protected ByteBuffer image;
public Icon(String path) {
this.path = path;
}
}
| Guerra24/NanoUI | nanoui-core/src/main/java/net/luxvacuos/nanoui/rendering/glfw/Icon.java | Java | gpl-3.0 | 936 |
<!--
/*
* 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.
*/
/*
* Autor= Javi
* Fecha= 08/01/2016
* Licencia= GNU General Public License v.3.0
* Version= 1.0
* Descripcion=
* /
-->
<?php
class Recuerdame
{
public function guardarInfo() {
if (isset($_POST["nombre"])) {
setcookie("nombre", $_POST["nombre"], time() + 60 * 60 * 24 * 365, "", "", false, true);
}
if (isset( $_POST["localizacion"])) {
setcookie( "localizacion", $_POST["localizacion"], time() + 60 * 60 * 24 *
365, "", "", false, true );
}
header("Location: index.php");
}
public function olvidarInfo() {
setcookie( "nombre", "", time() - 3600, "", "", false, true );
setcookie( "localizacion", "", time() - 3600, "", "", false, true );
header( "Location: index.php" );
}
} | cancelajavi/2-DAW | EjerTema4_5/guia/controlador/recuerdame.php | PHP | gpl-3.0 | 986 |
package za.co.bsg.services.api;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import za.co.bsg.config.AppPropertiesConfiguration;
import za.co.bsg.model.Meeting;
import za.co.bsg.model.User;
import za.co.bsg.services.api.exception.BigBlueButtonException;
import za.co.bsg.services.api.response.BigBlueButtonResponse;
import za.co.bsg.services.api.response.CreateMeeting;
import za.co.bsg.services.api.response.MeetingRunning;
import za.co.bsg.services.api.xml.BigBlueButtonXMLHandler;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Random;
@Service
public class BigBlueButtonImp implements BigBlueButtonAPI {
@Autowired
AppPropertiesConfiguration appPropertiesConfiguration;
@Autowired
BigBlueButtonXMLHandler bigBlueButtonXMLHandler;
// BBB API Keys
protected final static String API_SERVER_PATH = "api/";
protected final static String API_CREATE = "create";
protected final static String API_JOIN = "join";
protected final static String API_SUCCESS = "SUCCESS";
protected final static String API_MEETING_RUNNING = "isMeetingRunning";
protected final static String API_FAILED = "FAILED";
protected final static String API_END_MEETING = "end";
@Override
public String getUrl() {
return appPropertiesConfiguration.getBbbURL();
}
@Override
public String getSalt() {
return appPropertiesConfiguration.getBbbSalt();
}
@Override
public String getPublicAttendeePW() {
return appPropertiesConfiguration.getAttendeePW();
}
@Override
public String getPublicModeratorPW() {
return appPropertiesConfiguration.getModeratorPW();
}
@Override
public String getLogoutURL() {
return appPropertiesConfiguration.getLogoutURL();
}
/**
* This method creates a public bbb meeting that can be joined by external users.
* First the base url is retrieved, the a meeting query is constructed.
* If a defaultPresentationURL is not empty or null, set uploadPresentation to true
* and append the presentation link to the meeting query.
* A checksumParameter is then appended to the meeting.
* The bbb create api call is invoked to create a bbb meeting and the a
* response is build based on whether or not a presentation is uploaded
*
* @param meeting a Meeting data type - details of meeting to be created
* @param user User data type - user creating a bbb meeting
* @return a String object
*/
@Override
public String createPublicMeeting(Meeting meeting, User user) {
String base_url_join = getBaseURL(API_SERVER_PATH, API_JOIN);
boolean uploadPresentation = false;
// build query
StringBuilder query = new StringBuilder();
Random random = new Random();
String voiceBridge_param = "&voiceBridge=" + (70000 + random.nextInt(9999));
query.append("&name=");
query.append(urlEncode(meeting.getName()));
query.append("&meetingID=");
query.append(urlEncode(meeting.getMeetingId()));
query.append(voiceBridge_param);
query.append("&attendeePW=");
query.append(getPublicAttendeePW());
query.append("&moderatorPW=");
query.append(getPublicModeratorPW());
query.append("&isBreakoutRoom=false");
query.append("&record=");
query.append("false");
query.append("&logoutURL=");
query.append(urlEncode(getLogoutURL()));
query.append(getMetaData( meeting.getMeta() ));
query.append("&welcome=");
query.append(urlEncode("<br>" + meeting.getWelcomeMessage() + "<br>"));
if (meeting.getDefaultPresentationURL() != "" && meeting.getDefaultPresentationURL() != null) {
uploadPresentation = true;
query.append(urlEncode("<br><br><br>" + "The presentation will appear in a moment. To download click <a href=\"event:" + meeting.getDefaultPresentationURL() + "\"><u>" + meeting.getDefaultPresentationURL() + "</u></a>.<br>" + "<br>"));
}
query.append(getCheckSumParameter(API_CREATE, query.toString()));
//Make API call
CreateMeeting response = null;
String responseCode = "";
try {
//pre-upload presentation
if (uploadPresentation) {
String xml_presentation = "<modules> <module name=\"presentation\"> <document url=\"" + meeting.getDefaultPresentationURL() + "\" /> </module> </modules>";
response = makeAPICall(API_CREATE, query.toString(), xml_presentation, CreateMeeting.class);
} else {
response = makeAPICall(API_CREATE, query.toString(), CreateMeeting.class);
}
responseCode = response.getReturncode();
} catch (BigBlueButtonException e) {
e.printStackTrace();
}
if (API_SUCCESS.equals(responseCode)) {
// Looks good, now return a URL to join that meeting
String join_parameters = "meetingID=" + urlEncode(meeting.getMeetingId())
+ "&fullName=" + urlEncode(user.getName()) + "&password="+getPublicModeratorPW();
return base_url_join + join_parameters + "&checksum="
+ getCheckSumParameter(API_JOIN + join_parameters + getSalt());
}
return ""+response;
}
/**
* This method check whether or not meeting is running using meeting id
*
* @param meeting a Meeting object data type - which is used to get meeting id
* @return boolean value indicating whether or not meeting is running
*/
@Override
public boolean isMeetingRunning(Meeting meeting) {
try {
return isMeetingRunning(meeting.getMeetingId());
} catch (BigBlueButtonException e) {
e.printStackTrace();
}
return false;
}
/**
* This method ends a bbb meeting if the user ending the meeting is a moderator,
* by building a query containing meetingId and moderator password.
* This query is then used to make an API call to end the bbb meeting,
* if meeting has ended successfully or meeting does not exists return true boolean value
*
* @param meetingID a String data type - is used to query a meeting to be ended
* @param moderatorPassword a String data type - a moderator password used to end a meeting
* @return boolean value indicating whether meeting has ended
*/
@Override
public boolean endMeeting(String meetingID, String moderatorPassword) {
StringBuilder query = new StringBuilder();
query.append("meetingID=");
query.append(meetingID);
query.append("&password=");
query.append(moderatorPassword);
query.append(getCheckSumParameter(API_END_MEETING, query.toString()));
try {
makeAPICall(API_END_MEETING, query.toString(), BigBlueButtonResponse.class);
} catch (BigBlueButtonException e) {
if(BigBlueButtonException.MESSAGEKEY_NOTFOUND.equals(e.getMessageKey())) {
// we can safely ignore this one: the meeting is not running
return true;
}else{
System.out.println("Error: "+e);
}
}
return true;
}
/**
* This method gets public meeting url, which an external user can use to join meeting
* The url is generated by, getting the base url and join parameters, which are
* combined together with the checksum
*
* @param name a String data type - name of the meeting to be joined
* @param meetingID a String data type - meetingId of the bbb meeting to be joined
* @return a String object
*/
@Override
public String getPublicJoinURL(String name, String meetingID) {
String base_url_join = getUrl() + "api/join?";
String join_parameters = "meetingID=" + urlEncode(meetingID)
+ "&fullName=" + urlEncode(name) + "&password="+getPublicAttendeePW();
return base_url_join + join_parameters + "&checksum="
+ getCheckSumParameter(API_JOIN + join_parameters + getSalt());
}
/**
* This method builds the base url by combining the bbb url with provided path and api call
*
* @param path - a String data type - a server path
* @param api_call a String data type - name of api call
* @return a String object
*/
private String getBaseURL(String path, String api_call) {
StringBuilder url = new StringBuilder(getUrl());
if (url.toString().endsWith("/bigbluebutton")){
url.append("/");
}
url.append(path);
url.append(api_call);
url.append("?");
return url.toString();
}
/**
* This method converts string to UTF-8 type
*
* @param s a String data type - url to encoded
* @return a String object
*/
private String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* This method generates a metadata parameter name
* @param metadata Map of String type object - containing metadata keys user to generate parameter name
*
* @return a String object
*/
private String getMetaData( Map<String, String> metadata ) {
String metadata_params = "";
if ( metadata!=null ){
for(String key : metadata.keySet()){
metadata_params = metadata_params + "&meta_" + urlEncode(key) + "=" + urlEncode(metadata.get(key));
}
}
return metadata_params;
}
/**
* This method check whether a bbb meeting is running
* by building a query containing meetingId to get meeting by.
* This query is then used to make an API call to check whether
* the bbb meeting is running.
*
* @param meetingID a String data type - is used to query a meeting that is running
* @return boolean value
* @throws BigBlueButtonException
*/
public boolean isMeetingRunning(String meetingID)
throws BigBlueButtonException {
try {
StringBuilder query = new StringBuilder();
query.append("meetingID=");
query.append(meetingID);
query.append(getCheckSumParameter(API_MEETING_RUNNING, query.toString()));
MeetingRunning bigBlueButtonResponse = makeAPICall(API_MEETING_RUNNING, query.toString(), MeetingRunning.class);
return Boolean.parseBoolean(bigBlueButtonResponse.getRunning());
} catch (Exception e) {
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_INTERNALERROR, e.getMessage(), e);
}
}
/**
* This method gets check sum for a api call
*
* @param apiCall a String type - a api call name used as part of generation a checksum
* @param queryString a String type - query string used as part of generating a checksum
* @return a String object
*/
private String getCheckSumParameter(String apiCall, String queryString) {
if (getSalt() != null){
return "&checksum=" + DigestUtils.sha1Hex(apiCall + queryString + getSalt());
} else{
return "";
}
}
/**
* This method generates a checksum which must be included in all api calls
*
* @param s a String data type - which is a SHA-1 hash of callName + queryString + securitySalt
* @return a String object
*/
private String getCheckSumParameter(String s) {
String checksum = "";
try {
checksum = DigestUtils.sha1Hex(s);
} catch (Exception e) {
e.printStackTrace();
}
return checksum;
}
/**
* This method returns a bbb response, by making an api call taking api call type,
* query and response type as parameters.
*
* @param apiCall a String data type - type of api call being made
* @param query a String data type - query to query bbb data
* @param responseType - a generic Class type - used to determine response type
* @return a generic object
* @throws BigBlueButtonException
*/
protected <T extends BigBlueButtonResponse> T makeAPICall(String apiCall, String query, Class<T> responseType)
throws BigBlueButtonException {
return makeAPICall(apiCall, query, "", responseType);
}
/**
* This method returns a bbb response, by making an api call taking api call type,
* query, a presentation and response type as parameters.
* The api call is used to generate a base url that is used to open a connection.
* Once there a connection an XML response to be returned to a api call is processed
* Else a BigBlueButtonException is thrown
*
* @param apiCall a String data type - used to get the base url
* @param query a String data type - used to query bbb data
* @param presentation a String type - presentation
* @param responseType a generic class type - response type
* @return a BigBlueButtonResponse
* @throws BigBlueButtonException
*/
protected <T extends BigBlueButtonResponse> T makeAPICall(String apiCall, String query, String presentation, Class<T> responseType)
throws BigBlueButtonException {
StringBuilder urlStr = new StringBuilder(getBaseURL(API_SERVER_PATH, apiCall));
if (query != null) {
urlStr.append(query);
}
try {
// open connection
URL url = new URL(urlStr.toString());
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setUseCaches(false);
httpConnection.setDoOutput(true);
if(!presentation.equals("")){
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "text/xml");
httpConnection.setRequestProperty("Content-Length", "" + Integer.toString(presentation.getBytes().length));
httpConnection.setRequestProperty("Content-Language", "en-US");
httpConnection.setDoInput(true);
DataOutputStream wr = new DataOutputStream( httpConnection.getOutputStream() );
wr.writeBytes (presentation);
wr.flush();
wr.close();
} else {
httpConnection.setRequestMethod("GET");
}
httpConnection.connect();
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// read response
InputStreamReader isr = null;
BufferedReader reader = null;
StringBuilder xml = new StringBuilder();
try {
isr = new InputStreamReader(httpConnection.getInputStream(), "UTF-8");
reader = new BufferedReader(isr);
String line = reader.readLine();
while (line != null) {
if( !line.startsWith("<?xml version=\"1.0\"?>"))
xml.append(line.trim());
line = reader.readLine();
}
} finally {
if (reader != null)
reader.close();
if (isr != null)
isr.close();
}
httpConnection.disconnect();
String stringXml = xml.toString();
BigBlueButtonResponse bigBlueButtonResponse = bigBlueButtonXMLHandler.processXMLResponse(responseType, stringXml);
String returnCode = bigBlueButtonResponse.getReturncode();
if (API_FAILED.equals(returnCode)) {
throw new BigBlueButtonException(bigBlueButtonResponse.getMessageKey(), bigBlueButtonResponse.getMessage());
}
return responseType.cast(bigBlueButtonResponse);
} else {
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_HTTPERROR, "BBB server responded with HTTP status code " + responseCode);
}
} catch(BigBlueButtonException e) {
if( !e.getMessageKey().equals("notFound") )
System.out.println("BBBException: MessageKey=" + e.getMessageKey() + ", Message=" + e.getMessage());
throw new BigBlueButtonException( e.getMessageKey(), e.getMessage(), e);
} catch(IOException e) {
System.out.println("BBB IOException: Message=" + e.getMessage());
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_UNREACHABLE, e.getMessage(), e);
} catch(IllegalArgumentException e) {
System.out.printf("BBB IllegalArgumentException: Message=" + e.getMessage());
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_INVALIDRESPONSE, e.getMessage(), e);
} catch(Exception e) {
System.out.println("BBB Exception: Message=" + e.getMessage());
throw new BigBlueButtonException(BigBlueButtonException.MESSAGEKEY_UNREACHABLE, e.getMessage(), e);
}
}
}
| BSG-Africa/bbb | src/main/java/za/co/bsg/services/api/BigBlueButtonImp.java | Java | gpl-3.0 | 17,687 |
# Peerz - P2P python library using ZeroMQ sockets and gevent
# Copyright (C) 2014-2015 Steve Henderson
#
# 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 time
from transitions import Machine
class MessageState(object):
states = ['initialised', 'waiting response', 'complete', 'timedout']
transitions = [
{'trigger': 'query', 'source': 'initialised', 'dest': 'waiting response', 'before': '_update', 'after': '_send_query'},
{'trigger': 'response', 'source': 'waiting response', 'dest': 'complete', 'before': '_update', 'after': '_completed'},
{'trigger': 'timeout', 'source': '*', 'dest': 'timedout', 'before': '_update', 'after': '_completed', },
]
def __init__(self, engine, txid, msg, callback=None, max_duration=5000, max_concurrency=3):
self.engine = engine
self.callback = callback
self.machine = Machine(model=self,
states=self.states,
transitions=self.transitions,
initial='initialised')
self.start = self.last_change = time.time() * 1000
self.max_duration = max_duration
self.max_concurrency = max_concurrency
self.txid = txid
self.times = {}
self.parse_message(msg)
self.query()
def query(self):
pass
def parse_message(self, msg):
self.val = msg.pop(0)
def is_complete(self):
return self.state in ['complete', 'timedout']
def pack_request(self):
return None
@staticmethod
def unpack_response(content):
return None
@staticmethod
def pack_response(content):
return None
def _update(self):
now = time.time() * 1000
self.times.setdefault(self.state, 0.0)
self.times[self.state] += (now - self.last_change)
self.last_change = now
def duration(self):
return time.time() * 1000 - self.start
def latency(self):
return self.times.setdefault('waiting response', 0.0)
def _send_query(self):
pass
def _completed(self):
pass
| shendo/peerz | peerz/messaging/base.py | Python | gpl-3.0 | 2,720 |
package org.matheclipse.core.interfaces;
import org.apfloat.Apcomplex;
import org.hipparchus.complex.Complex;
import org.matheclipse.core.eval.EvalEngine;
import org.matheclipse.core.eval.exception.ArgumentTypeException;
import org.matheclipse.core.expression.ApcomplexNum;
import org.matheclipse.core.expression.ComplexNum;
import org.matheclipse.core.expression.F;
/** Implemented by all number interfaces */
public interface INumber extends IExpr {
/**
* Get the absolute value for a given number
*
* @return
*/
@Override
public IExpr abs();
/**
* Get a {@link Apcomplex} number wrapped into an <code>ApcomplexNum</code> object.
*
* @return this number represented as an ApcomplexNum
*/
public ApcomplexNum apcomplexNumValue();
/**
* Get a {@link Apcomplex} object.
*
* @return this number represented as an Apcomplex
*/
public Apcomplex apcomplexValue();
/**
* Returns the smallest (closest to negative infinity) <code>IInteger</code> value that is not
* less than <code>this</code> and is equal to a mathematical integer. This method raises
* {@link ArithmeticException} if a numeric value cannot be represented by an <code>long</code>
* type.
*
* @return the smallest (closest to negative infinity) <code>IInteger</code> value that is not
* less than <code>this</code> and is equal to a mathematical integer.
*/
public INumber ceilFraction() throws ArithmeticException;
/**
* Compare the absolute value of this number with <code>1</code> and return
*
* <ul>
* <li><code>1</code>, if the absolute value is greater than 1
* <li><code>0</code>, if the absolute value equals 1
* <li><code>-1</code>, if the absolute value is less than 1
* </ul>
*
* @return
*/
public int compareAbsValueToOne();
/**
* Get the argument of the complex number
*
* @return
*/
@Override
public IExpr complexArg();
/**
* Get a <code>ComplexNum</code> number bject.
*
* @return
*/
public ComplexNum complexNumValue();
/**
* Gets the signum value of a complex number
*
* @return 0 for <code>this == 0</code>; +1 for <code>real(this) > 0</code> or
* <code>( real(this)==0 && imaginary(this) > 0 )</code>; -1 for
* <code>real(this) < 0 || ( real(this) == 0 && imaginary(this) < 0 )
*/
public int complexSign();
@Override
public INumber conjugate();
/**
* Get the absolute value for a given number
*
* @return
* @deprecated use abs()
*/
@Deprecated
default IExpr eabs() {
return abs();
}
/**
* Check if this number equals the given <code>int</code> number?
*
* @param i the integer number
* @return
*/
public boolean equalsInt(int i);
default INumber evaluatePrecision(EvalEngine engine) {
return this;
}
/**
* Returns the largest (closest to positive infinity) <code>IInteger</code> value that is not
* greater than <code>this</code> and is equal to a mathematical integer. <br>
* This method raises {@link ArithmeticException} if a numeric value cannot be represented by an
* <code>long</code> type.
*
* @return the largest (closest to positive infinity) <code>IInteger</code> value that is not
* greater than <code>this</code> and is equal to a mathematical integer.
*/
public INumber floorFraction() throws ArithmeticException;
/**
* Return the fractional part of this number
*
* @return
*/
public INumber fractionalPart();
/**
* Return the integer (real and imaginary) part of this number
*
* @return
*/
public INumber integerPart();
/**
* Returns the imaginary part of a complex number
*
* @return real part
* @deprecated use {@link #imDoubleValue()}
*/
@Deprecated
default double getImaginary() {
return imDoubleValue();
}
/**
* Returns the real part of a complex number
*
* @return real part
* @deprecated use {@link #reDoubleValue()}
*/
@Override
@Deprecated
default double getReal() {
return reDoubleValue();
}
@Override
default boolean isNumber() {
return true;
}
@Override
default boolean isNumericFunction(boolean allowList) {
return true;
}
/**
* Returns the imaginary part of a complex number
*
* @return real part
*/
@Override
public ISignedNumber im();
/**
* Returns the imaginary part of a complex number
*
* @return real part
*/
public double imDoubleValue();
@Override
public default IExpr[] linear(IExpr variable) {
return new IExpr[] {this, F.C0};
}
@Override
public default IExpr[] linearPower(IExpr variable) {
return new IExpr[] {this, F.C0, F.C1};
}
@Override
public INumber opposite();
/**
* Return the rational Factor of this number. For IComplex numbers check if real and imaginary
* parts are equal or real part or imaginary part is zero.
*
* @return <code>null</code> if no factor could be extracted
*/
default IRational rationalFactor() {
if (this instanceof IRational) {
return (IRational) this;
}
return null;
}
/**
* Returns the real part of a complex number
*
* @return real part
*/
@Override
public ISignedNumber re();
/**
* Returns the real part of a complex number
*
* @return real part
*/
public double reDoubleValue();
/**
* Returns the closest <code>IInteger</code> real and imaginary part to the argument. The result
* is rounded to an integer by adding 1/2 and taking the floor of the result by applying round
* separately to the real and imaginary part . <br>
* This method raises {@link ArithmeticException} if a numeric value cannot be represented by an
* <code>long</code> type.
*
* @return the closest integer to the argument.
*/
public IExpr roundExpr();
/**
* Return the list <code>{r, theta}</code> of the polar coordinates of this number
*
* @return
*/
public IAST toPolarCoordinates();
@Override
default Complex evalComplex() throws ArgumentTypeException {
return new Complex(reDoubleValue(), imDoubleValue());
}
}
| axkr/symja_android_library | symja_android_library/matheclipse-core/src/main/java/org/matheclipse/core/interfaces/INumber.java | Java | gpl-3.0 | 6,182 |
from essence3.util import clamp
class Align(object):
def __init__(self, h, v = None):
self.h = h
self.v = h if v is None else v
def __call__(self, node, edge):
if edge in ('top', 'bottom'):
return node.width * self.h
if edge in ('left', 'right'):
return node.height * self.v
class FlowAlign(object):
def __init__(self, h, v = None):
self.h = h
self.v = h if v is None else v
def __call__(self, node, edge):
if edge in ('top', 'bottom'):
return node.flowline(edge, self.h)
if edge in ('left', 'right'):
return node.flowline(edge, self.v)
def flow_simple(node, (low, high), edge, which):
if which == 0:
return low + node.offset1[0] + node[0].flowline(edge, which)
if which == 2:
return low + node.offset1[-2] + node[-1].flowline(edge, which)
i = len(node) / 2
if which == 1:
if len(node) % 2 == 1:
return low + node.offset1[i] + node[i].flowline(edge, which)
else:
return low + (node.offset0[i] + node.offset1[i])*0.5
class Box(object):
def __init__(self, (left, top, width, height), style):
self.left = left
self.top = top
self.width = width
self.height = height
self.style = style
def flowline(self, edge, which):
if edge in ('top', 'bottom'):
return self.width * (0.0, 0.5, 1.0)[which]
if edge in ('left', 'right'):
return self.height * (0.0, 0.5, 1.0)[which]
def measure(self, parent):
pass
def arrange(self, parent, (left,top)):
self.left = left
self.top = top
def render(self):
background = self.style['background']
if background:
background(self)
def pick(self, (x,y), hits):
return hits
def subintrons(self, res):
return res
def traverse(self, res, cond):
if cond(self):
res.append(self)
return res
class Slate(Box):
def __init__(self, (width, height), style):
Box.__init__(self, (0, 0, width, height), style)
class Label(Box):
def __init__(self, source, style):
self.source = source
Box.__init__(self, (0, 0, 0, 0), style)
self.offsets = None
def flowline(self, edge, which):
left, top, right, bottom = self.style['padding']
if edge in ('top', 'bottom'):
return self.width * (0.0, 0.5, 1.0)[which] + left
if edge in ('left', 'right'):
if which == 0:
return top
if which == 1:
return top + self.style['font'].mathline * self.style['font_size']
if which == 2:
return top + self.style['font'].baseline * self.style['font_size']
def measure(self, parent):
left, top, right, bottom = self.style['padding']
self.offsets = self.style['font'].measure(self.source, self.style['font_size'])
self.width = left + right + self.offsets[-1]
self.height = top + bottom + self.style['font'].lineheight * self.style['font_size']
def arrange(self, parent, (left,top)):
self.left = left
self.top = top
def render(self):
background = self.style['background']
if background:
background(self)
self.style['font'](self)
def selection_rect(self, start, stop):
left, top, right, bottom = self.style['padding']
x0 = self.offsets[start]
x1 = self.offsets[stop]
return (self.left + left + x0 - 1, self.top, x1-x0 + 2, self.height)
def scan_offset(self, (x,y)):
left, top, right, bottom = self.style['padding']
x -= self.left + left
k = 0
best = abs(x - 0)
for index, offset in enumerate(self.offsets):
v = abs(x - offset)
if v <= best:
best = v
k = index
return k, best ** 2.0 + abs(y - clamp(self.top, self.top + self.height, y)) ** 2.0
class Container(Box):
def __init__(self, nodes, style):
self.nodes = nodes
self.offset0 = [0] * (len(nodes) + 1)
self.offset1 = [0] * (len(nodes) + 1)
self.flow0 = [0] * len(nodes)
self.flow1 = [0] * len(nodes)
self.base0 = 0
self.base1 = 0
Box.__init__(self, (0, 0, 0, 0), style)
def __getitem__(self, i):
return self.nodes[i]
def __iter__(self):
return iter(self.nodes)
def __len__(self):
return len(self.nodes)
def render(self):
background = self.style['background']
if background:
background(self)
for node in self:
node.render()
def pick(self, (x,y), hits):
for node in self:
res = node.pick((x,y), hits)
return hits
def subintrons(self, res):
for node in self:
res = node.subintrons(res)
return res
def traverse(self, res, cond):
if cond(self):
res.append(self)
for node in self:
res = node.traverse(res, cond)
return res
class HBox(Container):
def flowline(self, edge, which):
left, top, right, bottom = self.style['padding']
if edge == 'left':
return top + self.base0 - self.flow0[0] + self[0].flowline(edge, which)
elif edge == 'right':
return top + self.base1 - self.flow1[-1] + self[-1].flowline(edge, which)
else:
return self.style['flow'](self, (left, self.width-right), edge, which)
def measure(self, parent):
offset = cap = 0
low = org = high = 0
for i, node in enumerate(self):
node.measure(self)
self.offset0[i] = cap
self.offset1[i] = offset
self.flow0[i] = f0 = self.style['align'](node, 'left')
self.flow1[i] = f1 = self.style['align'](node, 'right')
low = min(low, 0 - f0)
high = max(high, node.height - f0)
low += f0 - f1
org += f0 - f1
high += f0 - f1
cap = offset + node.width
offset += node.width + self.style['spacing']
self.offset0[len(self)] = self.offset1[len(self)] = cap
self.base0 = org - low
self.base1 = 0 - low
left, top, right, bottom = self.style['padding']
self.width = cap + left + right
self.height = high - low + top + bottom
def arrange(self, parent, (left,top)):
self.left = left
self.top = top
left, top, right, bottom = self.style['padding']
base_x = self.left + left
base_y = self.base0 + self.top + top
for i, node in enumerate(self):
node.arrange(self, (base_x + self.offset1[i], base_y - self.flow0[i]))
base_y += self.flow1[i] - self.flow0[i]
def get_spacer(self, i):
left, top, right, bottom = self.style['padding']
x0 = self.offset0[i]
x1 = self.offset1[i]
return self.left + left+x0, self.top + top, x1-x0, self.height-bottom-top
class VBox(Container):
def flowline(self, edge, which):
left, top, right, bottom = self.style['padding']
if edge == 'top':
return left + self.base0 - self.flow0[0] + self[0].flowline(edge, which)
elif edge == 'bottom':
return left + self.base1 - self.flow1[-1] + self[-1].flowline(edge, which)
else:
return self.style['flow'](self, (top, self.height-bottom), edge, which)
def measure(self, parent):
offset = cap = 0
low = org = high = 0
for i, node in enumerate(self):
node.measure(self)
self.offset0[i] = cap
self.offset1[i] = offset
self.flow0[i] = f0 = self.style['align'](node, 'top')
self.flow1[i] = f1 = self.style['align'](node, 'bottom')
low = min(low, 0 - f0)
high = max(high, node.width - f0)
low += f0 - f1
org += f0 - f1
high += f0 - f1
cap = offset + node.height
offset += node.height + self.style['spacing']
self.offset0[len(self)] = self.offset1[len(self)] = cap
self.base0 = org - low
self.base1 = 0 - low
left, top, right, bottom = self.style['padding']
self.height = cap + top + bottom
self.width = high - low + left + right
def arrange(self, parent, (left,top)):
self.left = left
self.top = top
left, top, right, bottom = self.style['padding']
base_x = self.base0 + self.left + left
base_y = self.top + top
for i, node in enumerate(self):
node.arrange(self, (base_x - self.flow0[i], base_y + self.offset1[i]))
base_x += self.flow1[i] - self.flow0[i]
def get_spacer(self, i):
left, top, right, bottom = self.style['padding']
y0 = self.offset0[i]
y1 = self.offset1[i]
return self.left + left, self.top + y0+top, self.width - right-left, y1-y0
class Intron(Box):
def __init__(self, source, index, generator):
self.source = source
self.index = index
self.generator = generator
self.rebuild()
def rebuild(self):
self.node, self.style = self.generator(self.source)
def flowline(self, edge, which):
left, top, right, bottom = self.style['padding']
if edge in ('left', 'right'):
x0 = top
if edge in ('top', 'bottom'):
x0 = left
return x0 + self.node.flowline(edge, which)
def measure(self, parent):
left, top, right, bottom = self.style['padding']
min_width = self.style['min_width']
min_height = self.style['min_height']
self.node.measure(self)
self.width = max(min_width, self.node.width + left + right)
self.height = max(min_height, self.node.height + top + bottom)
def arrange(self, parent, (left, top)):
self.left = left
self.top = top
left, top, right, bottom = self.style['padding']
inner_width = self.width - left - right
inner_height = self.height - top - bottom
x = self.left + left + (inner_width - self.node.width)*0.5
y = self.top + top + (inner_height - self.node.height)*0.5
self.node.arrange(self, (x,y))
def render(self):
background = self.style['background']
if background:
background(self)
self.node.render()
def pick(self, (x,y), hits=None):
if hits == None:
hits = []
if 0 <= x - self.left < self.width and 0 <= y - self.top < self.height:
hits.append(self)
return self.node.pick((x,y), hits)
def subintrons(self, res=None):
if res == None:
return self.node.subintrons([])
else:
res.append(self)
return res
def find_context(self, intron):
if intron == self:
return ()
for subintron in self.subintrons():
match = subintron.find_context(intron)
if match is not None:
return (self,) + match
def traverse(self, res, cond):
if cond(self):
res.append(self)
return self.node.traverse(res, cond)
def scan_offset(self, (x,y)):
left = self.left
right = self.left + self.width
top = self.top
bottom = self.top + self.height
b0 = (x - left)**2 + (y - top)**2
b1 = (x - right)**2 + (y - bottom)**2
b = (x - clamp(left, right, x))**2 + (y - clamp(top, bottom, y))**2
if b0 < b1:
return self.index, b
else:
return self.index+1, b
def solve(root, (left, top)):
root.measure(None)
root.arrange(None, (left, top))
| cheery/essence | essence3/layout.py | Python | gpl-3.0 | 11,955 |
package name.abhijitsarkar.javaee.travel.repository;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.query.N1qlQueryRow;
import name.abhijitsarkar.javaee.travel.domain.Airport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.function.Function;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_CITY;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_COUNTRY;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_FAA;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_ICAO;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_NAME;
import static name.abhijitsarkar.javaee.travel.repository.AirportRepositoryImpl.FIELD_TIMEZONE;
/**
* @author Abhijit Sarkar
*/
public class N1qlQueryRowToAirportMapper implements Function<N1qlQueryRow, Airport> {
private static final Logger LOGGER = LoggerFactory.getLogger(N1qlQueryRowToAirportMapper.class);
@Override
public Airport apply(N1qlQueryRow row) {
JsonObject value = row.value();
try {
/* Get current time at airport timezone */
ZonedDateTime now = Instant.now().atZone(ZoneId.of(value.getString(FIELD_TIMEZONE)));
return Airport.builder()
.name(value.getString(FIELD_NAME))
.faaCode(value.getString(FIELD_FAA))
.icaoCode(value.getString(FIELD_ICAO))
.city(value.getString(FIELD_CITY))
.country(value.getString(FIELD_COUNTRY))
.timeZoneOffset(now.getOffset())
.build();
} catch (Exception e) {
LOGGER.error("Failed to convert result row: {} to airport object.", row, e);
return null;
}
}
}
| asarkar/spring | travel-app/src/main/java/name/abhijitsarkar/javaee/travel/repository/N1qlQueryRowToAirportMapper.java | Java | gpl-3.0 | 2,021 |
<?php if ( ! defined('BASEPATH')) exit('No direct access allowed');
class Local extends Main_Controller {
public function __construct() {
parent::__construct(); // calls the constructor
$this->load->model('Locations_model');
$this->load->model('Pages_model');
$this->load->model('Reviews_model');
$this->load->model('Packages_model');
$this->load->library('location'); // load the location library
$this->load->library('currency'); // load the currency library
$this->lang->load('local');
}
public function index() {
if (!($location = $this->Locations_model->getLocation($this->input->get('location_id')))) {
redirect('local/all');
}
$this->location->setLocation($location['location_id']);
$this->template->setBreadcrumb('<i class="fa fa-home"></i>', '/');
$this->template->setBreadcrumb($this->lang->line('text_heading'), 'local/all');
$this->template->setBreadcrumb($location['location_name']);
$text_heading = sprintf($this->lang->line('text_local_heading'), $location['location_name']);
$this->template->setTitle($text_heading);
$this->template->setScriptTag('js/jquery.mixitup.js', 'jquery-mixitup-js', '100330');
$filter = array();
if ($this->input->get('page')) {
$filter['page'] = (int) $this->input->get('page');
} else {
$filter['page'] = '';
}
if ($this->config->item('menus_page_limit')) {
$filter['limit'] = $this->config->item('menus_page_limit');
}
$filter['sort_by'] = 'menus.menu_priority';
$filter['order_by'] = 'ASC';
$filter['filter_status'] = '1';
$filter['filter_category'] = (int) $this->input->get('category_id'); // retrieve 3rd uri segment else set FALSE if unavailable.
$this->load->module('menus');
$data['menu_list'] = $this->menus->getList($filter);
$data['menu_total'] = $this->Menus_model->getCount();
if (is_numeric($data['menu_total']) AND $data['menu_total'] < 150) {
$filter['category_id'] = 0;
}
$data['location_name'] = $this->location->getName();
$data['local_info'] = $this->info();
$data['local_reviews'] = $this->reviews();
$data['show_package_images'] = $this->config->item('show_package_images');
$data['package_list'] = $this->Packages_model->getLocalPackages($location['location_id']);
$data['local_gallery'] = $this->gallery();
$data['local_food_gallery'] = $this->food_gallery();
$this->template->render('local', $data);
}
public function info($data = array()) {
$time_format = ($this->config->item('time_format')) ? $this->config->item('time_format') : '%h:%i %a';
if ($this->config->item('maps_api_key')) {
$map_key = '&key=' . $this->config->item('maps_api_key');
} else {
$map_key = '';
}
$this->template->setScriptTag('https://maps.googleapis.com/maps/api/js?v=3' . $map_key .'&sensor=false®ion=GB&libraries=geometry', 'google-maps-js', '104330');
$data['has_delivery'] = $this->location->hasDelivery();
$data['has_collection'] = $this->location->hasCollection();
$data['has_package'] = $this->location->hasPackage();
$data['opening_status'] = $this->location->workingStatus('opening');
$data['delivery_status'] = $this->location->workingStatus('delivery');
$data['collection_status'] = $this->location->workingStatus('collection');
$data['last_order_time'] = mdate($time_format, strtotime($this->location->lastOrderTime()));
$data['local_description'] = $this->location->getDescription();
$data['map_address'] = $this->location->getAddress(); // retrieve local location data
$data['location_telephone'] = $this->location->getTelephone(); // retrieve local location data
$data['working_hours'] = $this->location->workingHours(); //retrieve local restaurant opening hours from location library
$data['working_type'] = $this->location->workingType();
if (!$this->location->hasDelivery() OR empty($data['working_type']['delivery'])) {
unset($data['working_hours']['delivery']);
}
if (!$this->location->hasCollection() OR empty($data['working_type']['collection'])) {
unset($data['working_hours']['collection']);
}
$data['delivery_time'] = $this->location->deliveryTime();
if ($data['delivery_status'] === 'closed') {
$data['delivery_time'] = 'closed';
} else if ($data['delivery_status'] === 'opening') {
$data['delivery_time'] = $this->location->workingTime('delivery', 'open');
}
$data['collection_time'] = $this->location->collectionTime();
if ($data['collection_status'] === 'closed') {
$data['collection_time'] = 'closed';
} else if ($data['collection_status'] === 'opening') {
$data['collection_time'] = $this->location->workingTime('collection', 'open');
}
$local_payments = $this->location->payments();
$payments = $this->extension->getAvailablePayments(FALSE);
$payment_list = '';
foreach ($payments as $code => $payment) {
if ( empty($local_payments) OR in_array($code, $local_payments)) {
$payment_list[] = $payment['name'];
}
}
$data['payments'] = implode(', ', $payment_list);
$area_colors = array('#F16745', '#FFC65D', '#7BC8A4', '#4CC3D9', '#93648D', '#404040', '#F16745', '#FFC65D', '#7BC8A4', '#4CC3D9', '#93648D', '#404040', '#F16745', '#FFC65D', '#7BC8A4', '#4CC3D9', '#93648D', '#404040', '#F16745', '#FFC65D');
$data['area_colors'] = $area_colors;
$conditions = array(
'all' => $this->lang->line('text_delivery_all_orders'),
'above' => $this->lang->line('text_delivery_above_total'),
'below' => $this->lang->line('text_delivery_below_total'),
);
$data['delivery_areas'] = array();
$delivery_areas = $this->location->deliveryAreas();
foreach ($delivery_areas as $area_id => $area) {
if (isset($area['charge']) AND is_string($area['charge'])) {
$area['charge'] = array(array(
'amount' => $area['charge'],
'condition' => 'above',
'total' => (isset($area['min_amount'])) ? $area['min_amount'] : '0',
));
}
$text_condition = '';
foreach ($area['condition'] as $condition) {
$condition = explode('|', $condition);
$delivery = (isset($condition[0]) AND $condition[0] > 0) ? $this->currency->format($condition[0]) : $this->lang->line('text_free_delivery');
$con = (isset($condition[1])) ? $condition[1] : 'above';
$total = (isset($condition[2]) AND $condition[2] > 0) ? $this->currency->format($condition[2]) : $this->lang->line('text_no_min_total');
if ($con === 'all') {
$text_condition .= sprintf($conditions['all'], $delivery);
} else if ($con === 'above') {
$text_condition .= sprintf($conditions[$con], $delivery, $total) . ', ';
} else if ($con === 'below') {
$text_condition .= sprintf($conditions[$con], $total) . ', ';
}
}
$data['delivery_areas'][] = array(
'area_id' => $area['area_id'],
'name' => $area['name'],
'type' => $area['type'],
'color' => $area_colors[(int) $area_id - 1],
'shape' => $area['shape'],
'circle' => $area['circle'],
'condition' => trim($text_condition, ', '),
);
}
$data['location_lat'] = $data['location_lng'] = '';
if ($local_info = $this->location->local()) { //if local restaurant data is available
$data['location_lat'] = $local_info['location_lat'];
$data['location_lng'] = $local_info['location_lng'];
}
return $data;
}
public function gallery($data = array()) {
$gallery = $this->location->getGallery();
if (empty($gallery) OR empty($gallery['images'])) {
return $data;
}
$this->template->setScriptTag('js/jquery.bsPhotoGallery.js', 'jquery-bsPhotoGallery-js', '99330');
$data['title'] = isset($gallery['title']) ? $gallery['title'] : '';
$data['description'] = isset($gallery['description']) ? $gallery['description'] : '';
foreach ($gallery['images'] as $key => $image) {
if (isset($image['status']) AND $image['status'] !== '1') {
$data['images'][$key] = array(
'name' => isset($image['name']) ? $image['name'] : '',
'path' => isset($image['path']) ? $image['path'] : '',
'thumb' => isset($image['path']) ? $this->Image_tool_model->resize($image['path']) : '',
'alt_text' => isset($image['alt_text']) ? $image['alt_text'] : '',
'status' => $image['status'],
);
}
}
return $data;
}
public function food_gallery($data = array()) {
$gallery = $this->location->getFoodGallery();
if (empty($gallery) OR empty($gallery['images'])) {
return $data;
}
$this->template->setScriptTag('js/jquery.bsPhotoGallery.js', 'jquery-bsPhotoGallery-js', '99330');
$data['title'] = isset($gallery['title']) ? $gallery['title'] : '';
$data['description'] = isset($gallery['description']) ? $gallery['description'] : '';
foreach ($gallery['images'] as $key => $image) {
if (isset($image['status']) AND $image['status'] !== '1') {
$data['images'][$key] = array(
'name' => isset($image['name']) ? $image['name'] : '',
'path' => isset($image['path']) ? $image['path'] : '',
'thumb' => isset($image['path']) ? $this->Image_tool_model->resize($image['path']) : '',
'alt_text' => isset($image['alt_text']) ? $image['alt_text'] : '',
'status' => $image['status'],
);
}
}
return $data;
}
public function reviews($data = array()) {
$date_format = ($this->config->item('date_format')) ? $this->config->item('date_format') : '%d %M %y';
$url = '&';
$filter = array();
$filter['location_id'] = (int) $this->location->getId();
if ($this->input->get('page')) {
$filter['page'] = (int) $this->input->get('page');
} else {
$filter['page'] = '';
}
if ($this->config->item('page_limit')) {
$filter['limit'] = $this->config->item('page_limit');
}
$filter['filter_status'] = '1';
$ratings = $this->config->item('ratings');
$data['ratings'] = $ratings['ratings'];
$data['reviews'] = array();
$results = $this->Reviews_model->getList($filter); // retrieve all customer reviews from getMainList method in Reviews model
foreach ($results as $result) {
$data['reviews'][] = array( // create array of customer reviews to pass to view
'author' => $result['author'],
'city' => $result['location_city'],
'quality' => $result['quality'],
'delivery' => $result['delivery'],
'service' => $result['service'],
'date' => mdate($date_format, strtotime($result['date_added'])),
'text' => $result['review_text']
);
}
$prefs['base_url'] = site_url('local?location_id='.$this->location->getId() . $url);
$prefs['total_rows'] = $this->Reviews_model->getCount($filter);
$prefs['per_page'] = $filter['limit'];
$this->load->library('pagination');
$this->pagination->initialize($prefs);
$data['pagination'] = array(
'info' => $this->pagination->create_infos(),
'links' => $this->pagination->create_links()
);
return $data;
}
public function all() {
$this->load->library('country');
$this->load->library('pagination');
$this->load->library('cart'); // load the cart library
$this->load->model('Image_tool_model');
$url = '?';
$filter = array();
if ($this->input->get('page')) {
$filter['page'] = (int) $this->input->get('page');
} else {
$filter['page'] = '';
}
if ($this->config->item('menus_page_limit')) {
$filter['limit'] = $this->config->item('menus_page_limit');
}
$filter['filter_status'] = '1';
$filter['order_by'] = 'ASC';
if ($this->input->get('search')) {
$filter['filter_search'] = $this->input->get('search');
$url .= 'search='.$filter['filter_search'].'&';
}
if ($this->input->get('sort_by')) {
$sort_by = $this->input->get('sort_by');
if ($sort_by === 'newest') {
$filter['sort_by'] = 'location_id';
$filter['order_by'] = 'DESC';
} else if ($sort_by === 'name') {
$filter['sort_by'] = 'location_name';
}
$url .= 'sort_by=' . $sort_by . '&';
}
$this->template->setBreadcrumb('<i class="fa fa-home"></i>', '/');
$this->template->setBreadcrumb($this->lang->line('text_heading'), 'local/all');
$this->template->setTitle($this->lang->line('text_heading'));
$this->template->setHeading($this->lang->line('text_heading'));
$review_totals = $this->Reviews_model->getTotalsbyId(); // retrieve all customer reviews from getMainList method in Reviews model
$data['locations'] = array();
$locations = $this->Locations_model->getList($filter);
if ($locations) {
foreach ($locations as $location) {
$this->location->setLocation($location['location_id'], FALSE);
$opening_status = $this->location->workingStatus('opening');
$delivery_status = $this->location->workingStatus('delivery');
$collection_status = $this->location->workingStatus('collection');
$delivery_time = $this->location->deliveryTime();
if ($delivery_status === 'closed') {
$delivery_time = 'closed';
} else if ($delivery_status === 'opening') {
$delivery_time = $this->location->workingTime('delivery', 'open');
}
$collection_time = $this->location->collectionTime();
if ($collection_status === 'closed') {
$collection_time = 'closed';
} else if ($collection_status === 'opening') {
$collection_time = $this->location->workingTime('collection', 'open');
}
$review_totals = isset($review_totals[$location['location_id']]) ? $review_totals[$location['location_id']] : 0;
$data['locations'][] = array( // create array of menu data to be sent to view
'location_id' => $location['location_id'],
'location_name' => $location['location_name'],
'description' => (strlen($location['description']) > 120) ? substr($location['description'], 0, 120) . '...' : $location['description'],
'address' => $this->location->getAddress(TRUE),
'total_reviews' => $review_totals,
'location_image' => $this->location->getImage(),
'is_opened' => $this->location->isOpened(),
'is_closed' => $this->location->isClosed(),
'opening_status' => $opening_status,
'delivery_status' => $delivery_status,
'collection_status' => $collection_status,
'delivery_time' => $delivery_time,
'collection_time' => $collection_time,
'opening_time' => $this->location->openingTime(),
'closing_time' => $this->location->closingTime(),
'min_total' => $this->location->minimumOrder($this->cart->total()),
'delivery_charge' => $this->location->deliveryCharge($this->cart->total()),
'has_delivery' => $this->location->hasDelivery(),
'has_collection' => $this->location->hasCollection(),
'last_order_time' => $this->location->lastOrderTime(),
'distance' => round($this->location->checkDistance()),
'distance_unit' => $this->config->item('distance_unit') === 'km' ? $this->lang->line('text_kilometers') : $this->lang->line('text_miles'),
'href' => site_url('local?location_id=' . $location['location_id']),
);
}
}
if (!empty($sort_by) AND $sort_by === 'distance') {
$data['locations'] = sort_array($data['locations'], 'distance');
} else if (!empty($sort_by) AND $sort_by === 'rating') {
$data['locations'] = sort_array($data['locations'], 'total_reviews');
}
$config['base_url'] = site_url('local/all'.$url);
$config['total_rows'] = $this->Locations_model->getCount($filter);
$config['per_page'] = $filter['limit'];
$this->pagination->initialize($config);
$data['pagination'] = array(
'info' => $this->pagination->create_infos(),
'links' => $this->pagination->create_links()
);
$this->location->initialize();
$data['locations_filter'] = $this->filter($url);
$this->template->render('local_all', $data);
}
public function filter() {
$url = '';
$data['search'] = '';
if ($this->input->get('search')) {
$data['search'] = $this->input->get('search');
$url .= 'search='.$this->input->get('search').'&';
}
$filters['distance']['name'] = lang('text_filter_distance');
$filters['distance']['href'] = site_url('local/all?'.$url.'sort_by=distance');
$filters['newest']['name'] = lang('text_filter_newest');
$filters['newest']['href'] = site_url('local/all?'.$url.'sort_by=newest');
$filters['rating']['name'] = lang('text_filter_rating');
$filters['rating']['href'] = site_url('local/all?'.$url.'sort_by=rating');
$filters['name']['name'] = lang('text_filter_name');
$filters['name']['href'] = site_url('local/all?'.$url.'sort_by=name');
$data['sort_by'] = '';
if ($this->input->get('sort_by')) {
$data['sort_by'] = $this->input->get('sort_by');
$url .= 'sort_by=' . $data['sort_by'];
}
$data['filters'] = $filters;
$url = (!empty($url)) ? '?'.$url : '';
$data['search_action'] = site_url('local/all'.$url);
return $data;
}
}
/* End of file local.php */
/* Location: ./main/controllers/local.php */ | ankpristoriko/rasaini | main/controllers/Local.php | PHP | gpl-3.0 | 17,265 |
// InputExtraTimeDlg.cpp : implementation file
//
#include "stdafx.h"
#include "TimeM.h"
#include "InputExtraTimeDlg.h"
// CInputExtraTimeDlg dialog
IMPLEMENT_DYNAMIC(CInputExtraTimeDlg, CDialog)
CInputExtraTimeDlg::CInputExtraTimeDlg(CWnd* pParent /*=NULL*/)
: CDialog(CInputExtraTimeDlg::IDD, pParent)
, m_strTimeExtra(_T("00:00:00,000"))
{
}
CInputExtraTimeDlg::~CInputExtraTimeDlg()
{
}
void CInputExtraTimeDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT_TIME_OFFSET, m_TimeExtra);
DDX_Text(pDX, IDC_EDIT_TIME_OFFSET, m_strTimeExtra);
}
BEGIN_MESSAGE_MAP(CInputExtraTimeDlg, CDialog)
END_MESSAGE_MAP()
// CInputExtraTimeDlg message handlers
| BennyThink/TimeM | TimeM/InputExtraTimeDlg.cpp | C++ | gpl-3.0 | 710 |
# Copyright (C) 2018-2019 Matthias Klumpp <matthias@tenstral.net>
#
# Licensed under the GNU Lesser General Public License Version 3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the license, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import logging as log
from glob import glob
from laniakea import LkModule
from laniakea.dud import Dud
from laniakea.utils import get_dir_shorthand_for_uuid, random_string
from laniakea.db import session_scope, Job, JobResult, JobKind, SourcePackage
from laniakea.msgstream import EventEmitter
from .rubiconfig import RubiConfig
from .utils import safe_rename
def accept_upload(conf, dud, event_emitter):
'''
Accept the upload and move its data to the right places.
'''
job_success = dud.get('X-Spark-Success') == 'Yes'
job_id = dud.get('X-Spark-Job')
# mark job as accepted and done
with session_scope() as session:
job = session.query(Job).filter(Job.uuid == job_id).one_or_none()
if not job:
log.error('Unable to mark job \'{}\' as done: The Job was not found.'.format(job_id))
# this is a weird situation, there is no proper way to handle it as this indicates a bug
# in the Laniakea setup or some other oddity.
# The least harmful thing to do is to just leave the upload alone and try again later.
return
job.result = JobResult.SUCCESS if job_success else JobResult.FAILURE
job.latest_log_excerpt = None
# move the log file and Firehose reports to the log storage
log_target_dir = os.path.join(conf.log_storage_dir, get_dir_shorthand_for_uuid(job_id))
firehose_target_dir = os.path.join(log_target_dir, 'firehose')
for fname in dud.get_files():
if fname.endswith('.log'):
os.makedirs(log_target_dir, exist_ok=True)
# move the logfile to its destination and ensure it is named correctly
target_fname = os.path.join(log_target_dir, job_id + '.log')
safe_rename(fname, target_fname)
elif fname.endswith('.firehose.xml'):
os.makedirs(firehose_target_dir, exist_ok=True)
# move the firehose report to its own directory and rename it
fh_target_fname = os.path.join(firehose_target_dir, job_id + '.firehose.xml')
safe_rename(fname, fh_target_fname)
# handle different job data
if job.module == LkModule.ISOTOPE:
from .import_isotope import handle_isotope_upload
handle_isotope_upload(session,
success=job_success,
conf=conf,
dud=dud,
job=job,
event_emitter=event_emitter)
elif job.kind == JobKind.PACKAGE_BUILD:
# the package has been imported by Dak, so we just announce this
# event to the world
spkg = session.query(SourcePackage) \
.filter(SourcePackage.source_uuid == job.trigger) \
.filter(SourcePackage.version == job.version) \
.one_or_none()
if spkg:
suite_target_name = '?'
if job.data:
suite_target_name = job.data.get('suite', '?')
event_data = {'pkgname': spkg.name,
'version': job.version,
'architecture': job.architecture,
'suite': suite_target_name,
'job_id': job_id}
if job_success:
event_emitter.submit_event_for_mod(LkModule.ARCHIVE, 'package-build-success', event_data)
else:
event_emitter.submit_event_for_mod(LkModule.ARCHIVE, 'package-build-failed', event_data)
else:
event_emitter.submit_event('upload-accepted', {'job_id': job_id, 'job_failed': not job_success})
# remove the upload description file from incoming
os.remove(dud.get_dud_file())
log.info("Upload {} accepted.", dud.get_filename())
def reject_upload(conf, dud, reason='Unknown', event_emitter=None):
'''
If a file has issues, we reject it and put it into the rejected queue.
'''
os.makedirs(conf.rejected_dir, exist_ok=True)
# move the files referenced by the .dud file
random_suffix = random_string(4)
for fname in dud.get_files():
target_fname = os.path.join(conf.rejected_dir, os.path.basename(fname))
if os.path.isfile(target_fname):
target_fname = target_fname + '+' + random_suffix
# move the file to the rejected dir
safe_rename(fname, target_fname)
# move the .dud file itself
target_fname = os.path.join(conf.rejected_dir, dud.get_filename())
if os.path.isfile(target_fname):
target_fname = target_fname + '+' + random_suffix
safe_rename(dud.get_dud_file(), target_fname)
# also store the reject reason for future reference
with open(target_fname + '.reason', 'w') as f:
f.write(reason + '\n')
log.info('Upload {} rejected.', dud.get_filename())
if event_emitter:
event_emitter.submit_event('upload-rejected', {'dud_filename': dud.get_filename(), 'reason': reason})
def import_files_from(conf, incoming_dir):
'''
Import files from an untrusted incoming source.
IMPORTANT: We assume that the uploader can not edit their files post-upload.
If they could, we would be vulnerable to timing attacks here.
'''
emitter = EventEmitter(LkModule.RUBICON)
for dud_file in glob(os.path.join(incoming_dir, '*.dud')):
dud = Dud(dud_file)
try:
dud.validate(keyrings=conf.trusted_gpg_keyrings)
except Exception as e:
reason = 'Signature validation failed: {}'.format(str(e))
reject_upload(conf, dud, reason, emitter)
continue
# if we are here, the file is good to go
accept_upload(conf, dud, emitter)
def import_files(options):
conf = RubiConfig()
if not options.incoming_dir:
print('No incoming directory set. Can not process any files.')
sys.exit(1)
import_files_from(conf, options.incoming_dir)
| lkorigin/laniakea | src/rubicon/rubicon/fileimport.py | Python | gpl-3.0 | 6,906 |
package com.archeinteractive.dev.commonutils.command;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation interface that may be attached to
* a method to designate it as a command handler.
* When registering a handler with this class, only
* methods marked with this annotation will be
* considered for command registration.
*
* @originalauthor AmoebaMan
*/
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CommandHandler {
String name();
String[] aliases() default {""};
String description() default "";
String usage() default "";
String permission() default "";
String permissionMessage() default "You do not have permission to use that command";
}
| ewized/CommonUtils | src/main/java/com/archeinteractive/dev/commonutils/command/CommandHandler.java | Java | gpl-3.0 | 955 |
//===-- MipsMCCodeEmitter.cpp - Convert Mips code to machine code ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the MipsMCCodeEmitter class.
//
//===----------------------------------------------------------------------===//
//
#define DEBUG_TYPE "mccodeemitter"
#include "MCTargetDesc/MipsBaseInfo.h"
#include "MCTargetDesc/MipsFixupKinds.h"
#include "MCTargetDesc/MipsMCTargetDesc.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class MipsMCCodeEmitter : public MCCodeEmitter {
MipsMCCodeEmitter(const MipsMCCodeEmitter &); // DO NOT IMPLEMENT
void operator=(const MipsMCCodeEmitter &); // DO NOT IMPLEMENT
const MCInstrInfo &MCII;
const MCSubtargetInfo &STI;
MCContext &Ctx;
public:
MipsMCCodeEmitter(const MCInstrInfo &mcii, const MCSubtargetInfo &sti,
MCContext &ctx) : MCII(mcii), STI(sti) , Ctx(ctx) {}
~MipsMCCodeEmitter() {}
void EmitByte(unsigned char C, raw_ostream &OS) const {
OS << (char)C;
}
void EmitInstruction(uint64_t Val, unsigned Size, raw_ostream &OS) const {
// Output the instruction encoding in little endian byte order.
for (unsigned i = 0; i != Size; ++i) {
EmitByte(Val & 255, OS);
Val >>= 8;
}
}
void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups) const;
// getBinaryCodeForInstr - TableGen'erated function for getting the
// binary encoding for an instruction.
unsigned getBinaryCodeForInstr(const MCInst &MI,
SmallVectorImpl<MCFixup> &Fixups) const;
// getBranchJumpOpValue - Return binary encoding of the jump
// target operand. If the machine operand requires relocation,
// record the relocation and return zero.
unsigned getJumpTargetOpValue(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const;
// getBranchTargetOpValue - Return binary encoding of the branch
// target operand. If the machine operand requires relocation,
// record the relocation and return zero.
unsigned getBranchTargetOpValue(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const;
// getMachineOpValue - Return binary encoding of operand. If the machin
// operand requires relocation, record the relocation and return zero.
unsigned getMachineOpValue(const MCInst &MI,const MCOperand &MO,
SmallVectorImpl<MCFixup> &Fixups) const;
unsigned getMemEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const;
unsigned getSizeExtEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const;
unsigned getSizeInsEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const;
}; // class MipsMCCodeEmitter
} // namespace
MCCodeEmitter *llvm::createMipsMCCodeEmitter(const MCInstrInfo &MCII,
const MCSubtargetInfo &STI,
MCContext &Ctx)
{
return new MipsMCCodeEmitter(MCII, STI, Ctx);
}
/// EncodeInstruction - Emit the instruction.
/// Size the instruction (currently only 4 bytes
void MipsMCCodeEmitter::
EncodeInstruction(const MCInst &MI, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups) const
{
uint32_t Binary = getBinaryCodeForInstr(MI, Fixups);
// Check for unimplemented opcodes.
// Unfortunately in MIPS both NOT and SLL will come in with Binary == 0
// so we have to special check for them.
unsigned Opcode = MI.getOpcode();
if ((Opcode != Mips::NOP) && (Opcode != Mips::SLL) && !Binary)
llvm_unreachable("unimplemented opcode in EncodeInstruction()");
const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
uint64_t TSFlags = Desc.TSFlags;
// Pseudo instructions don't get encoded and shouldn't be here
// in the first place!
if ((TSFlags & MipsII::FormMask) == MipsII::Pseudo)
llvm_unreachable("Pseudo opcode found in EncodeInstruction()");
// For now all instructions are 4 bytes
int Size = 4; // FIXME: Have Desc.getSize() return the correct value!
EmitInstruction(Binary, Size, OS);
}
/// getBranchTargetOpValue - Return binary encoding of the branch
/// target operand. If the machine operand requires relocation,
/// record the relocation and return zero.
unsigned MipsMCCodeEmitter::
getBranchTargetOpValue(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const {
const MCOperand &MO = MI.getOperand(OpNo);
assert(MO.isExpr() && "getBranchTargetOpValue expects only expressions");
const MCExpr *Expr = MO.getExpr();
Fixups.push_back(MCFixup::Create(0, Expr,
MCFixupKind(Mips::fixup_Mips_PC16)));
return 0;
}
/// getJumpTargetOpValue - Return binary encoding of the jump
/// target operand. If the machine operand requires relocation,
/// record the relocation and return zero.
unsigned MipsMCCodeEmitter::
getJumpTargetOpValue(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const {
const MCOperand &MO = MI.getOperand(OpNo);
assert(MO.isExpr() && "getJumpTargetOpValue expects only expressions");
const MCExpr *Expr = MO.getExpr();
Fixups.push_back(MCFixup::Create(0, Expr,
MCFixupKind(Mips::fixup_Mips_26)));
return 0;
}
/// getMachineOpValue - Return binary encoding of operand. If the machine
/// operand requires relocation, record the relocation and return zero.
unsigned MipsMCCodeEmitter::
getMachineOpValue(const MCInst &MI, const MCOperand &MO,
SmallVectorImpl<MCFixup> &Fixups) const {
if (MO.isReg()) {
unsigned Reg = MO.getReg();
unsigned RegNo = getMipsRegisterNumbering(Reg);
return RegNo;
} else if (MO.isImm()) {
return static_cast<unsigned>(MO.getImm());
} else if (MO.isFPImm()) {
return static_cast<unsigned>(APFloat(MO.getFPImm())
.bitcastToAPInt().getHiBits(32).getLimitedValue());
} else if (MO.isExpr()) {
const MCExpr *Expr = MO.getExpr();
MCExpr::ExprKind Kind = Expr->getKind();
unsigned Ret = 0;
if (Kind == MCExpr::Binary) {
const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Expr);
Expr = BE->getLHS();
Kind = Expr->getKind();
const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(BE->getRHS());
assert((Kind == MCExpr::SymbolRef) && CE &&
"Binary expression must be sym+const.");
Ret = CE->getValue();
}
if (Kind == MCExpr::SymbolRef) {
Mips::Fixups FixupKind;
switch(cast<MCSymbolRefExpr>(Expr)->getKind()) {
case MCSymbolRefExpr::VK_Mips_GPREL:
FixupKind = Mips::fixup_Mips_GPREL16;
break;
case MCSymbolRefExpr::VK_Mips_GOT_CALL:
FixupKind = Mips::fixup_Mips_CALL16;
break;
case MCSymbolRefExpr::VK_Mips_GOT:
FixupKind = Mips::fixup_Mips_GOT16;
break;
case MCSymbolRefExpr::VK_Mips_ABS_HI:
FixupKind = Mips::fixup_Mips_HI16;
break;
case MCSymbolRefExpr::VK_Mips_ABS_LO:
FixupKind = Mips::fixup_Mips_LO16;
break;
case MCSymbolRefExpr::VK_Mips_TLSGD:
FixupKind = Mips::fixup_Mips_TLSGD;
break;
case MCSymbolRefExpr::VK_Mips_GOTTPREL:
FixupKind = Mips::fixup_Mips_GOTTPREL;
break;
case MCSymbolRefExpr::VK_Mips_TPREL_HI:
FixupKind = Mips::fixup_Mips_TPREL_HI;
break;
case MCSymbolRefExpr::VK_Mips_TPREL_LO:
FixupKind = Mips::fixup_Mips_TPREL_LO;
break;
default:
return Ret;
} // switch
Fixups.push_back(MCFixup::Create(0, Expr, MCFixupKind(FixupKind)));
} // if SymbolRef
// All of the information is in the fixup.
return Ret;
}
llvm_unreachable("Unable to encode MCOperand!");
// Not reached
return 0;
}
/// getMemEncoding - Return binary encoding of memory related operand.
/// If the offset operand requires relocation, record the relocation.
unsigned
MipsMCCodeEmitter::getMemEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const {
// Base register is encoded in bits 20-16, offset is encoded in bits 15-0.
assert(MI.getOperand(OpNo).isReg());
unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo),Fixups) << 16;
unsigned OffBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups);
return (OffBits & 0xFFFF) | RegBits;
}
unsigned
MipsMCCodeEmitter::getSizeExtEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const {
assert(MI.getOperand(OpNo).isImm());
unsigned szEncoding = getMachineOpValue(MI, MI.getOperand(OpNo), Fixups);
return szEncoding - 1;
}
// FIXME: should be called getMSBEncoding
//
unsigned
MipsMCCodeEmitter::getSizeInsEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups) const {
assert(MI.getOperand(OpNo-1).isImm());
assert(MI.getOperand(OpNo).isImm());
unsigned pos = getMachineOpValue(MI, MI.getOperand(OpNo-1), Fixups);
unsigned sz = getMachineOpValue(MI, MI.getOperand(OpNo), Fixups);
return pos + sz - 1;
}
#include "MipsGenMCCodeEmitter.inc"
| Bootz/multicore-opimization | llvm/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.cpp | C++ | gpl-3.0 | 9,919 |
#region
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using Game.Battle.CombatGroups;
using Game.Battle.CombatObjects;
using Game.Battle.Reporting;
using Game.Battle.RewardStrategies;
using Game.Data;
using Game.Setup;
using Game.Util;
using Game.Util.Locking;
using JsonFx.Json;
using Persistance;
#endregion
namespace Game.Battle
{
public class BattleManager : IBattleManager
{
public enum BattleSide
{
Defense = 0,
Attack = 1
}
public const string DB_TABLE = "battle_managers";
private readonly IBattleFormulas battleFormulas;
private readonly IBattleRandom battleRandom;
private readonly IBattleOrder battleOrder;
private readonly object battleLock = new object();
private readonly IDbManager dbManager;
private readonly LargeIdGenerator groupIdGen;
private readonly LargeIdGenerator idGen;
private readonly Dictionary<string, object> properties = new Dictionary<string, object>();
private readonly IRewardStrategy rewardStrategy;
public BattleManager(uint battleId,
BattleLocation location,
BattleOwner owner,
IRewardStrategy rewardStrategy,
IDbManager dbManager,
IBattleReport battleReport,
ICombatListFactory combatListFactory,
IBattleFormulas battleFormulas,
IBattleOrder battleOrder,
IBattleRandom battleRandom)
{
groupIdGen = new LargeIdGenerator(uint.MaxValue);
idGen = new LargeIdGenerator(uint.MaxValue);
// Group id 1 is always reserved for local troop
groupIdGen.Set(1);
BattleId = battleId;
Location = location;
Owner = owner;
BattleReport = battleReport;
Attackers = combatListFactory.GetAttackerCombatList();
Defenders = combatListFactory.GetDefenderCombatList();
this.rewardStrategy = rewardStrategy;
this.dbManager = dbManager;
this.battleOrder = battleOrder;
this.battleFormulas = battleFormulas;
this.battleRandom = battleRandom;
}
public uint BattleId { get; private set; }
public BattleLocation Location { get; private set; }
public BattleOwner Owner { get; private set; }
public bool BattleStarted { get; set; }
public uint Round { get; set; }
public uint Turn { get; set; }
public ICombatList Attackers { get; private set; }
public ICombatList Defenders { get; private set; }
public IBattleReport BattleReport { get; private set; }
public IEnumerable<ILockable> LockList
{
get
{
var locks = new HashSet<ILockable>();
foreach (var co in Attackers)
{
locks.Add(co);
}
foreach (var co in Defenders)
{
locks.Add(co);
}
return locks;
}
}
public ICombatObject GetCombatObject(uint id)
{
return Attackers.AllCombatObjects().FirstOrDefault(co => co.Id == id) ??
Defenders.AllCombatObjects().FirstOrDefault(co => co.Id == id);
}
public virtual Error CanWatchBattle(IPlayer player, out IEnumerable<string> errorParams)
{
errorParams = new string[0];
lock (battleLock)
{
if (Owner.IsOwner(player))
{
return Error.Ok;
}
int attackersUpkeepTotal = Attackers.UpkeepTotal;
int defendersRoundsLeft = int.MaxValue;
int attackersRoundsLeft = int.MaxValue;
// Check if player has a defender that is over the minimum battle rounds
var playersDefenders = Defenders.Where(combatGroup => combatGroup.BelongsTo(player)).ToList();
if (playersDefenders.Any())
{
if (attackersUpkeepTotal > 1000)
{
return Error.Ok;
}
defendersRoundsLeft = playersDefenders.Min(combatGroup =>
combatGroup.Min(combatObject => Config.battle_min_rounds - combatObject.RoundsParticipated));
if (defendersRoundsLeft < 0)
{
return Error.Ok;
}
}
// Check if player has an attacker that is over the minimum battle rounds
var playersAttackers = Attackers.Where(co => co.BelongsTo(player)).ToList();
if (playersAttackers.Any())
{
if (attackersUpkeepTotal > 1000)
{
return Error.Ok;
}
attackersRoundsLeft = playersAttackers.Min(combatGroup =>
combatGroup.Min(combatObject => Config.battle_min_rounds - combatObject.RoundsParticipated));
if (attackersRoundsLeft < 0)
{
return Error.Ok;
}
}
// Calculate how many rounds until player can see the battle
var roundsLeft = Math.Min(attackersRoundsLeft, defendersRoundsLeft);
if (roundsLeft == int.MaxValue)
{
return Error.BattleViewableNoTroopsInBattle;
}
roundsLeft = Math.Max(roundsLeft, 1);
errorParams = new[] {roundsLeft.ToString(CultureInfo.InvariantCulture)};
return Error.BattleViewableInRounds;
}
}
#region Database Loader
public void DbLoaderAddToCombatList(ICombatGroup group, BattleSide side)
{
if (side == BattleSide.Defense)
{
Defenders.Add(group, false);
}
else
{
Attackers.Add(group, false);
}
groupIdGen.Set(group.Id);
}
#endregion
#region Adding/Removing Groups
public uint GetNextGroupId()
{
return groupIdGen.GetNext();
}
public uint GetNextCombatObjectId()
{
return idGen.GetNext();
}
public void DbFinishedLoading()
{
uint maxId =
Math.Max(
Attackers.SelectMany(group => group)
.DefaultIfEmpty()
.Max(combatObject => combatObject == null ? 0 : combatObject.Id),
Defenders.SelectMany(group => group)
.DefaultIfEmpty()
.Max(combatObject => combatObject == null ? 0 : combatObject.Id));
idGen.Set(maxId);
}
public T GetProperty<T>(string name)
{
return (T)Convert.ChangeType(properties[name], typeof(T), CultureInfo.InvariantCulture);
}
public void SetProperty(string name, object value)
{
properties[name] = value;
}
public void DbLoadProperties(Dictionary<string, object> dbProperties)
{
properties.Clear();
foreach (var property in dbProperties)
{
properties.Add(property.Key, property.Value);
}
}
public IDictionary<string, object> ListProperties()
{
return new Dictionary<string, object>(properties);
}
public void Add(ICombatGroup combatGroup, BattleSide battleSide, bool allowReportAccess)
{
bool isAttacker = battleSide == BattleSide.Attack;
lock (battleLock)
{
if (GetCombatGroup(combatGroup.Id) != null)
{
throw new Exception(
string.Format("Trying to add a group to battle {0} with id {1} that already exists",
BattleId,
combatGroup.Id));
}
(battleSide == BattleSide.Attack ? Attackers : Defenders).Add(combatGroup);
if (isAttacker)
{
combatGroup.CombatObjectAdded += AttackerGroupOnCombatObjectAdded;
combatGroup.CombatObjectRemoved += AttackerGroupOnCombatObjectRemoved;
}
else
{
combatGroup.CombatObjectAdded += DefenderGroupOnCombatObjectAdded;
combatGroup.CombatObjectRemoved += DefenderGroupOnCombatObjectRemoved;
}
if (BattleStarted)
{
BattleReport.WriteReportGroup(combatGroup, isAttacker, ReportState.Entering);
if (isAttacker)
{
ReinforceAttacker(this, combatGroup);
}
else
{
ReinforceDefender(this, combatGroup);
}
}
if (allowReportAccess)
{
BattleReport.AddAccess(combatGroup, battleSide);
}
if (combatGroup.Tribe != null)
{
BattleReport.AddTribeToBattle(combatGroup.Tribe, battleSide);
}
}
}
public void Remove(ICombatGroup group, BattleSide side, ReportState state)
{
lock (battleLock)
{
// Remove from appropriate combat list
if (side == BattleSide.Attack)
{
if (!Attackers.Remove(group))
{
return;
}
group.CombatObjectAdded -= AttackerGroupOnCombatObjectAdded;
group.CombatObjectRemoved -= AttackerGroupOnCombatObjectRemoved;
}
else
{
if (!Defenders.Remove(group))
{
return;
}
group.CombatObjectAdded -= DefenderGroupOnCombatObjectAdded;
group.CombatObjectRemoved -= DefenderGroupOnCombatObjectRemoved;
}
// If battle hasnt started then dont worry about cleaning anything up since nothing has happened to these objects
if (!BattleStarted)
{
return;
}
// Snap a report of exit
BattleReport.WriteReportGroup(group, side == BattleSide.Attack, state);
// Tell objects to exit from battle
foreach (var co in group.Where(co => !co.Disposed))
{
co.ExitBattle();
}
// Send exit events
if (side == BattleSide.Attack)
{
WithdrawAttacker(this, group);
}
else
{
WithdrawDefender(this, group);
}
}
}
private void DefenderGroupOnCombatObjectAdded(ICombatGroup group, ICombatObject combatObject)
{
GroupUnitAdded(this, BattleSide.Defense, group, combatObject);
}
private void DefenderGroupOnCombatObjectRemoved(ICombatGroup group, ICombatObject combatObject)
{
GroupUnitRemoved(this, BattleSide.Defense, group, combatObject);
}
private void AttackerGroupOnCombatObjectAdded(ICombatGroup group, ICombatObject combatObject)
{
GroupUnitAdded(this, BattleSide.Attack, group, combatObject);
}
private void AttackerGroupOnCombatObjectRemoved(ICombatGroup group, ICombatObject combatObject)
{
GroupUnitRemoved(this, BattleSide.Attack, group, combatObject);
}
#endregion
#region Battle
public bool ExecuteTurn()
{
lock (battleLock)
{
battleRandom.UpdateSeed(Round, Turn);
ICombatList offensiveCombatList;
ICombatList defensiveCombatList;
BattleSide sideAttacking;
// This will finalize any reports already started.
BattleReport.CompleteReport(ReportState.Staying);
#region Battle Start
if (!BattleStarted)
{
// Makes sure battle is valid before even starting it
// This shouldnt really happen but I remember it happening in the past
// so until we can make sure that we dont even start invalid battles, it's better to leave it
if (!IsBattleValid())
{
BattleEnded(false);
return false;
}
BringWaitingTroopsIntoBattle();
BattleStarted = true;
BattleReport.CreateBattleReport();
EnterBattle(this, Attackers, Defenders);
}
#endregion
#region Targeting
List<CombatList.Target> currentDefenders;
ICombatGroup attackerGroup;
ICombatObject attackerObject;
do
{
#region Find Attacker
var newRound =
!battleOrder.NextObject(Round,
Attackers,
Defenders,
out attackerObject,
out attackerGroup,
out sideAttacking);
// Save the offensive/defensive side relative to the attacker to make it easier in this function to know
// which side is attacking.
defensiveCombatList = sideAttacking == BattleSide.Attack ? Defenders : Attackers;
offensiveCombatList = sideAttacking == BattleSide.Attack ? Attackers : Defenders;
if (newRound)
{
++Round;
Turn = 0;
BringWaitingTroopsIntoBattle();
EnterRound(this, Attackers, Defenders, Round);
// Since the EventEnterRound can remove the object from battle, we need to make sure he's still in the battle
// If they aren't, then we just find a new attacker
if (attackerObject != null && !offensiveCombatList.AllCombatObjects().Contains(attackerObject))
{
continue;
}
}
// Verify battle is still good to go
if (attackerObject == null || !IsBattleValid())
{
BattleEnded(true);
return false;
}
#endregion
#region Find Target(s)
var targetResult = defensiveCombatList.GetBestTargets(BattleId,
attackerObject,
out currentDefenders,
battleFormulas.GetNumberOfHits(attackerObject, defensiveCombatList),
Round);
if (currentDefenders.Count == 0 || attackerObject.Stats.Atk == 0)
{
attackerObject.ParticipatedInRound(Round);
dbManager.Save(attackerObject);
SkippedAttacker(this, sideAttacking, attackerGroup, attackerObject);
// If the attacker can't attack because it has no one in range, then we skip him and find another target right away.
if (targetResult == CombatList.BestTargetResult.NoneInRange)
{
continue;
}
return true;
}
#endregion
break;
}
while (true);
#endregion
for (int attackIndex = 0; attackIndex < currentDefenders.Count; attackIndex++)
{
var defender = currentDefenders[attackIndex];
// Make sure the target is still in the battle (they can leave if someone else in the group took dmg and caused the entire group to leave)
// We just skip incase they left while we were attacking
// which means if the attacker is dealing splash they may deal less hits in this fringe case
if (!defensiveCombatList.AllCombatObjects().Contains(defender.CombatObject))
{
continue;
}
// Target is still in battle, attack it
decimal carryOverDmg;
AttackTarget(offensiveCombatList,
defensiveCombatList,
attackerGroup,
attackerObject,
sideAttacking,
defender,
attackIndex,
Round,
out carryOverDmg);
// Add another target if we have to carry over some dmg and our current hit isnt from a carry over already
if (carryOverDmg > 0m && !defender.DamageCarryOverPercentage.HasValue)
{
List<CombatList.Target> carryOverDefender;
defensiveCombatList.GetBestTargets(BattleId,
attackerObject,
out carryOverDefender,
1,
Round);
if (carryOverDefender.Count > 0)
{
var target = carryOverDefender.First();
target.DamageCarryOverPercentage = carryOverDmg;
currentDefenders.Insert(attackIndex + 1, target);
}
}
}
// Just a safety check
if (attackerObject.Disposed)
{
throw new Exception("Attacker has been improperly disposed");
}
attackerObject.ParticipatedInRound(Round);
dbManager.Save(attackerObject);
ExitTurn(this, Attackers, Defenders, Turn++);
if (!IsBattleValid())
{
BattleEnded(true);
return false;
}
// Remove any attackers that don't have anyone in range
var groupsWithoutAnyoneInRange = Attackers.Where(attacker => attacker.All(combatObjects => !Defenders.HasInRange(combatObjects))).ToList();
foreach (var group in groupsWithoutAnyoneInRange)
{
Remove(group, BattleSide.Attack, ReportState.Exiting);
}
return true;
}
}
private void BringWaitingTroopsIntoBattle()
{
foreach (var defender in Defenders.AllCombatObjects().Where(co => co.IsWaitingToJoinBattle))
{
defender.JoinBattle(Round);
dbManager.Save(defender);
}
foreach (var attacker in Attackers.AllCombatObjects().Where(co => co.IsWaitingToJoinBattle))
{
attacker.JoinBattle(Round);
dbManager.Save(attacker);
}
}
public ICombatGroup GetCombatGroup(uint id)
{
return Attackers.FirstOrDefault(group => group.Id == id) ??
Defenders.FirstOrDefault(group => group.Id == id);
}
private bool IsBattleValid()
{
if (Attackers.Count == 0 || Defenders.Count == 0)
{
return false;
}
// Check to see if all units in the defense is dead
// and make sure units can still see each other
return Attackers.AllAliveCombatObjects().Any(combatObj => Defenders.HasInRange(combatObj));
}
private void BattleEnded(bool writeReport)
{
if (writeReport)
{
BattleReport.CompleteBattle();
}
AboutToExitBattle(this, Attackers, Defenders);
ExitBattle(this, Attackers, Defenders);
foreach (var combatObj in Defenders.AllCombatObjects().Where(combatObj => !combatObj.IsDead))
{
combatObj.ExitBattle();
}
foreach (var combatObj in Attackers.AllCombatObjects().Where(combatObj => !combatObj.IsDead))
{
combatObj.ExitBattle();
}
foreach (var group in Attackers)
{
WithdrawAttacker(this, group);
}
foreach (var group in Defenders)
{
WithdrawDefender(this, group);
}
// Delete all groups
Attackers.Clear();
Defenders.Clear();
}
protected virtual void AttackTarget(ICombatList offensiveCombatList,
ICombatList defensiveCombatList,
ICombatGroup attackerGroup,
ICombatObject attacker,
BattleSide sideAttacking,
CombatList.Target target,
int attackIndex,
uint round,
out decimal carryOverDmg)
{
var attackerCount = attacker.Count;
var targetCount = target.CombatObject.Count;
#region Damage
decimal dmg = battleFormulas.GetAttackerDmgToDefender(attacker, target.CombatObject,round);
if (target.DamageCarryOverPercentage.HasValue)
{
dmg *= target.DamageCarryOverPercentage.Value;
}
decimal actualDmg;
target.CombatObject.CalcActualDmgToBeTaken(offensiveCombatList,
defensiveCombatList,
battleRandom,
dmg,
attackIndex,
out actualDmg);
Resource defenderDroppedLoot;
int attackPoints;
int initialCount = target.CombatObject.Count;
carryOverDmg = 0;
if (dmg > 0 && target.CombatObject.Hp - actualDmg < 0m)
{
carryOverDmg = (actualDmg - target.CombatObject.Hp) / actualDmg;
}
actualDmg = Math.Min(target.CombatObject.Hp, actualDmg);
target.CombatObject.TakeDamage(actualDmg, out defenderDroppedLoot, out attackPoints);
if (initialCount > target.CombatObject.Count)
{
UnitCountDecreased(this,
sideAttacking == BattleSide.Attack ? BattleSide.Defense : BattleSide.Attack,
target.Group,
target.CombatObject,
initialCount - target.CombatObject.Count);
}
attacker.DmgDealt += actualDmg;
attacker.MaxDmgDealt = (ushort)Math.Max(attacker.MaxDmgDealt, actualDmg);
attacker.MinDmgDealt = (ushort)Math.Min(attacker.MinDmgDealt, actualDmg);
++attacker.HitDealt;
attacker.HitDealtByUnit += attacker.Count;
target.CombatObject.DmgRecv += actualDmg;
target.CombatObject.MaxDmgRecv = (ushort)Math.Max(target.CombatObject.MaxDmgRecv, actualDmg);
target.CombatObject.MinDmgRecv = (ushort)Math.Min(target.CombatObject.MinDmgRecv, actualDmg);
++target.CombatObject.HitRecv;
#endregion
#region Loot and Attack Points
// NOTE: In the following rewardStrategy calls we are in passing in whatever the existing implementations
// of reward startegy need. If some specific implementation needs more info then add more params or change it to
// take the entire BattleManager as a param.
if (sideAttacking == BattleSide.Attack)
{
// Only give loot if we are attacking the first target in the list
Resource loot;
rewardStrategy.RemoveLoot(this, attackIndex, attacker, target.CombatObject, out loot);
if (attackPoints > 0 || (loot != null && !loot.Empty))
{
rewardStrategy.GiveAttackerRewards(attacker, attackPoints, loot ?? new Resource());
}
}
else
{
// Give defender rewards if there are any
if (attackPoints > 0 || (defenderDroppedLoot != null && !defenderDroppedLoot.Empty))
{
rewardStrategy.GiveDefendersRewards(attacker,
attackPoints,
defenderDroppedLoot ?? new Resource());
}
}
#endregion
#region Object removal
bool isDefenderDead = target.CombatObject.IsDead;
ActionAttacked(this, sideAttacking, attackerGroup, attacker, target.Group, target.CombatObject, actualDmg, attackerCount, targetCount);
if (isDefenderDead)
{
bool isGroupDead = target.Group.IsDead();
if (isGroupDead)
{
// Remove the entire group
Remove(target.Group,
sideAttacking == BattleSide.Attack ? BattleSide.Defense : BattleSide.Attack,
ReportState.Dying);
}
else if (!target.CombatObject.Disposed)
{
// Only remove the single object
BattleReport.WriteExitingObject(target.Group, sideAttacking != BattleSide.Attack, target.CombatObject);
target.Group.Remove(target.CombatObject);
}
UnitKilled(this,
sideAttacking == BattleSide.Attack ? BattleSide.Defense : BattleSide.Attack,
target.Group,
target.CombatObject);
if (!target.CombatObject.Disposed)
{
target.CombatObject.ExitBattle();
}
if (isGroupDead)
{
GroupKilled(this, target.Group);
}
}
else
{
if (!target.CombatObject.Disposed)
{
dbManager.Save(target.CombatObject);
}
}
#endregion
}
#endregion
#region Events
public delegate void OnAttack(
IBattleManager battle,
BattleSide attackingSide,
ICombatGroup attackerGroup,
ICombatObject attacker,
ICombatGroup targetGroup,
ICombatObject target,
decimal damage,
int attackerCount,
int targetCount);
public delegate void OnBattle(IBattleManager battle, ICombatList attackers, ICombatList defenders);
public delegate void OnReinforce(IBattleManager battle, ICombatGroup combatGroup);
public delegate void OnRound(IBattleManager battle, ICombatList attackers, ICombatList defenders, uint round);
public delegate void OnTurn(IBattleManager battle, ICombatList attackers, ICombatList defenders, uint turn);
public delegate void OnUnitCountChange(
IBattleManager battle,
BattleSide combatObjectSide,
ICombatGroup combatGroup,
ICombatObject combatObject,
int count);
public delegate void OnUnitUpdate(
IBattleManager battle, BattleSide combatObjectSide, ICombatGroup combatGroup, ICombatObject combatObject
);
public delegate void OnWithdraw(IBattleManager battle, ICombatGroup group);
/// <summary>
/// Fired once when the battle begins
/// </summary>
public event OnBattle EnterBattle = delegate { };
/// <summary>
/// Fired right before the battle is about to end
/// </summary>
public event OnBattle AboutToExitBattle = delegate { };
/// <summary>
/// Fired once when the battle ends
/// </summary>
public event OnBattle ExitBattle = delegate { };
/// <summary>
/// Fired when a new round starts
/// </summary>
public event OnRound EnterRound = delegate { };
/// <summary>
/// Fired everytime a unit exits its turn
/// </summary>
public event OnTurn ExitTurn = delegate { };
/// <summary>
/// Fired when a new attacker joins the battle
/// </summary>
public event OnReinforce ReinforceAttacker = delegate { };
/// <summary>
/// Fired when a new defender joins the battle
/// </summary>
public event OnReinforce ReinforceDefender = delegate { };
/// <summary>
/// Fired when an attacker withdraws from the battle
/// </summary>
public event OnWithdraw WithdrawAttacker = delegate { };
/// <summary>
/// Fired when a defender withdraws from the battle
/// </summary>
public event OnWithdraw WithdrawDefender = delegate { };
/// <summary>
/// Fired when all of the units in a group are killed
/// </summary>
public event OnWithdraw GroupKilled = delegate { };
/// <summary>
/// Fired when one of the groups in battle receives a new unit
/// </summary>
public event OnUnitUpdate GroupUnitAdded = delegate { };
/// <summary>
/// Fired when one of the groups in battle loses a unit
/// </summary>
public event OnUnitUpdate GroupUnitRemoved = delegate { };
/// <summary>
/// Fired when obecj is killed
/// </summary>
public event OnUnitUpdate UnitKilled = delegate { };
/// <summary>
/// Fired when a single unit is killed
/// </summary>
public event OnUnitCountChange UnitCountDecreased = delegate { };
/// <summary>
/// Fired when an attacker is unable to take his turn
/// </summary>
public event OnUnitUpdate SkippedAttacker = delegate { };
/// <summary>
/// Fired when a unit hits another one
/// </summary>
public event OnAttack ActionAttacked = delegate { };
#endregion
#region IPersistableObject Members
public string DbTable
{
get
{
return DB_TABLE;
}
}
public DbColumn[] DbPrimaryKey
{
get
{
return new[] {new DbColumn("battle_id", BattleId, DbType.UInt32)};
}
}
public IEnumerable<DbDependency> DbDependencies
{
get
{
return new[] {new DbDependency("BattleReport", true, true)};
}
}
public DbColumn[] DbColumns
{
get
{
return new[]
{
new DbColumn("battle_started", BattleStarted, DbType.Boolean),
new DbColumn("round", Round, DbType.UInt32), new DbColumn("turn", Turn, DbType.UInt32),
new DbColumn("report_started", BattleReport.ReportStarted, DbType.Boolean),
new DbColumn("report_id", BattleReport.ReportId, DbType.UInt32),
new DbColumn("owner_type", Owner.Type.ToString(), DbType.String, 15),
new DbColumn("owner_id", Owner.Id, DbType.UInt32),
new DbColumn("location_type", Location.Type.ToString(), DbType.String, 15),
new DbColumn("location_id", Location.Id, DbType.UInt32),
new DbColumn("snapped_important_event", BattleReport.SnappedImportantEvent, DbType.Boolean),
new DbColumn("properties", new JsonWriter().Write(properties), DbType.String)
};
}
}
public bool DbPersisted { get; set; }
#endregion
}
} | giulianob/tribalhero | server/Game/Battle/BattleManager.cs | C# | gpl-3.0 | 35,668 |
package com.blogspot.minborgsjavapot.escape_analysis;
import java.io.IOException;
public class Main {
/*
-server
-XX:BCEATraceLevel=3
-XX:+PrintCompilation
-XX:+UnlockDiagnosticVMOptions
-XX:+PrintInlining
-verbose:gc
-XX:MaxInlineSize=256
-XX:FreqInlineSize=1024
-XX:MaxBCEAEstimateSize=1024
-XX:MaxInlineLevel=22
-XX:CompileThreshold=10
-Xmx4g
-Xms4g
*/
public static void main(String[] args) throws IOException, InterruptedException {
Point p = new Point(100, 200);
sum(p);
System.gc();
System.out.println("Press any key to continue");
System.in.read();
//Thread.sleep(1_000);
long sum = sum(p);
System.out.println(sum);
System.out.println("Press any key to continue2");
System.in.read();
sum = sum(p);
System.out.println(sum);
System.out.println("Press any key to exit");
System.in.read();
}
private static long sum(Point p) {
long sumLen = 0;
for (int i = 0; i < 1_000_000; i++) {
sumLen += p.toString().length();
}
return sumLen;
}
}
| minborg/javapot | src/main/java/com/blogspot/minborgsjavapot/escape_analysis/Main.java | Java | gpl-3.0 | 1,138 |
import { createSelector } from 'reselect';
import { bindActionCreators, compose } from 'redux';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import {
requestContact, createContact, deleteContact, invalidate as invalidateContacts,
} from '../../store/modules/contact';
import { requestUser } from '../../store/modules/user';
import { addAddressToContact, updateContact, getContact } from '../../modules/contact';
import { updateTagCollection as updateTagCollectionBase } from '../../modules/tags';
import { getNewContact } from '../../services/contact';
import { userSelector } from '../../modules/user';
import { withSearchParams } from '../../modules/routing';
import { contactValidation } from './services/contactValidation';
import Presenter from './presenter';
const contactIdSelector = (state, ownProps) => ownProps.match.params.contactId;
const contactSelector = state => state.contact;
const dirtyValuesSelector = createSelector(
[
(state, ownProps) => ownProps.searchParams,
],
({ address, protocol, label }) => ({ address, protocol, label })
);
const mapStateToProps = createSelector(
[userSelector, contactIdSelector, contactSelector, dirtyValuesSelector],
(user, contactId, contactState, dirtyValues) => {
const contact = contactState.contactsById[contactId] || getNewContact();
const { address, protocol, label } = dirtyValues;
return {
user,
contactId,
contact,
form: `contact-${contactId || 'new'}`,
// TODO: the following key fix this bug: https://github.com/erikras/redux-form/issues/2886#issuecomment-299426767
key: `contact-${contactId || 'new'}`,
initialValues: {
...contact,
...(protocol ? addAddressToContact(contact, { address, protocol }) : {}),
...(
label && label.length > 0 &&
(!contact.given_name || !contact.given_name.length) &&
(!contact.family_name || !contact.family_name.length) ? { given_name: label } : {}
),
},
isFetching: contactState.isFetching,
};
}
);
const updateTagCollection = (i18n, {
type, entity, tags: tagCollection, lazy,
}) => async (dispatch, getState) => {
const result = await dispatch(updateTagCollectionBase(i18n, {
type, entity, tags: tagCollection, lazy,
}));
const userContact = userSelector(getState()).contact;
if (userContact.contact_id === entity.contact_id) {
dispatch(requestUser());
}
return result;
};
const mapDispatchToProps = dispatch => ({
...bindActionCreators({
requestContact,
getContact,
updateContact,
createContact,
deleteContact,
invalidateContacts,
updateTagCollection,
}, dispatch),
onSubmit: values => Promise.resolve(values),
});
export default compose(
withSearchParams(),
connect(mapStateToProps, mapDispatchToProps),
reduxForm({
destroyOnUnmount: false,
enableReinitialize: true,
validate: contactValidation,
})
)(Presenter);
| CaliOpen/CaliOpen | src/frontend/web_application/src/scenes/Contact/index.js | JavaScript | gpl-3.0 | 2,978 |
package com.earth2me.essentials.update;
import com.earth2me.essentials.update.chat.*;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
public class EssentialsHelp implements Listener
{
private transient Player chatUser;
private final transient Server server;
private final transient Plugin plugin;
private transient IrcBot ircBot;
private final transient Map<String, Command> commands = new HashMap<String, Command>();
public EssentialsHelp(final Plugin plugin)
{
super();
this.plugin = plugin;
this.server = plugin.getServer();
commands.put("!help", new HelpCommand());
commands.put("!list", new ListCommand());
commands.put("!startup", new StartupCommand(plugin));
commands.put("!errors", new ErrorsCommand(plugin));
commands.put("!config", new ConfigCommand(plugin));
}
public void registerEvents()
{
final PluginManager pluginManager = server.getPluginManager();
pluginManager.registerEvents(this, plugin);
}
public void onCommand(final CommandSender sender)
{
if (sender instanceof Player && sender.hasPermission("essentials.helpchat"))
{
if (chatUser == null)
{
chatUser = (Player)sender;
ircBot = null;
sender.sendMessage("You will be connected to the Essentials Help Chat.");
sender.sendMessage("All your chat messages will be forwarded to the channel. You can't chat with other players on your server while in help chat, but you can use commands.");
sender.sendMessage("Please be patient, if noone is available, check back later.");
sender.sendMessage("Type !help to get a list of all commands.");
sender.sendMessage("Type !quit to leave the channel.");
sender.sendMessage("Do you want to join the channel now? (yes/no)");
}
if (!chatUser.equals(sender))
{
sender.sendMessage("The player " + chatUser.getDisplayName() + " is already using the essentialshelp.");
}
}
else
{
sender.sendMessage("Please run the command as op from in game.");
}
}
public void onDisable()
{
closeConnection();
}
private boolean sendChatMessage(final Player player, final String message)
{
final String messageCleaned = message.trim();
if (messageCleaned.isEmpty())
{
return false;
}
if (ircBot == null)
{
return handleAnswer(messageCleaned, player);
}
else
{
if (ircBot.isKicked())
{
closeConnection();
return false;
}
final String lowMessage = messageCleaned.toLowerCase(Locale.ENGLISH);
if (lowMessage.startsWith("!quit"))
{
closeConnection();
player.sendMessage("Connection closed.");
return true;
}
if (!ircBot.isConnected() || ircBot.getChannels().length == 0)
{
return false;
}
if (handleCommands(lowMessage, player))
{
return true;
}
ircBot.sendMessage(messageCleaned);
chatUser.sendMessage("§6" + ircBot.getNick() + ": §7" + messageCleaned);
return true;
}
}
private void closeConnection()
{
chatUser = null;
if (ircBot != null)
{
ircBot.quit();
ircBot = null;
}
}
private boolean handleAnswer(final String message, final Player player)
{
if (message.equalsIgnoreCase("yes"))
{
player.sendMessage("Connecting...");
connectToIRC(player);
return true;
}
if (message.equalsIgnoreCase("no") || message.equalsIgnoreCase("!quit"))
{
chatUser = null;
return true;
}
return false;
}
private boolean handleCommands(final String lowMessage, final Player player)
{
final String[] parts = lowMessage.split(" ");
if (commands.containsKey(parts[0]))
{
commands.get(parts[0]).run(ircBot, player);
return true;
}
return false;
}
private void connectToIRC(final Player player)
{
ircBot = new IrcBot(player, "Ess_" + player.getName(), UsernameUtil.createUsername(player));
}
@EventHandler
public void onPlayerChat(final PlayerChatEvent event)
{
if (event.getPlayer() == chatUser)
{
final boolean success = sendChatMessage(event.getPlayer(), event.getMessage());
event.setCancelled(success);
}
}
@EventHandler
public void onPlayerQuit(final PlayerQuitEvent event)
{
closeConnection();
}
}
| desces/Essentials | EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsHelp.java | Java | gpl-3.0 | 4,454 |
/*
* DrawCirclesCommand.java Copyright (C) 2021. Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package megan.commands.format;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* draw selected nodes as circles
* Daniel Huson, 3.2013
*/
public class DrawCirclesCommand extends CommandBase implements ICommand {
/**
* apply
*
* @param np
* @throws Exception
*/
public void apply(NexusStreamParser np) throws Exception {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ((Director) getDir()).getDocument().getSampleSelection().size() > 0;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Circle";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Circle node shape";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("BlueCircle16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
* @param ev
*/
public void actionPerformed(ActionEvent ev) {
execute("set nodeShape=circle;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| danielhuson/megan-ce | src/megan/commands/format/DrawCirclesCommand.java | Java | gpl-3.0 | 3,073 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3;
import android.content.ComponentName;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.TransitionDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import com.android.launcher3.compat.UserHandleCompat;
public class InfoDropTarget extends ButtonDropTarget {
private ColorStateList mOriginalTextColor;
private TransitionDrawable mDrawable;
public InfoDropTarget(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public InfoDropTarget(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mOriginalTextColor = getTextColors();
// Get the hover color
Resources r = getResources();
mHoverColor = r.getColor(R.color.info_target_hover_tint);
mDrawable = (TransitionDrawable) getCurrentDrawable();
if (mDrawable == null) {
// TODO: investigate why this is ever happening. Presently only on one known device.
mDrawable = (TransitionDrawable) r.getDrawable(R.drawable.info_target_selector);
setCompoundDrawablesRelativeWithIntrinsicBounds(mDrawable, null, null, null);
}
if (null != mDrawable) {
mDrawable.setCrossFadeEnabled(true);
}
// Remove the text in the Phone UI in landscape
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (!LauncherAppState.getInstance().isScreenLarge()) {
setText("");
}
}
}
@Override
public boolean acceptDrop(DragObject d) {
// acceptDrop is called just before onDrop. We do the work here, rather than
// in onDrop, because it allows us to reject the drop (by returning false)
// so that the object being dragged isn't removed from the drag source.
ComponentName componentName = null;
if (d.dragInfo instanceof AppInfo) {
componentName = ((AppInfo) d.dragInfo).componentName;
} else if (d.dragInfo instanceof ShortcutInfo) {
componentName = ((ShortcutInfo) d.dragInfo).intent.getComponent();
} else if (d.dragInfo instanceof PendingAddItemInfo) {
componentName = ((PendingAddItemInfo) d.dragInfo).componentName;
}
final UserHandleCompat user;
if (d.dragInfo instanceof ItemInfo) {
user = ((ItemInfo) d.dragInfo).user;
} else {
user = UserHandleCompat.myUserHandle();
}
if (componentName != null) {
mLauncher.startApplicationDetailsActivity(componentName, user);
}
// There is no post-drop animation, so clean up the DragView now
d.deferDragViewCleanupPostAnimation = false;
return false;
}
@Override
public void onDragStart(DragSource source, Object info, int dragAction) {
boolean isVisible = true;
// Hide this button unless we are dragging something from AllApps
if (!source.supportsAppInfoDropTarget()) {
isVisible = false;
}
mActive = isVisible;
mDrawable.resetTransition();
setTextColor(mOriginalTextColor);
((ViewGroup) getParent()).setVisibility(isVisible ? View.VISIBLE : View.GONE);
}
@Override
public void onDragEnd() {
super.onDragEnd();
mActive = false;
}
public void onDragEnter(DragObject d) {
super.onDragEnter(d);
mDrawable.startTransition(mTransitionDuration);
setTextColor(mHoverColor);
}
public void onDragExit(DragObject d) {
super.onDragExit(d);
if (!d.dragComplete) {
mDrawable.resetTransition();
setTextColor(mOriginalTextColor);
}
}
}
| s20121035/rk3288_android5.1_repo | packages/apps/Launcher3/src/com/android/launcher3/InfoDropTarget.java | Java | gpl-3.0 | 4,717 |
/*
* Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/>
* Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/>
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2011-2012 Darkpeninsula Project <http://www.darkpeninsula.eu/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "gamePCH.h"
#include "ScriptPCH.h"
#include "ScriptLoader.h"
//examples
void AddSC_example_creature();
void AddSC_example_escort();
void AddSC_example_gossip_codebox();
void AddSC_example_misc();
//player scripts
void AddSC_player_mage_scripts();
void AddSC_example_commandscript();
// spells
void AddSC_deathknight_spell_scripts();
void AddSC_druid_spell_scripts();
void AddSC_generic_spell_scripts();
void AddSC_hunter_spell_scripts();
void AddSC_mage_spell_scripts();
void AddSC_paladin_spell_scripts();
void AddSC_priest_spell_scripts();
void AddSC_rogue_spell_scripts();
void AddSC_shaman_spell_scripts();
void AddSC_warlock_spell_scripts();
void AddSC_warrior_spell_scripts();
void AddSC_quest_spell_scripts();
void AddSC_item_spell_scripts();
void AddSC_example_spell_scripts();
void AddSC_SmartSCripts();
//Commands
void AddSC_account_commandscript();
void AddSC_achievement_commandscript();
void AddSC_gm_commandscript();
void AddSC_go_commandscript();
void AddSC_learn_commandscript();
void AddSC_misc_commandscript();
void AddSC_modify_commandscript();
void AddSC_npc_commandscript();
void AddSC_debug_commandscript();
void AddSC_reload_commandscript();
void AddSC_titles_commandscript();
void AddSC_wp_commandscript();
void AddSC_gobject_commandscript();
void AddSC_honor_commandscript();
void AddSC_quest_commandscript();
void AddSC_reload_commandscript();
void AddSC_remove_commandscript();
#ifdef SCRIPTS
//world
void AddSC_areatrigger_scripts();
void AddSC_boss_emeriss();
void AddSC_boss_taerar();
void AddSC_boss_ysondre();
void AddSC_generic_creature();
void AddSC_go_scripts();
void AddSC_guards();
void AddSC_item_scripts();
void AddSC_npc_professions();
void AddSC_npc_innkeeper();
void AddSC_npc_spell_click_spells();
void AddSC_npcs_special();
void AddSC_npc_taxi();
void AddSC_achievement_scripts();
//eastern kingdoms
void AddSC_alterac_valley(); //Alterac Valley
void AddSC_boss_balinda();
void AddSC_boss_drekthar();
void AddSC_boss_galvangar();
void AddSC_boss_vanndar();
void AddSC_blackrock_depths(); //Blackrock Depths
void AddSC_boss_ambassador_flamelash();
void AddSC_boss_anubshiah();
void AddSC_boss_draganthaurissan();
void AddSC_boss_general_angerforge();
void AddSC_boss_gorosh_the_dervish();
void AddSC_boss_grizzle();
void AddSC_boss_high_interrogator_gerstahn();
void AddSC_boss_magmus();
void AddSC_boss_moira_bronzebeard();
void AddSC_boss_tomb_of_seven();
void AddSC_instance_blackrock_depths();
void AddSC_boss_drakkisath(); //Blackrock Spire
void AddSC_boss_halycon();
void AddSC_boss_highlordomokk();
void AddSC_boss_mothersmolderweb();
void AddSC_boss_overlordwyrmthalak();
void AddSC_boss_shadowvosh();
void AddSC_boss_thebeast();
void AddSC_boss_warmastervoone();
void AddSC_boss_quatermasterzigris();
void AddSC_boss_pyroguard_emberseer();
void AddSC_boss_gyth();
void AddSC_boss_rend_blackhand();
void AddSC_boss_razorgore(); //Blackwing lair
void AddSC_boss_vael();
void AddSC_boss_broodlord();
void AddSC_boss_firemaw();
void AddSC_boss_ebonroc();
void AddSC_boss_flamegor();
void AddSC_boss_chromaggus();
void AddSC_boss_nefarian();
void AddSC_boss_victor_nefarius();
void AddSC_deadmines(); //Deadmines
void AddSC_instance_deadmines();
void AddSC_boss_mr_smite();
void AddSC_boss_glubtok();
void AddSC_gnomeregan(); //Gnomeregan
void AddSC_instance_gnomeregan();
void AddSC_gilneas(); // gilneas
void AddSC_boss_attumen(); //Karazhan
void AddSC_boss_curator();
void AddSC_boss_maiden_of_virtue();
void AddSC_boss_shade_of_aran();
void AddSC_boss_malchezaar();
void AddSC_boss_terestian_illhoof();
void AddSC_boss_moroes();
void AddSC_bosses_opera();
void AddSC_boss_netherspite();
void AddSC_instance_karazhan();
void AddSC_karazhan();
void AddSC_boss_nightbane();
void AddSC_boss_felblood_kaelthas(); // Magister's Terrace
void AddSC_boss_selin_fireheart();
void AddSC_boss_vexallus();
void AddSC_boss_priestess_delrissa();
void AddSC_instance_magisters_terrace();
void AddSC_magisters_terrace();
void AddSC_boss_lucifron(); //Molten core
void AddSC_boss_magmadar();
void AddSC_boss_gehennas();
void AddSC_boss_garr();
void AddSC_boss_baron_geddon();
void AddSC_boss_shazzrah();
void AddSC_boss_golemagg();
void AddSC_boss_sulfuron();
void AddSC_boss_majordomo();
void AddSC_boss_ragnaros();
void AddSC_instance_molten_core();
void AddSC_molten_core();
void AddSC_the_scarlet_enclave(); //Scarlet Enclave
void AddSC_the_scarlet_enclave_c1();
void AddSC_the_scarlet_enclave_c2();
void AddSC_the_scarlet_enclave_c5();
void AddSC_boss_arcanist_doan(); //Scarlet Monastery
void AddSC_boss_azshir_the_sleepless();
void AddSC_boss_bloodmage_thalnos();
void AddSC_boss_headless_horseman();
void AddSC_boss_herod();
void AddSC_boss_high_inquisitor_fairbanks();
void AddSC_boss_houndmaster_loksey();
void AddSC_boss_interrogator_vishas();
void AddSC_boss_scorn();
void AddSC_instance_scarlet_monastery();
void AddSC_boss_mograine_and_whitemane();
void AddSC_boss_darkmaster_gandling(); //Scholomance
void AddSC_boss_death_knight_darkreaver();
void AddSC_boss_theolenkrastinov();
void AddSC_boss_illuciabarov();
void AddSC_boss_instructormalicia();
void AddSC_boss_jandicebarov();
void AddSC_boss_kormok();
void AddSC_boss_lordalexeibarov();
void AddSC_boss_lorekeeperpolkelt();
void AddSC_boss_rasfrost();
void AddSC_boss_theravenian();
void AddSC_boss_vectus();
void AddSC_instance_scholomance();
void AddSC_shadowfang_keep(); //Shadowfang keep
void AddSC_instance_shadowfang_keep();
void AddSC_boss_magistrate_barthilas(); //Stratholme
void AddSC_boss_maleki_the_pallid();
void AddSC_boss_nerubenkan();
void AddSC_boss_cannon_master_willey();
void AddSC_boss_baroness_anastari();
void AddSC_boss_ramstein_the_gorger();
void AddSC_boss_timmy_the_cruel();
void AddSC_boss_postmaster_malown();
void AddSC_boss_baron_rivendare();
void AddSC_boss_dathrohan_balnazzar();
void AddSC_boss_order_of_silver_hand();
void AddSC_instance_stratholme();
void AddSC_stratholme();
void AddSC_sunken_temple(); // Sunken Temple
void AddSC_instance_sunken_temple();
void AddSC_instance_sunwell_plateau(); //Sunwell Plateau
void AddSC_boss_kalecgos();
void AddSC_boss_brutallus();
void AddSC_boss_felmyst();
void AddSC_boss_eredar_twins();
void AddSC_boss_muru();
void AddSC_boss_kiljaeden();
void AddSC_sunwell_plateau();
void AddSC_boss_archaedas(); //Uldaman
void AddSC_boss_ironaya();
void AddSC_uldaman();
void AddSC_instance_uldaman();
void AddSC_boss_akilzon(); //Zul'Aman
void AddSC_boss_halazzi();
void AddSC_boss_hex_lord_malacrass();
void AddSC_boss_janalai();
void AddSC_boss_nalorakk();
void AddSC_boss_zuljin();
void AddSC_instance_zulaman();
void AddSC_zulaman();
void AddSC_boss_jeklik(); //Zul'Gurub
void AddSC_boss_venoxis();
void AddSC_boss_marli();
void AddSC_boss_mandokir();
void AddSC_boss_gahzranka();
void AddSC_boss_thekal();
void AddSC_boss_arlokk();
void AddSC_boss_jindo();
void AddSC_boss_hakkar();
void AddSC_boss_grilek();
void AddSC_boss_hazzarah();
void AddSC_boss_renataki();
void AddSC_boss_wushoolay();
void AddSC_instance_zulgurub();
//void AddSC_alterac_mountains();
void AddSC_arathi_highlands();
void AddSC_blasted_lands();
void AddSC_boss_kruul();
void AddSC_burning_steppes();
void AddSC_dun_morogh();
void AddSC_duskwood();
void AddSC_eastern_plaguelands();
void AddSC_elwynn_forest();
void AddSC_eversong_woods();
void AddSC_ghostlands();
void AddSC_hinterlands();
void AddSC_ironforge();
void AddSC_isle_of_queldanas();
void AddSC_loch_modan();
void AddSC_redridge_mountains();
void AddSC_searing_gorge();
void AddSC_silvermoon_city();
void AddSC_silverpine_forest();
void AddSC_stormwind_city();
void AddSC_stranglethorn_vale();
void AddSC_swamp_of_sorrows();
void AddSC_tirisfal_glades();
void AddSC_undercity();
void AddSC_western_plaguelands();
void AddSC_westfall();
void AddSC_wetlands();
//kalimdor
void AddSC_blackfathom_deeps(); //Blackfathom Depths
void AddSC_boss_gelihast();
void AddSC_boss_kelris();
void AddSC_boss_aku_mai();
void AddSC_instance_blackfathom_deeps();
void AddSC_hyjal(); //CoT Battle for Mt. Hyjal
void AddSC_boss_archimonde();
void AddSC_instance_mount_hyjal();
void AddSC_hyjal_trash();
void AddSC_boss_rage_winterchill();
void AddSC_boss_anetheron();
void AddSC_boss_kazrogal();
void AddSC_boss_azgalor();
void AddSC_boss_captain_skarloc(); //CoT Old Hillsbrad
void AddSC_boss_epoch_hunter();
void AddSC_boss_lieutenant_drake();
void AddSC_instance_old_hillsbrad();
void AddSC_old_hillsbrad();
void AddSC_boss_aeonus(); //CoT The Dark Portal
void AddSC_boss_chrono_lord_deja();
void AddSC_boss_temporus();
void AddSC_dark_portal();
void AddSC_instance_dark_portal();
void AddSC_boss_epoch(); //CoT Culling Of Stratholme
void AddSC_boss_infinite_corruptor();
void AddSC_boss_salramm();
void AddSC_boss_mal_ganis();
void AddSC_boss_meathook();
void AddSC_culling_of_stratholme();
void AddSC_instance_culling_of_stratholme();
void AddSC_boss_celebras_the_cursed(); //Maraudon
void AddSC_boss_landslide();
void AddSC_boss_noxxion();
void AddSC_boss_ptheradras();
void AddSC_boss_onyxia(); //Onyxia's Lair
void AddSC_instance_onyxias_lair();
void AddSC_boss_amnennar_the_coldbringer(); //Razorfen Downs
void AddSC_razorfen_downs();
void AddSC_instance_razorfen_downs();
void AddSC_razorfen_kraul(); //Razorfen Kraul
void AddSC_boss_kurinnaxx(); //Ruins of ahn'qiraj
void AddSC_boss_rajaxx();
void AddSC_boss_moam();
void AddSC_boss_buru();
void AddSC_boss_ayamiss();
void AddSC_boss_ossirian();
void AddSC_instance_ruins_of_ahnqiraj();
void AddSC_boss_cthun(); //Temple of ahn'qiraj
void AddSC_boss_fankriss();
void AddSC_boss_huhuran();
void AddSC_bug_trio();
void AddSC_boss_sartura();
void AddSC_boss_skeram();
void AddSC_boss_twinemperors();
void AddSC_mob_anubisath_sentinel();
void AddSC_instance_temple_of_ahnqiraj();
void AddSC_wailing_caverns(); //Wailing caverns
void AddSC_instance_wailing_caverns();
void AddSC_zulfarrak(); //Zul'Farrak generic
void AddSC_instance_zulfarrak(); //Zul'Farrak instance script
void AddSC_npc_pusillin(); //Dire Maul Pusillin
void AddSC_ashenvale();
void AddSC_azshara();
void AddSC_azuremyst_isle();
void AddSC_bloodmyst_isle();
void AddSC_boss_azuregos();
void AddSC_darkshore();
void AddSC_desolace();
void AddSC_durotar();
void AddSC_dustwallow_marsh();
void AddSC_felwood();
void AddSC_feralas();
void AddSC_moonglade();
void AddSC_mulgore();
void AddSC_orgrimmar();
void AddSC_silithus();
void AddSC_stonetalon_mountains();
void AddSC_tanaris();
void AddSC_teldrassil();
void AddSC_the_barrens();
void AddSC_thousand_needles();
void AddSC_thunder_bluff();
void AddSC_ungoro_crater();
void AddSC_winterspring();
//Northrend
void AddSC_boss_slad_ran();
void AddSC_boss_moorabi();
void AddSC_boss_drakkari_colossus();
void AddSC_boss_gal_darah();
void AddSC_boss_eck();
void AddSC_instance_gundrak();
void AddSC_boss_krik_thir(); //Azjol-Nerub
void AddSC_boss_hadronox();
void AddSC_boss_anub_arak();
void AddSC_instance_azjol_nerub();
void AddSC_instance_ahnkahet(); //Azjol-Nerub Ahn'kahet
void AddSC_boss_amanitar();
void AddSC_boss_taldaram();
void AddSC_boss_jedoga_shadowseeker();
void AddSC_boss_elder_nadox();
void AddSC_boss_volazj();
void AddSC_boss_argent_challenge(); //Trial of the Champion
void AddSC_boss_black_knight();
void AddSC_boss_grand_champions();
void AddSC_instance_trial_of_the_champion();
void AddSC_trial_of_the_champion();
void AddSC_boss_anubarak_trial(); //Trial of the Crusader
void AddSC_boss_faction_champions();
void AddSC_boss_jaraxxus();
void AddSC_boss_northrend_beasts();
void AddSC_boss_twin_valkyr();
void AddSC_trial_of_the_crusader();
void AddSC_instance_trial_of_the_crusader();
void AddSC_boss_anubrekhan(); //Naxxramas
void AddSC_boss_maexxna();
void AddSC_boss_patchwerk();
void AddSC_boss_grobbulus();
void AddSC_boss_razuvious();
void AddSC_boss_kelthuzad();
void AddSC_boss_loatheb();
void AddSC_boss_noth();
void AddSC_boss_gluth();
void AddSC_boss_sapphiron();
void AddSC_boss_four_horsemen();
void AddSC_boss_faerlina();
void AddSC_boss_heigan();
void AddSC_boss_gothik();
void AddSC_boss_thaddius();
void AddSC_instance_naxxramas();
void AddSC_boss_magus_telestra(); //The Nexus Nexus
void AddSC_boss_anomalus();
void AddSC_boss_ormorok();
void AddSC_boss_keristrasza();
void AddSC_instance_nexus();
void AddSC_boss_drakos(); //The Nexus The Oculus
void AddSC_boss_urom();
void AddSC_boss_varos();
void AddSC_instance_oculus();
void AddSC_oculus();
void AddSC_boss_sartharion(); //Obsidian Sanctum
void AddSC_instance_obsidian_sanctum();
void AddSC_boss_bjarngrim(); //Ulduar Halls of Lightning
void AddSC_boss_loken();
void AddSC_boss_ionar();
void AddSC_boss_volkhan();
void AddSC_instance_halls_of_lightning();
void AddSC_boss_maiden_of_grief(); //Ulduar Halls of Stone
void AddSC_boss_krystallus();
void AddSC_boss_sjonnir();
void AddSC_instance_halls_of_stone();
void AddSC_halls_of_stone();
void AddSC_boss_auriaya(); //Ulduar Ulduar
void AddSC_boss_flame_leviathan();
void AddSC_boss_ignis();
void AddSC_boss_razorscale();
void AddSC_boss_xt002();
void AddSC_boss_kologarn();
void AddSC_boss_assembly_of_iron();
void AddSC_ulduar_teleporter();
void AddSC_instance_ulduar();
void AddSC_boss_keleseth(); //Utgarde Keep
void AddSC_boss_skarvald_dalronn();
void AddSC_boss_ingvar_the_plunderer();
void AddSC_instance_utgarde_keep();
void AddSC_boss_svala(); //Utgarde pinnacle
void AddSC_boss_palehoof();
void AddSC_boss_skadi();
void AddSC_boss_ymiron();
void AddSC_instance_utgarde_pinnacle();
void AddSC_utgarde_keep();
void AddSC_boss_archavon(); //Vault of Archavon
void AddSC_boss_emalon();
void AddSC_boss_koralon();
void AddSC_boss_toravon();
void AddSC_instance_archavon();
void AddSC_boss_trollgore(); //Drak'Tharon Keep
void AddSC_boss_novos();
void AddSC_boss_dred();
void AddSC_boss_tharon_ja();
void AddSC_instance_drak_tharon();
void AddSC_boss_cyanigosa(); //Violet Hold
void AddSC_boss_erekem();
void AddSC_boss_ichoron();
void AddSC_boss_lavanthor();
void AddSC_boss_moragg();
void AddSC_boss_xevozz();
void AddSC_boss_zuramat();
void AddSC_instance_violet_hold();
void AddSC_violet_hold();
void AddSC_instance_forge_of_souls(); //Forge of Souls
void AddSC_forge_of_souls();
void AddSC_boss_bronjahm();
void AddSC_boss_devourer_of_souls();
void AddSC_instance_pit_of_saron(); //Pit of Saron
void AddSC_pit_of_saron();
void AddSC_boss_garfrost();
void AddSC_boss_ick();
void AddSC_boss_tyrannus();
void AddSC_instance_halls_of_reflection(); // Halls of Reflection
void AddSC_halls_of_reflection();
void AddSC_boss_falric();
void AddSC_boss_marwyn();
void AddSC_boss_lord_marrowgar(); // Icecrown Citadel
void AddSC_boss_lady_deathwhisper();
void AddSC_boss_deathbringer_saurfang();
void AddSC_boss_festergut();
void AddSC_boss_rotface();
void AddSC_boss_professor_putricide();
void AddSC_boss_blood_prince_council();
void AddSC_boss_blood_queen_lana_thel();
void AddSC_boss_sindragosa();
void AddSC_icecrown_citadel_teleport();
void AddSC_instance_icecrown_citadel();
void AddSC_icecrown_citadel();
void AddSC_dalaran();
void AddSC_borean_tundra();
void AddSC_dragonblight();
void AddSC_grizzly_hills();
void AddSC_howling_fjord();
void AddSC_icecrown();
void AddSC_sholazar_basin();
void AddSC_storm_peaks();
void AddSC_zuldrak();
void AddSC_crystalsong_forest();
void AddSC_isle_of_conquest();
//outland
void AddSC_boss_exarch_maladaar(); //Auchindoun Auchenai Crypts
void AddSC_boss_shirrak_the_dead_watcher();
void AddSC_boss_nexusprince_shaffar(); //Auchindoun Mana Tombs
void AddSC_boss_pandemonius();
void AddSC_boss_darkweaver_syth(); //Auchindoun Sekketh Halls
void AddSC_boss_talon_king_ikiss();
void AddSC_instance_sethekk_halls();
void AddSC_instance_shadow_labyrinth(); //Auchindoun Shadow Labyrinth
void AddSC_boss_ambassador_hellmaw();
void AddSC_boss_blackheart_the_inciter();
void AddSC_boss_grandmaster_vorpil();
void AddSC_boss_murmur();
void AddSC_black_temple(); //Black Temple
void AddSC_boss_illidan();
void AddSC_boss_shade_of_akama();
void AddSC_boss_supremus();
void AddSC_boss_gurtogg_bloodboil();
void AddSC_boss_mother_shahraz();
void AddSC_boss_reliquary_of_souls();
void AddSC_boss_teron_gorefiend();
void AddSC_boss_najentus();
void AddSC_boss_illidari_council();
void AddSC_instance_black_temple();
void AddSC_boss_fathomlord_karathress(); //CR Serpent Shrine Cavern
void AddSC_boss_hydross_the_unstable();
void AddSC_boss_lady_vashj();
void AddSC_boss_leotheras_the_blind();
void AddSC_boss_morogrim_tidewalker();
void AddSC_instance_serpentshrine_cavern();
void AddSC_boss_the_lurker_below();
void AddSC_boss_hydromancer_thespia(); //CR Steam Vault
void AddSC_boss_mekgineer_steamrigger();
void AddSC_boss_warlord_kalithresh();
void AddSC_instance_steam_vault();
void AddSC_boss_hungarfen(); //CR Underbog
void AddSC_boss_the_black_stalker();
void AddSC_boss_gruul(); //Gruul's Lair
void AddSC_boss_high_king_maulgar();
void AddSC_instance_gruuls_lair();
void AddSC_boss_broggok(); //HC Blood Furnace
void AddSC_boss_kelidan_the_breaker();
void AddSC_boss_the_maker();
void AddSC_instance_blood_furnace();
void AddSC_boss_magtheridon(); //HC Magtheridon's Lair
void AddSC_instance_magtheridons_lair();
void AddSC_boss_grand_warlock_nethekurse(); //HC Shattered Halls
void AddSC_boss_warbringer_omrogg();
void AddSC_boss_warchief_kargath_bladefist();
void AddSC_instance_shattered_halls();
void AddSC_boss_watchkeeper_gargolmar(); //HC Ramparts
void AddSC_boss_omor_the_unscarred();
void AddSC_boss_vazruden_the_herald();
void AddSC_instance_ramparts();
void AddSC_arcatraz(); //TK Arcatraz
void AddSC_boss_harbinger_skyriss();
void AddSC_instance_arcatraz();
void AddSC_boss_high_botanist_freywinn(); //TK Botanica
void AddSC_boss_laj();
void AddSC_boss_warp_splinter();
void AddSC_boss_alar(); //TK The Eye
void AddSC_boss_kaelthas();
void AddSC_boss_void_reaver();
void AddSC_boss_high_astromancer_solarian();
void AddSC_instance_the_eye();
void AddSC_the_eye();
void AddSC_boss_gatewatcher_iron_hand(); //TK The Mechanar
void AddSC_boss_nethermancer_sepethrea();
void AddSC_boss_pathaleon_the_calculator();
void AddSC_instance_mechanar();
void AddSC_blades_edge_mountains();
void AddSC_boss_doomlordkazzak();
void AddSC_boss_doomwalker();
void AddSC_hellfire_peninsula();
void AddSC_nagrand();
void AddSC_netherstorm();
void AddSC_shadowmoon_valley();
void AddSC_shattrath_city();
void AddSC_terokkar_forest();
void AddSC_zangarmarsh();
// Cataclysm Scripts
void AddSC_the_stonecore(); //TheStonecore
void AddSC_instance_the_stonecore();
void AddSC_instance_halls_of_origination(); //Halls of Origination
void AddSC_boss_temple_guardian_anhuur();
void AddSC_boss_earthrager_ptah();
void AddSC_boss_anraphet();
void AddSC_instance_baradin_hold(); //Baradin Hold
void AddSC_boss_argaloth();
void AddSC_lost_city_of_the_tolvir(); //The Lost City of the Tol'vir
void AddSC_instance_lost_city_of_the_tolvir();
void AddSC_boss_lockmaw();
void AddSC_boss_high_prophet_barim();
void AddSC_instance_the_vortex_pinnacle(); //The Vortex Pinnacle
void AddSC_instance_grim_batol(); //Grim Batol
void AddSC_instance_throne_of_the_tides(); //Throne of the Tides
void AddSC_instance_blackrock_caverns(); //Blackrock Caverns
// Darkpeninsula
void AddSC_premium();
// The Maelstrom
// Kezan
void AddSC_kezan();
// battlegrounds
// outdoor pvp
void AddSC_outdoorpvp_ep();
void AddSC_outdoorpvp_hp();
void AddSC_outdoorpvp_na();
void AddSC_outdoorpvp_si();
void AddSC_outdoorpvp_tf();
void AddSC_outdoorpvp_zm();
void AddSC_outdoorpvp_gh();
// player
void AddSC_chat_log();
#endif
void AddScripts()
{
AddExampleScripts();
AddPlayerScripts();
AddSpellScripts();
AddSC_SmartSCripts();
AddCommandScripts();
#ifdef SCRIPTS
AddWorldScripts();
AddEasternKingdomsScripts();
AddKalimdorScripts();
AddOutlandScripts();
AddNorthrendScripts();
AddBattlegroundScripts();
AddOutdoorPvPScripts();
AddCustomScripts();
#endif
}
void AddExampleScripts()
{
AddSC_example_creature();
AddSC_example_escort();
AddSC_example_gossip_codebox();
AddSC_example_misc();
AddSC_example_commandscript();
}
void AddPlayerScripts()
{
AddSC_player_mage_scripts();
}
void AddSpellScripts()
{
AddSC_deathknight_spell_scripts();
AddSC_druid_spell_scripts();
AddSC_generic_spell_scripts();
AddSC_hunter_spell_scripts();
AddSC_mage_spell_scripts();
AddSC_paladin_spell_scripts();
AddSC_priest_spell_scripts();
AddSC_rogue_spell_scripts();
AddSC_shaman_spell_scripts();
AddSC_warlock_spell_scripts();
AddSC_warrior_spell_scripts();
AddSC_quest_spell_scripts();
AddSC_item_spell_scripts();
AddSC_example_spell_scripts();
}
void AddCommandScripts()
{
AddSC_account_commandscript();
AddSC_achievement_commandscript();
AddSC_gm_commandscript();
AddSC_go_commandscript();
AddSC_learn_commandscript();
AddSC_misc_commandscript();
AddSC_modify_commandscript();
AddSC_npc_commandscript();
AddSC_debug_commandscript();
AddSC_reload_commandscript();
AddSC_reload_commandscript();
AddSC_titles_commandscript();
AddSC_wp_commandscript();
AddSC_gobject_commandscript();
AddSC_honor_commandscript();
AddSC_quest_commandscript();
AddSC_reload_commandscript();
AddSC_remove_commandscript();
}
void AddWorldScripts()
{
#ifdef SCRIPTS
AddSC_areatrigger_scripts();
AddSC_boss_emeriss();
AddSC_boss_taerar();
AddSC_boss_ysondre();
AddSC_generic_creature();
AddSC_go_scripts();
AddSC_guards();
AddSC_item_scripts();
AddSC_npc_professions();
AddSC_npc_innkeeper();
AddSC_npc_spell_click_spells();
AddSC_npcs_special();
AddSC_npc_taxi();
AddSC_achievement_scripts();
AddSC_chat_log();
#endif
}
void AddEasternKingdomsScripts()
{
#ifdef SCRIPTS
AddSC_alterac_valley(); //Alterac Valley
AddSC_boss_balinda();
AddSC_boss_drekthar();
AddSC_boss_galvangar();
AddSC_boss_vanndar();
AddSC_blackrock_depths(); //Blackrock Depths
AddSC_boss_ambassador_flamelash();
AddSC_boss_anubshiah();
AddSC_boss_draganthaurissan();
AddSC_boss_general_angerforge();
AddSC_boss_gorosh_the_dervish();
AddSC_boss_grizzle();
AddSC_boss_high_interrogator_gerstahn();
AddSC_boss_magmus();
AddSC_boss_moira_bronzebeard();
AddSC_boss_tomb_of_seven();
AddSC_instance_blackrock_depths();
AddSC_boss_drakkisath(); //Blackrock Spire
AddSC_boss_halycon();
AddSC_boss_highlordomokk();
AddSC_boss_mothersmolderweb();
AddSC_boss_overlordwyrmthalak();
AddSC_boss_shadowvosh();
AddSC_boss_thebeast();
AddSC_boss_warmastervoone();
AddSC_boss_quatermasterzigris();
AddSC_boss_pyroguard_emberseer();
AddSC_boss_gyth();
AddSC_boss_rend_blackhand();
AddSC_boss_razorgore(); //Blackwing lair
AddSC_boss_vael();
AddSC_boss_broodlord();
AddSC_boss_firemaw();
AddSC_boss_ebonroc();
AddSC_boss_flamegor();
AddSC_boss_chromaggus();
AddSC_boss_nefarian();
AddSC_boss_victor_nefarius();
AddSC_deadmines(); //Deadmines
AddSC_instance_deadmines();
AddSC_boss_mr_smite();
AddSC_boss_glubtok();
AddSC_gnomeregan(); //Gnomeregan
AddSC_instance_gnomeregan();
AddSC_gilneas(); // gilneas
AddSC_boss_attumen(); //Karazhan
AddSC_boss_curator();
AddSC_boss_maiden_of_virtue();
AddSC_boss_shade_of_aran();
AddSC_boss_malchezaar();
AddSC_boss_terestian_illhoof();
AddSC_boss_moroes();
AddSC_bosses_opera();
AddSC_boss_netherspite();
AddSC_instance_karazhan();
AddSC_karazhan();
AddSC_boss_nightbane();
AddSC_boss_felblood_kaelthas(); // Magister's Terrace
AddSC_boss_selin_fireheart();
AddSC_boss_vexallus();
AddSC_boss_priestess_delrissa();
AddSC_instance_magisters_terrace();
AddSC_magisters_terrace();
AddSC_boss_lucifron(); //Molten core
AddSC_boss_magmadar();
AddSC_boss_gehennas();
AddSC_boss_garr();
AddSC_boss_baron_geddon();
AddSC_boss_shazzrah();
AddSC_boss_golemagg();
AddSC_boss_sulfuron();
AddSC_boss_majordomo();
AddSC_boss_ragnaros();
AddSC_instance_molten_core();
AddSC_molten_core();
AddSC_the_scarlet_enclave(); //Scarlet Enclave
AddSC_the_scarlet_enclave_c1();
AddSC_the_scarlet_enclave_c2();
AddSC_the_scarlet_enclave_c5();
AddSC_boss_arcanist_doan(); //Scarlet Monastery
AddSC_boss_azshir_the_sleepless();
AddSC_boss_bloodmage_thalnos();
AddSC_boss_headless_horseman();
AddSC_boss_herod();
AddSC_boss_high_inquisitor_fairbanks();
AddSC_boss_houndmaster_loksey();
AddSC_boss_interrogator_vishas();
AddSC_boss_scorn();
AddSC_instance_scarlet_monastery();
AddSC_boss_mograine_and_whitemane();
AddSC_boss_darkmaster_gandling(); //Scholomance
AddSC_boss_death_knight_darkreaver();
AddSC_boss_theolenkrastinov();
AddSC_boss_illuciabarov();
AddSC_boss_instructormalicia();
AddSC_boss_jandicebarov();
AddSC_boss_kormok();
AddSC_boss_lordalexeibarov();
AddSC_boss_lorekeeperpolkelt();
AddSC_boss_rasfrost();
AddSC_boss_theravenian();
AddSC_boss_vectus();
AddSC_instance_scholomance();
AddSC_shadowfang_keep(); //Shadowfang keep
AddSC_instance_shadowfang_keep();
AddSC_boss_magistrate_barthilas(); //Stratholme
AddSC_boss_maleki_the_pallid();
AddSC_boss_nerubenkan();
AddSC_boss_cannon_master_willey();
AddSC_boss_baroness_anastari();
AddSC_boss_ramstein_the_gorger();
AddSC_boss_timmy_the_cruel();
AddSC_boss_postmaster_malown();
AddSC_boss_baron_rivendare();
AddSC_boss_dathrohan_balnazzar();
AddSC_boss_order_of_silver_hand();
AddSC_instance_stratholme();
AddSC_stratholme();
AddSC_sunken_temple(); // Sunken Temple
AddSC_instance_sunken_temple();
AddSC_instance_sunwell_plateau(); //Sunwell Plateau
AddSC_boss_kalecgos();
AddSC_boss_brutallus();
AddSC_boss_felmyst();
AddSC_boss_eredar_twins();
AddSC_boss_muru();
AddSC_boss_kiljaeden();
AddSC_sunwell_plateau();
AddSC_boss_archaedas(); //Uldaman
AddSC_boss_ironaya();
AddSC_uldaman();
AddSC_instance_uldaman();
AddSC_boss_akilzon(); //Zul'Aman
AddSC_boss_halazzi();
AddSC_boss_hex_lord_malacrass();
AddSC_boss_janalai();
AddSC_boss_nalorakk();
AddSC_boss_zuljin();
AddSC_instance_zulaman();
AddSC_zulaman();
AddSC_boss_jeklik(); //Zul'Gurub
AddSC_boss_venoxis();
AddSC_boss_marli();
AddSC_boss_mandokir();
AddSC_boss_gahzranka();
AddSC_boss_thekal();
AddSC_boss_arlokk();
AddSC_boss_jindo();
AddSC_boss_hakkar();
AddSC_boss_grilek();
AddSC_boss_hazzarah();
AddSC_boss_renataki();
AddSC_boss_wushoolay();
AddSC_instance_zulgurub();
//AddSC_alterac_mountains();
AddSC_arathi_highlands();
AddSC_blasted_lands();
AddSC_boss_kruul();
AddSC_burning_steppes();
AddSC_dun_morogh();
AddSC_duskwood();
AddSC_eastern_plaguelands();
AddSC_elwynn_forest();
AddSC_eversong_woods();
AddSC_ghostlands();
AddSC_hinterlands();
AddSC_ironforge();
AddSC_isle_of_queldanas();
AddSC_loch_modan();
AddSC_redridge_mountains();
AddSC_searing_gorge();
AddSC_silvermoon_city();
AddSC_silverpine_forest();
AddSC_stormwind_city();
AddSC_stranglethorn_vale();
AddSC_swamp_of_sorrows();
AddSC_tirisfal_glades();
AddSC_undercity();
AddSC_western_plaguelands();
AddSC_westfall();
AddSC_wetlands();
#endif
}
void AddKalimdorScripts()
{
#ifdef SCRIPTS
AddSC_blackfathom_deeps(); //Blackfathom Depths
AddSC_boss_gelihast();
AddSC_boss_kelris();
AddSC_boss_aku_mai();
AddSC_instance_blackfathom_deeps();
AddSC_hyjal(); //CoT Battle for Mt. Hyjal
AddSC_boss_archimonde();
AddSC_instance_mount_hyjal();
AddSC_hyjal_trash();
AddSC_boss_rage_winterchill();
AddSC_boss_anetheron();
AddSC_boss_kazrogal();
AddSC_boss_azgalor();
AddSC_boss_captain_skarloc(); //CoT Old Hillsbrad
AddSC_boss_epoch_hunter();
AddSC_boss_lieutenant_drake();
AddSC_instance_old_hillsbrad();
AddSC_old_hillsbrad();
AddSC_boss_aeonus(); //CoT The Dark Portal
AddSC_boss_chrono_lord_deja();
AddSC_boss_temporus();
AddSC_dark_portal();
AddSC_instance_dark_portal();
AddSC_boss_epoch(); //CoT Culling Of Stratholme
AddSC_boss_infinite_corruptor();
AddSC_boss_salramm();
AddSC_boss_mal_ganis();
AddSC_boss_meathook();
AddSC_culling_of_stratholme();
AddSC_instance_culling_of_stratholme();
AddSC_boss_celebras_the_cursed(); //Maraudon
AddSC_boss_landslide();
AddSC_boss_noxxion();
AddSC_boss_ptheradras();
AddSC_boss_onyxia(); //Onyxia's Lair
AddSC_instance_onyxias_lair();
AddSC_boss_amnennar_the_coldbringer(); //Razorfen Downs
AddSC_razorfen_downs();
AddSC_instance_razorfen_downs();
AddSC_razorfen_kraul(); //Razorfen Kraul
AddSC_boss_kurinnaxx(); //Ruins of ahn'qiraj
AddSC_boss_rajaxx();
AddSC_boss_moam();
AddSC_boss_buru();
AddSC_boss_ayamiss();
AddSC_boss_ossirian();
AddSC_instance_ruins_of_ahnqiraj();
AddSC_boss_cthun(); //Temple of ahn'qiraj
AddSC_boss_fankriss();
AddSC_boss_huhuran();
AddSC_bug_trio();
AddSC_boss_sartura();
AddSC_boss_skeram();
AddSC_boss_twinemperors();
AddSC_mob_anubisath_sentinel();
AddSC_instance_temple_of_ahnqiraj();
AddSC_wailing_caverns(); //Wailing caverns
AddSC_instance_wailing_caverns();
AddSC_zulfarrak(); //Zul'Farrak generic
AddSC_instance_zulfarrak(); //Zul'Farrak instance script
AddSC_npc_pusillin(); //Dire maul npc Pusillin
AddSC_ashenvale();
AddSC_azshara();
AddSC_azuremyst_isle();
AddSC_bloodmyst_isle();
AddSC_boss_azuregos();
AddSC_darkshore();
AddSC_desolace();
AddSC_durotar();
AddSC_dustwallow_marsh();
AddSC_felwood();
AddSC_feralas();
AddSC_moonglade();
AddSC_mulgore();
AddSC_orgrimmar();
AddSC_silithus();
AddSC_stonetalon_mountains();
AddSC_tanaris();
AddSC_teldrassil();
AddSC_the_barrens();
AddSC_thousand_needles();
AddSC_thunder_bluff();
AddSC_ungoro_crater();
AddSC_winterspring();
#endif
}
void AddOutlandScripts()
{
#ifdef SCRIPTS
AddSC_boss_exarch_maladaar(); //Auchindoun Auchenai Crypts
AddSC_boss_shirrak_the_dead_watcher();
AddSC_boss_nexusprince_shaffar(); //Auchindoun Mana Tombs
AddSC_boss_pandemonius();
AddSC_boss_darkweaver_syth(); //Auchindoun Sekketh Halls
AddSC_boss_talon_king_ikiss();
AddSC_instance_sethekk_halls();
AddSC_instance_shadow_labyrinth(); //Auchindoun Shadow Labyrinth
AddSC_boss_ambassador_hellmaw();
AddSC_boss_blackheart_the_inciter();
AddSC_boss_grandmaster_vorpil();
AddSC_boss_murmur();
AddSC_black_temple(); //Black Temple
AddSC_boss_illidan();
AddSC_boss_shade_of_akama();
AddSC_boss_supremus();
AddSC_boss_gurtogg_bloodboil();
AddSC_boss_mother_shahraz();
AddSC_boss_reliquary_of_souls();
AddSC_boss_teron_gorefiend();
AddSC_boss_najentus();
AddSC_boss_illidari_council();
AddSC_instance_black_temple();
AddSC_boss_fathomlord_karathress(); //CR Serpent Shrine Cavern
AddSC_boss_hydross_the_unstable();
AddSC_boss_lady_vashj();
AddSC_boss_leotheras_the_blind();
AddSC_boss_morogrim_tidewalker();
AddSC_instance_serpentshrine_cavern();
AddSC_boss_the_lurker_below();
AddSC_boss_hydromancer_thespia(); //CR Steam Vault
AddSC_boss_mekgineer_steamrigger();
AddSC_boss_warlord_kalithresh();
AddSC_instance_steam_vault();
AddSC_boss_hungarfen(); //CR Underbog
AddSC_boss_the_black_stalker();
AddSC_boss_gruul(); //Gruul's Lair
AddSC_boss_high_king_maulgar();
AddSC_instance_gruuls_lair();
AddSC_boss_broggok(); //HC Blood Furnace
AddSC_boss_kelidan_the_breaker();
AddSC_boss_the_maker();
AddSC_instance_blood_furnace();
AddSC_boss_magtheridon(); //HC Magtheridon's Lair
AddSC_instance_magtheridons_lair();
AddSC_boss_grand_warlock_nethekurse(); //HC Shattered Halls
AddSC_boss_warbringer_omrogg();
AddSC_boss_warchief_kargath_bladefist();
AddSC_instance_shattered_halls();
AddSC_boss_watchkeeper_gargolmar(); //HC Ramparts
AddSC_boss_omor_the_unscarred();
AddSC_boss_vazruden_the_herald();
AddSC_instance_ramparts();
AddSC_arcatraz(); //TK Arcatraz
AddSC_boss_harbinger_skyriss();
AddSC_instance_arcatraz();
AddSC_boss_high_botanist_freywinn(); //TK Botanica
AddSC_boss_laj();
AddSC_boss_warp_splinter();
AddSC_boss_alar(); //TK The Eye
AddSC_boss_kaelthas();
AddSC_boss_void_reaver();
AddSC_boss_high_astromancer_solarian();
AddSC_instance_the_eye();
AddSC_the_eye();
AddSC_boss_gatewatcher_iron_hand(); //TK The Mechanar
AddSC_boss_nethermancer_sepethrea();
AddSC_boss_pathaleon_the_calculator();
AddSC_instance_mechanar();
AddSC_blades_edge_mountains();
AddSC_boss_doomlordkazzak();
AddSC_boss_doomwalker();
AddSC_hellfire_peninsula();
AddSC_nagrand();
AddSC_netherstorm();
AddSC_shadowmoon_valley();
AddSC_shattrath_city();
AddSC_terokkar_forest();
AddSC_zangarmarsh();
#endif
}
void AddNorthrendScripts()
{
#ifdef SCRIPTS
AddSC_boss_slad_ran(); //Gundrak
AddSC_boss_moorabi();
AddSC_boss_drakkari_colossus();
AddSC_boss_gal_darah();
AddSC_boss_eck();
AddSC_instance_gundrak();
AddSC_boss_amanitar();
AddSC_boss_taldaram(); //Azjol-Nerub Ahn'kahet
AddSC_boss_elder_nadox();
AddSC_boss_jedoga_shadowseeker();
AddSC_boss_volazj();
AddSC_instance_ahnkahet();
AddSC_boss_argent_challenge(); //Trial of the Champion
AddSC_boss_black_knight();
AddSC_boss_grand_champions();
AddSC_instance_trial_of_the_champion();
AddSC_trial_of_the_champion();
AddSC_boss_anubarak_trial(); //Trial of the Crusader
AddSC_boss_faction_champions();
AddSC_boss_jaraxxus();
AddSC_trial_of_the_crusader();
AddSC_boss_twin_valkyr();
AddSC_boss_northrend_beasts();
AddSC_instance_trial_of_the_crusader();
AddSC_boss_krik_thir(); //Azjol-Nerub Azjol-Nerub
AddSC_boss_hadronox();
AddSC_boss_anub_arak();
AddSC_instance_azjol_nerub();
AddSC_boss_anubrekhan(); //Naxxramas
AddSC_boss_maexxna();
AddSC_boss_patchwerk();
AddSC_boss_grobbulus();
AddSC_boss_razuvious();
AddSC_boss_kelthuzad();
AddSC_boss_loatheb();
AddSC_boss_noth();
AddSC_boss_gluth();
AddSC_boss_sapphiron();
AddSC_boss_four_horsemen();
AddSC_boss_faerlina();
AddSC_boss_heigan();
AddSC_boss_gothik();
AddSC_boss_thaddius();
AddSC_instance_naxxramas();
AddSC_boss_magus_telestra(); //The Nexus Nexus
AddSC_boss_anomalus();
AddSC_boss_ormorok();
AddSC_boss_keristrasza();
AddSC_instance_nexus();
AddSC_boss_drakos(); //The Nexus The Oculus
AddSC_boss_urom();
AddSC_boss_varos();
AddSC_instance_oculus();
AddSC_oculus();
AddSC_boss_sartharion(); //Obsidian Sanctum
AddSC_instance_obsidian_sanctum();
AddSC_boss_bjarngrim(); //Ulduar Halls of Lightning
AddSC_boss_loken();
AddSC_boss_ionar();
AddSC_boss_volkhan();
AddSC_instance_halls_of_lightning();
AddSC_boss_maiden_of_grief(); //Ulduar Halls of Stone
AddSC_boss_krystallus();
AddSC_boss_sjonnir();
AddSC_instance_halls_of_stone();
AddSC_halls_of_stone();
AddSC_boss_auriaya(); //Ulduar Ulduar
AddSC_boss_flame_leviathan();
AddSC_boss_ignis();
AddSC_boss_razorscale();
AddSC_boss_xt002();
AddSC_boss_assembly_of_iron();
AddSC_boss_kologarn();
AddSC_ulduar_teleporter();
AddSC_instance_ulduar();
AddSC_boss_keleseth(); //Utgarde Keep
AddSC_boss_skarvald_dalronn();
AddSC_boss_ingvar_the_plunderer();
AddSC_instance_utgarde_keep();
AddSC_boss_svala(); //Utgarde pinnacle
AddSC_boss_palehoof();
AddSC_boss_skadi();
AddSC_boss_ymiron();
AddSC_instance_utgarde_pinnacle();
AddSC_utgarde_keep();
AddSC_boss_archavon(); //Vault of Archavon
AddSC_boss_emalon();
AddSC_boss_koralon();
AddSC_boss_toravon();
AddSC_instance_archavon();
AddSC_boss_trollgore(); //Drak'Tharon Keep
AddSC_boss_novos();
AddSC_boss_dred();
AddSC_boss_tharon_ja();
AddSC_instance_drak_tharon();
AddSC_boss_cyanigosa(); //Violet Hold
AddSC_boss_erekem();
AddSC_boss_ichoron();
AddSC_boss_lavanthor();
AddSC_boss_moragg();
AddSC_boss_xevozz();
AddSC_boss_zuramat();
AddSC_instance_violet_hold();
AddSC_violet_hold();
AddSC_instance_forge_of_souls(); //Forge of Souls
AddSC_forge_of_souls();
AddSC_boss_bronjahm();
AddSC_boss_devourer_of_souls();
AddSC_instance_pit_of_saron(); //Pit of Saron
AddSC_pit_of_saron();
AddSC_boss_garfrost();
AddSC_boss_ick();
AddSC_boss_tyrannus();
AddSC_instance_halls_of_reflection(); // Halls of Reflection
AddSC_halls_of_reflection();
AddSC_boss_falric();
AddSC_boss_marwyn();
AddSC_boss_lord_marrowgar(); // Icecrown Citadel
AddSC_boss_lady_deathwhisper();
AddSC_boss_deathbringer_saurfang();
AddSC_boss_festergut();
AddSC_boss_rotface();
AddSC_boss_professor_putricide();
AddSC_boss_blood_prince_council();
AddSC_boss_blood_queen_lana_thel();
AddSC_boss_sindragosa();
AddSC_icecrown_citadel_teleport();
AddSC_instance_icecrown_citadel();
AddSC_icecrown_citadel();
AddSC_dalaran();
AddSC_borean_tundra();
AddSC_dragonblight();
AddSC_grizzly_hills();
AddSC_howling_fjord();
AddSC_icecrown();
AddSC_sholazar_basin();
AddSC_storm_peaks();
AddSC_zuldrak();
AddSC_crystalsong_forest();
AddSC_isle_of_conquest();
// Cataclysm Scripts
AddSC_the_stonecore(); //The Stonecore
AddSC_instance_the_stonecore();
AddSC_instance_halls_of_origination(); //Halls of Origination
AddSC_boss_temple_guardian_anhuur();
AddSC_boss_earthrager_ptah();
AddSC_boss_anraphet();
AddSC_instance_baradin_hold(); //Baradin Hold
AddSC_boss_argaloth();
AddSC_lost_city_of_the_tolvir(); //Lost City of the Tol'vir
AddSC_instance_lost_city_of_the_tolvir();
AddSC_boss_lockmaw();
AddSC_boss_high_prophet_barim();
AddSC_instance_the_vortex_pinnacle(); //The Vortex Pinnacle
AddSC_instance_grim_batol(); //Grim Batol
AddSC_instance_throne_of_the_tides(); //Throne of the Tides
AddSC_instance_blackrock_caverns(); //Blackrock Caverns
// Darkpeninsula
AddSC_premium();
// The Maelstrom
// Kezan
AddSC_kezan();
#endif
}
void AddOutdoorPvPScripts()
{
#ifdef SCRIPTS
AddSC_outdoorpvp_ep();
AddSC_outdoorpvp_hp();
AddSC_outdoorpvp_na();
AddSC_outdoorpvp_si();
AddSC_outdoorpvp_tf();
AddSC_outdoorpvp_zm();
AddSC_outdoorpvp_gh();
#endif
}
void AddBattlegroundScripts()
{
#ifdef SCRIPTS
#endif
}
#ifdef SCRIPTS
/* This is where custom scripts' loading functions should be declared. */
#endif
void AddCustomScripts()
{
#ifdef SCRIPTS
/* This is where custom scripts should be added. */
#endif
} | Darkpeninsula/DarkCore-Old | src/server/game/Scripting/ScriptLoader.cpp | C++ | gpl-3.0 | 42,185 |
/*
This file is part of Descent II Workshop.
Descent II Workshop 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.
Descent II Workshop 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 Descent II Workshop. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PiggyDump
{
public interface DataFile
{
void LoadDataFile(string name);
void SaveDataFile(string name);
}
}
| InsanityBringer/D2Workshop | PiggyDump/DataFile.cs | C# | gpl-3.0 | 963 |
/*
* use bowtie2 to align all samples to piRBase
*/
package kw_jobinMiRNA;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class BowtieToPiRBase {
public static String DIR = "/nobackup/afodor_research/kwinglee/jobin/microRNA/";
public static String FQDIR = DIR + "adapterFiltered/";
public static String OUTDIR = DIR + "piRBaseBowtie/";
public static String SCRIPTDIR = "/projects/afodor_research/kwinglee/scripts/jobin/microRNA/piRNA/";
public static String REF = "/nobackup/afodor_research/kwinglee/piRBase_v1.0/piRbaseMouseBowtie";
public static void main(String[] args) throws IOException {
File odir = new File(OUTDIR);
if(!odir.exists()) {
odir.mkdirs();
}
File[] files = new File(FQDIR).listFiles();
BufferedWriter all = new BufferedWriter(new FileWriter(new File(
SCRIPTDIR + "bowtieAlignAll.sh")));
for(File fq : files) {
if(fq.getName().endsWith(".fastq")) {
String id = fq.getName().replace(".fastq", "");
String scriptName = "bowtieAlignPiR_" + id;
String name = id + ".piR.bowtie";
//add to run all script
all.write("qsub -q \"copperhead\" " + scriptName + "\n");
//write script
BufferedWriter script = new BufferedWriter(new FileWriter(new File(
SCRIPTDIR + scriptName)));
script.write("#PBS -l procs=1,mem=20GB,walltime=12:00:00\n");
script.write("module load bowtie2\n");
script.write("module load samtools\n");
//align
script.write("bowtie2 -x " + REF + " -U " + fq.getAbsolutePath()
+ " -S " + OUTDIR + name + ".sam\n");
script.write("samtools flagstat " + OUTDIR + name + ".sam > "
+ OUTDIR + name + ".flagstat\n");
script.close();
}
}
all.close();
}
}
| afodor/clusterstuff | src/kw_jobinMiRNA/BowtieToPiRBase.java | Java | gpl-3.0 | 1,812 |
/*
Copyright 2022 (C) Alexey Dynda
This file is part of Tiny Protocol Library.
GNU General Public License Usage
Protocol Library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Protocol Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Protocol Library. If not, see <http://www.gnu.org/licenses/>.
Commercial License Usage
Licensees holding valid commercial Tiny Protocol licenses may use this file in
accordance with the commercial license agreement provided in accordance with
the terms contained in a written agreement between you and Alexey Dynda.
For further information contact via email on github account.
*/
#include <functional>
#include <CppUTest/TestHarness.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <thread>
#include "helpers/tiny_fd_helper.h"
#include "helpers/fake_connection.h"
TEST_GROUP(FD_MULTI)
{
void setup()
{
// ...
// fprintf(stderr, "======== START =======\n" );
}
void teardown()
{
// ...
// fprintf(stderr, "======== END =======\n" );
}
};
TEST(FD_MULTI, send_to_secondary)
{
FakeSetup conn;
FakeEndpoint &endpoint1 = conn.endpoint1();
FakeEndpoint &endpoint2 = conn.endpoint2();
TinyHelperFd primary(&endpoint1, 4096, TINY_FD_MODE_NRM, nullptr);
TinyHelperFd secondary(&endpoint2, 4096, TINY_FD_MODE_NRM, nullptr);
primary.setAddress( TINY_FD_PRIMARY_ADDR );
primary.setTimeout( 250 );
primary.init();
secondary.setAddress( 1 );
secondary.setTimeout( 250 );
secondary.init();
// Run secondary station first, as it doesn't transmit until primary sends a marker
secondary.run(true);
primary.run(true);
CHECK_EQUAL(TINY_SUCCESS, primary.registerPeer( 1 ) );
// send 1 small packets
uint8_t txbuf[4] = {0xAA, 0xFF, 0xCC, 0x66};
int result = primary.sendto(1, txbuf, sizeof(txbuf));
CHECK_EQUAL(TINY_SUCCESS, result);
result = primary.sendto(2, txbuf, sizeof(txbuf));
CHECK_EQUAL(TINY_ERR_UNKNOWN_PEER, result);
// wait until last frame arrives
secondary.wait_until_rx_count(1, 250);
CHECK_EQUAL(1, secondary.rx_count());
}
TEST(FD_MULTI, send_to_secondary_dual)
{
FakeSetup conn;
FakeEndpoint &endpoint1 = conn.endpoint1();
FakeEndpoint &endpoint2 = conn.endpoint2();
FakeEndpoint endpoint3(conn.line2(), conn.line1(), 256, 256);
TinyHelperFd primary(&endpoint1, 4096, TINY_FD_MODE_NRM, nullptr);
TinyHelperFd secondary(&endpoint2, 4096, TINY_FD_MODE_NRM, nullptr);
TinyHelperFd secondary2(&endpoint3, 4096, TINY_FD_MODE_NRM, nullptr);
primary.setAddress( TINY_FD_PRIMARY_ADDR );
primary.setTimeout( 250 );
primary.setPeersCount( 2 );
primary.init();
secondary.setAddress( 1 );
secondary.setTimeout( 250 );
secondary.init();
secondary2.setAddress( 2 );
secondary2.setTimeout( 250 );
secondary2.init();
// Run secondary station first, as it doesn't transmit until primary sends a marker
secondary.run(true);
secondary2.run(true);
primary.run(true);
CHECK_EQUAL(TINY_SUCCESS, primary.registerPeer( 1 ) );
CHECK_EQUAL(TINY_SUCCESS, primary.registerPeer( 2 ) );
// send 1 small packets
uint8_t txbuf[4] = {0xAA, 0xFF, 0xCC, 0x66};
int result = primary.sendto(1, txbuf, sizeof(txbuf));
CHECK_EQUAL(TINY_SUCCESS, result);
// wait until last frame arrives
secondary.wait_until_rx_count(1, 250);
CHECK_EQUAL(1, secondary.rx_count());
CHECK_EQUAL(0, secondary2.rx_count());
result = primary.sendto(2, txbuf, sizeof(txbuf));
secondary2.wait_until_rx_count(1, 250);
CHECK_EQUAL(TINY_SUCCESS, result);
CHECK_EQUAL(1, secondary.rx_count());
CHECK_EQUAL(1, secondary2.rx_count());
}
| lexus2k/tinyproto | unittest/fd_multidrop_tests.cpp | C++ | gpl-3.0 | 4,272 |
#include "database.h"
#include <stdexcept>
#include <QFile>
#include <QSqlQuery>
#include "brauhelfer.h"
Database::Database() :
mVersion(-1),
mLastError(QString())
{
QSqlDatabase::addDatabase("QSQLITE", "kbh");
}
void Database::createTables(Brauhelfer* bh)
{
QSqlDatabase db = QSqlDatabase::database("kbh", false);
if (!db.isValid())
qCritical("Database connection is invalid.");
modelSud = new ModelSud(bh, db);
modelRasten = new ModelRasten(bh, db);
modelMalzschuettung = new ModelMalzschuettung(bh, db);
modelHopfengaben = new ModelHopfengaben(bh, db);
modelHefegaben = new ModelHefegaben(bh, db);
modelWeitereZutatenGaben = new ModelWeitereZutatenGaben(bh, db);
modelSchnellgaerverlauf = new ModelSchnellgaerverlauf(bh, db);
modelHauptgaerverlauf = new ModelHauptgaerverlauf(bh, db);
modelNachgaerverlauf = new ModelNachgaerverlauf(bh, db);
modelBewertungen = new ModelBewertungen(bh, db);
modelMalz = new ModelMalz(bh, db);
modelHopfen = new ModelHopfen(bh, db);
modelHefe = new ModelHefe(bh, db);
modelWeitereZutaten = new ModelWeitereZutaten(bh, db);
modelAnhang = new ModelAnhang(bh, db);
modelAusruestung = new ModelAusruestung(bh, db);
modelGeraete = new ModelGeraete(bh, db);
modelWasser = new ModelWasser(bh, db);
modelEtiketten = new ModelEtiketten(bh, db);
modeTags = new ModelTags(bh, db);
modelKategorien = new ModelKategorien(bh, db);
modelWasseraufbereitung = new ModelWasseraufbereitung(bh, db);
modelSud->createConnections();
}
void Database::setTables()
{
modelSud->setTable("Sud");
modelSud->setSort(ModelSud::ColBraudatum, Qt::DescendingOrder);
modelRasten->setTable("Rasten");
modelMalzschuettung->setTable("Malzschuettung");
modelHopfengaben->setTable("Hopfengaben");
modelHefegaben->setTable("Hefegaben");
modelWeitereZutatenGaben->setTable("WeitereZutatenGaben");
modelSchnellgaerverlauf->setTable("Schnellgaerverlauf");
modelSchnellgaerverlauf->setSort(ModelSchnellgaerverlauf::ColZeitstempel, Qt::AscendingOrder);
modelHauptgaerverlauf->setTable("Hauptgaerverlauf");
modelHauptgaerverlauf->setSort(ModelHauptgaerverlauf::ColZeitstempel, Qt::AscendingOrder);
modelNachgaerverlauf->setTable("Nachgaerverlauf");
modelNachgaerverlauf->setSort(ModelNachgaerverlauf::ColZeitstempel, Qt::AscendingOrder);
modelBewertungen->setTable("Bewertungen");
modelBewertungen->setSort(ModelBewertungen::ColDatum, Qt::AscendingOrder);
modelMalz->setTable("Malz");
modelHopfen->setTable("Hopfen");
modelHefe->setTable("Hefe");
modelWeitereZutaten->setTable("WeitereZutaten");
modelAnhang->setTable("Anhang");
modelAusruestung->setTable("Ausruestung");
modelGeraete->setTable("Geraete");
modelWasser->setTable("Wasser");
modelEtiketten->setTable("Etiketten");
modeTags->setTable("Tags");
modelKategorien->setTable("Kategorien");
modelWasseraufbereitung->setTable("Wasseraufbereitung");
// sanity check
Q_ASSERT(modelSud->columnCount() == ModelSud::NumCols);
Q_ASSERT(modelRasten->columnCount() == ModelRasten::NumCols);
Q_ASSERT(modelMalzschuettung->columnCount() == ModelMalzschuettung::NumCols);
Q_ASSERT(modelHopfengaben->columnCount() == ModelHopfengaben::NumCols);
Q_ASSERT(modelHefegaben->columnCount() == ModelHefegaben::NumCols);
Q_ASSERT(modelWeitereZutatenGaben->columnCount() == ModelWeitereZutatenGaben::NumCols);
Q_ASSERT(modelSchnellgaerverlauf->columnCount() == ModelSchnellgaerverlauf::NumCols);
Q_ASSERT(modelHauptgaerverlauf->columnCount() == ModelHauptgaerverlauf::NumCols);
Q_ASSERT(modelNachgaerverlauf->columnCount() == ModelNachgaerverlauf::NumCols);
Q_ASSERT(modelBewertungen->columnCount() == ModelBewertungen::NumCols);
Q_ASSERT(modelMalz->columnCount() == ModelMalz::NumCols);
Q_ASSERT(modelHopfen->columnCount() == ModelHopfen::NumCols);
Q_ASSERT(modelHefe->columnCount() == ModelHefe::NumCols);
Q_ASSERT(modelWeitereZutaten->columnCount() == ModelWeitereZutaten::NumCols);
Q_ASSERT(modelAnhang->columnCount() == ModelAnhang::NumCols);
Q_ASSERT(modelAusruestung->columnCount() == ModelAusruestung::NumCols);
Q_ASSERT(modelGeraete->columnCount() == ModelGeraete::NumCols);
Q_ASSERT(modelWasser->columnCount() == ModelWasser::NumCols);
Q_ASSERT(modelEtiketten->columnCount() == ModelEtiketten::NumCols);
Q_ASSERT(modeTags->columnCount() == ModelTags::NumCols);
Q_ASSERT(modelKategorien->columnCount() == ModelKategorien::NumCols);
Q_ASSERT(modelWasseraufbereitung->columnCount() == ModelWasseraufbereitung::NumCols);
}
Database::~Database()
{
disconnect();
delete modelSud;
delete modelRasten;
delete modelMalzschuettung;
delete modelHopfengaben;
delete modelHefegaben;
delete modelWeitereZutatenGaben;
delete modelSchnellgaerverlauf;
delete modelHauptgaerverlauf;
delete modelNachgaerverlauf;
delete modelBewertungen;
delete modelMalz;
delete modelHopfen;
delete modelHefe;
delete modelWeitereZutaten;
delete modelAnhang;
delete modelAusruestung;
delete modelGeraete;
delete modelWasser;
delete modelEtiketten;
delete modeTags;
delete modelKategorien;
delete modelWasseraufbereitung;
QSqlDatabase::removeDatabase("kbh");
}
bool Database::connect(const QString &dbPath, bool readonly)
{
if (!isConnected())
{
if (QFile::exists(dbPath))
{
QSqlDatabase db = QSqlDatabase::database("kbh", false);
if (!db.isValid())
{
qCritical("Database connection is invalid.");
return false;
}
db.close();
db.setDatabaseName(dbPath);
db.open();
if (readonly)
db.setConnectOptions("QSQLITE_OPEN_READONLY");
if (db.open())
{
try
{
QSqlQuery query = sqlExec(db, "SELECT db_Version FROM Global");
if (query.first())
{
int version = query.value(0).toInt();
if (version > 0)
{
mVersion = version;
return true;
}
}
}
catch (...)
{
}
}
disconnect();
}
}
return false;
}
void Database::disconnect()
{
if (isConnected())
{
modelSud->clear();
modelRasten->clear();
modelMalzschuettung->clear();
modelHopfengaben->clear();
modelHefegaben->clear();
modelWeitereZutatenGaben->clear();
modelSchnellgaerverlauf->clear();
modelHauptgaerverlauf->clear();
modelNachgaerverlauf->clear();
modelBewertungen->clear();
modelMalz->clear();
modelHopfen->clear();
modelHefe->clear();
modelWeitereZutaten->clear();
modelAnhang->clear();
modelAusruestung->clear();
modelGeraete->clear();
modelWasser->clear();
modelEtiketten->clear();
modeTags->clear();
modelKategorien->clear();
modelWasseraufbereitung->clear();
mVersion = -1;
}
}
bool Database::isConnected() const
{
return mVersion != -1;
}
bool Database::isDirty() const
{
return modelSud->isDirty() |
modelRasten->isDirty() |
modelMalzschuettung->isDirty() |
modelHopfengaben->isDirty() |
modelHefegaben->isDirty() |
modelWeitereZutatenGaben->isDirty() |
modelSchnellgaerverlauf->isDirty() |
modelHauptgaerverlauf->isDirty() |
modelNachgaerverlauf->isDirty() |
modelBewertungen->isDirty() |
modelMalz->isDirty() |
modelHopfen->isDirty() |
modelHefe->isDirty() |
modelWeitereZutaten->isDirty() |
modelAnhang->isDirty() |
modelAusruestung->isDirty() |
modelGeraete->isDirty() |
modelWasser->isDirty() |
modelEtiketten->isDirty() |
modeTags->isDirty() |
modelKategorien->isDirty() |
modelWasseraufbereitung->isDirty();
}
void Database::select()
{
modelMalz->select();
modelHopfen->select();
modelHefe->select();
modelWeitereZutaten->select();
modelWasser->select();
modelGeraete->select();
modelAusruestung->select();
modelRasten->select();
modelMalzschuettung->select();
modelHopfengaben->select();
modelHefegaben->select();
modelWeitereZutatenGaben->select();
modelSchnellgaerverlauf->select();
modelHauptgaerverlauf->select();
modelNachgaerverlauf->select();
modelBewertungen->select();
modelAnhang->select();
modelEtiketten->select();
modeTags->select();
modelKategorien->select();
modelWasseraufbereitung->select();
modelSud->select();
}
int Database::version() const
{
return mVersion;
}
bool Database::save()
{
bool ret = true;
if (!modelMalz->submitAll())
{
mLastError = modelMalz->lastError();
ret = false;
}
if (!modelHopfen->submitAll())
{
mLastError = modelHopfen->lastError();
ret = false;
}
if (!modelHefe->submitAll())
{
mLastError = modelHefe->lastError();
ret = false;
}
if (!modelWeitereZutaten->submitAll())
{
mLastError = modelWeitereZutaten->lastError();
ret = false;
}
if (!modelWasser->submitAll())
{
mLastError = modelWasser->lastError();
ret = false;
}
if (!modelGeraete->submitAll())
{
mLastError = modelGeraete->lastError();
ret = false;
}
if (!modelAusruestung->submitAll())
{
mLastError = modelAusruestung->lastError();
ret = false;
}
if (!modelRasten->submitAll())
{
mLastError = modelRasten->lastError();
ret = false;
}
if (!modelMalzschuettung->submitAll())
{
mLastError = modelMalzschuettung->lastError();
ret = false;
}
if (!modelHopfengaben->submitAll())
{
mLastError = modelHopfengaben->lastError();
ret = false;
}
if (!modelHefegaben->submitAll())
{
mLastError = modelHefegaben->lastError();
ret = false;
}
if (!modelWeitereZutatenGaben->submitAll())
{
mLastError = modelWeitereZutatenGaben->lastError();
ret = false;
}
if (!modelSchnellgaerverlauf->submitAll())
{
mLastError = modelSchnellgaerverlauf->lastError();
ret = false;
}
if (!modelHauptgaerverlauf->submitAll())
{
mLastError = modelHauptgaerverlauf->lastError();
ret = false;
}
if (!modelNachgaerverlauf->submitAll())
{
mLastError = modelNachgaerverlauf->lastError();
ret = false;
}
if (!modelBewertungen->submitAll())
{
mLastError = modelBewertungen->lastError();
ret = false;
}
if (!modelAnhang->submitAll())
{
mLastError = modelAnhang->lastError();
ret = false;
}
if (!modelEtiketten->submitAll())
{
mLastError = modelEtiketten->lastError();
ret = false;
}
if (!modeTags->submitAll())
{
mLastError = modeTags->lastError();
ret = false;
}
if (!modelKategorien->submitAll())
{
mLastError = modelKategorien->lastError();
ret = false;
}
if (!modelWasseraufbereitung->submitAll())
{
mLastError = modelWasseraufbereitung->lastError();
ret = false;
}
if (!modelSud->submitAll())
{
mLastError = modelSud->lastError();
ret = false;
}
return ret;
}
void Database::discard()
{
modelMalz->revertAll();
modelHopfen->revertAll();
modelHefe->revertAll();
modelWeitereZutaten->revertAll();
modelWasser->revertAll();
modelAusruestung->revertAll();
modelGeraete->revertAll();
modelRasten->revertAll();
modelMalzschuettung->revertAll();
modelHopfengaben->revertAll();
modelHefegaben->revertAll();
modelWeitereZutatenGaben->revertAll();
modelSchnellgaerverlauf->revertAll();
modelHauptgaerverlauf->revertAll();
modelNachgaerverlauf->revertAll();
modelBewertungen->revertAll();
modelAnhang->revertAll();
modelEtiketten->revertAll();
modeTags->revertAll();
modelKategorien->revertAll();
modelWasseraufbereitung->revertAll();
modelSud->revertAll();
}
QSqlQuery Database::sqlExec(QSqlDatabase& db, const QString &query)
{
QSqlQuery sqlQuery = db.exec(query);
QSqlError error = db.lastError();
if (error.isValid())
{
mLastError = error;
qCritical() << query;
qCritical() << error;
throw std::runtime_error(error.text().toStdString());
}
return sqlQuery;
}
QSqlError Database::lastError() const
{
return mLastError;
}
| BourgeoisLab/kleiner-brauhelfer-app | kleiner-brauhelfer-core/database.cpp | C++ | gpl-3.0 | 13,123 |
/*
* @formatter:off
* Li Song Mechlab - A 'mech building tool for PGI's MechWarrior: Online.
* Copyright (C) 2013 Li Song
*
* 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/>.
*/
//@formatter:on
package org.lisoft.lsml.math.probability;
import org.lisoft.lsml.math.FastFactorial;
import java.math.BigDecimal;
import java.math.BigInteger;
import static org.lisoft.lsml.math.FastFactorial.*;
/**
* This class models a binomial distribution
*
* @author Li Song
*/
public class BinomialDistribution implements Distribution {
private final double p;
private final int n;
public static long nChooseK(int n, long aK) {
if(n-aK < aK){
return nChooseK(n, n-aK);
}
long ans = 1;
for (int kk = 0; kk < aK; ++kk) {
ans = ans * (n - kk) / (kk + 1);
}
return ans;
}
public static BigInteger nChooseKLargeNumbers(int n, int aK) {
if(n-aK < aK){
return nChooseKLargeNumbers(n, n-aK);
}
return factorial(n).divide(factorial(aK).multiply(factorial(n-aK)));
/*
BigInteger ans = BigInteger.valueOf(1);
for (int kk = 0; kk < aK; ++kk) {
ans = ans.multiply(BigInteger.valueOf(n - kk)).divide(BigInteger.valueOf(kk + 1));
}
return ans;*/
}
public BinomialDistribution(double aP, int aN) {
p = aP;
n = aN;
}
@Override
public double pdf(double aX) {
long k = Math.round(aX);
return nChooseK(n, k) * Math.pow(p, k) * Math.pow(1.0 - p, n - k);
}
public static double pdf(int aK, int aN, double aP){
BigDecimal Pk = BigDecimal.valueOf(aP).pow(aK);
BigDecimal PnotK = BigDecimal.valueOf(1.0-aP).pow(aN-aK);
BigDecimal permutations = new BigDecimal(nChooseKLargeNumbers(aN, aK));
return permutations.multiply(Pk).multiply(PnotK).doubleValue();
}
@Override
public double cdf(double aX) {
double ans = 0;
final long k = (long) (aX + Math.ulp(aX)); // Accept anything within truncation error of k as k.
for (int i = 0; i <= k; ++i) {
ans += pdf(i);
}
return ans;
}
}
| EmilyBjoerk/lsml | src/main/java/org/lisoft/lsml/math/probability/BinomialDistribution.java | Java | gpl-3.0 | 2,791 |
package zzz.study.utils;
import cc.lovesq.service.CreativeService;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static zzz.study.utils.BaseTool.*;
/**
* 移除指定类的 Javadoc 注释 Created by shuqin on 16/5/4.
*/
public class RemoveJavadocComments {
private static final String javadocRegexStr = "(\\/\\*.*?\\*\\/)";
private static final Pattern javadocPattern =
Pattern.compile(javadocRegexStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
public static void main(String[] args) {
// 移除指定包下面的类 Javadoc 注释
String tradeDALPackage = ALLIN_PROJ_PATH_SRC + "/cc/lovesq/controller";
List<Class> classes = getClasses(tradeDALPackage);
for (Class c : classes) {
if (c.getSimpleName().endsWith("Controller")) {
removeJavadoc(c);
}
}
// 移除单个类的 Javadoc 注释
removeJavadoc(CreativeService.class);
}
public static void removeJavadoc(Class<?> coreServiceCls) {
String coreServiceName = coreServiceCls.getSimpleName();
String packageName = coreServiceCls.getPackage().getName();
String packagePath = "/" + packageName.replaceAll("\\.", "/");
String coreServiceClsRelativePath = packagePath + "/" + coreServiceName + ".java";
String coreServiceClsPath = ALLIN_PROJ_PATH_SRC + coreServiceClsRelativePath;
String coreServiceContent = readFile(coreServiceClsPath);
Matcher m = javadocPattern.matcher(coreServiceContent);
String newContent = coreServiceContent;
while (m.find()) {
String matchedJavadoc = coreServiceContent.substring(m.start(), m.end());
newContent = newContent.replace(matchedJavadoc, "");
}
newContent = newContent.replaceAll("\n\\s*\n", "\n\n");
writeFile(coreServiceClsPath, newContent);
}
}
| shuqin/ALLIN | src/main/java/zzz/study/utils/RemoveJavadocComments.java | Java | gpl-3.0 | 1,951 |
load_library :control_panel # Se carga la libreria de panel de control
attr_reader :panel # Habilita solo la lectura del pael
def settings
size 600, 600
end
def setup
control_panel do |c| # Inicia el panel de control
c.title = "Slider" # Titúlo del panel de control
c.slider :Tamano, 10..300, 20 # Controla la variable de nombre Tamano dandole la posibilidad de estar entre 10 al 300 y avanzar de 20 en 20
@panel = c # la variable que transmite la información al panel.
end
@Tamano = 50 # Valor inicial de la variable
end
def draw
unless @hide # El bucle mantiene abierto el panel de control durante la ejecución del sketch
hide = true
panel.set_visible(hide)
end
background color('#e91e63')
fill (color('#9c27b0'))
ellipse(300,300,@Tamano,@Tamano)
end
| MoiRouhs/scriptyoutube-dl | jruby_art/control_panel/slider.rb | Ruby | gpl-3.0 | 780 |
'use strict';
var menu = angular.module('irc.views.menu', [
'irc.networks',
'irc.views.menu.directives',
]);
menu.controller(
'MenuCtrl', [
'$scope',
'$timeout',
'$state',
'networks',
function MenuCtrl(
$scope,
$timeout,
$state,
networks) {
$scope.networks = networks;
var MainCtrl = $scope.MC;
var activeRoom = null;
function focus() {
if (activeRoom) {
activeRoom.focused = false;
}
activeRoom = MainCtrl.room;
if (MainCtrl.room) {
MainCtrl.room.focused = true;
}
if (MainCtrl.channel) {
MainCtrl.network.collapsed = false;
MainCtrl.channel.unreadCount = 0;
}
}
$scope.$on('$stateChangeSuccess', function() {
focus();
});
// Networks
this.onNetClick = function(network) {
if (!network.online) {
network.connect();
$state.go('main.conversation', {
network: network.name,
channel: null
});
return;
}
if (!network.focused) {
$state.go('main.conversation', {
network: network.name,
channel: null
});
}
$scope.drawer.open = false;
};
this.onNetContext = function(network) {
$scope.networkDialog.network = network;
$timeout(function() {
$scope.networkDialog.open();
});
};
this.onNetworkDialogClosed = function() {
$scope.networkDialog.network = null;
};
this.onDelete = function() {
var network = $scope.networkDialog.network;
$scope.networkDialog.close();
$scope.confirmDialog.toBeDeleted = network;
$scope.confirmDialog.open();
$scope.confirmDialog.onConfirm = function() {
network.delete();
};
};
// Channels
this.onChanClick = function(channel) {
if (!channel.focused) {
$state.go('main.conversation', {
network: channel.network.name,
channel: channel.name
});
}
if (channel.network.online) {
channel.join();
$scope.drawer.open = false;
} else {
channel.network.connect().then(function() {
channel.join();
$scope.drawer.open = false;
});
}
};
this.onChanContext = function(channel) {
$scope.channelDialog.channel = channel;
$scope.channelDialog.open();
};
this.onChannelDialogClosed = function() {
$scope.channelDialog.channel = null;
};
this.onRemove = function(channel) {
channel.delete();
// One additional digest cycle, so it will notice the height change
$timeout();
};
}]);
| christopher-l/fxos-irc | app/views/menu/menu.js | JavaScript | gpl-3.0 | 2,535 |
#!/usr/bin/env ruby
require 'swineherd' ; include Swineherd
require 'swineherd/script/pig_script' ; include Swineherd::Script
require 'swineherd/script/wukong_script' ; include Swineherd::Script
Settings.define :flow_id, :required => true, :description => "Workflow needs a unique numeric id"
Settings.define :input_dir, :required => true, :description => "Path to necessary data"
Settings.define :n_users, :description => "Number of users who've used tokens, see warning"
Settings.define :reduce_tasks, :default => 96, :description => "Change to reduce task capacity on cluster"
Settings.define :script_path, :default => "/home/jacob/Programming/infochimps-data/social/network/twitter/base/corpus"
Settings.define :n_toks, :default => "100", :description => "Number of tokens to include in wordbag"
Settings.resolve!
#
# WARNING: You cannot run this workflow from end-to-end at the moment. You
# should run up to and including 'user_frequencies'. Then, fetch the number of
# users by looking at the 'combine input groups' on the jobtracker for
# document_frequencies.pig. Next, run the workflow the same, this time passing
# in the number of users as an option.
#
flow = Workflow.new(Settings.flow_id) do
tokenizer = WukongScript.new("#{Settings.script_path}/tokenize/extract_word_tokens.rb")
frequencies = PigScript.new("#{Settings.script_path}/wordbag/tfidf/document_frequencies.pig")
tfidf = PigScript.new("#{Settings.script_path}/wordbag/tfidf/tfidf.pig")
top_n_bag = PigScript.new("#{Settings.script_path}/wordbag/tfidf/top_n_bag.pig")
task :tokenize do
tokenizer.input << "#{Settings.input_dir}/tweet"
tokenizer.output << next_output(:tokenize)
tokenizer.run
end
task :user_frequencies => [:tokenize] do
frequencies.output << next_output(:user_frequencies)
frequencies.pig_options = "-Dmapred.reduce.tasks=#{Settings.reduce_tasks}"
frequencies.options = {
:usages => latest_output(:tokenize),
:usage_freqs => latest_output(:user_frequencies)
}
frequencies.run
end
task :tfidf_weights => [:user_frequencies] do
tfidf.output << next_output(:tfidf_weights)
tfidf.pig_options = "-Dmapred.reduce.tasks=#{Settings.reduce_tasks}"
tfidf.options = {
:usage_freqs => latest_output(:user_frequencies),
:n_users => "#{Settings.n_users}l",
:user_token_graph => latest_output(:tfidf_weights)
}
tfidf.run
end
task :top_n_bag => [:tfidf_weights] do
top_n_bag.output << next_output(:top_n_bag)
top_n_bag.pig_options = "-Dmapred.reduce.tasks=#{Settings.reduce_tasks}"
top_n_bag.options = {
:n => Settings.n_tokens,
:twuid => "#{Settings.input_dir}/twitter_user_id",
:bigrph => latest_output(:tfidf_weights),
:wordbag => latest_output(:top_n_bag)
}
top_n_bag.run
end
end
flow.workdir = "/tmp/wordbag"
flow.describe
flow.run(Settings.rest.first)
| mrflip/prep-wu-data | social/network/twitter/base/corpus/wordbag/tfidf/tfidf_workflow.rb | Ruby | gpl-3.0 | 3,005 |
class CreateRoles < ActiveRecord::Migration
def self.up
create_table :roles do |t|
t.integer :id
t.string :rol
t.timestamps
end
end
def self.down
drop_table :roles
end
end
| GARUMFundatio/Bazar | db/migrate/20100927074933_create_roles.rb | Ruby | gpl-3.0 | 212 |
<?php
/**
* FanPress CM static data model
*
* @author Stefan Seehafer aka imagine <fanpress@nobody-knows.org>
* @copyright (c) 2011-2017, Stefan Seehafer
* @license http://www.gnu.org/licenses/gpl.txt GPLv3
*/
namespace fpcm\model\abstracts;
/**
* Statisches Model ohen DB-Verbindung
*
* @package fpcm\model\abstracts
* @abstract
* @author Stefan Seehafer <sea75300@yahoo.de>
*/
abstract class staticModel {
/**
* Data array
* @var array
*/
protected $data;
/**
* Cache object
* @var \fpcm\classes\cache
*/
protected $cache;
/**
* Event list
* @var \fpcm\model\events\eventList
*/
protected $events;
/**
* Config object
* @var \fpcm\model\system\config
*/
protected $config;
/**
* Sprachobjekt
* @var \fpcm\classes\language
*/
protected $language;
/**
* Session objekt
* @var \fpcm\model\system\session
*/
protected $session;
/**
* Notifications
* @var \fpcm\model\theme\notifications
* @since FPCM 3.6
*/
protected $notifications;
/**
* Cache name
* @var string
*/
protected $cacheName = false;
/**
* Cache Modul
* @var string
* @since FPCM 3.4
*/
protected $cacheModule = '';
/**
* Konstruktor
* @return void
*/
public function __construct() {
$this->events = \fpcm\classes\baseconfig::$fpcmEvents;
$this->cache = new \fpcm\classes\cache($this->cacheName ? $this->cacheName : md5(microtime(false)), $this->cacheModule);
if (!\fpcm\classes\baseconfig::dbConfigExists()) return;
$this->session = \fpcm\classes\baseconfig::$fpcmSession;
$this->config = \fpcm\classes\baseconfig::$fpcmConfig;
$this->language = \fpcm\classes\baseconfig::$fpcmLanguage;
$this->notifications = !empty(\fpcm\classes\baseconfig::$fpcmNotifications) ? \fpcm\classes\baseconfig::$fpcmNotifications : null;
if (is_object($this->config)) $this->config->setUserSettings();
}
/**
* Magic get
* @param string $name
* @return mixed
*/
public function __get($name) {
return isset($this->data[$name]) ? $this->data[$name] : false;
}
/**
* Magic set
* @param mixed $name
* @param mixed $value
*/
public function __set($name, $value) {
$this->data[$name] = $value;
}
/**
* Magische Methode für nicht vorhandene Methoden
* @param string $name
* @param mixed $arguments
* @return boolean
*/
public function __call($name, $arguments) {
print "Function '{$name}' not found in ".get_class($this).'<br>';
return false;
}
/**
* Magische Methode für nicht vorhandene, statische Methoden
* @param string $name
* @param mixed $arguments
* @return boolean
*/
public static function __callStatic($name, $arguments) {
print "Static function '{$name}' not found in ".get_class($this).'<br>';
return false;
}
}
| sea75300/fanpresscm3 | inc/model/abstracts/staticModel.php | PHP | gpl-3.0 | 3,718 |
package crux;
/**
* studentName = "XXXXXXXX XXXXXXXX";
* studentID = "XXXXXXXX";
* uciNetID = "XXXXXXXX";
*/
public class Symbol {
private String name;
public Symbol(String name) {
this.name = name;
}
public String name()
{
return this.name;
}
public String toString()
{
return "Symbol(" + name + ")";
}
public static Symbol newError(String message) {
return new ErrorSymbol(message);
}
}
class ErrorSymbol extends Symbol
{
public ErrorSymbol(String message)
{
super(message);
}
}
| kevdez/abstract-syntax-tree | src/crux/Symbol.java | Java | gpl-3.0 | 601 |
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2022 Equinor ASA
//
// ResInsight 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.
//
// ResInsight 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 at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RimSummaryMultiPlotCollection.h"
#include "RimProject.h"
#include "RimSummaryMultiPlot.h"
#include "cafPdmFieldReorderCapability.h"
CAF_PDM_SOURCE_INIT( RimSummaryMultiPlotCollection, "RimSummaryMultiPlotCollection" );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimSummaryMultiPlotCollection::RimSummaryMultiPlotCollection()
{
CAF_PDM_InitObject( "Summary Multi Plots", ":/MultiPlot16x16.png" );
CAF_PDM_InitFieldNoDefault( &m_summaryMultiPlots, "MultiSummaryPlots", "Multi Summary Plots" );
m_summaryMultiPlots.uiCapability()->setUiTreeHidden( true );
caf::PdmFieldReorderCapability::addToField( &m_summaryMultiPlots );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimSummaryMultiPlotCollection::~RimSummaryMultiPlotCollection()
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimSummaryMultiPlotCollection::deleteAllPlots()
{
m_summaryMultiPlots.deleteAllChildObjects();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<RimSummaryMultiPlot*> RimSummaryMultiPlotCollection::multiPlots() const
{
return m_summaryMultiPlots.childObjects();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimSummaryMultiPlotCollection::addMultiSummaryPlot( RimSummaryMultiPlot* plot )
{
m_summaryMultiPlots().push_back( plot );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimSummaryMultiPlotCollection::loadDataAndUpdateAllPlots()
{
for ( const auto& p : m_summaryMultiPlots.childObjects() )
p->loadDataAndUpdate();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
size_t RimSummaryMultiPlotCollection::plotCount() const
{
return m_summaryMultiPlots.size();
}
| OPM/ResInsight | ApplicationLibCode/ProjectDataModel/Summary/RimSummaryMultiPlotCollection.cpp | C++ | gpl-3.0 | 3,525 |
<?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 local_o365
* @author James McQuillan <james.mcquillan@remote-learner.net>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @copyright (C) 2014 onwards Microsoft, Inc. (http://microsoft.com/)
*/
namespace local_o365\feature\sds\task;
/**
* Scheduled task to run school data sync sync.
*/
class sync extends \core\task\scheduled_task {
/**
* Get a descriptive name for this task (shown to admins).
*
* @return string
*/
public function get_name() {
return get_string('task_sds_sync', 'local_o365');
}
/**
* Run the sync process
*
* @param \local_o365\rest\sds $apiclient The SDS apiclient.
*/
public static function runsync($apiclient) {
global $DB, $CFG;
require_once($CFG->dirroot.'/lib/accesslib.php');
require_once($CFG->dirroot.'/lib/enrollib.php');
$schools = get_config('local_o365', 'sdsschools');
$profilesyncenabled = get_config('local_o365', 'sdsprofilesyncenabled');
$fieldmap = get_config('local_o365', 'sdsfieldmap');
$fieldmap = (!empty($fieldmap)) ? @unserialize($fieldmap) : [];
if (empty($fieldmap) || !is_array($fieldmap)) {
$fieldmap = [];
}
if (empty($fieldmap)) {
$profilesyncenabled = false;
}
$enrolenabled = get_config('local_o365', 'sdsenrolmentenabled');
// Get role records.
$studentrole = $DB->get_record('role', ['shortname' => 'student']);
if (empty($studentrole)) {
throw new \Exception('Could not find the student role.');
}
$teacherrole = $DB->get_record('role', ['shortname' => 'manager']);
if (empty($teacherrole)) {
throw new \Exception('Could not find the teacher role');
}
$schools = explode(',', $schools);
foreach ($schools as $school) {
$school = trim($school);
if (empty($school)) {
continue;
}
try {
$schooldata = $apiclient->get_school($school);
} catch (\Exception $e) {
mtrace('... Skipped SDS school '.$school.' because we received an error from the API');
continue;
}
$coursecat = static::get_or_create_school_coursecategory($schooldata['objectId'], $schooldata['displayName']);
mtrace('... Processing '.$schooldata['displayName']);
$schoolnumber = $schooldata[$apiclient::PREFIX.'_SchoolNumber'];
$sections = $apiclient->get_school_sections($schoolnumber);
foreach ($sections['value'] as $section) {
mtrace('...... Processing '.$section['displayName']);
$fullname = $section[$apiclient::PREFIX.'_CourseName'];
$fullname .= ' '.$section[$apiclient::PREFIX.'_SectionNumber'];
$course = static::get_or_create_section_course($section['objectId'], $section['displayName'], $fullname, $coursecat->id);
$coursecontext = \context_course::instance($course->id);
if (!empty($enrolenabled) || !empty($profilesyncenabled)) {
$members = $apiclient->get_section_members($section['objectId']);
foreach ($members['value'] as $member) {
$objectrec = $DB->get_record('local_o365_objects', ['type' => 'user', 'objectid' => $member['objectId']]);
if (!empty($objectrec)) {
if (!empty($enrolenabled)) {
$type = $member[$apiclient::PREFIX.'_ObjectType'];
switch ($type) {
case 'Student':
$role = $studentrole;
break;
case 'Teacher':
$role = $teacherrole;
break;
default:
continue;
}
$roleparams = [
'roleid' => $role->id,
'contextid' => $coursecontext->id,
'userid' => $objectrec->moodleid,
'component' => '',
'itemid' => 0,
];
$ra = $DB->get_record('role_assignments', $roleparams, 'id');
if (empty($ra)) {
mtrace('......... Assigning role for user '.$objectrec->moodleid.' in course '.$course->id);
role_assign($role->id, $objectrec->moodleid, $coursecontext->id);
mtrace('......... Enrolling user '.$objectrec->moodleid.' into course '.$course->id);
enrol_try_internal_enrol($course->id, $objectrec->moodleid);
}
}
}
}
}
}
if (!empty($profilesyncenabled)) {
mtrace('...... Running profile sync');
$skiptoken = get_config('local_o365', 'sdsprofilesync_skiptoken');
$students = $apiclient->get_school_users($schooldata['objectId'], $skiptoken);
foreach ($students['value'] as $student) {
$objectrec = $DB->get_record('local_o365_objects', ['type' => 'user', 'objectid' => $student['objectId']]);
if (!empty($objectrec)) {
$muser = $DB->get_record('user', ['id' => $objectrec->moodleid]);
static::update_profiledata($muser, $student, $fieldmap);
}
}
set_config('sdsprofilesync_skiptoken', '', 'local_o365');
if (!empty($students['odata.nextLink'])) {
// Extract skiptoken.
$nextlink = parse_url($students['odata.nextLink']);
if (isset($nextlink['query'])) {
$query = [];
parse_str($nextlink['query'], $query);
if (isset($query['$skiptoken'])) {
mtrace('...... Skip token saved for next run');
set_config('sdsprofilesync_skiptoken', $query['$skiptoken'], 'local_o365');
}
}
} else {
mtrace('...... Full run complete.');
}
}
}
}
/**
* Update a user's information based on configured field map.
*
* @param object $muser The Moodle user record.
* @param array $sdsdata Incoming data from SDS.
* @param array $fieldmaps Array of configured field maps.
* @return bool Success/Failure.
*/
public static function update_profiledata($muser, $sdsdata, $fieldmaps) {
global $DB, $CFG;
require_once($CFG->dirroot.'/user/profile/lib.php');
mtrace("......... Updating user {$muser->id}");
foreach ($fieldmaps as $fieldmap) {
$fieldmap = explode('/', $fieldmap);
list($remotefield, $localfield) = $fieldmap;
if (strpos($remotefield, 'pre_') === 0) {
$remotefield = \local_o365\rest\sds::PREFIX.'_'.substr($remotefield, 4);
}
if (!isset($sdsdata[$remotefield])) {
$debugmsg = "SDS: no remotefield: {$remotefield} for user {$muser->id}";
$caller = 'update_profiledata';
\local_o365\utils::debug($debugmsg, $caller);
continue;
}
$newdata = $sdsdata[$remotefield];
if ($localfield === 'country') {
// Update country with two letter country code.
$newdata = strtoupper($newdata);
$countrymap = get_string_manager()->get_list_of_countries();
if (isset($countrymap[$newdata])) {
$countrycode = $incoming;
} else {
$muser->$localfield = '';
foreach ($countrymap as $code => $name) {
if (strtoupper($name) === $newdata) {
$muser->$localfield = $code;
break;
}
}
}
} else if ($localfield === 'lang') {
$muser->$localfield = (strlen($newdata) > 2) ? substr($newdata, 0, 2) : $newdata;
} else {
$muser->$localfield = $newdata;
}
}
$DB->update_record('user', $muser);
profile_save_data($muser);
return true;
}
/**
* Retrieve or create a course for a section.
*
* @param string $sectionobjectid The object ID of the section.
* @param string $sectionshortname The shortname of the section.
* @param string $sectionfullname The fullname of the section.
* @param int $categoryid The ID of the category to create the course in (if necessary).
* @return object The course object.
*/
public static function get_or_create_section_course($sectionobjectid, $sectionshortname, $sectionfullname, $categoryid = 0) {
global $DB, $CFG;
require_once($CFG->dirroot.'/course/lib.php');
// Look for existing category.
$params = ['type' => 'sdssection', 'subtype' => 'course', 'objectid' => $sectionobjectid];
$objectrec = $DB->get_record('local_o365_objects', $params);
if (!empty($objectrec)) {
$course = $DB->get_record('course', ['id' => $objectrec->moodleid]);
if (!empty($course)) {
return $course;
} else {
// Course was deleted, remove object record and recreate.
$DB->delete_records('local_o365_objects', ['id' => $objectrec->id]);
$objectrec = null;
}
}
// Create new course category and object record.
$data = [
'category' => $categoryid,
'shortname' => $sectionshortname,
'fullname' => $sectionfullname,
'idnumber' => $sectionobjectid,
];
$course = create_course((object)$data);
$now = time();
$objectrec = [
'type' => 'sdssection',
'subtype' => 'course',
'objectid' => $sectionobjectid,
'moodleid' => $course->id,
'o365name' => $sectionshortname,
'timecreated' => $now,
'timemodified' => $now,
];
$DB->insert_record('local_o365_objects', $objectrec);
return $course;
}
/**
* Get or create the course category for a school.
*
* @param string $schoolobjectid The Office 365 object ID of the school.
* @param string $schoolname The name of the school.
* @return \coursecat A coursecat object for the retrieved or created course category.
*/
public static function get_or_create_school_coursecategory($schoolobjectid, $schoolname) {
global $DB, $CFG;
require_once($CFG->dirroot.'/lib/coursecatlib.php');
// Look for existing category.
$params = ['type' => 'sdsschool', 'subtype' => 'coursecat', 'objectid' => $schoolobjectid];
$existingobject = $DB->get_record('local_o365_objects', $params);
if (!empty($existingobject)) {
$coursecat = \coursecat::get($existingobject->moodleid, IGNORE_MISSING, true);
if (!empty($coursecat)) {
return $coursecat;
} else {
// Course category was deleted, remove object record and recreate.
$DB->delete_records('local_o365_objects', ['id' => $existingobject->id]);
$existingobject = null;
}
}
// Create new course category and object record.
$data = [
'visible' => 1,
'name' => $schoolname,
'idnumber' => $schoolobjectid,
];
if (strlen($data['name']) > 255) {
$data['name'] = substr($data['name'], 0, 255);
}
$coursecat = \coursecat::create($data);
$now = time();
$objectrec = [
'type' => 'sdsschool',
'subtype' => 'coursecat',
'objectid' => $schoolobjectid,
'moodleid' => $coursecat->id,
'o365name' => $schoolname,
'timecreated' => $now,
'timemodified' => $now,
];
$DB->insert_record('local_o365_objects', $objectrec);
return $coursecat;
}
/**
* Get the SDS api client.
*
* @return \local_o365\rest\sds The SDS API client.
*/
public static function get_apiclient() {
$httpclient = new \local_o365\httpclient();
$clientdata = \local_o365\oauth2\clientdata::instance_from_oidc();
$resource = \local_o365\rest\sds::get_resource();
$token = \local_o365\oauth2\systemtoken::instance(null, $resource, $clientdata, $httpclient);
$apiclient = new \local_o365\rest\sds($token, $httpclient);
return $apiclient;
}
/**
* Do the job.
*/
public function execute() {
global $DB, $CFG;
if (\local_o365\utils::is_configured() !== true) {
return false;
}
$apiclient = static::get_apiclient();
return static::runsync($apiclient);
}
}
| nitro2010/moodle | local/o365/classes/feature/sds/task/sync.php | PHP | gpl-3.0 | 14,459 |
#include<iostream>
using namespace std;
int main()
{
int a,d,x[20],y[20],a1,temp,i,j;
while(1)
{
a1=20000;
cin>>a>>d;
if(a==0 & d==0)
break;
for(i=0;i<a;i++)
{
cin>>x[i];
if(x[i]<a1)
a1=x[i];
}
for(i=0;i<d;i++)
{
cin>>y[i];
}
for(i=0;i<2;i++)
{
for(j=i+1;j<d;j++)
{
if(y[i]>y[j])
{
temp=y[i];
y[i]=y[j];
y[j]=temp;
}
}
}
if(a1>=y[1] || (a1>=y[0] && a1>=y[1]))
{
cout<<"N\n";
}
else
cout<<"Y\n";
}
}
| ProgDan/maratona | SPOJ/OFFSIDE.cpp | C++ | gpl-3.0 | 495 |
/* ****************************************************************************
* eID Middleware Project.
* Copyright (C) 2008-2009 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, see
* http://www.gnu.org/licenses/.
**************************************************************************** */
#include "P15Correction.h"
using namespace eIDMW;
CP15Correction::~CP15Correction(){}
| 12019/svn.gov.pt | _src/eidmw/cardlayer/P15Correction.cpp | C++ | gpl-3.0 | 936 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-07-30 01:56
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0008_contactphone_place_on_header'),
]
operations = [
migrations.AddField(
model_name='contactemail',
name='place_on_header',
field=models.BooleanField(default=False, verbose_name='Размещать в заголовке'),
),
migrations.AddField(
model_name='contactperson',
name='photo',
field=models.ImageField(blank=True, null=True, upload_to='', verbose_name='Фото'),
),
]
| andrius-momzyakov/grade | web/migrations/0009_auto_20170730_0156.py | Python | gpl-3.0 | 735 |
#pragma once
/* This file is part of Imagine.
Imagine 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.
Imagine 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 Imagine. If not, see <http://www.gnu.org/licenses/> */
#include <imagine/gfx/GeomQuadMesh.hh>
namespace Gfx
{
struct LGradientStopDesc
{
GC pos;
VertexColor color;
};
class LGradient
{
public:
constexpr LGradient() {}
void deinit()
{
g.deinit();
}
void draw()
{
g.draw();
}
void setColor(ColorComp r, ColorComp g, ColorComp b)
{
this->g.setColorRGB(r, g, b);
}
void setTranslucent(ColorComp a)
{
g.setColorTranslucent(a);
}
void setColorStop(ColorComp r, ColorComp g, ColorComp b, uint i)
{
this->g.setColorRGBV(r, g, b, i*2);
this->g.setColorRGBV(r, g, b, (i*2)+1);
}
void setTranslucentStop(ColorComp a, uint i)
{
g.setColorTranslucentV(a, i*2);
g.setColorTranslucentV(a, (i*2)+1);
}
void setPos(const LGradientStopDesc *stop, uint stops, GC x, GC y, GC x2, GC y2)
{
if(stops != stops_)
{
assert(stops >= 2);
stops_ = stops;
VertexPos thickness[2]{x, x2};
VertexPos stopPos[stops];
iterateTimes(stops, i)
{
stopPos[i] = stop[i].pos;
}
g.init(thickness, stopPos, stops);
}
ColVertex *v = g.v;
iterateTimes(stops, i)
{
v[i*2].x = x;
v[i*2].y = v[(i*2)+1].y = IG::scalePointRange(stop[i].pos, GC(0), GC(1), y, y2);
v[(i*2)+1].x = x2;
v[i*2].color = stop[i].color;
v[(i*2)+1].color = stop[i].color;
}
}
void setPos(const LGradientStopDesc *stop, uint stops, const GCRect &d)
{
setPos(stop, stops, d.x, d.y2, d.x2, d.y);
}
uint stops()
{
return stops_;
}
explicit operator bool()
{
return stops_;
}
private:
GeomQuadMesh g{};
uint stops_ = 0;
};
}
| sails/emu-ex-plus-alpha | imagine/include/imagine/gfx/GfxLGradient.hh | C++ | gpl-3.0 | 2,181 |
"""
Created by Emille Ishida in May, 2015.
Class to implement calculations on data matrix.
"""
import os
import sys
import matplotlib.pylab as plt
import numpy as np
from multiprocessing import Pool
from snclass.treat_lc import LC
from snclass.util import read_user_input, read_snana_lc, translate_snid
from snclass.functions import core_cross_val, screen
##############################################
class DataMatrix(object):
"""
Data matrix class.
Methods:
- build: Build data matrix according to user input file specifications.
- reduce_dimension: Perform dimensionality reduction.
- cross_val: Perform cross-validation.
Attributes:
- user_choices: dict, user input choices
- snid: vector, list of objects identifiers
- datam: array, data matrix for training
- redshift: vector, redshift for training data
- sntype: vector, classification of training data
- low_dim_matrix: array, data matrix in KernelPC space
- transf_test: function, project argument into KernelPC space
- final: vector, optimize parameter values
"""
def __init__(self, input_file=None):
"""
Read user input file.
input: input_file -> str
name of user input file
"""
self.datam = None
self.snid = []
self.redshift = None
self.sntype = None
self.low_dim_matrix = None
self.transf_test = None
self.final = None
self.test_projection = []
if input_file is not None:
self.user_choices = read_user_input(input_file)
def check_file(self, filename, epoch=True, ref_filter=None):
"""
Construct one line of the data matrix.
input: filename, str
file of raw data for 1 supernova
epoch, bool - optional
If true, check if SN satisfies epoch cuts
Default is True
ref_filter, str - optional
Reference filter for peak MJD calculation
Default is None
"""
screen('Fitting ' + filename, self.user_choices)
# translate identifier
self.user_choices['path_to_lc'] = [translate_snid(filename, self.user_choices['photon_flag'][0])[0]]
# read light curve raw data
raw = read_snana_lc(self.user_choices)
# initiate light curve object
lc_obj = LC(raw, self.user_choices)
# load GP fit
lc_obj.load_fit_GP(self.user_choices['samples_dir'][0] + filename)
# normalize
lc_obj.normalize(ref_filter=ref_filter)
# shift to peak mjd
lc_obj.mjd_shift()
if epoch:
# check epoch requirements
lc_obj.check_epoch()
else:
lc_obj.epoch_cuts = True
if lc_obj.epoch_cuts:
# build data matrix lines
lc_obj.build_steps()
# store
obj_line = []
for fil in self.user_choices['filters']:
for item in lc_obj.flux_for_matrix[fil]:
obj_line.append(item)
rflag = self.user_choices['redshift_flag'][0]
redshift = raw[rflag][0]
obj_class = raw[self.user_choices['type_flag'][0]][0]
self.snid.append(raw['SNID:'][0])
return obj_line, redshift, obj_class
else:
screen('... Failed to pass epoch cuts!', self.user_choices)
screen('\n', self.user_choices)
return None
def store_training(self, file_out):
"""
Store complete training matrix.
input: file_out, str
output file name
"""
# write to file
if file_out is not None:
op1 = open(file_out, 'w')
op1.write('SNID type z LC...\n')
for i in xrange(len(self.datam)):
op1.write(str(self.snid[i]) + ' ' + str(self.sntype[i]) +
' ' + str(self.redshift[i]) + ' ')
for j in xrange(len(self.datam[i])):
op1.write(str(self.datam[i][j]) + ' ')
op1.write('\n')
op1.close()
def build(self, file_out=None, check_epoch=True, ref_filter=None):
"""
Build data matrix according to user input file specifications.
input: file_out -> str, optional
file to store data matrix (str). Default is None
check_epoch -> bool, optional
If True check if SN satisfies epoch cuts
Default is True
ref_filter -> str, optional
Reference filter for MJD calculation
Default is None
"""
# list all files in sample directory
file_list = os.listdir(self.user_choices['samples_dir'][0])
datam = []
redshift = []
sntype = []
for obj in file_list:
if 'mean' in obj:
sn_char = self.check_file(obj, epoch=check_epoch,
ref_filter=ref_filter)
if sn_char is not None:
datam.append(sn_char[0])
redshift.append(sn_char[1])
sntype.append(sn_char[2])
self.datam = np.array(datam)
self.redshift = np.array(redshift)
self.sntype = np.array(sntype)
# store results
self.store_training(file_out)
def reduce_dimension(self):
"""Perform dimensionality reduction with user defined function."""
# define dimensionality reduction function
func = self.user_choices['dim_reduction_func']
# reduce dimensionality
self.low_dim_matrix = func(self.datam, self.user_choices)
# define transformation function
self.transf_test = func(self.datam, self.user_choices, transform=True)
def cross_val(self):
"""Optimize the hyperparameters for RBF kernel and ncomp."""
# correct type parameters if necessary
types_func = self.user_choices['transform_types_func']
if types_func is not None:
self.sntype = types_func(self.sntype, self.user_choices['Ia_flag'][0])
# initialize parameters
data = self.datam
types = self.sntype
choices = self.user_choices
nparticles = self.user_choices['n_cross_val_particles']
parameters = []
for i in xrange(nparticles):
pars = {}
pars['data'] = data
pars['types'] = types
pars['user_choices'] = choices
parameters.append(pars)
if int(self.user_choices['n_proc'][0]) > 0:
cv_func = self.user_choices['cross_validation_func']
pool = Pool(processes=int(self.user_choices['n_proc'][0]))
my_pool = pool.map_async(cv_func, parameters)
try:
results = my_pool.get(0xFFFF)
except KeyboardInterrupt:
print 'Interruputed by the user!'
sys.exit()
pool.close()
pool.join()
results = np.array(results)
else:
number = self.user_choices['n_cross_val_particles']
results = np.array([core_cross_val(pars)
for pars in parameters])
flist = list(results[:,len(results[0])-1])
max_success = max(flist)
indx_max = flist.index(max_success)
self.final = {}
for i in xrange(len(self.user_choices['cross_val_par'])):
par_list = self.user_choices['cross_val_par']
self.final[par_list[i]] = results[indx_max][i]
def final_configuration(self):
"""Determine final configuraton based on cross-validation results."""
#update optimized hyper-parameters
for par in self.user_choices['cross_val_par']:
indx = self.user_choices['cross_val_par'].index(par)
self.user_choices[par] = self.final[par]
#update low dimensional matrix
self.reduce_dimension()
def plot(self, pcs, file_out, show=False, test=None):
"""
Plot 2-dimensional scatter of data matrix in kPCA space.
input: pcs, vector of int
kernel PCs to be used as horizontal and vertical axis
file_out, str
file name to store final plot
show, bool, optional
if True show plot in screen
Default is False
test, dict, optional
keywords: data, type
if not None plot the projection of 1 photometric object
Default is None
"""
#define vectors to plot
xdata = self.low_dim_matrix[:,pcs[0]]
ydata = self.low_dim_matrix[:,pcs[1]]
if '0' in self.sntype:
snIa = self.sntype == '0'
nonIa = self.sntype != '0'
else:
snIa = self.sntype == 'Ia'
snIbc = self.sntype == 'Ibc'
snII = self.sntype == 'II'
plt.figure(figsize=(10,10))
if '0' in self.sntype:
plt.scatter(xdata[nonIa], ydata[nonIa], color='purple', marker='s',
label='spec non-Ia')
plt.scatter(xdata[snIa], ydata[snIa], color='blue', marker='o',
label='spec Ia')
else:
plt.scatter(xdata[snII], ydata[snII], color='purple', marker='s',
label='spec II')
plt.scatter(xdata[snIbc], ydata[snIbc], color='green', marker='^',
s=30, label='spec Ibc')
plt.scatter(xdata[snIa], ydata[snIa], color='blue', marker='o',
label='spec Ia')
if test is not None:
if len(test.samples_for_matrix) > 0:
plt.title('prob_Ia = ' + str(round(test['prob_Ia'], 2)))
if test.raw['SIM_NON1a:'][0] == '0':
sntype = 'Ia'
else:
sntype = 'nonIa'
plt.scatter([test.test_proj[0][pcs[0]]], [test.test_proj[0][pcs[1]]],
marker='*', color='red', s=75,
label='photo ' + sntype)
plt.xlabel('kPC' + str(pcs[0] + 1), fontsize=14)
plt.ylabel('kPC' + str(pcs[1] + 1), fontsize=14)
plt.legend(fontsize=12)
if show:
plt.show()
if file_out is not None:
plt.savefig(file_out)
plt.close()
def main():
"""Print documentation."""
print __doc__
if __name__ == '__main__':
main()
| emilleishida/snclass | snclass/matrix.py | Python | gpl-3.0 | 10,669 |
<html>
<head>
<meta charset="utf-8">
<title>VideoTech</title>
</head>
<body id="ID">
<?php $Pseudo = $_POST['psd']; $Password = $_POST['mdp']; ?>
<form action="connexion.php" method="post">
<input type="pseudo" name="psd" required placeholder="Pseudo..." />
<input type="password" name="mdp" required placeholder="Mot de passe..." />
<input type="submit" value="Connexion" />
</form>
<?php
if (isset($Pseudo) && isset($Password)) {
$host = "localhost"; $user="root"; $passwd="root"; $base="VideoTech"; $table="USER";
$conn = mysqli_connect($host,$user,$passwd, $base);
if(mysqli_connect_errno()){
echo "Erreur de connexion a MySQL: " . mysqli_connect_errno();
exit(0);
}
$query = "SELECT * FROM $table WHERE USER_Pseudo = '$Pseudo' AND USER_Password = '$Password'";
$result = mysqli_query($conn, $query) or die("Echec pseudo");
$ligne=mysqli_fetch_array($result);
if ($ligne["USER_Pseudo"] == $Pseudo && $ligne["USER_Password"]) {
header("location: ./index.php");
}
else {
echo "<p>Pseudo ou Mot de passe invalide</p>";
}
mysqli_free_result($result);
mysqli_close($conn);
}
?>
<a href="./inscription.php">Toujours pas de compte ? ...</a>
</body>
</html>
| RallStack/VideoTech | Source/connexion.php | PHP | gpl-3.0 | 1,341 |
using System.ComponentModel;
using System.Windows.Forms;
namespace WolvenKit
{
partial class frmRenameDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btOk = new System.Windows.Forms.Button();
this.btCancel = new System.Windows.Forms.Button();
this.txFileName = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// btOk
//
this.btOk.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btOk.Location = new System.Drawing.Point(493, 43);
this.btOk.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btOk.Name = "btOk";
this.btOk.Size = new System.Drawing.Size(100, 28);
this.btOk.TabIndex = 0;
this.btOk.Text = "Ok";
this.btOk.UseVisualStyleBackColor = true;
//
// btCancel
//
this.btCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.btCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btCancel.Location = new System.Drawing.Point(16, 43);
this.btCancel.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btCancel.Name = "btCancel";
this.btCancel.Size = new System.Drawing.Size(100, 28);
this.btCancel.TabIndex = 1;
this.btCancel.Text = "Cancel";
this.btCancel.UseVisualStyleBackColor = true;
//
// txFileName
//
this.txFileName.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txFileName.Location = new System.Drawing.Point(16, 11);
this.txFileName.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txFileName.Name = "txFileName";
this.txFileName.Size = new System.Drawing.Size(576, 22);
this.txFileName.TabIndex = 2;
this.txFileName.Enter += new System.EventHandler(this.txFileName_Enter);
//
// frmRenameDialog
//
this.AcceptButton = this.btOk;
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btCancel;
this.ClientSize = new System.Drawing.Size(609, 75);
this.ControlBox = false;
this.Controls.Add(this.txFileName);
this.Controls.Add(this.btCancel);
this.Controls.Add(this.btOk);
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.MaximumSize = new System.Drawing.Size(1327, 122);
this.MinimumSize = new System.Drawing.Size(261, 122);
this.Name = "frmRenameDialog";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Rename";
this.Activated += new System.EventHandler(this.frmRenameDialog_Activated);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Button btOk;
private Button btCancel;
private TextBox txFileName;
}
} | Traderain/Wolven-kit | WolvenKit.Legacy/Forms/Dialog/frmRenameDialog.Designer.cs | C# | gpl-3.0 | 4,700 |
__author__ = 'harsha'
class ForceReply(object):
def __init__(self, force_reply, selective):
self.force_reply = force_reply
self.selective = selective
def get_force_reply(self):
return self.force_reply
def get_selective(self):
return self.selective
def __str__(self):
return str(self.__dict__) | harsha5500/pytelegrambot | telegram/ForceReply.py | Python | gpl-3.0 | 353 |
import React from 'react';
// 参照界面,适合选中参照数据
export default class extends React.Component {
}
| saas-plat/saas-plat-appfx | src/components/widgets/md/Reference.js | JavaScript | gpl-3.0 | 123 |
using System;
using System.Linq;
namespace RabbitOperations.Domain
{
public class TypeName : IEquatable<TypeName>
{
public TypeName()
{
}
public TypeName(string fullName)
{
var parts = fullName.Split(',');
ParseClassAndNamespace(parts);
ParseAssemblyName(parts);
ParseVersion(parts);
ParseCulture(parts);
ParsePublicKeyToken(parts);
}
public string ClassName { get; set; }
public string Namespace { get; set; }
public string Assembly { get; set; }
public Version Version { get; set; }
public string Culture { get; set; }
public string PublicKeyToken { get; set; }
public bool Equals(TypeName other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(PublicKeyToken, other.PublicKeyToken) && Equals(Version, other.Version) &&
string.Equals(Culture, other.Culture) && string.Equals(Assembly, other.Assembly) &&
string.Equals(Namespace, other.Namespace) && string.Equals(ClassName, other.ClassName);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TypeName) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (PublicKeyToken != null ? PublicKeyToken.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (Version != null ? Version.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (Culture != null ? Culture.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (Assembly != null ? Assembly.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (Namespace != null ? Namespace.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (ClassName != null ? ClassName.GetHashCode() : 0);
return hashCode;
}
}
private void ParseCulture(string[] parts)
{
if (parts.Length > 3)
{
var cultureParts = parts[3].Trim().Split('=');
if (cultureParts.Length == 2)
{
Culture = cultureParts[1];
}
}
}
private void ParsePublicKeyToken(string[] parts)
{
if (parts.Length > 4)
{
var keyTokenParts = parts[4].Trim().Split('=');
if (keyTokenParts.Length == 2)
{
PublicKeyToken = keyTokenParts[1];
}
}
}
private void ParseVersion(string[] parts)
{
if (parts.Length > 2)
{
var versionParts = parts[2].Trim().Split('=');
if (versionParts.Length == 2)
{
Version = new Version(versionParts[1]);
}
}
}
private void ParseAssemblyName(string[] parts)
{
if (parts.Length > 1)
{
Assembly = parts[1].Trim();
}
}
private void ParseClassAndNamespace(string[] parts)
{
if (parts.Length > 0)
{
var classParts = parts[0].Trim().Split('.');
ClassName = classParts.Last();
Namespace = string.Join(".", classParts.Take(classParts.Length - 1));
}
}
public override string ToString()
{
return string.Format("{0}.{1}, {2}, Version={3}, Culture={4}, PublicKeyToken={5}", Namespace, ClassName,
Assembly, Version, Culture, PublicKeyToken);
}
}
} | SouthsideSoftware/RabbitOperations | app/RabbitOperations.Domain/TypeName.cs | C# | gpl-3.0 | 4,007 |
/*
* Copyright 2010-2013 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom 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.
*
* OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include "Ufopaedia.h"
#include "ArticleStateCraftWeapon.h"
#include "../Ruleset/ArticleDefinition.h"
#include "../Ruleset/Ruleset.h"
#include "../Ruleset/RuleCraftWeapon.h"
#include "../Engine/Game.h"
#include "../Engine/Palette.h"
#include "../Engine/Surface.h"
#include "../Engine/Language.h"
#include "../Resource/ResourcePack.h"
#include "../Interface/Text.h"
#include "../Interface/TextButton.h"
#include "../Interface/TextList.h"
namespace OpenXcom
{
ArticleStateCraftWeapon::ArticleStateCraftWeapon(Game *game, ArticleDefinitionCraftWeapon *defs, int palSwitch) : ArticleState(game, defs->id, palSwitch)
{
RuleCraftWeapon *weapon = _game->getRuleset()->getCraftWeapon(defs->id);
// add screen elements
_txtTitle = new Text(200, 32, 5, 24);
// Set palette
_game->setPalette(_game->getResourcePack()->getPalette("PALETTES.DAT_4")->getColors());
ArticleState::initLayout();
// add other elements
add(_txtTitle);
// Set up objects
_game->getResourcePack()->getSurface(defs->image_id)->blit(_bg);
_btnOk->setColor(Palette::blockOffset(1));
_btnPrev->setColor(Palette::blockOffset(1));
_btnNext->setColor(Palette::blockOffset(1));
_txtTitle->setColor(Palette::blockOffset(14)+15);
_txtTitle->setBig();
_txtTitle->setWordWrap(true);
_txtTitle->setText(Ufopaedia::buildText(_game, defs->title));
_txtInfo = new Text(310, 32, 5, 160);
add(_txtInfo);
_txtInfo->setColor(Palette::blockOffset(14)+15);
_txtInfo->setWordWrap(true);
_txtInfo->setText(Ufopaedia::buildText(_game, defs->text));
_lstInfo = new TextList(250, 111, 5, 80);
add(_lstInfo);
std::wstringstream ss;
_lstInfo->setColor(Palette::blockOffset(14)+15);
_lstInfo->setColumns(2, 180, 70);
_lstInfo->setDot(true);
_lstInfo->setBig();
ss.str(L"");ss.clear();
ss << weapon->getDamage();
_lstInfo->addRow(2, _game->getLanguage()->getString("STR_DAMAGE").c_str(), ss.str().c_str());
_lstInfo->setCellColor(0, 1, Palette::blockOffset(15)+4);
ss.str(L"");ss.clear();
ss << weapon->getRange() << _game->getLanguage()->getString("STR_KM").c_str();
_lstInfo->addRow(2, _game->getLanguage()->getString("STR_RANGE").c_str(), ss.str().c_str());
_lstInfo->setCellColor(1, 1, Palette::blockOffset(15)+4);
ss.str(L"");ss.clear();
ss << weapon->getAccuracy() << "%";
_lstInfo->addRow(2, _game->getLanguage()->getString("STR_ACCURACY").c_str(), ss.str().c_str());
_lstInfo->setCellColor(2, 1, Palette::blockOffset(15)+4);
ss.str(L"");ss.clear();
ss << weapon->getStandardReload() << _game->getLanguage()->getString("STR_S").c_str();
_lstInfo->addRow(2, _game->getLanguage()->getString("STR_RE_LOAD_TIME").c_str(), ss.str().c_str());
_lstInfo->setCellColor(3, 1, Palette::blockOffset(15)+4);
}
ArticleStateCraftWeapon::~ArticleStateCraftWeapon()
{}
}
| lt90/RPG | src/Ufopaedia/ArticleStateCraftWeapon.cpp | C++ | gpl-3.0 | 3,553 |
Ext.define('Wif.setup.trend.trendnewEmploymentCard', {
extend : 'Ext.form.Panel',
project : null,
title : 'Employment Trends',
assocLuCbox : null,
assocLuColIdx : 1,
model : null,
pendingChanges : null,
sortKey : 'label',
isEditing: true,
isLoadingExisting: true,
constructor : function(config) {
var me = this;
Ext.apply(this, config);
var projectId = me.project.projectId;
var isnew = me.project.isnew;
me.isLoadingExisting = true;
this.Output2 = [];
this.gridfields = [];
this.modelfields = [];
this.modelfields.push("_id");
this.modelfields.push("item");
var gfield_id = {
text : "_id",
dataIndex : "_id",
hidden: true
};
var gfield = {
text : "item",
dataIndex : "item"
};
this.gridfields.push(gfield_id);
this.gridfields.push(gfield);
var definition = this.project.getDefinition();
var rows =[];
var sortfields = [];
var rows = definition.projections.sort();
_.log(me, 'projections', rows);
for (var i = 0; i < rows.count(); i++)
{
sortfields.push(rows[i].label);
}
sortfields.sort();
for (var i = 0; i < sortfields.count(); i++)
{
var field = {
text : sortfields[i],
dataIndex : sortfields[i],
editor: 'numberfield',
type: 'number'
};
this.gridfields.push(field);
this.modelfields.push(sortfields[i]);
}
_.log(me, 'sortFields', sortfields);
_.log(me, 'modelFields1', this.modelfields);
_.log(me, 'gridFields', this.gridfields);
var storeData = [];
var sectors = definition.sectors;
for (var i=0; i <sectors.length; i++)
{
var mjsonStr='{';
mjsonStr = mjsonStr + '\"_id\" :' + '\"' + sectors[i].label +'\",';
mjsonStr = mjsonStr + '\"item\" :' + '\"' + sectors[i].label +'\",';
for (var m = 2; m < me.modelfields.count(); m++)
{
var myear=me.modelfields[m];
mjsonStr = mjsonStr + '\"' + myear + '\"' + ':0,';
}
mjsonStr = mjsonStr.substring(0,mjsonStr.length-1) + '}';
storeData.push(JSON.parse(mjsonStr));
}
this.model = Ext.define('User', {
extend: 'Ext.data.Model',
fields: this.modelfields
});
this.store = Ext.create('Ext.data.Store', {
model: this.model,
data : storeData
});
this.grid = Ext.create('Ext.grid.Panel', {
//title: 'Projection Population',
selType: 'cellmodel',
border : 0,
margin : '0 5 5 5',
store : this.store,
height : 400,
autoRender : true,
columns : this.gridfields,
flex: 1,
viewConfig: {
plugins: {
ptype: 'gridviewdragdrop',
dragText: 'Drag and drop to reorganize'
}
},
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1
})
]
});
this.grid.reconfigure(this.store, this.gridfields);
// var cmbData=[];
var cmbData ={};
var rows = definition.demographicTrends;
// if (definition.demographicTrends2 == undefined)
// {
// definition.demographicTrends2= definition.demographicTrends;
// }
//this.Output2 = definition.demographicTrends;
//var rows = this.Output2;
var st='[';
for (var i = 0; i< rows.length; i++)
{
st = st + '{\"label\":' + '\"' + rows[i].label+ '\"},';
}
st = st.substring(0,st.length-1) + ']';
if (st == ']')
{
st = '[]';
}
this.cmbStore = Ext.create('Ext.data.Store', {
//autoLoad : true,
fields: ['label'],
data : JSON.parse(st)
});
this.cmb=Ext.create('Ext.form.field.ComboBox', {
extend : 'Aura.Util.RemoteComboBox',
fieldLabel: 'Choose Trend',
//width: 500,
labelWidth: 200,
store: this.cmbStore,
//data : cmbData,
queryMode: 'local',
displayField: 'label',
valueField: 'label',
autoLoad : false,
multiSelect : false,
forceSelection: true,
projectId : null,
editable : true,
allowBlank : false,
emptyText : "Choose Trendo",
//renderTo: Ext.getBody()
listeners: {
change: function (cb, newValue, oldValue, options) {
console.log(newValue, oldValue);
if (oldValue != undefined){
me.saveGrid(oldValue);
}
me.loadGrid(newValue);
}
}
});
this.cmb.bindStore(this.cmbStore);
var enumDistrictFieldSet = Ext.create('Ext.form.FieldSet', {
columnWidth : 0.5,
title : 'Trends',
collapsible : true,
margin : '15 5 5 0',
defaults : {
bodyPadding : 10,
anchor : '90%'
},
items : [this.cmb]
});
this.items = [enumDistrictFieldSet,this.grid];
this.callParent(arguments);
},
listeners : {
activate : function() {
_.log(this, 'activate');
//this.build(this.fillcombo());
this.build();
var definition = this.project.getDefinition();
this.Output2 = definition.demographicTrends;
//this.Output2 = definition.demographicTrends;
// if (definition.demographicTrends2 == undefined)
// {
// definition.demographicTrends2= definition.demographicTrends;
// }
//
// this.Output2 = definition.demographicTrends2;
//this.cmb.setValue("");
//this.build(function() { this.fillcombo; if (callback) { callback(); }});
}
},
loadGrid : function(cmbValue) {
var me = this, projectId = this.project.projectId;
me.isLoadingExisting = true;
var definition = this.project.getDefinition();
var storeDataNew = [];
//if (definition.demographicTrends != undefined)
if (this.Output2 != undefined)
{
//var mainrows = definition.demographicTrends;
var mainrows = this.Output2;
//for projection population
var lsw1 = false;
var storeData = [];
var sectors = definition.sectors;
for (var i=0; i <sectors.length; i++)
{
var mjson0Str='{';
mjson0Str = mjson0Str + '\"_id\" :' + '\"' + sectors[i].label +'\",';
mjson0Str = mjson0Str + '\"item\" :' + '\"' + sectors[i].label +'\",';
for (var m = 2; m < me.modelfields.count(); m++)
{
var myear=me.modelfields[m];
mjson0Str = mjson0Str + '\"' + myear + '\"' + ':0,';
}
mjson0Str = mjson0Str.substring(0,mjson0Str.length-1) + '}';
storeData.push(JSON.parse(mjson0Str));
}
this.store.removeAll();
this.grid.getSelectionModel().deselectAll();
this.store.loadData(storeData);
this.grid.reconfigure(this.store, this.gridfields);
this.store.each(function(record,idx){
val = record.get('_id');
var totalRows = mainrows.count();
for (var l = 0; l < totalRows; l++)
{
if (mainrows[l].label == cmbValue)
{
// var cnt0= mainrows[l].demographicData.count();
// for (var j = 0; j < cnt0; j++)
// {
// if (mainrows[l].demographicData[j]["@class"] == ".EmploymentDemographicData" )
// {
var sectors = definition.sectors;
for (var i=0; i <sectors.length; i++)
{
var jsonStr='{';
jsonStr = jsonStr + '\"_id\" :' + '\"' + sectors[i].label +'\",';
jsonStr = jsonStr + '\"item\" :' + '\"' + sectors[i].label +'\",';
if (val == sectors[i].label)
{
// if (lsw1 == false)
// {
for (var m = 0; m < me.modelfields.count(); m++)
{
var cnt01 = mainrows[l].demographicData.count();
for (var v = 0; v < cnt01; v++)
{
if (mainrows[l].demographicData[v]["@class"] == ".EmploymentDemographicData" )
{
if ( me.modelfields[m] == mainrows[l].demographicData[v].projectionLabel)
{
var myear=me.modelfields[m];
if ( mainrows[l].demographicData[v].sectorLabel == sectors[i].label)
{
jsonStr = jsonStr + '\"' + myear + '\"' + ':' + mainrows[l].demographicData[v].employees + ',';
}
}//end if ( me.modelfields[m]
}//end if (mainrows[l]
}//end for (var v = 0
}//end for (var m = 0
jsonStr = jsonStr.substring(0,jsonStr.length-1) + '}';
storeDataNew.push(JSON.parse(jsonStr));
lsw1 = true;
//}//end if lsw
}//end if (sectors[i].label)
}// end for sectors
//}//end if (mainrows[l].demographicData[j]["@class"]
//} //end for (var j = 0
}//end if (mainrows[l].label == cmbValue)
}//end for (var l = 0)
}); //end this.store
}//end if definition.demographicTrends
if (storeDataNew.length>0)
{
this.store.removeAll();
this.grid.getSelectionModel().deselectAll();
this.store.loadData(storeDataNew);
this.grid.reconfigure(this.store, this.gridfields);
}
return true;
}, //end build function
saveGrid : function(cmbValue) {
var me = this, projectId = this.project.projectId;
me.isLoadingExisting = true;
var definition = this.project.getDefinition();
var storeDataNew = [];
var demographicData = [];
//saving projection population
var jsonStrTotal='';
for (var m = 2; m < this.modelfields.count(); m++)
{
// jsonStr='{';
// jsonStr = jsonStr + '\"@class\" :' + '\".EmploymentDemographicData\",';
// jsonStr = jsonStr + '\"projectionLabel\" :\"' +this.modelfields[m] + '\",';
var i = 0;
var sectors = definition.sectors;
for (var z=0; z <sectors.length; z++)
{
jsonStr='{';
jsonStr = jsonStr + '\"@class\" :' + '\".EmploymentDemographicData\",';
jsonStr = jsonStr + '\"projectionLabel\" :\"' +this.modelfields[m] + '\",';
var slbl = sectors[z].label;
this.store.each(function(record,idx){
i = i + 1;
//var x= '\"' +record.get('_id') + '\"';
if (record.get('_id') == slbl)
{
jsonStr = jsonStr + '\"sectorLabel\" :\"' +slbl + '\",';
var x1 = ':' + 0 +',';
if (record.get(me.modelfields[m]) =='' || record.get(me.modelfields[m]) ==null)
{
x1 = ':' + 0 +',';
}
else
{
x1 = ':' + record.get(me.modelfields[m]) +',';
}
jsonStr = jsonStr + '\"employees\"' + x1;
}
});
jsonStr = jsonStr.substring(0,jsonStr.length-1);
jsonStr = jsonStr + '}';
jsonStrTotal = jsonStrTotal + jsonStr + ',';
//jsonStr = jsonStr.substring(0,jsonStr.length-1) + '}';
demographicData.push(JSON.parse(jsonStr));
}
}
var demographicTrends = [];
jsonStrTotal = jsonStrTotal.substring(0,jsonStrTotal.length-1);
var strNew = '[{';
//strNew = strNew + '\"label\" :' + '\"' + me.cmb.getValue() + '\",';
strNew = strNew + '\"label\" :' + '\"' + cmbValue + '\",';
var strOld = '\"' + 'demographicData' + '\"' + ':[' + jsonStrTotal +']';
strNew = strNew + strOld + '}]';
demographicTrends.push(JSON.parse(strNew));
for (var l = 0; l < this.Output2.count(); l++)
{
// if (this.Output2[l].label == cmbValue)
// {
// //this.Output2[l].demographicData.add = JSON.parse('[' + jsonStrTotal + ']');
// for(var t=0; t<this.Output2[l].demographicData.count(); t++)
// {
// if (this.Output2[l].demographicData[t]["@class"] == ".EmploymentDemographicData")
// {
// this.Output2[l].demographicData.removeAt(t);
// }
// }
// }
//this.Output2[l].demographicData.add(JSON.parse('[' + jsonStrTotal + ']'));
//// this.Output2[l].demographicData = JSON.parse('[' + jsonStrTotal + ']');
}
var emp =[];
emp.push(JSON.parse('[' + jsonStrTotal + ']'));
for (var l = 0; l < this.Output2.count(); l++)
{
if (this.Output2[l].label == cmbValue)
{
///this.Output[l].demographicData = JSON.parse('[' + jsonStrTotal + ']');
}
if (this.Output2[l].label == cmbValue)
{
//this.Output[l].demographicData.add = JSON.parse('[' + jsonStrTotal + ']');
for(var t=0; t<this.Output2[l].demographicData.count(); t++)
{
if (this.Output2[l].demographicData[t]["@class"] == ".EmploymentDemographicData")
{
////this.Output[l].demographicData.removeAt(t);
}
else if (this.Output2[l].demographicData[t]["@class"] == ".ResidentialDemographicData")
{
emp[0].push(this.Output2[l].demographicData[t]);
}
}
}
//////this.Output[l].demographicData.add(JSON.parse('[' + jsonStrTotal + ']'));
}
for (var l = 0; l < this.Output2.count(); l++)
{
if (this.Output2[l].label == cmbValue)
{
this.Output2[l].demographicData = emp[0];
}
}
var ccc=0;
return true;
}, //end build
build : function() {
var me = this, projectId = this.project.projectId;
me.isLoadingExisting = true;
var definition = this.project.getDefinition();
if (definition.demographicTrends != undefined)
//if(this.Output2 != undefined)
{
var rows = definition.demographicTrends;
//var rows = this.Output2;
var st='[';
for (var i = 0; i< rows.length; i++)
{
st = st + '{\"label\":' + '\"' + rows[i].label+ '\"},';
}
st = st.substring(0,st.length-1) + ']';
var arr=[];
arr.push(JSON.parse(st));
this.cmbStore.removeAll();
this.cmbStore.load(JSON.parse(st));
this.cmb.store.loadData(JSON.parse(st),false);
this.cmb.bindStore(this.cmbStore);
}
return true;
}, //end build function
validate : function(callback) {
var me = this, gridValid = true;
me.store.each(function(record) {
if (!record.isValid()) {
_.log(this, 'validate', 'record is not valid');
gridValid = false;
}
});
if (!gridValid) {
Ext.Msg.alert('Status', 'All fields should have values!');
return false;
}
if (me.cmb.getValue() != undefined){
me.saveGrid(me.cmb.getValue());
}
var definition = me.project.getDefinition();
Ext.merge(definition, {
demographicTrends:this.Output2
});
me.project.setDefinition(definition);
_.log(this, 'validate', _.translate3(this.store.data.items, me.sectorTranslators), me.project.getDefinition());
if (callback) {
_.log(this, 'callback');
callback();
}
return true;
}
});
| AURIN/online-whatif-ui | src/main/webapp/js/wif/setup/trend/trendnewEmploymentCard.js | JavaScript | gpl-3.0 | 17,630 |
package org.dicadeveloper.weplantaforest.trees;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface UserRepository extends CrudRepository<User, Long> {
@Query
public User findByName(@Param("name") String name);
}
| Gab0rB/weplantaforest | user/src/main/java/org/dicadeveloper/weplantaforest/trees/UserRepository.java | Java | gpl-3.0 | 358 |
const Clutter = imports.gi.Clutter;
const Lang = imports.lang;
const ModalDialog = imports.ui.modalDialog;
const Signals = imports.signals;
const St = imports.gi.St;
const Gettext = imports.gettext;
const _ = Gettext.domain('gnome-shell-extensions-scriptproxies').gettext;
const EditProxyDialog = new Lang.Class({
Name: 'EditProxyDialog',
Extends: ModalDialog.ModalDialog,
_init: function(callback, action) {
this.callback = callback;
this.action = action;
this.parent({
styleClass: 'prompt-dialog'
});
let label, buttons;
if (this.action == 'add') {
buttons = [{
label: _('Cancel'),
action: Lang.bind(this, this._onCancelButton),
key: Clutter.Escape
}, {
label: _('Add proxy'),
action: Lang.bind(this, this._addButton)
}];
label = new St.Label({
style_class: 'edit-proxy-dialog-label',
text: _('Enter the name for the new proxy')
});
} else if (this.action == 'edit') {
buttons = [{
label: _('Cancel'),
action: Lang.bind(this, this._onCancelButton),
key: Clutter.Escape
}, {
label: _('Modify script'),
action: Lang.bind(this, this._modifyButton)
}, {
label: _('Rename'),
action: Lang.bind(this, this._renameButton)
}];
label = new St.Label({
style_class: 'edit-proxy-dialog-label',
text: _('Modify the proxy script.') + '\n' + _('Or rename it (leave blank to remove the proxy).')
});
} else {
// this should be this.action == 'editor'
buttons = [{
label: _('Cancel'),
action: Lang.bind(this, this._onCancelButton),
key: Clutter.Escape
}, {
label: _('OK'),
action: Lang.bind(this, this._onSetEditorButton)
}];
label = new St.Label({
style_class: 'edit-proxy-dialog-label',
text: _('To edit your proxy script,') + '\n' + _('please provide the binary name of your text editor.')
});
}
this.contentLayout.add(label, {
y_align: St.Align.START
});
let entry = new St.Entry({
style_class: 'edit-proxy-dialog-entry'
});
entry.label_actor = label;
this._entryText = entry.clutter_text;
this.contentLayout.add(entry, {
y_align: St.Align.START
});
this.setInitialKeyFocus(this._entryText);
this.setButtons(buttons);
this._entryText.connect('key-press-event', Lang.bind(this, function(o, e) {
let symbol = e.get_key_symbol();
if (symbol == Clutter.Return || symbol == Clutter.KP_Enter) {
if (this.action == 'add')
this._addButton();
else if (this.action == 'edit')
this._renameButton();
else
this._onSetEditorButton();
}
}));
},
close: function() {
this.parent();
},
_onCancelButton: function() {
this.close();
},
_addButton: function() {
this.callback(this._entryText.get_text(), 'new');
this.close();
},
_modifyButton: function() {
this.callback(this._entryText.get_text(), 'modify');
this.close();
},
_renameButton: function() {
this.callback(this._entryText.get_text(), 'rename');
this.close();
},
_onSetEditorButton: function() {
this.callback(this._entryText.get_text());
this.close();
},
open: function(initialText) {
if (initialText === null) {
this._entryText.set_text('');
} else {
this._entryText.set_text(initialText);
}
this.parent();
}
});
Signals.addSignalMethods(EditProxyDialog.prototype);
| Eimji/gnome-shell-extension-scriptproxies | editProxyDialog.js | JavaScript | gpl-3.0 | 4,159 |
package com.sk89q.craftbook.circuits.gates.logic;
import org.bukkit.Server;
import com.sk89q.craftbook.ChangedSign;
import com.sk89q.craftbook.circuits.ic.AbstractIC;
import com.sk89q.craftbook.circuits.ic.AbstractICFactory;
import com.sk89q.craftbook.circuits.ic.ChipState;
import com.sk89q.craftbook.circuits.ic.IC;
import com.sk89q.craftbook.circuits.ic.ICFactory;
public class Dispatcher extends AbstractIC {
public Dispatcher(Server server, ChangedSign block, ICFactory factory) {
super(server, block, factory);
}
@Override
public String getTitle() {
return "Dispatcher";
}
@Override
public String getSignTitle() {
return "DISPATCHER";
}
@Override
public void trigger(ChipState chip) {
boolean value = chip.getInput(0);
boolean targetB = chip.getInput(1);
boolean targetC = chip.getInput(2);
if (targetB) {
chip.setOutput(1, value);
}
if (targetC) {
chip.setOutput(2, value);
}
}
public static class Factory extends AbstractICFactory {
public Factory(Server server) {
super(server);
}
@Override
public IC create(ChangedSign sign) {
return new Dispatcher(getServer(), sign, this);
}
@Override
public String getShortDescription() {
return "Send middle signal out high sides.";
}
@Override
public String[] getLineHelp() {
String[] lines = new String[] {null, null};
return lines;
}
}
}
| wizjany/craftbook | src/main/java/com/sk89q/craftbook/circuits/gates/logic/Dispatcher.java | Java | gpl-3.0 | 1,687 |
/*
* Copyright (C) 2017 University of Pittsburgh.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package edu.cmu.tetrad.annotation;
import edu.cmu.tetrad.algcomparison.algorithm.MultiDataSetAlgorithm;
import edu.cmu.tetrad.algcomparison.utils.HasKnowledge;
import edu.cmu.tetrad.algcomparison.utils.TakesIndependenceWrapper;
import edu.cmu.tetrad.algcomparison.utils.UsesScoreWrapper;
import java.util.List;
/**
*
* Sep 26, 2017 12:19:41 AM
*
* @author Kevin V. Bui (kvb2@pitt.edu)
*/
public class AlgorithmAnnotations extends AbstractAnnotations<Algorithm> {
private static final AlgorithmAnnotations INSTANCE = new AlgorithmAnnotations();
private AlgorithmAnnotations() {
super("edu.cmu.tetrad.algcomparison.algorithm", Algorithm.class);
}
public static AlgorithmAnnotations getInstance() {
return INSTANCE;
}
public List<AnnotatedClass<Algorithm>> filterOutExperimental(List<AnnotatedClass<Algorithm>> list) {
return filterOutByAnnotation(list, Experimental.class);
}
public boolean acceptMultipleDataset(Class clazz) {
return (clazz == null)
? false
: MultiDataSetAlgorithm.class.isAssignableFrom(clazz);
}
public boolean acceptKnowledge(Class clazz) {
return (clazz == null)
? false
: HasKnowledge.class.isAssignableFrom(clazz);
}
public boolean requireIndependenceTest(Class clazz) {
return (clazz == null)
? false
: TakesIndependenceWrapper.class.isAssignableFrom(clazz);
}
public boolean requireScore(Class clazz) {
return (clazz == null)
? false
: UsesScoreWrapper.class.isAssignableFrom(clazz);
}
public boolean handleUnmeasuredConfounder(Class clazz) {
return (clazz == null)
? false
: clazz.isAnnotationPresent(UnmeasuredConfounder.class);
}
}
| bd2kccd/tetradR | java/edu/cmu/tetrad/annotation/AlgorithmAnnotations.java | Java | gpl-3.0 | 2,669 |
<?php
/*
* Copyright (C) 2015-2018 P. Mergey
* 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/>.
*/
// Text
$_['text_title'] = 'Carte de crédit ou de débit (BluePay)';
$_['text_credit_card'] = 'Détails de la carte';
$_['text_description'] = 'Articles sur %s commande n°: %s';
$_['text_card_type'] = 'Type de carte';
$_['text_card_name'] = 'Nom de la carte : ';
$_['text_card_digits'] = 'Derniers numéros : ';
$_['text_card_expiry'] = 'Date d’expiration';
$_['text_transaction_error'] = 'Attention : une erreur s’est produite pendant le déroulement de l’opération - ';
// Entry
$_['entry_card'] = 'Nouvelle carte ou carte existante : ';
$_['entry_card_existing'] = 'Existant';
$_['entry_card_new'] = 'Nouveau';
$_['entry_card_save'] = 'Se souvenir des détails de la carte';
$_['entry_cc_owner'] = 'Titulaire de la carte';
$_['entry_cc_number'] = 'Numéro de la carte';
$_['entry_cc_start_date'] = 'Carte valable depuis la date';
$_['entry_cc_expire_date'] = 'Date d’expiration de la carte';
$_['entry_cc_cvv2'] = 'Cryptogramme visuel';
$_['entry_cc_address'] = 'Adresse';
$_['entry_cc_city'] = 'Localité';
$_['entry_cc_state'] = 'Pays';
$_['entry_cc_zipcode'] = 'Code postal';
$_['entry_cc_phone'] = 'Téléphone';
$_['entry_cc_email'] = 'Adresse électronique';
$_['entry_cc_choice'] = 'Sélectionner une carte existante';
| GizMecano/opencart-2-fr | catalog/language/fr-FR/extension/payment/bluepay_hosted.php | PHP | gpl-3.0 | 1,932 |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserAddress extends Model
{
// user_address table
protected $table = 'user_address';
}
| CodeforAustralia/vhs | app/Models/UserAddress.php | PHP | gpl-3.0 | 172 |
<?php
Echo "<br> <br> Online database API for Sketchware.<br>";
Echo "Created by Leivison Dias with the help of Marcos Vinicius.<br><br><br><br>";
Echo "To save data use the url below replacing \"suakey\" with the data key and \"seuvalue\" by the value of the given.<br>";
Echo "http://sketchwaresql.esy.es/setdata.php?key=suakey&value=seuvalue <br>";
Echo "the system will return the url http://sketchwaresql.esy.es/saved.php?suakey-seuvalue if the data is saved correctly.<br><br><br><br>";
Echo "To retrieve saved data, use the url below replacing \"suakeysalva\" with the given key.<br>";
Echo "http://sketchwaresql.esy.es/getdata.php?key=suakeysalva <br>";
Echo "the system will return to url http://sketchwaresql.esy.es/result.php?result=seuvaluesalvo, if the data is saved correctly in \"seuvalue\". <br><br><br><br>";
echo "<br><br>API de banco de dados online para Sketchware.<br>";
echo "Criado por Leivison Dias com a ajuda de Marcos Vinicius.<br><br><br><br>";
echo "Para salvar dados use a url abaixo substituindo \"suakey\" pela chave do dado e \"seuvalue\" pelo valor do dado.<br>";
echo "http://sketchwaresql.esy.es/setdata.php?key=suakey&value=seuvalue <br>";
echo "o sistema vai retornar a url http://sketchwaresql.esy.es/saved.php?suakey-seuvalue se o dado for salvo corretamente.<br><br><br><br>";
echo "Para recuperar dados salvos use a url abaixo substituindo \"suakeysalva\" pela chave do dado.<br>";
echo "http://sketchwaresql.esy.es/getdata.php?key=suakeysalva <br>";
echo "o sistema vai retornar a url http://sketchwaresql.esy.es/result.php?result=seuvaluesalvo, se o dado for salvo corretamente em \"seuvaluesalvo\".";
?> | LeivisonDias/sketchwaresql | index.php | PHP | gpl-3.0 | 1,667 |
// $Id: UMLReceptionSignalComboBoxModel.java 15837 2008-09-30 23:53:25Z bobtarling $
// Copyright (c) 1996-2006 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.behavior.common_behavior;
import java.util.Collection;
import org.argouml.kernel.Project;
import org.argouml.kernel.ProjectManager;
import org.argouml.model.Model;
import org.argouml.model.RemoveAssociationEvent;
import org.argouml.model.UmlChangeEvent;
import org.argouml.uml.ui.UMLComboBoxModel2;
/**
* The model for the signal combobox on the reception proppanel.
*/
public class UMLReceptionSignalComboBoxModel extends UMLComboBoxModel2 {
/**
* Constructor for UMLReceptionSignalComboBoxModel.
*/
public UMLReceptionSignalComboBoxModel() {
super("signal", false);
Model.getPump().addClassModelEventListener(this,
Model.getMetaTypes().getNamespace(), "ownedElement");
}
/*
* @see org.argouml.uml.ui.UMLComboBoxModel2#buildModelList()
*/
protected void buildModelList() {
Object target = getTarget();
if (Model.getFacade().isAReception(target)) {
Object rec = /*(MReception)*/ target;
removeAllElements();
Project p = ProjectManager.getManager().getCurrentProject();
Object model = p.getRoot();
setElements(Model.getModelManagementHelper()
.getAllModelElementsOfKindWithModel(
model,
Model.getMetaTypes().getSignal()));
setSelectedItem(Model.getFacade().getSignal(rec));
}
}
/*
* @see org.argouml.uml.ui.UMLComboBoxModel2#isValidElement(Object)
*/
protected boolean isValidElement(Object m) {
return Model.getFacade().isASignal(m);
}
/*
* @see org.argouml.uml.ui.UMLComboBoxModel2#getSelectedModelElement()
*/
protected Object getSelectedModelElement() {
if (getTarget() != null) {
return Model.getFacade().getSignal(getTarget());
}
return null;
}
/**
* Override UMLComboBoxModel2's default handling of RemoveAssociation. We
* get this from MDR for the previous signal when a different signal is
* selected. Don't let that remove it from the combo box. Only remove it if
* the signal was removed from the namespace.
* <p>
* @param evt the event describing the property change
*/
public void modelChanged(UmlChangeEvent evt) {
if (evt instanceof RemoveAssociationEvent) {
if ("ownedElement".equals(evt.getPropertyName())) {
Object o = getChangedElement(evt);
if (contains(o)) {
buildingModel = true;
if (o instanceof Collection) {
removeAll((Collection) o);
} else {
removeElement(o);
}
buildingModel = false;
}
}
} else {
super.propertyChange(evt);
}
}
}
| ckaestne/LEADT | workspace/argouml_diagrams/argouml-app/src/org/argouml/uml/ui/behavior/common_behavior/UMLReceptionSignalComboBoxModel.java | Java | gpl-3.0 | 4,665 |
Karma is a set of patches to access point software to get it to respond to probe requests not just for itself but for any ESSID requested. This allows the AP to act as a lure to draw in any clients probing for known networks.
<br><br>
The original Karma patches were released by Dino Dia Zovi for Madwifi, I then took over and ported the patches to Madwifi-ng and have now taken them to the new hostapd. (Robin @digininja)
<br><br>
<b>Author</b>
<br>
https://digi.ninja/karma/ | xtr4nge/module_karma | includes/about.php | PHP | gpl-3.0 | 477 |
/*******************************************************************************
* Copyright (c) 2012 Dmitry Tikhomirov.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Dmitry Tikhomirov - initial API and implementation
******************************************************************************/
package org.opensheet.client.mvc.views;
import org.opensheet.client.mvc.events.AppEvents;
import org.opensheet.client.widges.SheetToolBar;
import org.opensheet.client.widges.project.ProjectPanel;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
public class ProjectView extends View{
private LayoutContainer container;
Dispatcher dispatcher = Dispatcher.get();
public ProjectView(Controller controller) {
super(controller);
}
@Override
protected void handleEvent(AppEvent event) {
if (event.getType() == AppEvents.Project) {
LayoutContainer toolbar = (LayoutContainer) Registry.get(AppView.NORTH_PANEL);
if(toolbar.getItems().isEmpty() != true && !toolbar.getItem(0).getItemId().equalsIgnoreCase("sheetToolBarId")){
SheetToolBar sheetToolBar = new SheetToolBar();
toolbar.removeAll();
toolbar.add(sheetToolBar);
toolbar.layout();
}else if(toolbar.getItems().isEmpty()){
SheetToolBar sheetToolBar = new SheetToolBar();
toolbar.add(sheetToolBar);
toolbar.layout();
}
LayoutContainer wrapper = (LayoutContainer) Registry.get(AppView.CENTER_PANEL);
wrapper.removeAll();
wrapper.add(container);
wrapper.layout();
return;
}
}
@Override
protected void initialize() {
container = new LayoutContainer();
BorderLayout layout = new BorderLayout();
layout.setEnableState(false);
container.setLayout(layout);
ProjectPanel pp = new ProjectPanel();
// pp.doLoad();
container.add(pp, new BorderLayoutData(LayoutRegion.CENTER));
}
}
| treblereel/Opensheet | src/main/java/org/opensheet/client/mvc/views/ProjectView.java | Java | gpl-3.0 | 2,557 |
using UnityEngine;
using System.Collections;
public class ReadyToFightUI : MonoBehaviour {
public GameObject readyToFightButton = null;
private Mediator mediator = null;
void Start()
{
if( readyToFightButton == null )
{
Debug.Log( "Please set all game objects needed by the ReadyToFightUI component" );
return;
}
DataManager dataManager = DataManager.getDataManagerInstance();
if( dataManager == null )
{
Debug.Log( "The ReadyToFightUI component couldn't find the data manager" );
}
mediator = dataManager.mediator;
mediator.Subscribe<DataCommands.ReadyToFight>( this.onReadyToFight );
}
public void onReadyToFight( DataCommands.ReadyToFight cmd )
{
readyToFightButton.SetActive( cmd.isReady );
}
}
| JumboSchrimp/FantasyCrescendo | Assets/UIAssets/Scripts/CharacterSelection/ReadyToFightUI.cs | C# | gpl-3.0 | 750 |
/*
* Copyright 2005-2011 by BerryWorks Software, LLC. All rights reserved.
*
* This file is part of EDIReader. You may obtain a license for its use directly from
* BerryWorks Software, and you may also choose to use this software under the terms of the
* GPL version 3. Other products in the EDIReader software suite are available only by licensing
* with BerryWorks. Only those files bearing the GPL statement below are available under the GPL.
*
* EDIReader 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.
*
* EDIReader 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 EDIReader. If not,
* see <http://www.gnu.org/licenses/>.
*/
package com.berryworks.edireader.plugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A runtime data structure that optimizes the LoopDescriptors of a plugin
* for access by an EDI parser.
*
* @see com.berryworks.edireader.Plugin
*/
public class PluginPreparation
{
protected final Map<String, List<LoopDescriptor>> segmentMap = new HashMap<String, List<LoopDescriptor>>();
/**
* Constructs an instance given an array of LoopDescriptors.
* <p/>
* The LoopDescriptors typically are taken directly from the EDIPlugin for a given type of document.
*
* @param loops
*/
public PluginPreparation(LoopDescriptor[] loops)
{
if (loops == null)
return;
for (LoopDescriptor loop : loops)
{
String segmentName = loop.getFirstSegment();
List<LoopDescriptor> descriptorList = segmentMap.get(segmentName);
if (descriptorList == null)
{
descriptorList = new ArrayList<LoopDescriptor>();
segmentMap.put(segmentName, descriptorList);
}
descriptorList.add(loop);
}
}
/**
* Returns an ordered list of LoopDescriptors corresponding to loops that start with a
* given segment name.
* <p/>
* The LoopDescriptors appear in the same order as they were mentioned in the plugin.
*
* @param segment
* @return
*/
public List<LoopDescriptor> getList(String segment)
{
return segmentMap.get(segment);
}
}
| vonwenm/EDIReader | src/com/berryworks/edireader/plugin/PluginPreparation.java | Java | gpl-3.0 | 2,574 |
package com.cyborgJenn.alphaCentauri.utils;
import com.cyborgJenn.alphaCentauri.item.ModItems;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
public class AlphaCentauriTab extends CreativeTabs
{
public AlphaCentauriTab(int id, String name)
{
super(id, name);
this.setNoTitle();
this.setBackgroundImageName("cyborgutils.png");
}
@Override
public ItemStack getTabIconItem()
{
return new ItemStack(ModItems.Sword4);
}
@Override
public boolean hasSearchBar()
{
return false;
}
}
| JennyLeeP/AlphaCentauri | src/main/java/com/cyborgJenn/alphaCentauri/utils/AlphaCentauriTab.java | Java | gpl-3.0 | 566 |
// Decompiled with JetBrains decompiler
// Type: RaidRoomSectionLD
// Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 19851F1B-4780-4223-BA01-2C20F2CD781E
// Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Assembly-CSharp.dll
using UnityEngine;
public class RaidRoomSectionLD : MonoBehaviour
{
public int Weight;
public RaidRoomSectionLD()
{
base.\u002Ector();
}
private void OnDrawGizmos()
{
Gizmos.set_color(Color.get_yellow());
Gizmos.DrawSphere(Vector3.op_Addition(((Component) this).get_transform().get_position(), new Vector3(0.0f, 0.75f, 0.0f)), 0.75f);
}
}
| mater06/LEGOChimaOnlineReloaded | LoCO Client Files/Decompressed Client/Extracted DLL/Assembly-CSharp/RaidRoomSectionLD.cs | C# | gpl-3.0 | 741 |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the files COPYING and Copyright.html. COPYING can be found at the root *
* of the source code distribution tree; Copyright.html can be found at the *
* root level of an installed copy of the electronic HDF5 document set and *
* is linked from the top-level documents page. It can also be found at *
* http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have *
* access to either file, you may request a copy from help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifdef OLD_HEADER_FILENAME
#include <iostream.h>
#else
#include <iostream>
#endif
#include <string>
#include "H5Include.h"
#include "H5Exception.h"
#include "H5IdComponent.h"
#include "H5PropList.h"
#include "H5Object.h"
#include "H5AbstractDs.h"
#include "H5FaccProp.h"
#include "H5FcreatProp.h"
#include "H5DcreatProp.h"
#include "H5DxferProp.h"
#include "H5DataSpace.h"
#include "H5DataSet.h"
#include "H5CommonFG.h"
#include "H5Attribute.h"
#include "H5Group.h"
#include "H5File.h"
#include "H5Alltypes.h"
#ifndef H5_NO_NAMESPACE
namespace H5 {
#ifndef H5_NO_STD
using std::cerr;
using std::endl;
#endif // H5_NO_STD
#endif
//--------------------------------------------------------------------------
// Function: Group default constructor
///\brief Default constructor: creates a stub Group.
// Programmer Binh-Minh Ribler - 2000
// Modification
// Jul, 08 No longer inherit data member 'id' from IdComponent.
// - bugzilla 1068
//--------------------------------------------------------------------------
Group::Group() : H5Object(), id(0) {}
//--------------------------------------------------------------------------
// Function: Group copy constructor
///\brief Copy constructor: makes a copy of the original Group object.
///\param original - IN: Original group to copy
// Programmer Binh-Minh Ribler - 2000
// Modification
// Jul, 08 No longer inherit data member 'id' from IdComponent.
// - bugzilla 1068
//--------------------------------------------------------------------------
Group::Group(const Group& original) : H5Object(original)
{
id = original.getId();
incRefCount(); // increment number of references to this id
}
//--------------------------------------------------------------------------
// Function: Group::getLocId
///\brief Returns the id of this group.
///\return Id of this group
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
hid_t Group::getLocId() const
{
return( getId() );
}
//--------------------------------------------------------------------------
// Function: Group overloaded constructor
///\brief Creates a Group object using the id of an existing group.
///\param group_id - IN: Id of an existing group
// Programmer Binh-Minh Ribler - 2000
// Modification
// Jul, 08 No longer inherit data member 'id' from IdComponent.
// - bugzilla 1068
//--------------------------------------------------------------------------
Group::Group(const hid_t existing_id) : H5Object()
{
id = existing_id;
}
//--------------------------------------------------------------------------
// Function: Group overload constructor - dereference
///\brief Given a reference, ref, to an hdf5 group, creates a Group object
///\param obj - IN: Specifying location referenced object is in
///\param ref - IN: Reference pointer
///\param ref_type - IN: Reference type - default to H5R_OBJECT
///\exception H5::ReferenceException
///\par Description
/// \c obj can be DataSet, Group, or named DataType, that
/// is a datatype that has been named by DataType::commit.
// Programmer Binh-Minh Ribler - Oct, 2006
//--------------------------------------------------------------------------
Group::Group(H5Object& obj, void* ref, H5R_type_t ref_type) : H5Object()
{
try {
id = p_dereference(obj.getId(), ref, ref_type);
} catch (ReferenceException deref_error) {
throw ReferenceException("Group constructor - located by an H5Object",
deref_error.getDetailMsg());
}
}
//--------------------------------------------------------------------------
// Function: Group overload constructor - dereference
///\brief Given a reference, ref, to an hdf5 group, creates a Group object
///\param h5file - IN: Location referenced object is in
///\param ref - IN: Reference pointer
///\param ref_type - IN: Reference type - default to H5R_OBJECT
///\exception H5::ReferenceException
// Programmer Binh-Minh Ribler - Oct, 2006
//--------------------------------------------------------------------------
Group::Group(H5File& h5file, void* ref, H5R_type_t ref_type) : H5Object()
{
try {
id = p_dereference(h5file.getId(), ref, ref_type);
} catch (ReferenceException deref_error) {
throw ReferenceException("Group constructor - located by an H5File",
deref_error.getDetailMsg());
}
}
//--------------------------------------------------------------------------
// Function: Group overload constructor - dereference
///\brief Given a reference, ref, to an hdf5 group, creates a Group object
///\param attr - IN: Specifying location where the referenced object is in
///\param ref - IN: Reference pointer
///\param ref_type - IN: Reference type - default to H5R_OBJECT
///\exception H5::ReferenceException
// Programmer Binh-Minh Ribler - Oct, 2006
//--------------------------------------------------------------------------
Group::Group(Attribute& attr, void* ref, H5R_type_t ref_type) : H5Object()
{
try {
id = p_dereference(attr.getId(), ref, ref_type);
} catch (ReferenceException deref_error) {
throw ReferenceException("Group constructor - located by an Attribute",
deref_error.getDetailMsg());
}
}
//--------------------------------------------------------------------------
// Function: H5File::getObjType
///\brief This function was misnamed and will be deprecated in favor of
/// H5Object::getRefObjType; please use getRefObjType instead.
// Programmer Binh-Minh Ribler - May, 2004
// Note: Replaced by getRefObjType. - BMR - Jul, 2008
//--------------------------------------------------------------------------
H5G_obj_t Group::getObjType(void *ref, H5R_type_t ref_type) const
{
return(getRefObjType(ref, ref_type));
}
//--------------------------------------------------------------------------
// Function: Group::getRegion
///\brief Retrieves a dataspace with the region pointed to selected.
///\param ref - IN: Reference to get region of
/// ref_type - IN: Type of reference to get region of - default
///\return DataSpace instance
///\exception H5::GroupIException
// Programmer Binh-Minh Ribler - May, 2004
//--------------------------------------------------------------------------
DataSpace Group::getRegion(void *ref, H5R_type_t ref_type) const
{
try {
DataSpace dataspace(p_get_region(ref, ref_type));
return(dataspace);
}
catch (IdComponentException E) {
throw GroupIException("Group::getRegion", E.getDetailMsg());
}
}
//--------------------------------------------------------------------------
// Function: Group::getId
// Purpose: Get the id of this group
// Modification:
// May 2008 - BMR
// Class hierarchy is revised to address bugzilla 1068. Class
// AbstractDS and Attribute are moved out of H5Object. In
// addition, member IdComponent::id is moved into subclasses, and
// IdComponent::getId now becomes pure virtual function.
// Programmer Binh-Minh Ribler - May, 2008
//--------------------------------------------------------------------------
hid_t Group::getId() const
{
return(id);
}
//--------------------------------------------------------------------------
// Function: Group::p_setId
///\brief Sets the identifier of this group to a new value.
///
///\exception H5::IdComponentException when the attempt to close the
/// currently open group fails
// Description:
// The underlaying reference counting in the C library ensures
// that the current valid id of this object is properly closed.
// Then the object's id is reset to the new id.
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void Group::p_setId(const hid_t new_id)
{
// handling references to this old id
try {
close();
}
catch (Exception close_error) {
throw GroupIException("Group::p_setId", close_error.getDetailMsg());
}
// reset object's id to the given id
id = new_id;
}
//--------------------------------------------------------------------------
// Function: Group::close
///\brief Closes this group.
///
///\exception H5::GroupIException
// Programmer Binh-Minh Ribler - Mar 9, 2005
//--------------------------------------------------------------------------
void Group::close()
{
if (p_valid_id(id))
{
herr_t ret_value = H5Gclose( id );
if( ret_value < 0 )
{
throw GroupIException("Group::close", "H5Gclose failed");
}
// reset the id when the group that it represents is no longer
// referenced
if (getCounter() == 0)
id = 0;
}
}
//--------------------------------------------------------------------------
// Function: Group::throwException
///\brief Throws H5::GroupIException.
///\param func_name - Name of the function where failure occurs
///\param msg - Message describing the failure
///\exception H5::GroupIException
// Description
// This function is used in CommonFG implementation so that
// proper exception can be thrown for file or group. The
// argument func_name is a member of CommonFG and "Group::"
// will be inserted to indicate the function called is an
// implementation of Group.
// Programmer Binh-Minh Ribler - 2000
//--------------------------------------------------------------------------
void Group::throwException(const H5std_string& func_name, const H5std_string& msg) const
{
H5std_string full_name = func_name;
full_name.insert(0, "Group::");
throw GroupIException(full_name, msg);
}
//--------------------------------------------------------------------------
// Function: Group destructor
///\brief Properly terminates access to this group.
// Programmer Binh-Minh Ribler - 2000
// Modification
// - Replaced resetIdComponent() with decRefCount() to use C
// library ID reference counting mechanism - BMR, Feb 20, 2005
// - Replaced decRefCount with close() to let the C library
// handle the reference counting - BMR, Jun 1, 2006
//--------------------------------------------------------------------------
Group::~Group()
{
try {
close();
}
catch (Exception close_error) {
cerr << "Group::~Group - " << close_error.getDetailMsg() << endl;
}
}
#ifndef H5_NO_NAMESPACE
} // end namespace
#endif
| glentner/Gadget | Source/hdf5-1.6.10/c++/src/H5Group.cpp | C++ | gpl-3.0 | 11,238 |
package SchwartzSet;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.WritableComparable;
/**
* Datatype containing an array of {@link IntWritable IntWritables}.
*
* @author -----
*
*/
public class IntArrayWritable implements WritableComparable<Object> {
/**
* Array of {@link IntWritable IntWritables}.
*/
public IntWritable[] values;
/**
* Constructs an {@link IntArrayWritable} with an array of length N.
* @param N number of {@link IntWritable IntWritables} in the object
*/
public IntArrayWritable(int N) {
values = new IntWritable[N];
}
/**
* Constructs an {@link IntArrayWritable} with an array of length 0.
*/
public IntArrayWritable() {
values = new IntWritable[0];
}
/**
* Constructs an {@link IntArrayWritable} containing the input array values.
* @param values array of {@link IntWritable IntWritables}
*/
public IntArrayWritable(IntWritable[] values) {
this.values = values;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(values.length);
for(int i=0; i<values.length; i++){
values[i].write(out);
}
}
@Override
public void readFields(DataInput in) throws IOException {
values = new IntWritable[in.readInt()];
for (int i=0; i<values.length; i++){
IntWritable value = new IntWritable();
value.readFields(in);
values[i]=value;
}
}
@Override
public int compareTo(Object o) {
IntArrayWritable other = (IntArrayWritable) o;
return(this.values[1].compareTo(other.values[1]));
}
public void setValues(int[] values) {
this.values = new IntWritable[values.length];
for(int i=0; i<values.length; i++){
this.values[i].set(values[i]);
}
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
IntArrayWritable other = (IntArrayWritable) obj;
if(values.length != other.values.length){
return false;
}
for (int i=0; i<values.length; i++){
if(values[i].get()!=other.values[i].get()){
return false;
}
}
return true;
}
@Override
public int hashCode() {
if (values == null) {
return 0;
}
if(values.length==0){
return 0;
}
return values[0].hashCode()+values.length*13;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.valueOf(values.length));
if(values.length>0) {
sb.append(",");
for (int i = 0; i < values.length; i++) {
sb.append(values[i].toString());
if (i != values.length - 1) {
sb.append(",");
}
}
}
return sb.toString();
}
} | theresacsar/BigVoting | MR_SchwartzSet/src/SchwartzSet/IntArrayWritable.java | Java | gpl-3.0 | 2,708 |
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Tag;
class TagController extends Controller
{
public function index()
{
$tags = Tag::select('id', 'name')->get();
return response()->json(compact('tags'));
}
}
| tradzero/blog | app/Http/Controllers/Api/TagController.php | PHP | gpl-3.0 | 307 |
<?php
/*
* This file is part of the 2amigos/yii2-usuario project.
*
* (c) 2amigOS! <http://2amigos.us/>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Da\User\Command;
use Da\User\Factory\MailFactory;
use Da\User\Model\User;
use Da\User\Service\UserCreateService;
use Da\User\Traits\ContainerAwareTrait;
use Yii;
use yii\console\Controller;
use yii\helpers\Console;
class CreateController extends Controller
{
use ContainerAwareTrait;
public function actionIndex($email, $username, $password = null, $role = null)
{
/** @var User $user */
$user = $this->make(
User::class,
[],
['scenario' => 'create', 'email' => $email, 'username' => $username, 'password' => $password]
);
$mailService = MailFactory::makeWelcomeMailerService($user);
if ($this->make(UserCreateService::class, [$user, $mailService])->run()) {
$this->stdout(Yii::t('usuario', 'User has been created') . "!\n", Console::FG_GREEN);
if (null !== $role) {
$this->assignRole($user, $role);
}
} else {
$this->stdout(Yii::t('usuario', 'Please fix following errors:') . "\n", Console::FG_RED);
foreach ($user->errors as $errors) {
foreach ($errors as $error) {
$this->stdout(' - ' . $error . "\n", Console::FG_RED);
}
}
}
}
protected function assignRole(User $user, $role)
{
$auth = Yii::$app->getAuthManager();
if (false === $auth) {
$this->stdout(
Yii::t(
'usuario',
'Cannot assign role "{0}" as the AuthManager is not configured on your console application.',
$role
) . "\n",
Console::FG_RED
);
} else {
$userRole = $auth->getRole($role);
if (null === $userRole) {
$this->stdout(Yii::t('usuario', 'Role "{0}" not found. Creating it.') . "!\n", Console::FG_GREEN);
$userRole = $auth->createRole($role);
$auth->add($userRole);
}
$auth->assign($userRole, $user->id);
}
}
}
| patschwork/meta_grid | meta_grid/vendor/2amigos/yii2-usuario/src/User/Command/CreateController.php | PHP | gpl-3.0 | 2,359 |
#total_ordering_student.py
import functools
@functools.total_ordering
class Student:
def __init__(self, firstname, lastname): #姓和名
self.firstname = firstname
self.lastname = lastname
def __eq__(self, other): #判断姓名是否一致
return ((self.lastname.lower(), self.firstname.lower()) ==
(other.lastname.lower(), other.firstname.lower()))
def __lt__(self, other): #self姓名<other姓名
return ((self.lastname.lower(), self.firstname.lower()) <
(other.lastname.lower(), other.firstname.lower()))
#测试代码
if __name__ == '__main__':
s1 = Student('Mary','Clinton')
s2 = Student('Mary','Clinton')
s3 = Student('Charlie','Clinton')
print(s1==s2)
print(s1>s3)
| GH1995/tools | archives/Python_江老师给的代码/chapter09/total_ordering_student.py | Python | gpl-3.0 | 777 |
// Decompiled with JetBrains decompiler
// Type: System.Web.Util.Profiler
// Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll
using System.Collections;
using System.Runtime;
using System.Web;
namespace System.Web.Util
{
internal class Profiler
{
private int _requestsToProfile;
private Queue _requests;
private bool _pageOutput;
private bool _isEnabled;
private bool _oldEnabled;
private bool _localOnly;
private bool _mostRecent;
private TraceMode _outputMode;
internal bool IsEnabled
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._isEnabled;
}
set
{
this._isEnabled = value;
this._oldEnabled = value;
}
}
internal bool PageOutput
{
get
{
if (!this._pageOutput)
return false;
if (this._localOnly)
return HttpContext.Current.Request.IsLocal;
return true;
}
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] set
{
this._pageOutput = value;
}
}
internal TraceMode OutputMode
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._outputMode;
}
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] set
{
this._outputMode = value;
}
}
internal bool LocalOnly
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._localOnly;
}
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] set
{
this._localOnly = value;
}
}
internal bool MostRecent
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._mostRecent;
}
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] set
{
this._mostRecent = value;
}
}
internal bool IsConfigEnabled
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._oldEnabled;
}
}
internal int RequestsToProfile
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._requestsToProfile;
}
set
{
if (value > 10000)
value = 10000;
this._requestsToProfile = value;
}
}
internal int RequestsRemaining
{
get
{
return this._requestsToProfile - this._requests.Count;
}
}
internal Profiler()
{
this._requestsToProfile = 10;
this._outputMode = TraceMode.SortByTime;
this._localOnly = true;
this._mostRecent = false;
this._requests = new Queue(this._requestsToProfile);
}
internal void Reset()
{
this._requests = new Queue(this._requestsToProfile);
if (this._requestsToProfile != 0)
this._isEnabled = this._oldEnabled;
else
this._isEnabled = false;
}
internal void StartRequest(HttpContext context)
{
context.Trace.VerifyStart();
}
internal void EndRequest(HttpContext context)
{
context.Trace.EndRequest();
if (!this.IsEnabled)
return;
lock (this._requests)
{
this._requests.Enqueue((object) context.Trace.GetData());
if (this.MostRecent)
{
if (this._requests.Count > this._requestsToProfile)
this._requests.Dequeue();
}
}
if (this.MostRecent || this._requests.Count < this._requestsToProfile)
return;
this.EndProfiling();
}
internal void EndProfiling()
{
this._isEnabled = false;
}
internal IList GetData()
{
return (IList) this._requests.ToArray();
}
}
}
| mater06/LEGOChimaOnlineReloaded | LoCO Client Files/Decompressed Client/Extracted DLL/System.Web/System/Web/Util/Profiler.cs | C# | gpl-3.0 | 4,449 |
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, Response
from celery import Celery
from werkzeug.utils import secure_filename
from VideoPlayer import VideoPlayer
from subprocess import Popen
import os
app = Flask(__name__)
local = False
if local:
UPLOAD_FOLDER = '/home/dabo02/Desktop/Projects/Side_Projects/Upwork_Tom_VideoShowroom/static/video/'
else:
UPLOAD_FOLDER='/home/pi/Desktop/Upwork_Tom_VideoShowroom/static/video/'
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(24, GPIO.OUT)
app.config['CELERY_BROKER_URL'] = 'amqp://'
app.config['CELERY_RESULT_BACKEND'] = 'amqp://'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
ALLOWED_EXTENSIONS = set(['mp3', 'mp4'])
light_state = False
exit_flag = False
current_video = None
preview_video = ''
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def check_for_current():
global current_video
if not current_video:
list_of_videos = os.listdir(UPLOAD_FOLDER)
current_video = list_of_videos[0]
@celery.task
def main_routine():
vp = VideoPlayer()
while True:
mag_switch = GPIO.input(23)
if mag_switch:
if not vp.video_is_playing:
GPIO.output(24, 0)
check_for_current()
global current_video
vp.set_video(UPLOAD_FOLDER + current_video)
vp.play_video()
else:
GPIO.output(24, 1)
vp.stop_video()
@app.route('/')
def dashboard():
video_list = os.listdir(UPLOAD_FOLDER)
video_info = {}
videos = []
global current_video
global preview_video
global light_state
preview = ''
for v in video_list:
if current_video:
if current_video in v:
current = True
else:
current = False
else:
current = False
if preview_video:
if preview_video in v:
preview = v
name = v.rsplit('.', 1)[0]
video_info = {'name': name, 'id': v, 'current': current}
videos.append(video_info)
return render_template('index.html', videos=videos, preview=preview, light_state=light_state)
@app.route('/upload_video', methods=['POST'])
def upload_video():
if 'video' not in request.files:
flash('No file part')
return redirect(url_for('dashboard'))
file = request.files['video']
if file.filename == '':
flash('No selected file')
return redirect(url_for('dashboard'))
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
return redirect(url_for('dashboard'))
@app.route('/remove_video/<id>', methods=['GET'])
def remove_video(id):
video_to_remove = UPLOAD_FOLDER + '/' + id
os.remove(os.path.join(app.config['UPLOAD_FOLDER'], video_to_remove))
return redirect(url_for('dashboard'))
@app.route('/update_video/<id>', methods=['GET'])
def change_current_video(id):
new_video = id
global current_video
current_video = new_video
return redirect(url_for('dashboard'))
@app.route('/preview_video/<id>', methods=['GET'])
def preview_current_video(id):
global preview_video
preview_video = id
return redirect(url_for('dashboard'))
@app.route('/light_state/<state>', methods=['GET'])
def light_state(state):
global light_state
if state in 'True':
GPIO.output(24, 1)
light_state = True
return redirect(url_for('dashboard'))
GPIO.output(24, 0)
light_state = False
return redirect(url_for('dashboard'))
@app.route('/start')
def start_loop():
task = main_routine.apply_async()
return redirect(url_for('dashboard'))
@app.route('/reboot')
def reboot_pi():
GPIO.cleanup()
Popen('reboot', shell=True)
return '<div><h1>Rebooting Pi.....</h1></div>'
@app.route('/shutdown')
def shutdown_pi():
GPIO.cleanup()
Popen('shutdown -h now', shell=True)
return '<div><h1>Shutting Down Pi.....</h1></div>'
if __name__ == '__main__':
if local:
app.run(host='localhost', port=3000)
else:
app.run(host='0.0.0.0', port=3500)
| dabo02/Upwork_Tom_VideoShowroom | Back-End.py | Python | gpl-3.0 | 4,500 |
package com.baeldung.samples.java.vavr;
import java.util.ArrayList;
import java.util.List;
import io.vavr.collection.Stream;
/**
*
* @author baeldung
*/
public class VavrSampler {
static int[] intArray = new int[] { 1, 2, 4 };
static List<Integer> intList = new ArrayList<>();
static int[][] intOfInts = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
public static void main(String[] args) {
vavrStreamElementAccess();
System.out.println("====================================");
vavrParallelStreamAccess();
System.out.println("====================================");
vavrFlatMapping();
System.out.println("====================================");
vavrStreamManipulation();
System.out.println("====================================");
vavrStreamDistinct();
}
public static void vavrStreamElementAccess() {
System.out.println("Vavr Element Access");
System.out.println("====================================");
Stream<Integer> vavredStream = Stream.ofAll(intArray);
System.out.println("Vavr index access: " + vavredStream.get(2));
System.out.println("Vavr head element access: " + vavredStream.get());
Stream<String> vavredStringStream = Stream.of("foo", "bar", "baz");
System.out.println("Find foo " + vavredStringStream.indexOf("foo"));
}
public static void vavrParallelStreamAccess() {
System.out.println("Vavr Stream Concurrent Modification");
System.out.println("====================================");
Stream<Integer> vavrStream = Stream.ofAll(intList);
// intList.add(5);
vavrStream.forEach(i -> System.out.println("in a Vavr Stream: " + i));
// Stream<Integer> wrapped = Stream.ofAll(intArray);
// intArray[2] = 5;
// wrapped.forEach(i -> System.out.println("Vavr looped " + i));
}
public static void jdkFlatMapping() {
System.out.println("Java flatMapping");
System.out.println("====================================");
java.util.stream.Stream.of(42).flatMap(i -> java.util.stream.Stream.generate(() -> {
System.out.println("nested call");
return 42;
})).findAny();
}
public static void vavrFlatMapping() {
System.out.println("Vavr flatMapping");
System.out.println("====================================");
Stream.of(42)
.flatMap(i -> Stream.continually(() -> {
System.out.println("nested call");
return 42;
}))
.get(0);
}
public static void vavrStreamManipulation() {
System.out.println("Vavr Stream Manipulation");
System.out.println("====================================");
List<String> stringList = new ArrayList<>();
stringList.add("foo");
stringList.add("bar");
stringList.add("baz");
Stream<String> vavredStream = Stream.ofAll(stringList);
vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
Stream<String> vavredStream2 = vavredStream.insert(2, "buzz");
vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
Stream<String> deletionStream = vavredStream.remove("bar");
deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
}
public static void vavrStreamDistinct() {
Stream<String> vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
Stream<String> distinctVavrStream = vavredStream.distinctBy((y, z) -> {
return y.compareTo(z);
});
distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
}
}
| Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/vavr/src/main/java/com/baeldung/samples/java/vavr/VavrSampler.java | Java | gpl-3.0 | 4,000 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage Amazon
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php,v 1.1.2.4 2011-05-30 08:30:48 root Exp $
*/
/**
* Zend_Service_Exception
*/
require_once 'Zend/Service/Exception.php';
/**
* @category Zend
* @package Zend_Service
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_Amazon_Exception extends Zend_Service_Exception
{} | MailCleaner/MailCleaner | www/framework/Zend/Service/Amazon/Exception.php | PHP | gpl-3.0 | 1,146 |
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
#define all(t) begin(t), end(t)
#define sp << " " <<
long gcd(long m, long n) {
while (m != 0) {
long k = n%m;
n=m;
m=k;
}
return n;
}
bool is_square(long S) {
long sqr = sqrt(S);
return sqr*sqr == S;
}
int main() {
long sum{0};
while (cin) {
long n;
cin >> n;
if (cin) {if (is_square(n)) {cout << n << endl;sum += n;}}
}
cout << endl << sum << endl;
}
| frits-scholer/pr | pr141/test.cpp | C++ | gpl-3.0 | 511 |
/**
* barsuift-simlife is a life simulator program
*
* Copyright (C) 2010 Cyrille GACHOT
*
* This file is part of barsuift-simlife.
*
* barsuift-simlife 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.
*
* barsuift-simlife 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 barsuift-simlife. If not, see
* <http://www.gnu.org/licenses/>.
*/
package barsuift.simLife.j3d.tree;
import java.util.ArrayList;
import java.util.List;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Transform3D;
public class MockTreeBranch3D implements TreeBranch3D {
private List<TreeLeaf3D> leaves;
private float length;
private float radius;
private BranchGroup branchGroup;
private TreeBranch3DState state;
private int synchronizedCalled;
private int increaseOneLeafSizeCalled;
private Transform3D transform;
public MockTreeBranch3D() {
super();
reset();
}
public void reset() {
leaves = new ArrayList<TreeLeaf3D>();
length = 0;
radius = 0;
branchGroup = new BranchGroup();
state = new TreeBranch3DState();
synchronizedCalled = 0;
increaseOneLeafSizeCalled = 0;
transform = new Transform3D();
}
@Override
public List<TreeLeaf3D> getLeaves() {
return leaves;
}
@Override
public void addLeaf(TreeLeaf3D leaf3D) {
leaves.add(leaf3D);
}
public void removeLeaf(TreeLeaf3D leaf3D) {
leaves.remove(leaf3D);
}
@Override
public float getLength() {
return length;
}
public void setLength(float length) {
this.length = length;
}
@Override
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
}
@Override
public BranchGroup getBranchGroup() {
return branchGroup;
}
public void setGroup(BranchGroup branchGroup) {
this.branchGroup = branchGroup;
}
@Override
public TreeBranch3DState getState() {
return state;
}
public void setState(TreeBranch3DState state) {
this.state = state;
}
@Override
public void synchronize() {
this.synchronizedCalled++;
}
public int getNbSynchronize() {
return synchronizedCalled;
}
@Override
public void increaseOneLeafSize() {
this.increaseOneLeafSizeCalled++;
}
public int getNbIncreaseOneLeafSizeCalled() {
return increaseOneLeafSizeCalled;
}
@Override
public Transform3D getTransform() {
return transform;
}
public void setTransform(Transform3D transform) {
this.transform = transform;
}
}
| sdp0et/barsuift-simlife | simLifeDisplayAPI/src/test/java/barsuift/simLife/j3d/tree/MockTreeBranch3D.java | Java | gpl-3.0 | 3,316 |
<?php
require_once('/wamp/www/banp/nobelba_data/common/DbMgr.php');
//SignUp
//This is test
class MASTERREGISTER
{
//**************** UserMaster Register **************
function registerusermaster($userexist)
{
//Check User Input
if (!empty($_POST["inputemail"]) && !empty($_POST["inputpass"])) {
$newemail = $_POST['inputemail'];
$newpassword = $_POST['inputpass'];
$phoneNo = $_POST['inputph'];
//Check if the user exist or not
$sqluserexist = 'SELECT email FROM user_detail WHERE email = ?';
try {
$dbh = DbMgr::getDB();
$stmt = $dbh->prepare($sqluserexist);
$ret = $stmt->execute(array($newemail));
if (!$ret) {
print("Authentication Error");
exit();
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$data = array($result ['email']);
} catch (Exception $e) {
print('Error:'.$e->getMessage());
die();
}
echo "This is user exit" .$userexist."" ;
echo "This is user Email in DB" .$result['email']. "" ;
echo "This is user Email input" .$_POST["inputemail"]. "";
if (($_POST["inputemail"] == $result['email'])) {
$userexist = 1;
return $userexist;
} else {
echo "I am inside Registration";
//If User Does Not Exist then proceed for registration
//Register User Data
$sql = "INSERT INTO user_detail(email, password, phone_no) VALUES (
'$newemail','$newpassword','$phoneNo')";
try {
$dbh = DbMgr::getDB();
$stmt = $dbh->prepare($sql);
$ret = $stmt->execute();
if (!$ret) {
print("Errro in Registraion");
exit();
}
} catch (Exception $e) {
print('Error:'.$e->getMessage());
die();
}
//Send Email for Authentication
require "phpmailer/class.phpmailer.php";
$Auth_URL = "http://nobelprize.aimjapan.org/authenticate.php/sjeiw7w829290102929";
// Instantiate Class
try {
$mail = new PHPMailer();
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Host = "smtp.lolipop.jp"; //SMTP server address
$mail->Port = 465; //SMTP port
$mail->Encoding = '7bit';
// Authentication
$mail->Username = "yogesh@shintensystems.com"; // Your full Address
$mail->Password = "yogesh1123"; // Your Email password
$mail->From = "admin@nobelprizetobrambedkar.com";
$mail->Subject = "Welcome to Nobel Prize To Dr. Ambedkar Nomination";
$body = ' Jai Bhim!! <br /><br />
Thank you for registering to Nominate Dr. B.R.Ambedkar for Nobel Prize <br /><br />
User ID = '.$_POST['inputemail'].'<br />
Password = '.$_POST['inputpass'].'<br /><br />
Please click below URL to complte your registration <br />
'.$Auth_URL.'<br /><br /><br />
Regards <br />
Team AIM Japan <br />
http://nobelprize.aimjapan.org/ <br />
';
$to = $_POST["inputemail"];
$mail->AddAddress($to);
$mail->MsgHTML($body);
$mail->Send();
} catch (phpmailerException $e) {
echo $e->errorMessage();
}
$userexist = 2;
return $userexist;
}
}
}
}
?>
| ShintenSystems/banp | nobelba/master_register.php | PHP | gpl-3.0 | 3,141 |
import React, { Component } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { Components, registerComponent } from "@reactioncommerce/reaction-components";
class CardHeader extends Component {
static defaultProps = {
actAsExpander: false,
expandable: false
};
static propTypes = {
actAsExpander: PropTypes.bool,
children: PropTypes.node,
expandOnSwitchOn: PropTypes.bool,
expanded: PropTypes.bool,
i18nKeyTitle: PropTypes.string,
icon: PropTypes.string,
imageView: PropTypes.node,
onClick: PropTypes.func,
onSwitchChange: PropTypes.func,
showSwitch: PropTypes.bool,
switchName: PropTypes.string,
switchOn: PropTypes.bool,
title: PropTypes.string
};
handleClick = (event) => {
event.preventDefault();
if (typeof this.props.onClick === "function") {
this.props.onClick(event);
}
}
handleSwitchChange = (event, isChecked, name) => {
if (this.props.expandOnSwitchOn && this.props.actAsExpander && this.props.expanded === false && isChecked === true) {
this.handleClick(event);
}
if (typeof this.props.onSwitchChange === "function") {
this.props.onSwitchChange(event, isChecked, name);
}
}
renderTitle() {
if (this.props.title) {
return (
<Components.CardTitle
i18nKeyTitle={this.props.i18nKeyTitle}
title={this.props.title}
/>
);
}
return null;
}
renderImage() {
if (this.props.icon) {
return (
<div className="image">
<Components.Icon icon={this.props.icon} />
</div>
);
}
if (this.props.imageView) {
return (
<div className="image">
{this.props.imageView}
</div>
);
}
return null;
}
renderDisclsoureArrow() {
const expanderClassName = classnames({
rui: true,
expander: true,
open: this.props.expanded
});
return (
<div className={expanderClassName}>
<Components.IconButton
icon="fa fa-angle-down"
bezelStyle="outline"
style={{ borderColor: "#dddddd" }}
onClick={this.handleClick}
/>
</div>
);
}
renderChildren() {
if (this.props.showSwitch) {
return (
<Components.Switch
checked={this.props.switchOn}
name={this.props.switchName}
onChange={this.handleSwitchChange}
/>
);
}
return this.props.children;
}
render() {
const baseClassName = classnames({
"rui": true,
"panel-heading": true,
"card-header": true,
"expandable": this.props.actAsExpander
});
if (this.props.actAsExpander) {
return (
<div className={baseClassName}>
<div className="content-view" onClick={this.handleClick}>
{this.renderImage()}
{this.renderTitle()}
</div>
<div className="action-view">
{this.renderChildren()}
</div>
{this.renderDisclsoureArrow()}
</div>
);
}
return (
<div className={baseClassName}>
<div className="content-view">
{this.renderTitle()}
</div>
<div className="action-view">
{this.props.children}
</div>
</div>
);
}
}
registerComponent("CardHeader", CardHeader);
export default CardHeader;
| xxbooking/reaction | imports/plugins/core/ui/client/components/cards/cardHeader.js | JavaScript | gpl-3.0 | 3,437 |
/**
* libz80
* Copyright (C) 2015 David Jolly
* ----------------------
*
* libz80 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.
*
* libz80 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 <fstream>
#include "../include/z80.h"
#include "../include/z80_assembler_type.h"
namespace Z80_NS {
namespace Z80_LANG_NS {
#define CODE_COUNT 1
#define CODE_EXTENDED 2
#define CODE_OFFSET 0
#define COND_EXPRESSION_COUNT 3
#define COND_EXPRESSION_OPERAND_LEFT 0
#define COND_EXPRESSION_OPERAND_RIGHT 2
#define COND_EXPRESSION_OPERATOR 1
#define DEFS_EXPRESSION_COUNT 2
#define DEFS_EXPRESSION_OFFSET 1
#define DEFS_EXPRESSION_VALUE_OFFSET 0
#define EXPRESSION_COUNT_MIN 1
#define EXPRESSION_LEFT_OFF 0
#define EXPRESSION_RIGHT_OFF 1
#define IF_CONDITIONAL_COUNT_MAX 3
#define IF_CONDITIONAL_COUNT_MIN 2
#define IF_CONDITIONAL_ID_OFF 0
#define IF_CONDITIONAL_STMT_MAIN_OFF 1
#define IF_CONDITIONAL_STMT_AUX_OFF 2
#define MACRO_CHILD_OFF 0
#define MACRO_COUNT 1
#define OPERATOR_CHILD_OFF 0
#define OPERATOR_COUNT 1
#define UNARY_OPERATOR_CHILD_OFF 0
#define UNARY_OPERATOR_COUNT 1
#define THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT(_EXCEPT_, _TOK_, _VERB_) \
THROW_Z80_ASSEMBLER_EXCEPTION_MESSAGE(_EXCEPT_, \
"%s\n%lu:%s", CHECK_STR(z80_token::as_string(_TOK_)), \
(TOKEN_CONTEXT_ROW((_TOK_).context()) + 1), \
CHECK_STR(z80_token::token_exception_as_string((_TOK_).context(), _VERB_)))
#define THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(_EXCEPT_, _TOK_, _VERB_, _FORMAT_, ...) \
THROW_Z80_ASSEMBLER_EXCEPTION_MESSAGE(_EXCEPT_, _FORMAT_ "\n%lu:%s", __VA_ARGS__, \
(TOKEN_CONTEXT_ROW((_TOK_).context()) + 1), \
CHECK_STR(z80_token::token_exception_as_string((_TOK_).context(), _VERB_)))
bool
operator==(
__in const z80_bin_t &left,
__in const z80_bin_t &right
)
{
bool result;
size_t iter = 0;
TRACE_ENTRY();
result = (&left == &right);
if(!result) {
result = (left.size() == right.size());
if(result) {
for(; iter < left.size(); ++iter) {
if(left.at(iter) != right.at(iter)) {
result = false;
break;
}
}
}
}
TRACE_EXIT("Return Value: 0x%x", result);
return result;
}
bool
operator!=(
__in const z80_bin_t &left,
__in const z80_bin_t &right
)
{
bool result;
TRACE_ENTRY();
result = !(left == right);
TRACE_EXIT("Return Value: 0x%x", result);
return result;
}
bool
operator==(
__in const z80_lst_t &left,
__in const z80_lst_t &right
)
{
bool result;
z80_lst_t::const_iterator iter, right_iter;
TRACE_ENTRY();
result = (&left == &right);
if(!result) {
result = (left.size() == right.size());
if(result) {
for(iter = left.begin(); iter != left.end(); ++iter) {
right_iter = right.find(iter->first);
if((right_iter == right.end())
|| (right_iter->second != iter->second)) {
result = false;
break;
}
}
}
}
TRACE_EXIT("Return Value: 0x%x", result);
return result;
}
bool
operator!=(
__in const z80_lst_t &left,
__in const z80_lst_t &right
)
{
bool result;
TRACE_ENTRY();
result = !(left == right);
TRACE_EXIT("Return Value: 0x%x", result);
return result;
}
_z80_assembler::_z80_assembler(
__in_opt const std::string &input,
__in_opt bool is_file
)
{
TRACE_ENTRY();
z80_assembler::set(input, is_file);
TRACE_EXIT("Return Value: 0x%x", 0);
}
_z80_assembler::_z80_assembler(
__in const _z80_assembler &other
) :
z80_parser(other),
m_binary(other.m_binary),
m_identifier_map(other.m_identifier_map),
m_label_map(other.m_label_map)
{
TRACE_ENTRY();
TRACE_EXIT("Return Value: 0x%x", 0);
}
_z80_assembler::~_z80_assembler(void)
{
TRACE_ENTRY();
TRACE_EXIT("Return Value: 0x%x", 0);
}
_z80_assembler &
_z80_assembler::operator=(
__in const _z80_assembler &other
)
{
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
z80_parser::operator=(other);
m_binary = other.m_binary;
m_identifier_map = other.m_identifier_map;
m_label_map = other.m_label_map;
TRACE_EXIT("Return Value: 0x%p", this);
return *this;
}
z80_bin_t
_z80_assembler::binary(void)
{
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
TRACE_EXIT("Return Value: size: %lu", m_binary.size());
return m_binary;
}
std::string
_z80_assembler::binary_as_string(
__in const z80_bin_t &binary,
__in_opt bool verbose
)
{
size_t iter = 0;
std::stringstream result;
TRACE_ENTRY();
if(verbose) {
result << "Binary size: " << std::setprecision(3)
<< (binary.size() / BYTES_PER_KBYTE)
<< " KB (" << binary.size() << " bytes)"
<< std::endl;
}
for(; iter < binary.size(); ++iter) {
if(!(iter % BLOCK_LEN)) {
if(iter) {
result << std::endl;
}
result << VALUE_AS_HEX(uint16_t, iter) << " |";
}
result << " " << VALUE_AS_HEX(uint8_t, binary.at(iter));
}
TRACE_EXIT("Return Value: %s", CHECK_STR(result.str()));
return result.str();
}
void
_z80_assembler::clear(void)
{
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
z80_parser::reset();
m_binary.clear();
m_identifier_map.clear();
m_label_map.clear();
TRACE_EXIT("Return Value: 0x%x", 0);
}
size_t
_z80_assembler::discover(void)
{
size_t result;
z80_node_factory_ptr node_fact = NULL;
z80_token_factory_ptr tok_fact = NULL;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
node_fact = z80_node_factory::acquire();
tok_fact = z80_token_factory::acquire();
z80_assembler::clear();
run_preprocessor(tok_fact, node_fact);
run_assembler(tok_fact, node_fact);
result = m_binary.size();
TRACE_EXIT("Return Value: size: %lu", result);
return result;
}
void
_z80_assembler::evaluate_command(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__inout bool &exit_condition
)
{
uint16_t val;
uint32_t code;
z80_token tok;
size_t iter, off;
z80_command_info_comp_t info;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_CODE) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(Z80_ASSEMBLER_EXCEPTION_EXPECTING_COMMAND,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
if(!tok.length()) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
code = tok.code();
if(!determine_command_simple(tok.subtype())) {
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if(node.children().size() == CODE_COUNT) {
val = evaluate_expression(statement, node.children().at(CODE_OFFSET), origin,
token_factory, node_factory);
info = determine_command_information(tok.subtype(), tok.mode());
if(determine_command_relative(tok.subtype())) {
if(val > origin) {
val = (val - origin - tok.length()) % UINT8_MAX;
} else {
val = UINT8_MAX - ((origin - val) % UINT8_MAX)
- (info.first.second - info.second.size());
}
}
off = info.second.front();
if(info.second.size() == CODE_EXTENDED) {
((uint8_t *) &code)[off] = (val & UINT8_MAX);
((uint8_t *) &code)[++off] = ((val >> BITS_PER_BYTE) & UINT8_MAX);
} else {
((uint8_t *) &code)[off] = (val & UINT8_MAX);
}
}
}
for(iter = 0; iter < tok.length(); ++iter) {
m_binary.push_back((code >> (iter * BITS_PER_BYTE)) & UINT8_MAX);
}
origin += tok.length();
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit);
}
void
_z80_assembler::evaluate_directive(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__in const std::string &base_path,
__inout bool &exit_condition
)
{
uint8_t val;
z80_token tok;
std::string text;
size_t len, count = 0;
z80_lst_t::iterator iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_DIRECTIVE) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(Z80_ASSEMBLER_EXCEPTION_EXPECTING_DIRECTIVE,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
switch(tok.subtype()) {
case DIRECTIVE_DEFINE:
tok = z80_parser::acquire_token(statement, ++offset,
token_factory, node_factory);
if(tok.type() != TOKEN_IDENTIFIER) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_IDENTIFIER,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
text = tok.text();
iter = m_identifier_map.find(text);
if(iter != m_identifier_map.end()) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_DUPLICATE_DEFINITION,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
m_identifier_map.insert(std::pair<std::string, uint16_t>(text,
evaluate_expression(statement, ++offset, origin,
token_factory, node_factory)));
break;
case DIRECTIVE_DEFINE_BYTE:
case DIRECTIVE_DEFINE_WORD:
evaluate_expression_list(statement, ++offset, origin, token_factory,
node_factory, exit_condition, tok.subtype() == DIRECTIVE_DEFINE_WORD);
break;
case DIRECTIVE_DEFINE_SPACE: {
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if(node.children().size() != DEFS_EXPRESSION_COUNT) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
val = evaluate_expression(statement, node.children().at(DEFS_EXPRESSION_VALUE_OFFSET),
origin, token_factory, node_factory);
len = evaluate_expression(statement, node.children().at(DEFS_EXPRESSION_OFFSET),
origin, token_factory, node_factory);
for(; count < len; ++count) {
m_binary.push_back(val);
}
origin += len;
} break;
case DIRECTIVE_END_SEGMENT:
exit_condition = true;
break;
case DIRECTIVE_IF_CONDITIONAL: {
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if((node.children().size() < IF_CONDITIONAL_COUNT_MIN)
|| (node.children().size() > IF_CONDITIONAL_COUNT_MAX)) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
if(evaluate_expression_conditional(statement,
node.children().at(IF_CONDITIONAL_ID_OFF),
origin, token_factory, node_factory)) {
evaluate_statement_list(statement,
node.children().at(IF_CONDITIONAL_STMT_MAIN_OFF),
origin, token_factory, node_factory,
exit_condition);
} else if(node.children().size() == IF_CONDITIONAL_COUNT_MAX) {
evaluate_statement_list(statement,
node.children().at(IF_CONDITIONAL_STMT_AUX_OFF),
origin, token_factory, node_factory,
exit_condition);
}
} break;
case DIRECTIVE_IF_DEFINED: {
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if((node.children().size() < IF_CONDITIONAL_COUNT_MIN)
|| (node.children().size() > IF_CONDITIONAL_COUNT_MAX)) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, node.children().at(IF_CONDITIONAL_ID_OFF),
token_factory, node_factory);
if(tok.type() != TOKEN_IDENTIFIER) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_IDENTIFIER,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
if(m_identifier_map.find(tok.text()) != m_identifier_map.end()) {
evaluate_statement_list(statement,
node.children().at(IF_CONDITIONAL_STMT_MAIN_OFF),
origin, token_factory, node_factory,
exit_condition);
} else if(node.children().size() == IF_CONDITIONAL_COUNT_MAX) {
evaluate_statement_list(statement,
node.children().at(IF_CONDITIONAL_STMT_AUX_OFF),
origin, token_factory, node_factory,
exit_condition);
}
} break;
case DIRECTIVE_INCLUDE:
break;
case DIRECTIVE_INCLUDE_BINARY: {
tok = z80_parser::acquire_token(statement, ++offset,
token_factory, node_factory);
if(tok.type() != TOKEN_LITERAL_STRING) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_LITERAL_STRING,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
std::ifstream file(z80_lexer_base::base_path() + tok.text(),
std::ios::in | std::ios::binary);
if(!file) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_FILE_NOT_FOUND,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
file.seekg(0, std::ios::end);
len = file.tellg();
file.seekg(0, std::ios::beg);
for(; count < len; ++count) {
if(file.eof()) {
break;
}
m_binary.push_back(file.get());
}
file.close();
origin += len;
} break;
case DIRECTIVE_ORIGIN:
tok = z80_parser::acquire_token(statement, ++offset,
token_factory, node_factory);
if(tok.type() != TOKEN_IMMEDIATE) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_IMMEDIATE,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
origin = tok.value();
break;
case DIRECTIVE_UNDEFINE:
tok = z80_parser::acquire_token(statement, ++offset,
token_factory, node_factory);
if(tok.type() != TOKEN_IDENTIFIER) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_IDENTIFIER,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
iter = m_identifier_map.find(tok.text());
if(iter == m_identifier_map.end()) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_UNDEFINED_DEFINITION,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
m_identifier_map.erase(iter);
break;
default:
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_INVALID_DIRECTIVE,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit);
}
uint16_t
_z80_assembler::evaluate_expression(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory
)
{
z80_token tok;
uint16_t result = 0;
size_t expr_off = offset;
bool expr_header = false;
z80_node_child_lst_t::iterator child_iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if(tok.type() == TOKEN_EXPRESSION) {
expr_header = true;
if(node.children().size() < EXPRESSION_COUNT_MIN) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
expr_off = node.children().at(EXPRESSION_LEFT_OFF);
tok = z80_parser::acquire_token(statement, expr_off, token_factory,
node_factory);
}
switch(tok.type()) {
case TOKEN_EXPRESSION:
result = evaluate_expression(statement, expr_off, origin, token_factory,
node_factory);
break;
case TOKEN_MACRO: {
z80_node node = z80_parser::acquire_node(statement, expr_off, node_factory);
if(node.children().size() != MACRO_COUNT) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
result = evaluate_expression(statement, node.children().at(MACRO_CHILD_OFF),
origin, token_factory, node_factory);
switch(tok.subtype()) {
case MACRO_HIGH:
result = (result >> BITS_PER_BYTE) & UINT8_MAX;
break;
case MACRO_LOW:
result = result & UINT8_MAX;
break;
case MACRO_WORD:
break;
default:
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_INVALID_MACRO,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
} break;
case TOKEN_SYMBOL: {
z80_node node = z80_parser::acquire_node(statement, expr_off, node_factory);
if(node.children().size() != UNARY_OPERATOR_COUNT) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
result = evaluate_expression(statement, node.children().at(UNARY_OPERATOR_CHILD_OFF),
origin, token_factory, node_factory);
switch(tok.subtype()) {
case SYMBOL_ARITHMETIC_SUBTRACTION:
result *= -1;
break;
case SYMBOL_UNARY_NOT:
result = !result;
break;
default:
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_INVALID_UNARY_OPERATOR,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
} break;
default:
result = evaluate_expression_terminal(statement, expr_off, origin, token_factory,
node_factory);
break;
}
if(expr_header &&
(node.children().size() > EXPRESSION_COUNT_MIN)) {
for(child_iter = node.children().begin() + EXPRESSION_RIGHT_OFF;
child_iter != node.children().end(); ++child_iter) {
result = evaluate_expression_operator(statement, *child_iter, origin,
token_factory, node_factory, result);
}
}
TRACE_EXIT("Return Value: 0x%04x (off: %lu, org: 0x%04x)", result, offset, origin);
return result;
}
bool
_z80_assembler::evaluate_expression_conditional(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory
)
{
z80_token tok;
bool result = false;
uint16_t left, right;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_EXPRESSION_CONDITIONAL) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_EXPRESSION_CONDITIONAL,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if(node.children().size() != COND_EXPRESSION_COUNT) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
left = evaluate_expression(statement, node.children().at(COND_EXPRESSION_OPERAND_LEFT),
origin, token_factory, node_factory);
right = evaluate_expression(statement, node.children().at(COND_EXPRESSION_OPERAND_RIGHT),
origin, token_factory, node_factory);
tok = z80_parser::acquire_token(statement, node.children().at(COND_EXPRESSION_OPERATOR),
token_factory, node_factory);
if(tok.type() != TOKEN_SYMBOL) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_OPERATOR,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
switch(tok.subtype()) {
case SYMBOL_EQUALS:
result = (left == right);
break;
case SYMBOL_GREATER_THAN:
result = (left > right);
break;
case SYMBOL_GREATER_THAN_EQUALS:
result = (left >= right);
break;
case SYMBOL_LESS_THAN:
result = (left < right);
break;
case SYMBOL_LESS_THAN_EQUALS:
result = (left <= right);
break;
case SYMBOL_NOT_EQUALS:
result = (left != right);
break;
default:
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_INVALID_OPERATOR,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
TRACE_EXIT("Return Value: 0x%x (off: %lu, org: 0x%04x)", result, offset, origin);
return result;
}
void
_z80_assembler::evaluate_expression_list(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__inout bool &exit_condition,
__in_opt bool wide
)
{
uint16_t val;
z80_token tok;
std::string::iterator str_iter;
z80_node_child_lst_t::iterator iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_EXPRESSION_LIST) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(Z80_ASSEMBLER_EXCEPTION_EXPECTING_EXPRESSION_LIST,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
for(iter = node.children().begin(); iter != node.children().end(); ++iter) {
tok = z80_parser::acquire_token(statement, *iter, token_factory,
node_factory);
switch(tok.type()) {
case TOKEN_LITERAL_STRING:
for(str_iter = tok.text().begin(); str_iter != tok.text().end();
++str_iter) {
if(wide) {
m_binary.push_back(0);
origin += sizeof(uint8_t);
}
m_binary.push_back(*str_iter);
origin += sizeof(uint8_t);
}
break;
default:
val = evaluate_expression(statement, *iter, origin,
token_factory, node_factory);
if(wide) {
m_binary.push_back((val >> BITS_PER_BYTE) & UINT8_MAX);
origin += sizeof(uint8_t);
}
m_binary.push_back(val & UINT8_MAX);
origin += sizeof(uint8_t);
break;
}
}
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit_condition);
}
uint16_t
_z80_assembler::evaluate_expression_operator(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__in uint16_t current
)
{
z80_token tok;
uint16_t result = 0, right_result;
z80_node_child_lst_t::iterator child_iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_SYMBOL) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_OPERATOR,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if(node.children().size() < OPERATOR_COUNT) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
right_result = evaluate_expression(statement, node.children().at(OPERATOR_CHILD_OFF),
origin, token_factory, node_factory);
if(node.children().size() > OPERATOR_COUNT) {
for(child_iter = node.children().begin() + OPERATOR_COUNT;
child_iter != node.children().end();
++child_iter) {
result += evaluate_expression_operator(statement, *child_iter,
origin, token_factory, node_factory,
right_result);
}
} else {
switch(tok.subtype()) {
case SYMBOL_ARITHMETIC_ADDITION:
result = current + right_result;
break;
case SYMBOL_ARITHMETIC_DIVISION:
result = current / right_result;
break;
case SYMBOL_ARITHMETIC_MODULUS:
result = current % right_result;
break;
case SYMBOL_ARITHMETIC_MULTIPLICATION:
result = current * right_result;
break;
case SYMBOL_ARITHMETIC_SUBTRACTION:
result = current - right_result;
break;
case SYMBOL_BINARY_AND:
result = current & right_result;
break;
case SYMBOL_BINARY_OR:
result = current | right_result;
break;
case SYMBOL_BINARY_XOR:
result = current ^ right_result;
break;
case SYMBOL_SHIFT_LEFT:
result = current << right_result;
break;
case SYMBOL_SHIFT_RIGHT:
result = current >> right_result;
break;
default:
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_INVALID_OPERATOR,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
}
TRACE_EXIT("Return Value: 0x%04x (off: %lu, org: 0x%04x, curr: %lu)", result,
offset, origin, current);
return result;
}
uint16_t
_z80_assembler::evaluate_expression_terminal(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory
)
{
z80_token tok;
uint16_t result = 0;
z80_lst_t::iterator iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
switch(tok.type()) {
case TOKEN_CONSTANT:
result = tok.subtype();
break;
case TOKEN_IDENTIFIER:
iter = m_identifier_map.find(tok.text());
if(iter == m_identifier_map.end()) {
iter = m_label_map.find(tok.text());
if(iter == m_label_map.end()) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_UNDEFINED_DEFINITION,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
}
result = iter->second;
break;
case TOKEN_IMMEDIATE:
case TOKEN_LITERAL_CHARACTER:
result = tok.value();
break;
default:
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_INVALID_EXPRESSION_TERMINAL,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
TRACE_EXIT("Return Value: 0x%04x (off: %lu, org: 0x%04x)", result, offset, origin);
return result;
}
void
_z80_assembler::evaluate_preprocessor_command(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__inout bool &exit_condition
)
{
z80_token tok;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_CODE) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(Z80_ASSEMBLER_EXCEPTION_EXPECTING_COMMAND,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
origin += tok.length();
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit_condition);
}
void
_z80_assembler::evaluate_preprocessor_directive(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__in const std::string &base_path,
__inout bool &exit_condition
)
{
z80_token tok;
size_t len, pos;
std::string text;
z80_lst_t::iterator iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_DIRECTIVE) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(Z80_ASSEMBLER_EXCEPTION_EXPECTING_DIRECTIVE,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
switch(tok.subtype()) {
case DIRECTIVE_DEFINE:
tok = z80_parser::acquire_token(statement, ++offset,
token_factory, node_factory);
if(tok.type() != TOKEN_IDENTIFIER) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_IDENTIFIER,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
text = tok.text();
iter = m_identifier_map.find(text);
if(iter != m_identifier_map.end()) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_DUPLICATE_DEFINITION,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
m_identifier_map.insert(std::pair<std::string, uint16_t>(text,
evaluate_expression(statement, ++offset, origin,
token_factory, node_factory)));
break;
case DIRECTIVE_DEFINE_BYTE:
case DIRECTIVE_DEFINE_WORD:
evaluate_preprocessor_expression_list(statement, ++offset, origin, token_factory,
node_factory, exit_condition, tok.subtype() == DIRECTIVE_DEFINE_WORD);
break;
case DIRECTIVE_DEFINE_SPACE: {
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if(node.children().size() != DEFS_EXPRESSION_COUNT) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
origin += evaluate_expression(statement, node.children().at(DEFS_EXPRESSION_OFFSET),
origin, token_factory, node_factory);
} break;
case DIRECTIVE_END_SEGMENT:
exit_condition = true;
break;
case DIRECTIVE_IF_CONDITIONAL: {
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if((node.children().size() < IF_CONDITIONAL_COUNT_MIN)
|| (node.children().size() > IF_CONDITIONAL_COUNT_MAX)) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
if(evaluate_expression_conditional(statement,
node.children().at(IF_CONDITIONAL_ID_OFF),
origin, token_factory, node_factory)) {
evaluate_preprocessor_statement_list(statement,
node.children().at(IF_CONDITIONAL_STMT_MAIN_OFF),
origin, token_factory, node_factory,
exit_condition);
} else if(node.children().size() == IF_CONDITIONAL_COUNT_MAX) {
evaluate_preprocessor_statement_list(statement,
node.children().at(IF_CONDITIONAL_STMT_AUX_OFF),
origin, token_factory, node_factory,
exit_condition);
}
} break;
case DIRECTIVE_IF_DEFINED: {
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
if((node.children().size() < IF_CONDITIONAL_COUNT_MIN)
|| (node.children().size() > IF_CONDITIONAL_COUNT_MAX)) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, node.children().at(IF_CONDITIONAL_ID_OFF),
token_factory, node_factory);
if(tok.type() != TOKEN_IDENTIFIER) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_IDENTIFIER,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
if(m_identifier_map.find(tok.text()) != m_identifier_map.end()) {
evaluate_preprocessor_statement_list(statement,
node.children().at(IF_CONDITIONAL_STMT_MAIN_OFF),
origin, token_factory, node_factory,
exit_condition);
} else if(node.children().size() == IF_CONDITIONAL_COUNT_MAX) {
evaluate_preprocessor_statement_list(statement,
node.children().at(IF_CONDITIONAL_STMT_AUX_OFF),
origin, token_factory, node_factory,
exit_condition);
}
} break;
case DIRECTIVE_INCLUDE: {
tok = z80_parser::acquire_token(statement, ++offset,
token_factory, node_factory);
if(tok.type() != TOKEN_LITERAL_STRING) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_LITERAL_STRING,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
z80_parser par(z80_lexer_base::base_path() + tok.text(), true);
par.discover();
if(par.size()) {
pos = position();
if(par.statement() == par.statement_begin()) {
par.move_next_statement();
}
while(par.has_next_statement()) {
insert_statement(par.statement(), ++pos);
par.move_next_statement();
}
}
} break;
case DIRECTIVE_INCLUDE_BINARY: {
tok = z80_parser::acquire_token(statement, ++offset,
token_factory, node_factory);
if(tok.type() != TOKEN_LITERAL_STRING) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_LITERAL_STRING,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
std::ifstream file(z80_lexer_base::base_path() + tok.text(),
std::ios::in | std::ios::binary);
if(!file) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_FILE_NOT_FOUND,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
file.seekg(0, std::ios::end);
len = file.tellg();
file.close();
origin += len;
} break;
case DIRECTIVE_ORIGIN:
tok = z80_parser::acquire_token(statement, ++offset,
token_factory, node_factory);
if(tok.type() != TOKEN_IMMEDIATE) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_IMMEDIATE,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
origin = tok.value();
break;
case DIRECTIVE_UNDEFINE:
tok = z80_parser::acquire_token(statement, ++offset,
token_factory, node_factory);
if(tok.type() != TOKEN_IDENTIFIER) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_IDENTIFIER,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
iter = m_identifier_map.find(tok.text());
if(iter == m_identifier_map.end()) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_UNDEFINED_DEFINITION,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
m_identifier_map.erase(iter);
break;
default:
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_INVALID_DIRECTIVE,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit_condition);
}
void
_z80_assembler::evaluate_preprocessor_expression_list(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__inout bool &exit_condition,
__in_opt bool wide
)
{
z80_token tok;
z80_node_child_lst_t::iterator iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_EXPRESSION_LIST) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(Z80_ASSEMBLER_EXCEPTION_EXPECTING_EXPRESSION_LIST,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
for(iter = node.children().begin(); iter != node.children().end(); ++iter) {
tok = z80_parser::acquire_token(statement, *iter, token_factory,
node_factory);
switch(tok.type()) {
case TOKEN_LITERAL_STRING:
origin += (wide ? (sizeof(uint16_t) * tok.text().size()) : tok.text().size());
break;
default:
origin += (wide ? sizeof(uint16_t) : sizeof(uint8_t));
break;
}
}
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit_condition);
}
void
_z80_assembler::evaluate_preprocessor_label(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__inout bool &exit_condition
)
{
z80_token tok;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_LABEL) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(Z80_ASSEMBLER_EXCEPTION_EXPECTING_LABEL,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
if(m_label_map.find(tok.text()) != m_label_map.end()) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(Z80_ASSEMBLER_EXCEPTION_DUPLICATE_LABEL,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
m_label_map.insert(std::pair<std::string, uint16_t>(tok.text(), origin));
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit_condition);
}
void
_z80_assembler::evaluate_preprocessor_statement(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__inout bool &exit_condition
)
{
z80_token tok;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
if(!statement.empty()) {
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_STATEMENT) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_MALFORMED_STATEMENT,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
tok = z80_parser::acquire_token(statement, ++offset, token_factory,
node_factory);
switch(tok.type()) {
case TOKEN_CODE:
evaluate_preprocessor_command(statement, offset, origin,
token_factory, node_factory,
exit_condition);
break;
case TOKEN_DIRECTIVE:
evaluate_preprocessor_directive(statement, offset, origin,
token_factory, node_factory,
z80_lexer_base::base_path(),
exit_condition);
break;
case TOKEN_LABEL:
evaluate_preprocessor_label(statement, offset, origin,
token_factory, node_factory,
exit_condition);
break;
default:
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_INVALID_STATEMENT,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
}
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit_condition);
}
void
_z80_assembler::evaluate_preprocessor_statement_list(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__inout bool &exit_condition
)
{
z80_token tok;
z80_node_child_lst_t::iterator iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_STATEMENT_LIST) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_STATEMENT_LIST,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
for(iter = node.children().begin(); iter != node.children().end(); ++iter) {
evaluate_preprocessor_statement(statement, *iter, origin, token_factory,
node_factory, exit_condition);
}
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit_condition);
}
void
_z80_assembler::evaluate_statement(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__inout bool &exit_condition
)
{
z80_token tok;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!statement.empty()) {
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_STATEMENT) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_MALFORMED_STATEMENT,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
tok = z80_parser::acquire_token(statement, ++offset, token_factory,
node_factory);
switch(tok.type()) {
case TOKEN_CODE:
evaluate_command(statement, offset, origin, token_factory,
node_factory, exit_condition);
break;
case TOKEN_DIRECTIVE:
evaluate_directive(statement, offset, origin, token_factory,
node_factory, z80_lexer_base::base_path(),
exit_condition);
break;
case TOKEN_LABEL:
break;
default:
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_INVALID_STATEMENT,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
}
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit_condition);
}
void
_z80_assembler::evaluate_statement_list(
__in const z80_stmt_t &statement,
__inout size_t &offset,
__inout uint16_t &origin,
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory,
__inout bool &exit_condition
)
{
z80_token tok;
z80_node_child_lst_t::iterator iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
tok = z80_parser::acquire_token(statement, offset, token_factory,
node_factory);
if(tok.type() != TOKEN_STATEMENT_LIST) {
THROW_Z80_ASSEMBLER_EXCEPTION_CONTEXT_MESSAGE(
Z80_ASSEMBLER_EXCEPTION_EXPECTING_STATEMENT_LIST,
tok, true, "%s", CHECK_STR(tok.to_string()));
}
z80_node node = z80_parser::acquire_node(statement, offset, node_factory);
for(iter = node.children().begin(); iter != node.children().end(); ++iter) {
evaluate_statement(statement, *iter, origin, token_factory,
node_factory, exit_condition);
}
TRACE_EXIT("Return Value: off: %lu, org: 0x%04x, exit: 0x%x", offset, origin, exit_condition);
}
z80_lst_t
_z80_assembler::identifier(void)
{
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
TRACE_EXIT("Return Value: 0x%x", 0);
return m_identifier_map;
}
z80_lst_t
_z80_assembler::label(void)
{
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
TRACE_EXIT("Return Value: 0x%x", 0);
return m_label_map;
}
std::string
_z80_assembler::listing(void)
{
z80_lst_t::iterator iter;
std::stringstream result;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
for(iter = m_identifier_map.begin(); iter != m_identifier_map.end();
++iter) {
result << iter->first << LISTING_SYMBOL_SEPERATOR << LISTING_TYPE_IDENTIFIER
<< LISTING_SYMBOL_SEPERATOR << iter->second << std::endl;
}
for(iter = m_label_map.begin(); iter != m_label_map.end(); ++iter) {
result << iter->first << LISTING_SYMBOL_SEPERATOR << LISTING_TYPE_LABEL
<< LISTING_SYMBOL_SEPERATOR << iter->second << std::endl;
}
TRACE_EXIT("Return Value: %s", CHECK_STR(result.str()));
return result.str();
}
void
_z80_assembler::run_assembler(
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory
)
{
size_t offset;
z80_token tok;
z80_stmt_t stmt;
bool exit_condition = false;
uint16_t origin = ORIGIN_INIT;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
m_binary.clear();
m_identifier_map.clear();
z80_parser::reset();
if(statement() == statement_begin()) {
stmt = move_next_statement();
} else {
stmt = statement();
}
while(has_next_statement()) {
offset = 0;
if(stmt.empty()) {
THROW_Z80_ASSEMBLER_EXCEPTION_MESSAGE(Z80_ASSEMBLER_EXCEPTION_EMPTY_STATEMENT,
"pos: %lu", z80_parser::position());
}
evaluate_statement(stmt, offset, origin, token_factory, node_factory,
exit_condition);
if(exit_condition) {
break;
}
stmt = move_next_statement();
}
TRACE_EXIT("Return Value: 0x%x", 0);
}
void
_z80_assembler::run_preprocessor(
__in z80_token_factory_ptr token_factory,
__in z80_node_factory_ptr node_factory
)
{
size_t offset;
z80_token tok;
z80_stmt_t stmt;
bool exit_condition = false;
uint16_t origin = ORIGIN_INIT;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
if(!token_factory || !node_factory) {
THROW_Z80_ASSEMBLER_EXCEPTION(Z80_ASSEMBLER_EXCEPTION_INTERNAL_EXCEPTION);
}
z80_parser::reset();
if(statement() == statement_begin()) {
stmt = move_next_statement();
} else {
stmt = statement();
}
while(has_next_statement()) {
offset = 0;
if(stmt.empty()) {
THROW_Z80_ASSEMBLER_EXCEPTION_MESSAGE(Z80_ASSEMBLER_EXCEPTION_EMPTY_STATEMENT,
"pos: %lu", z80_parser::position());
}
evaluate_preprocessor_statement(stmt, offset, origin, token_factory,
node_factory, exit_condition);
if(exit_condition) {
break;
}
stmt = move_next_statement();
}
TRACE_EXIT("Return Value: 0x%x", 0);
}
void
_z80_assembler::set(
__in const std::string &input,
__in_opt bool is_file
)
{
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
z80_assembler::clear();
z80_parser::set(input, is_file);
TRACE_EXIT("Return Value: 0x%x", 0);
}
size_t
_z80_assembler::size(void)
{
size_t result;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
result = m_binary.size();
TRACE_EXIT("Return Value: %lu", result);
return result;
}
std::string
_z80_assembler::to_string(
__in_opt bool verbose
)
{
std::stringstream result;
z80_lst_t::iterator iter;
TRACE_ENTRY();
SERIALIZE_CALL_RECUR(m_lock);
result << binary_as_string(m_binary, verbose);
if(!m_binary.empty()) {
result << std::endl;
}
result << "Identifier[" << m_identifier_map.size() << "]";
if(verbose) {
for(iter = m_identifier_map.begin(); iter != m_identifier_map.end();
++iter) {
result << std::endl << "--- [" << VALUE_AS_HEX(uint16_t, iter->second)
<< "] " << iter->first;
}
}
result << std::endl << "Label[" << m_label_map.size() << "]";
if(verbose) {
for(iter = m_label_map.begin(); iter != m_label_map.end();
++iter) {
result << std::endl << "--- [" << VALUE_AS_HEX(uint16_t, iter->second)
<< "] " << iter->first;
}
}
TRACE_EXIT("Return Value: %s", CHECK_STR(result.str()));
return result.str();
}
}
}
| majestic53/libz80 | src/lib/src/z80_assembler.cpp | C++ | gpl-3.0 | 48,518 |
package microtrafficsim.core.vis.glui;
import com.jogamp.newt.event.KeyListener;
import microtrafficsim.core.vis.glui.events.MouseListener;
import microtrafficsim.core.vis.glui.renderer.ComponentRenderPass;
import microtrafficsim.math.Mat3d;
import microtrafficsim.math.Rect2d;
import microtrafficsim.math.Vec2d;
import java.util.ArrayList;
public abstract class Component {
protected UIManager manager = null;
protected ComponentRenderPass[] renderer = null;
protected Mat3d transform = Mat3d.identity();
protected Mat3d invtransform = Mat3d.identity();
protected Rect2d aabb = null;
protected Component parent = null;
protected ArrayList<Component> children = new ArrayList<>();
protected boolean focusable = true;
protected boolean focused = false;
protected boolean mouseover = false;
protected boolean active = true;
protected boolean visible = true;
private ArrayList<MouseListener> mouseListeners = new ArrayList<>();
private ArrayList<KeyListener> keyListeners = new ArrayList<>();
protected Component(ComponentRenderPass... renderer) {
this.renderer = renderer;
}
protected void setUIManager(UIManager manager) {
this.manager = manager;
for (Component c : children)
c.setUIManager(manager);
if (manager != null)
manager.redraw(this);
}
public UIManager getUIManager() {
return manager;
}
protected ComponentRenderPass[] getRenderPasses() {
return renderer;
}
public void setTransform(Mat3d transform) {
this.transform = transform;
this.invtransform = Mat3d.invert(transform);
redraw();
}
public Mat3d getTransform() {
return transform;
}
public Mat3d getInverseTransform() {
return invtransform;
}
protected void setBounds(Rect2d aabb) {
this.aabb = aabb;
redraw();
}
protected Rect2d getBounds() {
return aabb;
}
protected abstract boolean contains(Vec2d p);
public Component getParent() {
return parent;
}
protected void add(Component child) {
if (child.parent != null)
child.parent.remove(child);
children.add(child);
child.parent = this;
child.setUIManager(manager);
updateBounds();
redraw();
}
protected boolean remove(Component child) {
if (children.remove(child)) {
child.parent = null;
child.setUIManager(null);
updateBounds();
redraw();
return true;
}
return false;
}
protected ArrayList<Component> getComponents() {
return children;
}
protected void updateBounds() {
Rect2d aabb = new Rect2d(Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE);
for (Component c : children) {
Rect2d cbb = Rect2d.transform(c.transform, c.getBounds());
if (aabb.xmin > cbb.xmin) aabb.xmin = cbb.xmin;
if (aabb.xmax < cbb.xmax) aabb.xmax = cbb.xmax;
if (aabb.ymin > cbb.ymin) aabb.ymin = cbb.ymin;
if (aabb.ymax < cbb.ymax) aabb.ymax = cbb.ymax;
}
this.aabb = aabb;
}
public void redraw(boolean recursive) {
if (manager != null) {
if (recursive)
for (Component c : children)
c.redraw(true);
manager.redraw(this);
}
}
public void redraw() {
redraw(false);
}
public void setFocusable(boolean focusable) {
this.focusable = focusable;
if (manager != null)
manager.redraw(this);
}
public boolean isFocusable() {
return focusable;
}
public void setFocused(boolean focused) {
if (!focusable) return;
if (this.manager != null)
this.manager.setFocus(this);
}
public boolean isFocused() {
return focused;
}
public boolean isMouseOver() {
return mouseover;
}
public void setActive(boolean active) {
this.active = active;
if (manager != null)
manager.redraw(this);
}
public boolean isActive() {
return active;
}
public void setVisible(boolean visible) {
this.visible = visible;
if (manager != null)
manager.redraw(this);
}
public boolean isVisible() {
return visible;
}
public void addMouseListener(MouseListener listener) {
mouseListeners.add(listener);
}
public void removeMouseListener(MouseListener listener) {
mouseListeners.remove(listener);
}
public ArrayList<MouseListener> getMouseListeners() {
return mouseListeners;
}
public void addKeyListener(KeyListener listener) {
keyListeners.add(listener);
}
public void removeKeyListener(KeyListener listener) {
keyListeners.remove(listener);
}
public ArrayList<KeyListener> getKeyListeners() {
return keyListeners;
}
}
| sgs-us/microtrafficsim | microtrafficsim-core/src/main/java/microtrafficsim/core/vis/glui/Component.java | Java | gpl-3.0 | 5,134 |
import todsynth
import os
import numpy
import json
import pandas
class Calibrator( object ):
'''
A todsynth.calibrator object is a container that stores coefficients
that transform RAW dac units to physical units for a given TOD.
'''
# Calibrator description.
#000000000000000000000000000000000000000000000000000000000000000000000000
name = ""
description = ""
calType = ""
# Information stored in the form of a dictionary. Careful not to abuse
# of this in the sense of using it to process data!
info = {}
#000000000000000000000000000000000000000000000000000000000000000000000000
# Calibration coefficients
coeffs = numpy.empty(0)
# Detector index to Unique Identifier array
__uid = numpy.empty(0)
def __init__( self ):
'''
self.name = name
self.description = descrp
self.calType = calType
'''
def setCoeffs( self, c , uid=None ):
'''
Set calibrator coefficients to c.
'''
# Perform numpy.copy() to avoid cross referencing stuff
self.__coeffs = numpy.copy( c )
if uid is not None:
self.__uid = numpy.copy(uid)
self.coeffs = self.coeffs[ self.__uid ]
else:
self.__uid = numpy.arange( len( self.coeffs ) )
def getCoeffs( self ):
'''
Get a *copy* of the coefficients array.
'''
return numpy.copy( self.coeffs )
def updateInfo( self, prop, value ):
'''
Update calibrator info with a pair of prop : value
'''
self.info.update( { 'prop' : value } )
def storeInPath( self , outPath ):
'''
Stores the calibrator in JSON format at the specified path.
'''
# Serialize this object
data = {
'coefficients' : self.__coeffs,
'uid' : self.__uid }
# Create PANDAS DataFrame out data
df = pandas.DataFrame( data )
# Save DataFrame to HDF5 format
df.to_csv( os.path.join(
outPath, "%s.%s.cal" % (self.name,self.calType) ),
index=False,
sep=' ',
header=True )
@classmethod
def readFromPath( cls, systemPath ):
'''
'''
self = cls()
name,caltype,_ = os.path.basename( systemPath ).split('.')
self.name = name
self.calType = caltype
self.description = ''
# Load file
calDF = pandas.read_csv(
systemPath,
header=0,
names=['coefficients', 'uid'],
delimiter=' ' )
self.setCoeffs( calDF['coefficients'], uid = calDF['uid'] )
return self
| pafluxa/todsynth | build/lib.linux-x86_64-2.7/todsynth/calibration/calibrator.py | Python | gpl-3.0 | 2,810 |