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 |
|---|---|---|---|---|---|
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
public class Director : MonoBehaviour {
private List<GameObject> levelElements = new List<GameObject>();
private List<float> elementTimes = new List<float>();
private float right = 17.0f;
private float left = -19.0f;
public float levelSpeed = 0.5f;
public GameObject BG1, BG2, floor;
public GameObject dashable;
public GameObject GUIbg;
public CameraController cam;
public CharController pony;
public GUIText textBlob;
public enum Element{
CHANGER,
MEANNICE,
EVENTS
};
public static float normalSpeed = 0.5f;
public void SetSpeed(float speed) {
if (speed == 0)
levelSpeed = normalSpeed;
else
levelSpeed = speed;
floor.GetComponent<BackgroundScroller>().speed = levelSpeed;
BG1.GetComponent<BackgroundScroller>().speed = levelSpeed*.15f;
BG2.GetComponent<BackgroundScroller>().speed = levelSpeed*.75f;
}
int crashCounter = 0;
int dashCounter = 0;
public void ShowHitMessage(FaceController face) {
string message;
if ((pony.GetCurrentState() & CharController.State.BURST) == CharController.State.BURST) {
message = dashEffects[dashCounter];
dashCounter = Mathf.Min (dashEffects.Length-1, ++dashCounter);
GUIbg.renderer.material.SetColor("_TintColor", Color.blue);
StartCoroutine(fadeToFrom(Color.black, Color.blue));
face.Explode(true);
pony.Explode();
} else {
message = crashEffects[crashCounter];
cam.Shake();
face.Explode(true);
crashCounter = Mathf.Min (crashEffects.Length-1, ++crashCounter);
StartCoroutine(fadeToFrom(Color.black, Color.red));
GUIbg.renderer.material.SetColor("_TintColor", Color.red);
}
if (dashCounter+crashCounter >= crashEffects.Length + dashEffects.Length - 2) {
ended = true;
message = "That's all I got for you, Chen! :)";
}
textBlob.text = message;
}
private IEnumerator fadeToFrom(Color a, Color b) {
float completion = 0f;
while (completion < 0.8f) {
completion += Time.deltaTime;
Color c = Color.Lerp(a, b, completion);
GUIbg.renderer.material.SetColor("_TintColor", c);
yield return null;
}
// Return
completion = 0.2f;
while (completion < 1.0f) {
completion += Time.deltaTime;
Color c = Color.Lerp(b, a, completion);
GUIbg.renderer.material.SetColor("_TintColor", c);
yield return null;
}
yield return null;
}
void Start () {
Init ();
//print(GUIbg.renderer.material.GetColor("_TintColor") );
}
public static bool gamePaused = false;
public static bool ended = false;
public GUIText credits;
void Update () {
SpawnManager();
if (Input.GetKeyUp(KeyCode.Space)) {
Time.timeScale = 1.0f - Time.timeScale;
gamePaused = !gamePaused;
credits.text = (gamePaused||ended)?"Credits:\nAll game development: Keerthik\n" +
"Inspiration for raw material: Roydan\nA friend worth doing this for: CHYENN"
:"Press space to pause";
if (gamePaused) textBlob.text = "Press Space to upause the game";
else textBlob.text = "Z = Dash\nX = Jump";
}
/*
// Control game pacing
if (time > elementTimes[(int)(elementTimes.Count/2)])
normalSpeed = 0.750f;
*/
}
void OnGUI() {
if (gamePaused) {
if (GUI.Button(RelRect(0.3f, 0.7f, 0.15f, 0.05f), "Change Music")) {
MusicController.NextTrack();
}
if (GUI.Button(RelRect(0.55f, 0.7f, 0.15f, 0.05f), "Rewatch Intro")) {
Application.LoadLevel("IntroScene");
}
}
}
void Init() {
// Set parameters
levelSpeed = 0.5f;
normalSpeed = 0.5f;
levelElements = new List<GameObject>();
elementTimes = new List<float>();
for (int i = 0; i < crashEffects.Length+dashEffects.Length; i++) {
int thisY = Random.Range(1, 3);
levelElements.Add(Instantiate(dashable, new Vector3(30, floor.transform.position.y + 4 + 1.5f*thisY, pony.transform.position.z), Quaternion.identity) as GameObject);
levelElements[i].GetComponent<FaceController>().director = this;
elementTimes.Add(4.0f + i*(3.5f + 0.1f*i));
}
}
private float time = 0.0f;
private void SpawnManager() {
time += levelSpeed*Time.deltaTime;
// Manage adding new elements for leftover
if (elementTimes.Count < dashEffects.Length + crashEffects.Length - dashCounter - crashCounter) {
int thisY = Random.Range(1, 3);
levelElements.Add(Instantiate(dashable, new Vector3(30, floor.transform.position.y + 4 + 1.5f*thisY, pony.transform.position.z), Quaternion.identity) as GameObject);
levelElements[levelElements.Count-1].GetComponent<FaceController>().director = this;
elementTimes.Add(elementTimes[elementTimes.Count-1] + 5f);
}
// Manage spawning level Elements into game
for (int i=0; i<elementTimes.Count; i++) {
float timePos = time - elementTimes[i];
if (timePos > 0) {
GameObject element = levelElements[i];
element.transform.position = new Vector3(Mathf.Lerp(right, left, 0.5f*timePos), element.transform.position.y, pony.transform.position.z);
if (element.transform.position.x < left/2f) {
// dodge-effect
}
if (element.transform.position.x < left+.01f) {
Destroy(element);
levelElements.RemoveAt(i);
elementTimes.RemoveAt(i);
}
}
}
}
private Rect RelRect(float left, float top, float width, float height) {
return new Rect(left*Screen.width, top*Screen.height, width*Screen.width, height*Screen.height);
}
private string [] dashEffects = {
"You have forgiven me for all the mean things\n I've said to you (right?) ^_^\n" +
"[ Keep dashing through for me to not be mean ]",
"You are the first person who bought me a gift\n I always wanted [Oppa Gundam Style]",
"You were always a good friend to talk to \nwhen I was lonely and stuff",
"You are the only person I remembered to get\n anything(Halwa) for, even when \n" +
"I forgot to get anyone else stuff",
"I had a blast all the time we hung out\nwinter 2012! Quality single friends' time :) Thanks!",
"I just wanted to let you know, even when\nyou thought you were being whiny\n" +
"and sad, I was happy to talk to and\nhang out with you, and I hope \nI made you feel better~",
"You made it this far! I hope we can be\nthere for each other always!",
"Congratulations!!!\n You have just experienced the \nnicest thing I've done/made for anyone :)",
"This game took a total of around 75 hours for me to make\n - about 3 months of bart rides :O\n" +
"I hope you enjoyed it :)\n[ Feel free to keep playing \nto see the rest of the mean stuff ]",
};
private string [] crashEffects = {
"I enjoyed making you throw a shoe at Roydan ^_^\n\n" +
"[ Dash through these for nicer things, \n" +
"otherwise I'll say mean things ]",
"Mean as it was, that thing I said \ncomparing your writing papers to \n" +
"making relationships work was darn straight clever,\n" +
"right?",
"You're a jerk with how terribly you respond on IM",
"I found this on your facebook wall from me:\nYou're fugly\n -Albert",
"Oh that was when QED took over your wall for a night",
"Shortly before QED issued you an infraction notice teehee >:D",
"You dropped comparch in sophomore year \nand we gave you much crap about it :D",
"YOU'RE AS CRAZY AS ROYDAN SOMETIMES",
"Damn I should have more mean things to say to you...",
"Oh right. You're fat. Hehe. Moo",
"Gee, stop running into them *dash* through them~",
"Ok seriously, figure out the game already, and stop getting hit\n" +
"...unless you already finished it and just want to read the mean stuff :D",
};
} | keerthik/fluttercorn | Assets/Scripts/Director.cs | C# | gpl-3.0 | 7,502 |
from Products.CMFCore.utils import getToolByName
from cStringIO import StringIO
from Products.OpenPlans.Extensions.Install import installZ3Types
from Products.OpenPlans.Extensions.setup import migrate_listen_member_lookup
from Products.OpenPlans.Extensions.setup import reinstallSubskins
def migrate_listen(self):
out = StringIO()
# set listen to the active property configuration
portal_setup_tool = getToolByName(self, 'portal_setup')
portal_setup_tool.setImportContext('profile-listen:default')
out.write('updated generic setup tool properties\n')
# run the listen import step
portal_setup_tool.runImportStep('listen-various', True)
out.write('Listen import step run\n')
# remove the open mailing list fti
portal_types = getToolByName(self, 'portal_types')
portal_types.manage_delObjects(['Open Mailing List'])
out.write('open mailing list fti removed\n')
# now run the install z3types to add it back
installZ3Types(self, out)
out.write('z3 types installed (Open Mailing List fti)\n')
# migrate the listen local utility
# self, self?
migrate_listen_member_lookup(self, self)
out.write('listen member lookup utility migrated\n')
# remove openplans skins
portal_skins = getToolByName(self, 'portal_skins')
skins_to_remove = ['openplans', 'openplans_images', 'openplans_patches', 'openplans_richwidget', 'openplans_styles']
portal_skins.manage_delObjects(skins_to_remove)
out.write('removed openplans skins: %s\n' % ', '.join(skins_to_remove))
# reinstall openplans skins
portal_quickinstaller = getToolByName(self, 'portal_quickinstaller')
portal_quickinstaller.reinstallProducts(['opencore.siteui'])
out.write('reinstall opencore.siteui - openplans skins\n')
# reinstall subskins
reinstallSubskins(self, self)
out.write('subskins reinstalled\n')
# run listen migration?
return out.getvalue()
| socialplanning/opencore | Products/OpenPlans/Extensions/migrate_listen.py | Python | gpl-3.0 | 1,938 |
package org.mindroid.impl.statemachine.properties.sensorproperties;
import org.mindroid.api.statemachine.properties.IProperty;
import org.mindroid.api.statemachine.properties.SimpleEV3SensorProperty;
import org.mindroid.common.messages.hardware.Sensormode;
import org.mindroid.impl.ev3.EV3PortID;
/**
* Created by Torbe on 02.05.2017.
*/
public class Ambient extends SimpleEV3SensorProperty {
/**
*
* @param port brickport of the Ambient-mode running sensor
*/
public Ambient(EV3PortID port) {
super(port);
}
@Override
public IProperty copy() {
return new Ambient(getSensorPort());
}
@Override
public Sensormode getSensormode() {
return Sensormode.AMBIENT;
}
}
| Echtzeitsysteme/mindroid | impl/androidApp/api/src/main/java/org/mindroid/impl/statemachine/properties/sensorproperties/Ambient.java | Java | gpl-3.0 | 745 |
jQuery(window).load( function() {
if( local_data.form_id ) {
var pardot_id = local_data.form_id;
}
else{
var pardot_id = jQuery('[id^="form-wysija-"]').attr('id');
}
jQuery('.pardotform').contents().find('#pardot-form').submit(function () {
var ajax_data = {
action: 'pardot_capture_lead',
'firstname': jQuery("input[name='" + local_data.first_name + "']").val(),
'lastname': jQuery("input[name='" + local_data.last_name + "']").val(),
'email': jQuery("input[name='" + local_data.email + "']").val(),
'form_id': pardot_id,
}
jQuery.ajax( {
url: local_data.url,
type: 'POST',
dataType: 'json',
data: ajax_data,
});
});
}); | leadferry/lf-leads | leads/classes/vendors/js/pardot.js | JavaScript | gpl-3.0 | 673 |
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package cz.cuni.mff.d3s.tools.perfdoc.doclets.internal.toolkit.builders;
import java.util.*;
import com.sun.javadoc.*;
import cz.cuni.mff.d3s.tools.perfdoc.doclets.internal.toolkit.*;
import cz.cuni.mff.d3s.tools.perfdoc.doclets.internal.toolkit.util.*;
/**
* Builds documentation for a constructor.
*
* This code is not part of an API.
* It is implementation that is subject to change.
* Do not use it as an API
*
* @author Jamie Ho
* @author Bhavesh Patel (Modified)
* @since 1.5
*/
public class ConstructorBuilder extends AbstractMemberBuilder {
/**
* The name of this builder.
*/
public static final String NAME = "ConstructorDetails";
/**
* The index of the current field that is being documented at this point
* in time.
*/
private int currentConstructorIndex;
/**
* The class whose constructors are being documented.
*/
private ClassDoc classDoc;
/**
* The visible constructors for the given class.
*/
private VisibleMemberMap visibleMemberMap;
/**
* The writer to output the constructor documentation.
*/
private ConstructorWriter writer;
/**
* The constructors being documented.
*/
private List<ProgramElementDoc> constructors;
/**
* Construct a new ConstructorBuilder.
*
* @param configuration the current configuration of the
* doclet.
*/
private ConstructorBuilder(Configuration configuration) {
super(configuration);
}
/**
* Construct a new ConstructorBuilder.
*
* @param configuration the current configuration of the doclet.
* @param classDoc the class whoses members are being documented.
* @param writer the doclet specific writer.
*/
public static ConstructorBuilder getInstance(
Configuration configuration,
ClassDoc classDoc,
ConstructorWriter writer) {
ConstructorBuilder builder = new ConstructorBuilder(configuration);
builder.classDoc = classDoc;
builder.writer = writer;
builder.visibleMemberMap =
new VisibleMemberMap(
classDoc,
VisibleMemberMap.CONSTRUCTORS,
configuration.nodeprecated);
builder.constructors =
new ArrayList<ProgramElementDoc>(builder.visibleMemberMap.getMembersFor(classDoc));
for (int i = 0; i < builder.constructors.size(); i++) {
if (builder.constructors.get(i).isProtected()
|| builder.constructors.get(i).isPrivate()) {
writer.setFoundNonPubConstructor(true);
}
}
if (configuration.getMemberComparator() != null) {
Collections.sort(
builder.constructors,
configuration.getMemberComparator());
}
return builder;
}
/**
* {@inheritDoc}
*/
public String getName() {
return NAME;
}
/**
* {@inheritDoc}
*/
public boolean hasMembersToDocument() {
return constructors.size() > 0;
}
/**
* Returns a list of constructors that will be documented for the given class.
* This information can be used for doclet specific documentation
* generation.
*
* @return a list of constructors that will be documented.
*/
public List<ProgramElementDoc> members(ClassDoc classDoc) {
return visibleMemberMap.getMembersFor(classDoc);
}
/**
* Return the constructor writer for this builder.
*
* @return the constructor writer for this builder.
*/
public ConstructorWriter getWriter() {
return writer;
}
/**
* Build the constructor documentation.
*
* @param node the XML element that specifies which components to document
* @param memberDetailsTree the content tree to which the documentation will be added
*/
public void buildConstructorDoc(XMLNode node, Content memberDetailsTree) {
if (writer == null) {
return;
}
int size = constructors.size();
if (size > 0) {
Content constructorDetailsTree = writer.getConstructorDetailsTreeHeader(
classDoc, memberDetailsTree);
for (currentConstructorIndex = 0; currentConstructorIndex < size;
currentConstructorIndex++) {
Content constructorDocTree = writer.getConstructorDocTreeHeader(
(ConstructorDoc) constructors.get(currentConstructorIndex),
constructorDetailsTree);
buildChildren(node, constructorDocTree);
constructorDetailsTree.addContent(writer.getConstructorDoc(
constructorDocTree, (currentConstructorIndex == size - 1)));
}
memberDetailsTree.addContent(
writer.getConstructorDetails(constructorDetailsTree));
}
}
/**
* Build the signature.
*
* @param node the XML element that specifies which components to document
* @param constructorDocTree the content tree to which the documentation will be added
*/
public void buildSignature(XMLNode node, Content constructorDocTree) {
constructorDocTree.addContent(
writer.getSignature(
(ConstructorDoc) constructors.get(currentConstructorIndex)));
}
/**
* Build the deprecation information.
*
* @param node the XML element that specifies which components to document
* @param constructorDocTree the content tree to which the documentation will be added
*/
public void buildDeprecationInfo(XMLNode node, Content constructorDocTree) {
writer.addDeprecated(
(ConstructorDoc) constructors.get(currentConstructorIndex), constructorDocTree);
}
/**
* Build the comments for the constructor. Do nothing if
* {@link Configuration#nocomment} is set to true.
*
* @param node the XML element that specifies which components to document
* @param constructorDocTree the content tree to which the documentation will be added
*/
public void buildConstructorComments(XMLNode node, Content constructorDocTree) {
if (!configuration.nocomment) {
writer.addComments(
(ConstructorDoc) constructors.get(currentConstructorIndex),
constructorDocTree);
}
}
/**
* Build the tag information.
*
* @param node the XML element that specifies which components to document
* @param constructorDocTree the content tree to which the documentation will be added
*/
public void buildTagInfo(XMLNode node, Content constructorDocTree) {
writer.addTags((ConstructorDoc) constructors.get(currentConstructorIndex),
constructorDocTree);
}
}
| arahusky/performance_javadoc | src/java-doclet/cz/cuni/mff/d3s/tools/perfdoc/doclets/internal/toolkit/builders/ConstructorBuilder.java | Java | gpl-3.0 | 8,166 |
package me.jezzadabomb.es2.client.renderers.tile;
import static org.lwjgl.opengl.GL11.*;
import java.util.Random;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import me.jezzadabomb.es2.client.utils.RenderUtils;
import me.jezzadabomb.es2.common.lib.TextureMaps;
import me.jezzadabomb.es2.common.tileentity.TileQuantumStateDisruptor;
@SideOnly(Side.CLIENT)
public class TileQuantumStateDisruptorRenderer extends TileEntitySpecialRenderer {
int texture;
public TileQuantumStateDisruptorRenderer() {
texture = new Random().nextInt(TextureMaps.QUANTUM_TEXTURES.length);
}
private void renderQuantumStateDisruptor(TileQuantumStateDisruptor tileEntity, double x, double y, double z, float tick) {
glPushMatrix();
glDisable(GL_LIGHTING);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glTranslated(x - 0.75F, y - 1.60F, z + 1.75F);
float translate = 1.28F;
glTranslatef(translate, 0.0F, -translate);
glRotatef(-(float) (720.0 * (System.currentTimeMillis() & 0x3FFFL) / 0x3FFFL), 0.0F, 1.0F, 0.0F);
glTranslatef(-translate, 0.0F, translate);
glRotatef(-90F, 1.0F, 0.0F, 0.0F);
glColor4f(1.0F, 1.0F, 1.0F, 0.5F);
float scale = 0.01F;
glScalef(scale, scale, scale);
RenderUtils.bindTexture(TextureMaps.QUANTUM_TEXTURES[texture]);
RenderUtils.drawTexturedQuad(0, 0, 0, 0, 256, 256, 161);
glEnable(GL_CULL_FACE);
glDisable(GL_BLEND);
glPopMatrix();
}
@Override
public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float tick) {
if (tileEntity instanceof TileQuantumStateDisruptor)
renderQuantumStateDisruptor(((TileQuantumStateDisruptor) tileEntity), x, y, z, tick);
}
}
| Jezza/Elemental-Sciences-2 | es_common/me/jezzadabomb/es2/client/renderers/tile/TileQuantumStateDisruptorRenderer.java | Java | gpl-3.0 | 2,037 |
/*
* Copyright 2014 pushbit <pushbit@gmail.com>
*
* This file is part of Dining Out.
*
* Dining Out 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.
*
* Dining Out 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 Dining Out. If not,
* see <http://www.gnu.org/licenses/>.
*/
package net.sf.diningout.app;
import android.app.IntentService;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import net.sf.diningout.provider.Contract.Restaurants;
import net.sf.sprockets.database.Cursors;
import net.sf.sprockets.util.Geos;
import java.io.IOException;
import java.util.List;
import static net.sf.sprockets.app.SprocketsApplication.context;
import static net.sf.sprockets.app.SprocketsApplication.cr;
import static net.sf.sprockets.gms.analytics.Trackers.exception;
/**
* Gets latitude and longitude of a restaurant's address and downloads a Street View image. Callers
* must include {@link #EXTRA_ID} in their Intent extras.
*/
public class RestaurantGeocodeService extends IntentService {
/**
* ID of the restaurant.
*/
public static final String EXTRA_ID = "intent.extra.ID";
private static final String TAG = RestaurantGeocodeService.class.getSimpleName();
public RestaurantGeocodeService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
long id = intent.getLongExtra(EXTRA_ID, 0L);
Uri uri = ContentUris.withAppendedId(Restaurants.CONTENT_URI, id);
String[] proj = {Restaurants.ADDRESS};
String address = Cursors.firstString(cr().query(uri, proj, null, null, null));
if (!TextUtils.isEmpty(address)) {
try {
ContentValues vals = new ContentValues(3);
if (geocode(address, vals)) {
cr().update(uri, vals, null, null);
RestaurantService.photo(id, vals);
}
} catch (IOException e) {
Log.e(TAG, "geocoding address or downloading Street View image", e);
exception(e);
}
}
}
/**
* Put the {@link Restaurants#LATITUDE LATITUDE}, {@link Restaurants#LONGITUDE LONGITUDE}, and
* {@link Restaurants#LONGITUDE_COS LONGITUDE_COS} in the values.
*
* @return true if coordinates were put in the values
*/
public static boolean geocode(String address, ContentValues vals) throws IOException {
List<Address> locs = new Geocoder(context()).getFromLocationName(address, 1);
if (locs != null && locs.size() > 0) {
Address loc = locs.get(0);
if (loc.hasLatitude() && loc.hasLongitude()) {
double lat = loc.getLatitude();
vals.put(Restaurants.LATITUDE, lat);
vals.put(Restaurants.LONGITUDE, loc.getLongitude());
vals.put(Restaurants.LONGITUDE_COS, Geos.cos(lat));
return true;
}
}
return false;
}
}
| mobilist/dining-out | src/net/sf/diningout/app/RestaurantGeocodeService.java | Java | gpl-3.0 | 3,609 |
<?php
/*******************************************************************************
* Copyright 2009-2016 Amazon Services. All Rights Reserved.
* 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://aws.amazon.com/apache2.0
* This file 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.
*******************************************************************************
* PHP Version 5
* @category Amazon
* @package FBA Inventory Service MWS
* @version 2010-10-01
* Library Version: 2014-09-30
* Generated: Wed May 04 17:14:15 UTC 2016
*/
/**
* @see FBAInventoryServiceMWS_Interface
*/
require_once (dirname(__FILE__) . '/Interface.php');
/**
* FBAInventoryServiceMWS_Client is an implementation of FBAInventoryServiceMWS
*
*/
class FBAInventoryServiceMWS_Client implements FBAInventoryServiceMWS_Interface
{
const SERVICE_VERSION = '2010-10-01';
const MWS_CLIENT_VERSION = '2014-09-30';
/** @var string */
private $_awsAccessKeyId = null;
/** @var string */
private $_awsSecretAccessKey = null;
/** @var array */
private $_config = array ('ServiceURL' => null,
'UserAgent' => 'FBAInventoryServiceMWS PHP5 Library',
'SignatureVersion' => 2,
'SignatureMethod' => 'HmacSHA256',
'ProxyHost' => null,
'ProxyPort' => -1,
'ProxyUsername' => null,
'ProxyPassword' => null,
'MaxErrorRetry' => 3,
'Headers' => array()
);
/**
* Get Service Status
* Gets the status of the service.
* Status is one of GREEN, RED representing:
* GREEN: The service section is operating normally.
* RED: The service section disruption.
*
* @param mixed $request array of parameters for FBAInventoryServiceMWS_Model_GetServiceStatus request or FBAInventoryServiceMWS_Model_GetServiceStatus object itself
* @see FBAInventoryServiceMWS_Model_GetServiceStatusRequest
* @return FBAInventoryServiceMWS_Model_GetServiceStatusResponse
*
* @throws FBAInventoryServiceMWS_Exception
*/
public function getServiceStatus($request)
{
if (!($request instanceof FBAInventoryServiceMWS_Model_GetServiceStatusRequest)) {
require_once (dirname(__FILE__) . '/Model/GetServiceStatusRequest.php');
$request = new FBAInventoryServiceMWS_Model_GetServiceStatusRequest($request);
}
$parameters = $request->toQueryParameterArray();
$parameters['Action'] = 'GetServiceStatus';
$httpResponse = $this->_invoke($parameters);
require_once (dirname(__FILE__) . '/Model/GetServiceStatusResponse.php');
$response = FBAInventoryServiceMWS_Model_GetServiceStatusResponse::fromXML($httpResponse['ResponseBody']);
$response->setResponseHeaderMetadata($httpResponse['ResponseHeaderMetadata']);
return $response;
}
/**
* Convert GetServiceStatusRequest to name value pairs
*/
private function _convertGetServiceStatus($request) {
$parameters = array();
$parameters['Action'] = 'GetServiceStatus';
if ($request->isSetSellerId()) {
$parameters['SellerId'] = $request->getSellerId();
}
if ($request->isSetMWSAuthToken()) {
$parameters['MWSAuthToken'] = $request->getMWSAuthToken();
}
if ($request->isSetMarketplace()) {
$parameters['Marketplace'] = $request->getMarketplace();
}
return $parameters;
}
/**
* List Inventory Supply
* Get information about the supply of seller-owned inventory in
* Amazon's fulfillment network. "Supply" is inventory that is available
* for fulfilling (a.k.a. Multi-Channel Fulfillment) orders. In general
* this includes all sellable inventory that has been received by Amazon,
* that is not reserved for existing orders or for internal FC processes,
* and also inventory expected to be received from inbound shipments.
*
* This operation provides 2 typical usages by setting different
* ListInventorySupplyRequest value:
*
* 1. Set value to SellerSkus and not set value to QueryStartDateTime,
* this operation will return all sellable inventory that has been received
* by Amazon's fulfillment network for these SellerSkus.
*
* 2. Not set value to SellerSkus and set value to QueryStartDateTime,
* This operation will return information about the supply of all seller-owned
* inventory in Amazon's fulfillment network, for inventory items that may have had
* recent changes in inventory levels. It provides the most efficient mechanism
* for clients to maintain local copies of inventory supply data.
*
* Only 1 of these 2 parameters (SellerSkus and QueryStartDateTime) can be set value for 1 request.
* If both with values or neither with values, an exception will be thrown.
*
* This operation is used with ListInventorySupplyByNextToken
* to paginate over the resultset. Begin pagination by invoking the
* ListInventorySupply operation, and retrieve the first set of
* results. If more results are available,continuing iteratively requesting further
* pages results by invoking the ListInventorySupplyByNextToken operation (each time
* passing in the NextToken value from the previous result), until the returned NextToken
* is null, indicating no further results are available.
*
* @param mixed $request array of parameters for FBAInventoryServiceMWS_Model_ListInventorySupply request or FBAInventoryServiceMWS_Model_ListInventorySupply object itself
* @see FBAInventoryServiceMWS_Model_ListInventorySupplyRequest
* @return FBAInventoryServiceMWS_Model_ListInventorySupplyResponse
*
* @throws FBAInventoryServiceMWS_Exception
*/
public function listInventorySupply($request)
{
if (!($request instanceof FBAInventoryServiceMWS_Model_ListInventorySupplyRequest)) {
require_once (dirname(__FILE__) . '/Model/ListInventorySupplyRequest.php');
$request = new FBAInventoryServiceMWS_Model_ListInventorySupplyRequest($request);
}
$parameters = $request->toQueryParameterArray();
$parameters['Action'] = 'ListInventorySupply';
$httpResponse = $this->_invoke($parameters);
require_once (dirname(__FILE__) . '/Model/ListInventorySupplyResponse.php');
$response = FBAInventoryServiceMWS_Model_ListInventorySupplyResponse::fromXML($httpResponse['ResponseBody']);
$response->setResponseHeaderMetadata($httpResponse['ResponseHeaderMetadata']);
return $response;
}
/**
* Convert ListInventorySupplyRequest to name value pairs
*/
private function _convertListInventorySupply($request) {
$parameters = array();
$parameters['Action'] = 'ListInventorySupply';
if ($request->isSetSellerId()) {
$parameters['SellerId'] = $request->getSellerId();
}
if ($request->isSetMWSAuthToken()) {
$parameters['MWSAuthToken'] = $request->getMWSAuthToken();
}
if ($request->isSetMarketplace()) {
$parameters['Marketplace'] = $request->getMarketplace();
}
if ($request->isSetMarketplaceId()) {
$parameters['MarketplaceId'] = $request->getMarketplaceId();
}
if ($request->isSetSellerSkus()) {
$SellerSkusListInventorySupplyRequest = $request->getSellerSkus();
foreach ($SellerSkusListInventorySupplyRequest->getmember() as $memberSellerSkusIndex => $memberSellerSkus) {
$parameters['SellerSkus' . '.' . 'member' . '.' . ($memberSellerSkusIndex + 1)] = $memberSellerSkus;
}
}
if ($request->isSetQueryStartDateTime()) {
$parameters['QueryStartDateTime'] = $request->getQueryStartDateTime();
}
if ($request->isSetResponseGroup()) {
$parameters['ResponseGroup'] = $request->getResponseGroup();
}
return $parameters;
}
/**
* List Inventory Supply By Next Token
* Continues pagination over a resultset of inventory data for inventory
* items.
*
* This operation is used in conjunction with ListUpdatedInventorySupply.
* Please refer to documentation for that operation for further details.
*
* @param mixed $request array of parameters for FBAInventoryServiceMWS_Model_ListInventorySupplyByNextToken request or FBAInventoryServiceMWS_Model_ListInventorySupplyByNextToken object itself
* @see FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenRequest
* @return FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenResponse
*
* @throws FBAInventoryServiceMWS_Exception
*/
public function listInventorySupplyByNextToken($request)
{
if (!($request instanceof FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenRequest)) {
require_once (dirname(__FILE__) . '/Model/ListInventorySupplyByNextTokenRequest.php');
$request = new FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenRequest($request);
}
$parameters = $request->toQueryParameterArray();
$parameters['Action'] = 'ListInventorySupplyByNextToken';
$httpResponse = $this->_invoke($parameters);
require_once (dirname(__FILE__) . '/Model/ListInventorySupplyByNextTokenResponse.php');
$response = FBAInventoryServiceMWS_Model_ListInventorySupplyByNextTokenResponse::fromXML($httpResponse['ResponseBody']);
$response->setResponseHeaderMetadata($httpResponse['ResponseHeaderMetadata']);
return $response;
}
/**
* Convert ListInventorySupplyByNextTokenRequest to name value pairs
*/
private function _convertListInventorySupplyByNextToken($request) {
$parameters = array();
$parameters['Action'] = 'ListInventorySupplyByNextToken';
if ($request->isSetSellerId()) {
$parameters['SellerId'] = $request->getSellerId();
}
if ($request->isSetMWSAuthToken()) {
$parameters['MWSAuthToken'] = $request->getMWSAuthToken();
}
if ($request->isSetMarketplace()) {
$parameters['Marketplace'] = $request->getMarketplace();
}
if ($request->isSetNextToken()) {
$parameters['NextToken'] = $request->getNextToken();
}
return $parameters;
}
/**
* Construct new Client
*
* @param string $awsAccessKeyId AWS Access Key ID
* @param string $awsSecretAccessKey AWS Secret Access Key
* @param array $config configuration options.
* Valid configuration options are:
* <ul>
* <li>ServiceURL</li>
* <li>UserAgent</li>
* <li>SignatureVersion</li>
* <li>TimesRetryOnError</li>
* <li>ProxyHost</li>
* <li>ProxyPort</li>
* <li>ProxyUsername<li>
* <li>ProxyPassword<li>
* <li>MaxErrorRetry</li>
* </ul>
*/
public function __construct(
$awsAccessKeyId, $awsSecretAccessKey, $config, $applicationName, $applicationVersion, $attributes = null)
{
iconv_set_encoding('output_encoding', 'UTF-8');
iconv_set_encoding('input_encoding', 'UTF-8');
iconv_set_encoding('internal_encoding', 'UTF-8');
$this->_awsAccessKeyId = $awsAccessKeyId;
$this->_awsSecretAccessKey = $awsSecretAccessKey;
$this->_serviceVersion = $applicationVersion;
if (!is_null($config)) $this->_config = array_merge($this->_config, $config);
$this->setUserAgentHeader($applicationName, $applicationVersion, $attributes);
}
public function setUserAgentHeader(
$applicationName,
$applicationVersion,
$attributes = null) {
if (is_null($attributes)) {
$attributes = array ();
}
$this->_config['UserAgent'] =
$this->constructUserAgentHeader($applicationName, $applicationVersion, $attributes);
}
private function constructUserAgentHeader($applicationName, $applicationVersion, $attributes = null) {
if (is_null($applicationName) || $applicationName === "") {
throw new InvalidArgumentException('$applicationName cannot be null');
}
if (is_null($applicationVersion) || $applicationVersion === "") {
throw new InvalidArgumentException('$applicationVersion cannot be null');
}
$userAgent =
$this->quoteApplicationName($applicationName)
. '/'
. $this->quoteApplicationVersion($applicationVersion);
$userAgent .= ' (';
$userAgent .= 'Language=PHP/' . phpversion();
$userAgent .= '; ';
$userAgent .= 'Platform=' . php_uname('s') . '/' . php_uname('m') . '/' . php_uname('r');
$userAgent .= '; ';
$userAgent .= 'MWSClientVersion=' . self::MWS_CLIENT_VERSION;
foreach ($attributes as $key => $value) {
if (empty($value)) {
throw new InvalidArgumentException("Value for $key cannot be null or empty.");
}
$userAgent .= '; '
. $this->quoteAttributeName($key)
. '='
. $this->quoteAttributeValue($value);
}
$userAgent .= ')';
return $userAgent;
}
/**
* Collapse multiple whitespace characters into a single ' ' character.
* @param $s
* @return string
*/
private function collapseWhitespace($s) {
return preg_replace('/ {2,}|\s/', ' ', $s);
}
/**
* Collapse multiple whitespace characters into a single ' ' and backslash escape '\',
* and '/' characters from a string.
* @param $s
* @return string
*/
private function quoteApplicationName($s) {
$quotedString = $this->collapseWhitespace($s);
$quotedString = preg_replace('/\\\\/', '\\\\\\\\', $quotedString);
$quotedString = preg_replace('/\//', '\\/', $quotedString);
return $quotedString;
}
/**
* Collapse multiple whitespace characters into a single ' ' and backslash escape '\',
* and '(' characters from a string.
*
* @param $s
* @return string
*/
private function quoteApplicationVersion($s) {
$quotedString = $this->collapseWhitespace($s);
$quotedString = preg_replace('/\\\\/', '\\\\\\\\', $quotedString);
$quotedString = preg_replace('/\\(/', '\\(', $quotedString);
return $quotedString;
}
/**
* Collapse multiple whitespace characters into a single ' ' and backslash escape '\',
* and '=' characters from a string.
*
* @param $s
* @return unknown_type
*/
private function quoteAttributeName($s) {
$quotedString = $this->collapseWhitespace($s);
$quotedString = preg_replace('/\\\\/', '\\\\\\\\', $quotedString);
$quotedString = preg_replace('/\\=/', '\\=', $quotedString);
return $quotedString;
}
/**
* Collapse multiple whitespace characters into a single ' ' and backslash escape ';', '\',
* and ')' characters from a string.
*
* @param $s
* @return unknown_type
*/
private function quoteAttributeValue($s) {
$quotedString = $this->collapseWhitespace($s);
$quotedString = preg_replace('/\\\\/', '\\\\\\\\', $quotedString);
$quotedString = preg_replace('/\\;/', '\\;', $quotedString);
$quotedString = preg_replace('/\\)/', '\\)', $quotedString);
return $quotedString;
}
// Private API ------------------------------------------------------------//
/**
* Invoke request and return response
*/
private function _invoke(array $parameters)
{
try {
if (empty($this->_config['ServiceURL'])) {
require_once (dirname(__FILE__) . '/Exception.php');
throw new FBAInventoryServiceMWS_Exception(
array ('ErrorCode' => 'InvalidServiceURL',
'Message' => "Missing serviceUrl configuration value. You may obtain a list of valid MWS URLs by consulting the MWS Developer's Guide, or reviewing the sample code published along side this library."));
}
$parameters = $this->_addRequiredParameters($parameters);
$retries = 0;
for (;;) {
$response = $this->_httpPost($parameters);
$status = $response['Status'];
if ($status == 200) {
return array('ResponseBody' => $response['ResponseBody'],
'ResponseHeaderMetadata' => $response['ResponseHeaderMetadata']);
}
if ($status == 500 && $this->_pauseOnRetry(++$retries)) {
continue;
}
throw $this->_reportAnyErrors($response['ResponseBody'],
$status, $response['ResponseHeaderMetadata']);
}
} catch (FBAInventoryServiceMWS_Exception $se) {
throw $se;
} catch (Exception $t) {
require_once (dirname(__FILE__) . '/Exception.php');
throw new FBAInventoryServiceMWS_Exception(array('Exception' => $t, 'Message' => $t->getMessage()));
}
}
/**
* Look for additional error strings in the response and return formatted exception
*/
private function _reportAnyErrors($responseBody, $status, $responseHeaderMetadata, Exception $e = null)
{
$exProps = array();
$exProps["StatusCode"] = $status;
$exProps["ResponseHeaderMetadata"] = $responseHeaderMetadata;
libxml_use_internal_errors(true); // Silence XML parsing errors
$xmlBody = simplexml_load_string($responseBody);
if ($xmlBody !== false) { // Check XML loaded without errors
$exProps["XML"] = $responseBody;
$exProps["ErrorCode"] = $xmlBody->Error->Code;
$exProps["Message"] = $xmlBody->Error->Message;
$exProps["ErrorType"] = !empty($xmlBody->Error->Type) ? $xmlBody->Error->Type : "Unknown";
$exProps["RequestId"] = !empty($xmlBody->RequestID) ? $xmlBody->RequestID : $xmlBody->RequestId; // 'd' in RequestId is sometimes capitalized
} else { // We got bad XML in response, just throw a generic exception
$exProps["Message"] = "Internal Error";
}
require_once (dirname(__FILE__) . '/Exception.php');
return new FBAInventoryServiceMWS_Exception($exProps);
}
/**
* Perform HTTP post with exponential retries on error 500 and 503
*
*/
private function _httpPost(array $parameters)
{
$config = $this->_config;
$query = $this->_getParametersAsString($parameters);
$url = parse_url ($config['ServiceURL']);
$uri = array_key_exists('path', $url) ? $url['path'] : null;
if (!isset ($uri)) {
$uri = "/";
}
switch ($url['scheme']) {
case 'https':
$scheme = 'https://';
$port = isset($url['port']) ? $url['port'] : 443;
break;
default:
$scheme = 'http://';
$port = isset($url['port']) ? $url['port'] : 80;
}
$allHeaders = $config['Headers'];
$allHeaders['Content-Type'] = "application/x-www-form-urlencoded; charset=utf-8"; // We need to make sure to set utf-8 encoding here
$allHeaders['Expect'] = null; // Don't expect 100 Continue
$allHeadersStr = array();
foreach($allHeaders as $name => $val) {
$str = $name . ": ";
if(isset($val)) {
$str = $str . $val;
}
$allHeadersStr[] = $str;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $scheme . $url['host'] . $uri);
curl_setopt($ch, CURLOPT_PORT, $port);
$this->setSSLCurlOptions($ch);
curl_setopt($ch, CURLOPT_USERAGENT, $this->_config['UserAgent']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_HTTPHEADER, $allHeadersStr);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($config['ProxyHost'] != null && $config['ProxyPort'] != -1)
{
curl_setopt($ch, CURLOPT_PROXY, $config['ProxyHost'] . ':' . $config['ProxyPort']);
}
if ($config['ProxyUsername'] != null && $config['ProxyPassword'] != null)
{
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $config['ProxyUsername'] . ':' . $config['ProxyPassword']);
}
$response = "";
$response = curl_exec($ch);
if($response === false) {
require_once (dirname(__FILE__) . '/Exception.php');
$exProps["Message"] = curl_error($ch);
$exProps["ErrorType"] = "HTTP";
curl_close($ch);
throw new FBAInventoryServiceMWS_Exception($exProps);
}
curl_close($ch);
return $this->_extractHeadersAndBody($response);
}
/**
* This method will attempt to extract the headers and body of our response.
* We need to split the raw response string by 2 'CRLF's. 2 'CRLF's should indicate the separation of the response header
* from the response body. However in our case we have some circumstances (certain client proxies) that result in
* multiple responses concatenated. We could encounter a response like
*
* HTTP/1.1 100 Continue
*
* HTTP/1.1 200 OK
* Date: Tue, 01 Apr 2014 13:02:51 GMT
* Content-Type: text/html; charset=iso-8859-1
* Content-Length: 12605
*
* ... body ..
*
* This method will throw away extra response status lines and attempt to find the first full response headers and body
*
* return [status, body, ResponseHeaderMetadata]
*/
private function _extractHeadersAndBody($response){
//First split by 2 'CRLF'
$responseComponents = preg_split("/(?:\r?\n){2}/", $response, 2);
$body = null;
for ($count = 0;
$count < count($responseComponents) && $body == null;
$count++) {
$headers = $responseComponents[$count];
$responseStatus = $this->_extractHttpStatusCode($headers);
if($responseStatus != null &&
$this->_httpHeadersHaveContent($headers)){
$responseHeaderMetadata = $this->_extractResponseHeaderMetadata($headers);
//The body will be the next item in the responseComponents array
$body = $responseComponents[++$count];
}
}
//If the body is null here then we were unable to parse the response and will throw an exception
if($body == null){
require_once (dirname(__FILE__) . '/Exception.php');
$exProps["Message"] = "Failed to parse valid HTTP response (" . $response . ")";
$exProps["ErrorType"] = "HTTP";
throw new FBAInventoryServiceMWS_Exception($exProps);
}
return array(
'Status' => $responseStatus,
'ResponseBody' => $body,
'ResponseHeaderMetadata' => $responseHeaderMetadata);
}
/**
* parse the status line of a header string for the proper format and
* return the status code
*
* Example: HTTP/1.1 200 OK
* ...
* returns String statusCode or null if the status line can't be parsed
*/
private function _extractHttpStatusCode($headers){
$statusCode = null;
if (1 === preg_match("/(\\S+) +(\\d+) +([^\n\r]+)(?:\r?\n|\r)/", $headers, $matches)) {
//The matches array [entireMatchString, protocol, statusCode, the rest]
$statusCode = $matches[2];
}
return $statusCode;
}
/**
* Tries to determine some valid headers indicating this response
* has content. In this case
* return true if there is a valid "Content-Length" or "Transfer-Encoding" header
*/
private function _httpHeadersHaveContent($headers){
return (1 === preg_match("/[cC]ontent-[lL]ength: +(?:\\d+)(?:\\r?\\n|\\r|$)/", $headers) ||
1 === preg_match("/Transfer-Encoding: +(?!identity[\r\n;= ])(?:[^\r\n]+)(?:\r?\n|\r|$)/i", $headers));
}
/**
* extract a ResponseHeaderMetadata object from the raw headers
*/
private function _extractResponseHeaderMetadata($rawHeaders){
$inputHeaders = preg_split("/\r\n|\n|\r/", $rawHeaders);
$headers = array();
$headers['x-mws-request-id'] = null;
$headers['x-mws-response-context'] = null;
$headers['x-mws-timestamp'] = null;
$headers['x-mws-quota-max'] = null;
$headers['x-mws-quota-remaining'] = null;
$headers['x-mws-quota-resetsOn'] = null;
foreach ($inputHeaders as $currentHeader) {
$keyValue = explode (': ', $currentHeader);
if (isset($keyValue[1])) {
list ($key, $value) = $keyValue;
if (isset($headers[$key]) && $headers[$key]!==null) {
$headers[$key] = $headers[$key] . "," . $value;
} else {
$headers[$key] = $value;
}
}
}
require_once(dirname(__FILE__) . '/Model/ResponseHeaderMetadata.php');
return new FBAInventoryServiceMWS_Model_ResponseHeaderMetadata(
$headers['x-mws-request-id'],
$headers['x-mws-response-context'],
$headers['x-mws-timestamp'],
$headers['x-mws-quota-max'],
$headers['x-mws-quota-remaining'],
$headers['x-mws-quota-resetsOn']);
}
/**
* Set curl options relating to SSL. Protected to allow overriding.
* @param $ch curl handle
*/
protected function setSSLCurlOptions($ch) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
}
/**
* Exponential sleep on failed request
*
* @param retries current retry
*/
private function _pauseOnRetry($retries)
{
if ($retries <= $this->_config['MaxErrorRetry']) {
$delay = (int) (pow(4, $retries) * 100000);
usleep($delay);
return true;
}
return false;
}
/**
* Add authentication related and version parameters
*/
private function _addRequiredParameters(array $parameters)
{
$parameters['AWSAccessKeyId'] = $this->_awsAccessKeyId;
$parameters['Timestamp'] = $this->_getFormattedTimestamp();
$parameters['Version'] = self::SERVICE_VERSION;
$parameters['SignatureVersion'] = $this->_config['SignatureVersion'];
if ($parameters['SignatureVersion'] > 1) {
$parameters['SignatureMethod'] = $this->_config['SignatureMethod'];
}
$parameters['Signature'] = $this->_signParameters($parameters, $this->_awsSecretAccessKey);
return $parameters;
}
/**
* Convert paremeters to Url encoded query string
*/
private function _getParametersAsString(array $parameters)
{
$queryParameters = array();
foreach ($parameters as $key => $value) {
$queryParameters[] = $key . '=' . $this->_urlencode($value);
}
return implode('&', $queryParameters);
}
/**
* Computes RFC 2104-compliant HMAC signature for request parameters
* Implements AWS Signature, as per following spec:
*
* If Signature Version is 0, it signs concatenated Action and Timestamp
*
* If Signature Version is 1, it performs the following:
*
* Sorts all parameters (including SignatureVersion and excluding Signature,
* the value of which is being created), ignoring case.
*
* Iterate over the sorted list and append the parameter name (in original case)
* and then its value. It will not URL-encode the parameter values before
* constructing this string. There are no separators.
*
* If Signature Version is 2, string to sign is based on following:
*
* 1. The HTTP Request Method followed by an ASCII newline (%0A)
* 2. The HTTP Host header in the form of lowercase host, followed by an ASCII newline.
* 3. The URL encoded HTTP absolute path component of the URI
* (up to but not including the query string parameters);
* if this is empty use a forward '/'. This parameter is followed by an ASCII newline.
* 4. The concatenation of all query string components (names and values)
* as UTF-8 characters which are URL encoded as per RFC 3986
* (hex characters MUST be uppercase), sorted using lexicographic byte ordering.
* Parameter names are separated from their values by the '=' character
* (ASCII character 61), even if the value is empty.
* Pairs of parameter and values are separated by the '&' character (ASCII code 38).
*
*/
private function _signParameters(array $parameters, $key) {
$signatureVersion = $parameters['SignatureVersion'];
$algorithm = "HmacSHA1";
$stringToSign = null;
if (2 == $signatureVersion) {
$algorithm = $this->_config['SignatureMethod'];
$parameters['SignatureMethod'] = $algorithm;
$stringToSign = $this->_calculateStringToSignV2($parameters);
} else {
throw new Exception("Invalid Signature Version specified");
}
return $this->_sign($stringToSign, $key, $algorithm);
}
/**
* Calculate String to Sign for SignatureVersion 2
* @param array $parameters request parameters
* @return String to Sign
*/
private function _calculateStringToSignV2(array $parameters) {
$data = 'POST';
$data .= "\n";
$endpoint = parse_url ($this->_config['ServiceURL']);
$data .= $endpoint['host'];
$data .= "\n";
$uri = array_key_exists('path', $endpoint) ? $endpoint['path'] : null;
if (!isset ($uri)) {
$uri = "/";
}
$uriencoded = implode("/", array_map(array($this, "_urlencode"), explode("/", $uri)));
$data .= $uriencoded;
$data .= "\n";
uksort($parameters, 'strcmp');
$data .= $this->_getParametersAsString($parameters);
return $data;
}
private function _urlencode($value) {
return str_replace('%7E', '~', rawurlencode($value));
}
/**
* Computes RFC 2104-compliant HMAC signature.
*/
private function _sign($data, $key, $algorithm)
{
if ($algorithm === 'HmacSHA1') {
$hash = 'sha1';
} else if ($algorithm === 'HmacSHA256') {
$hash = 'sha256';
} else {
throw new Exception ("Non-supported signing method specified");
}
return base64_encode(
hash_hmac($hash, $data, $key, true)
);
}
/**
* Formats date as ISO 8601 timestamp
*/
private function _getFormattedTimestamp()
{
return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
}
/**
* Formats date as ISO 8601 timestamp
*/
private function getFormattedTimestamp($dateTime)
{
return $dateTime->format(DATE_ISO8601);
}
}
| davygeek/mws | mwsapi/FBAInventoryServiceMWS/Client.php | PHP | gpl-3.0 | 32,332 |
package xyz.stupidwolf.enums;
/**
* 定义各个操作的返回状态码
* Created by stupidwolf on 2016/8/4.
*/
public enum ResultCode {
DELETE_SUCCESS("40"),
DELETE_FAIL("41"),
WRITE_SUCCESS("50"),
WRITE_FAIL("51")
;
private String code;
ResultCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
| stupidwolf/stupid-blog | src/main/java/xyz/stupidwolf/enums/ResultCode.java | Java | gpl-3.0 | 392 |
package model;
/**
* @author Yi Zheng
* Class to represent suppliers of sushi ingredients.
*
*/
public class Supplier{
private String name;
private int distance; // assume it is in kms and manually entered.
// in the real world, the distance may depends on traffic, security issues, etc.
// so it would be better to enter it manually.
/**
*
* @param name the name of supplier
* @param distance the distance to the business (how far to deliver the ingredient(s))
*/
public Supplier(String name, int distance) {
this.setName(name);
this.setDistance(distance);
}
/*
* Setters and Getters
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
}
| zhengyi20201/SushiSystem | src/model/Supplier.java | Java | gpl-3.0 | 876 |
/*
* SLD Editor - The Open Source Java SLD Editor
*
* Copyright (C) 2016, SCISYS UK Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sldeditor.tool.mapbox;
import com.sldeditor.common.NodeInterface;
import com.sldeditor.common.SLDDataInterface;
import com.sldeditor.common.console.ConsoleManager;
import com.sldeditor.common.data.SLDUtils;
import com.sldeditor.common.localisation.Localisation;
import com.sldeditor.common.output.SLDOutputFormatEnum;
import com.sldeditor.common.output.SLDWriterInterface;
import com.sldeditor.common.output.impl.SLDWriterFactory;
import com.sldeditor.common.utils.ExternalFilenames;
import com.sldeditor.datasource.SLDEditorFile;
import com.sldeditor.datasource.extension.filesystem.node.file.FileTreeNode;
import com.sldeditor.datasource.extension.filesystem.node.file.FileTreeNodeTypeEnum;
import com.sldeditor.tool.GenerateFilename;
import com.sldeditor.tool.ToolButton;
import com.sldeditor.tool.ToolInterface;
import com.sldeditor.tool.ToolPanel;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import org.geotools.styling.StyledLayerDescriptor;
/**
* Tool which given a list of SLD objects saves them to SLD files.
*
* @author Robert Ward (SCISYS)
*/
public class MapBoxTool implements ToolInterface {
/** The Constant PANEL_WIDTH. */
private static final int PANEL_WIDTH = 75;
/** The Constant MAPBOX_FILE_EXTENSION. */
private static final String MAPBOX_FILE_EXTENSION = "json";
/** The export to sld button. */
private JButton exportToSLDButton;
/** The group panel. */
private JPanel groupPanel = null;
/** The sld data list. */
private List<SLDDataInterface> sldDataList;
/** Instantiates a new mapbox tool. */
public MapBoxTool() {
createUI();
}
/*
* (non-Javadoc)
*
* @see com.sldeditor.tool.ToolInterface#getPanel()
*/
@Override
public JPanel getPanel() {
return groupPanel;
}
/*
* (non-Javadoc)
*
* @see com.sldeditor.tool.ToolInterface#setSelectedItems(java.util.List, java.util.List)
*/
@Override
public void setSelectedItems(
List<NodeInterface> nodeTypeList, List<SLDDataInterface> sldDataList) {
this.sldDataList = sldDataList;
if (exportToSLDButton != null) {
int mapBoxFilesCount = 0;
if (sldDataList != null) {
for (SLDDataInterface sldData : sldDataList) {
String fileExtension =
ExternalFilenames.getFileExtension(
sldData.getSLDFile().getAbsolutePath());
if (fileExtension.compareTo(MapBoxTool.MAPBOX_FILE_EXTENSION) == 0) {
mapBoxFilesCount++;
}
}
}
exportToSLDButton.setEnabled(mapBoxFilesCount > 0);
}
}
/** Creates the ui. */
private void createUI() {
groupPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout) groupPanel.getLayout();
flowLayout.setVgap(0);
flowLayout.setHgap(0);
TitledBorder titledBorder =
BorderFactory.createTitledBorder(
Localisation.getString(MapBoxTool.class, "MapBoxTool.groupTitle"));
groupPanel.setBorder(titledBorder);
// Export to SLD
exportToSLDButton =
new ToolButton(
Localisation.getString(MapBoxTool.class, "MapBoxTool.exportToSLD"),
"tool/exporttosld.png");
exportToSLDButton.setEnabled(false);
exportToSLDButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
exportToSLD();
}
});
groupPanel.setPreferredSize(new Dimension(PANEL_WIDTH, ToolPanel.TOOL_PANEL_HEIGHT));
groupPanel.add(exportToSLDButton);
}
/** Export to SLD. */
private void exportToSLD() {
SLDWriterInterface sldWriter = SLDWriterFactory.createWriter(SLDOutputFormatEnum.SLD);
for (SLDDataInterface sldData : sldDataList) {
StyledLayerDescriptor sld = SLDUtils.createSLDFromString(sldData);
String layerName = sldData.getLayerNameWithOutSuffix();
if (sld != null) {
String sldString = sldWriter.encodeSLD(sldData.getResourceLocator(), sld);
String destinationFolder = sldData.getSLDFile().getParent();
File fileToSave =
GenerateFilename.findUniqueName(
destinationFolder, layerName, SLDEditorFile.getSLDFileExtension());
String sldFilename = fileToSave.getName();
if (fileToSave.exists()) {
ConsoleManager.getInstance()
.error(
this,
Localisation.getField(
MapBoxTool.class,
"MapBoxTool.destinationAlreadyExists")
+ " "
+ sldFilename);
} else {
ConsoleManager.getInstance()
.information(
this,
Localisation.getField(
MapBoxTool.class, "MapBoxTool.exportToSLDMsg")
+ " "
+ sldFilename);
try (BufferedWriter out = new BufferedWriter(new FileWriter(fileToSave))) {
out.write(sldString);
} catch (IOException e) {
ConsoleManager.getInstance().exception(this, e);
}
}
}
}
}
/*
* (non-Javadoc)
*
* @see com.sldeditor.tool.ToolInterface#getToolName()
*/
@Override
public String getToolName() {
return getClass().getName();
}
/*
* (non-Javadoc)
*
* @see com.sldeditor.tool.ToolInterface#supports(java.util.List, java.util.List)
*/
@Override
public boolean supports(
List<Class<?>> uniqueNodeTypeList,
List<NodeInterface> nodeTypeList,
List<SLDDataInterface> sldDataList) {
if (nodeTypeList == null) {
return false;
}
for (NodeInterface node : nodeTypeList) {
if (node instanceof FileTreeNode) {
FileTreeNode fileTreeNode = (FileTreeNode) node;
if (fileTreeNode.isDir()) {
// Folder
for (int childIndex = 0;
childIndex < fileTreeNode.getChildCount();
childIndex++) {
FileTreeNode f = (FileTreeNode) fileTreeNode.getChildAt(childIndex);
if (f.getFileCategory() == FileTreeNodeTypeEnum.SLD) {
String fileExtension =
ExternalFilenames.getFileExtension(
f.getFile().getAbsolutePath());
return (fileExtension.compareTo(MapBoxTool.MAPBOX_FILE_EXTENSION) == 0);
}
}
} else {
// Single file
if (fileTreeNode.getFileCategory() == FileTreeNodeTypeEnum.SLD) {
String fileExtension =
ExternalFilenames.getFileExtension(
fileTreeNode.getFile().getAbsolutePath());
return (fileExtension.compareTo(MapBoxTool.MAPBOX_FILE_EXTENSION) == 0);
}
}
return false;
} else {
return true;
}
}
return true;
}
}
| robward-scisys/sldeditor | modules/application/src/main/java/com/sldeditor/tool/mapbox/MapBoxTool.java | Java | gpl-3.0 | 9,130 |
$(window).load(function() {
/* Seleccionar el primer radio button (Persona) */
var contr = $('#form-adhere input[type=radio]');
contr.first().prop( "checked", true );
/* Cargar lista de paises en el select */
$.ajax({ url: location.origin + location.pathname + '/assets/js/countries.json', dataType: 'text'})
.done(function( data ) {
data = JSON.parse(data);
var select = $('#pais-adherente-1');
$.each( data, function( key, val ) {
select.append('<option value="'+key+'">'+val+'</option>')
});
select.select2();
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
/* Evento de selección de radio button para cambiar el placeholder de los textboxes */
contr.on('change', function(ev){
if($(ev.target).attr('id') == "tipo-persona-adherente")
{
$('#nombre-adherente-1').attr('placeholder', 'Escribe tu nombre');
$('#email-adherente-1').attr('placeholder', 'Escribe tu email');
}
else if($(ev.target).attr('id') == "tipo-organizacion-adherente")
{
$('#nombre-adherente-1').attr('placeholder', 'Escribe el nombre de la organización');
$('#email-adherente-1').attr('placeholder', 'Escribe el email de la organización');
}
})
/* Enviamos el formulario */
$( '#form-adhere' ).submit(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var $this = $( this ),
action = $this.attr( 'action' );
// The AJAX requrest
var data = $this.serialize();
$.get( action, data )
.done(function(data) {
$("#form-adhere").slideToggle('slow', function(){
$("#form-adhere-done").slideToggle('slow');
});
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
return false;
});
/*
$('#submit-adhere').click(function(ev){
$("#form-adhere").slideToggle('slow', function(){
$("#form-adhere-done").slideToggle('slow');
});
});
*/
}); | DemocraciaEnRed/redinnovacionpolitica.org | assets/js/adhere-form.js | JavaScript | gpl-3.0 | 2,368 |
<?php
function loadXMLDoc($xmlfile)
{
$doc = new DOMDocument();
$doc->load($xmlfile);
return $doc;
}
function getSingleAttribValue($xmlfile,$tag,$attrib)
{
return getXMLAttrib(loadXMLDoc($xmlfile)->getElementsByTagName($tag)->item(0),$attrib);
}
function getXMLNodeList($xmldoc,$nodename)
{
return $xmldoc->getElementsByTagName( $nodename );
}
function getXMLAttrib($xmlnode,$attrib)
{
return $xmlnode->getAttributeNode($attrib)->value;
}
?> | PossibilitiesForLearning/pfl-wptheme | wp.custom.src/xmlfuncs.php | PHP | gpl-3.0 | 476 |
package rd.neuron.neuron;
import org.jblas.FloatMatrix;
import rd.neuron.neuron.Layer.Function;
/**
* Build a fully connected random layer with a middle and max value
* @author azahar
*
*/
public class FullyRandomLayerBuilder implements LayerBuilder {
private final float mid, max;
/**
*
* @param mid - middle value
* @param max - max value
*/
public FullyRandomLayerBuilder(float mid, float max) {
this.mid = mid;
this.max = max;
}
/**
* Default with random values between 0 and 1
*/
public FullyRandomLayerBuilder() {
this.mid = 0;
this.max = 1;
}
@Override
public Layer build(int numberOfInputNeurons, int numberOfOutputNeurons, Function f) {
if (numberOfInputNeurons <= 0 || numberOfOutputNeurons <= 0) {
throw new IllegalArgumentException("Number of neurons cannont be <=0");
}
FloatMatrix weights = FloatMatrix.rand(numberOfInputNeurons, numberOfOutputNeurons); // Out
// x
// In
FloatMatrix bias = FloatMatrix.rand(numberOfOutputNeurons, 1); // Out x
// 1
if (max != 0 && mid != 0) {
weights = weights.sub(mid).mul(max);
bias = bias.sub(mid).mul(max);
}
return new Layer(weights, bias, f);
}
}
| amachwe/NeuralNetwork | src/main/java/rd/neuron/neuron/FullyRandomLayerBuilder.java | Java | gpl-3.0 | 1,234 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-13 09:57
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('db', '0077_auto_20161113_2049'),
]
operations = [
migrations.AlterModelOptions(
name='learningresource',
options={'verbose_name': 'lr', 'verbose_name_plural': 'lr'},
),
]
| caw/curriculum | db/migrations/0078_auto_20161113_2057.py | Python | gpl-3.0 | 444 |
/*
* Copyright (C) 2017 Schürmann & Breitmoser GbR
*
* 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.sufficientlysecure.keychain.ui.base;
import android.os.Bundle;
import android.os.Parcelable;
import org.sufficientlysecure.keychain.operations.results.OperationResult;
/** CryptoOperationFragment which calls crypto operation results only while
* attached to Activity.
*
* This subclass of CryptoOperationFragment substitutes the onCryptoOperation*
* methods for onQueuedOperation* ones, which are ensured to be called while
* the fragment is attached to an Activity, possibly delaying the call until
* the Fragment is re-attached.
*
* TODO merge this functionality into CryptoOperationFragment?
*
* @see CryptoOperationFragment
*/
public abstract class QueueingCryptoOperationFragment<T extends Parcelable, S extends OperationResult>
extends CryptoOperationFragment<T,S> {
public static final String ARG_QUEUED_RESULT = "queued_result";
private S mQueuedResult;
public QueueingCryptoOperationFragment() {
super();
}
public QueueingCryptoOperationFragment(Integer initialProgressMsg) {
super(initialProgressMsg);
}
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (mQueuedResult != null) {
try {
if (mQueuedResult.success()) {
onQueuedOperationSuccess(mQueuedResult);
} else {
onQueuedOperationError(mQueuedResult);
}
} finally {
mQueuedResult = null;
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(ARG_QUEUED_RESULT, mQueuedResult);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mQueuedResult = savedInstanceState.getParcelable(ARG_QUEUED_RESULT);
}
}
public abstract void onQueuedOperationSuccess(S result);
public void onQueuedOperationError(S result) {
hideKeyboard();
result.createNotify(getActivity()).show();
}
@Override
final public void onCryptoOperationSuccess(S result) {
if (getActivity() == null) {
mQueuedResult = result;
return;
}
onQueuedOperationSuccess(result);
}
@Override
final public void onCryptoOperationError(S result) {
if (getActivity() == null) {
mQueuedResult = result;
return;
}
onQueuedOperationError(result);
}
}
| open-keychain/open-keychain | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/base/QueueingCryptoOperationFragment.java | Java | gpl-3.0 | 3,377 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-21 05:36
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='QuizInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('quiz_title', models.CharField(max_length=100)),
('quizDate', models.DateField(default=datetime.date.today)),
('quizTime', models.TimeField(default=datetime.time)),
],
),
migrations.CreateModel(
name='QuizQuestions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question', models.CharField(max_length=200)),
('isMultipleChoice', models.CharField(max_length=1)),
('choice_1', models.CharField(blank=True, max_length=10, null=True)),
('choice_2', models.CharField(blank=True, max_length=10, null=True)),
('choice_3', models.CharField(blank=True, max_length=10, null=True)),
('choice_4', models.CharField(blank=True, max_length=10, null=True)),
('answer', models.CharField(blank=True, max_length=200, null=True)),
('quiz', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.QuizInfo')),
],
),
migrations.CreateModel(
name='StudentProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('school', models.CharField(blank=True, max_length=200, null=True)),
('standard', models.PositiveSmallIntegerField(blank=True, null=True)),
('doj', models.DateField(blank=True, default=datetime.date.today, null=True)),
('student', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, to_field='username', unique=True)),
],
),
migrations.CreateModel(
name='StudentQuizAttempts',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('attempt_date', models.DateField(default=datetime.date.today)),
('score', models.PositiveSmallIntegerField(default=0)),
('quiz', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.QuizInfo')),
('student', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='quiz.StudentProfile', to_field='student')),
],
),
migrations.CreateModel(
name='StudentResponses',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('response', models.CharField(blank=True, max_length=200, null=True)),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.QuizQuestions')),
('quiz', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.QuizInfo')),
('student', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='quiz.StudentProfile', to_field='student')),
],
),
migrations.CreateModel(
name='TeacherProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('doj', models.DateField(blank=True, default=datetime.date.today, null=True)),
('teacher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, to_field='username')),
],
),
migrations.CreateModel(
name='TeacherS',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.StudentProfile')),
('teacher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='quiz.TeacherProfile')),
],
),
migrations.AlterUniqueTogether(
name='teachers',
unique_together=set([('teacher', 'student')]),
),
migrations.AlterUniqueTogether(
name='studentresponses',
unique_together=set([('student', 'quiz', 'question')]),
),
migrations.AlterUniqueTogether(
name='studentquizattempts',
unique_together=set([('student', 'quiz')]),
),
]
| rubyAce71697/QMS | quiz_system/quiz/migrations/0001_initial.py | Python | gpl-3.0 | 5,170 |
package ch.cyberduck.core.onedrive;
/*
* Copyright (c) 2002-2020 iterate GmbH. All rights reserved.
* https://cyberduck.io/
*
* 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.
*/
import ch.cyberduck.core.AttributedList;
import ch.cyberduck.core.ListProgressListener;
import ch.cyberduck.core.ListService;
import ch.cyberduck.core.Path;
import ch.cyberduck.core.exception.BackgroundException;
import ch.cyberduck.core.onedrive.features.GraphFileIdProvider;
import ch.cyberduck.core.onedrive.features.sharepoint.SiteDrivesListService;
import ch.cyberduck.core.onedrive.features.sharepoint.SitesListService;
import java.util.Optional;
import static ch.cyberduck.core.onedrive.SharepointListService.*;
public abstract class AbstractSharepointListService implements ListService {
private final AbstractSharepointSession session;
private final GraphFileIdProvider fileid;
public AbstractSharepointListService(final AbstractSharepointSession session, final GraphFileIdProvider fileid) {
this.session = session;
this.fileid = fileid;
}
public AbstractSharepointSession getSession() {
return session;
}
@Override
public final AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
if((!session.isSingleSite() && directory.isRoot())
|| (session.isSingleSite() && session.isHome(directory))) {
return getRoot(directory, listener);
}
final AttributedList<Path> result = processList(directory, listener);
if(result != AttributedList.<Path>emptyList()) {
return result;
}
final GraphSession.ContainerItem container = session.getContainer(directory);
if(container.getCollectionPath().map(p -> container.isContainerInCollection() && SITES_CONTAINER.equals(p.getName())).orElse(false)) {
return addSiteItems(directory, listener);
}
final Optional<ListService> collectionListService = container.getCollectionPath().map(p -> {
if(SITES_CONTAINER.equals(p.getName())) {
return new SitesListService(session, fileid);
}
else if(DRIVES_CONTAINER.equals(p.getName())) {
return new SiteDrivesListService(session, fileid);
}
return null;
});
if(collectionListService.isPresent() && (!container.isDefined() || container.isCollectionInContainer())) {
return collectionListService.get().list(directory, listener);
}
return new GraphItemListService(session, fileid).list(directory, listener);
}
AttributedList<Path> addSiteItems(final Path directory, final ListProgressListener listener) throws BackgroundException {
final AttributedList<Path> list = new AttributedList<>();
list.add(new Path(directory, DRIVES_NAME.getName(), DRIVES_NAME.getType(), DRIVES_NAME.attributes()));
list.add(new Path(directory, SITES_NAME.getName(), SITES_NAME.getType(), SITES_NAME.attributes()));
listener.chunk(directory, list);
return list;
}
abstract AttributedList<Path> getRoot(final Path directory, final ListProgressListener listener) throws BackgroundException;
AttributedList<Path> processList(final Path directory, final ListProgressListener listener) throws BackgroundException {
return AttributedList.emptyList();
}
}
| iterate-ch/cyberduck | onedrive/src/main/java/ch/cyberduck/core/onedrive/AbstractSharepointListService.java | Java | gpl-3.0 | 3,894 |
#!/usr/bin/env python
"""
Copyright (C) 2015 Ivan Gregor
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/>.
The master script of the Snowball gene assembler. Module version 1.2
"""
import os
import sys
import platform
import tempfile
import shutil
import argparse
import multiprocessing as mp
from algbioi.com import fq
from algbioi.com import parallel
from algbioi.hsim import comh
from algbioi.haplo import hmain
from algbioi.haplo import hio
def mainSnowball(fq1Path, fq2Path, profileHmmFile, insertSize, readLen=None, outFile=None, outFormat='fna',
workingDir=None, hmmsearchPath=None, pfamMinScore=None, pOverlap=None, overlapLen=None,
outAnnot=False, cleanUp=False, processors=mp.cpu_count()):
"""
Main function, the interface of the Snowball gene assembler.
@param fq1Path: FASTQ 1 file path (containing first ends of Illumina paired-end reads)
@param fq2Path: FASTQ 2 file path (containing second ends)
@param profileHmmFile: profile HMMs file, containing models generated by the HMMER 3 software
@param insertSize: mean insert size used for the library preparation (i.e. read generation)
@param readLen: read length (if None, it will be derived from the FASTQ file)
@param outFile: output file (if None, it will be derived from the FASTQ 1 file)
@param outFormat: output file format 'fna' or 'fq'
@param workingDir: temporary files will be stored here (if None, a temporary directory will be created/deleted)
@param hmmsearchPath: path to the HMMER hmmsearch command (if None, it will take version that is in the PATH)
@param pfamMinScore: minimum score for the hmmsearch (if None, use default)
@param pOverlap: minimum overlap probability for the Snowball algorithm
@param overlapLen: minimum overlap length for the Snowball algorithm
@param outAnnot: if true, additional annotation will be stored along with the resulting contigs
@param cleanUp: if true, delete temporary files at the end
@param processors: Number of processors (default: use all processors available)
@type fq1Path: str
@type fq2Path: str
@type profileHmmFile: str
@type insertSize: int
@type readLen: str
@type outFile: str
@type outFormat: str
@type workingDir: str
@type hmmsearchPath: str
@type pfamMinScore: int
@type pOverlap: float
@type overlapLen: float
@type outAnnot: bool
@type cleanUp: bool
@type processors: int
"""
assert os.name == 'posix', 'Snowball runs only on "posix" systems, your system is: %s' % os.name
# checking input parameters
assert os.path.isfile(fq1Path), 'File does not exist: %s' % fq1Path
assert os.path.isfile(fq2Path), 'File does not exist: %s' % fq2Path
# derive the read length
if readLen is None:
for name, dna, p, qs in fq.ReadFqGen(fq1Path):
readLen = len(dna)
assert readLen == len(qs), 'File corrupted %s' % fq1Path
break
assert readLen is not None, 'Cannot derive read length from %s' % fq1Path
assert readLen <= insertSize < 2 * readLen, 'Invalid read length (%s) and insert size (%s) combination' \
% (readLen, insertSize)
assert os.path.isfile(profileHmmFile), 'File does not exist: %s' % profileHmmFile
outFormat = outFormat.strip()
assert outFormat == 'fna' or outFormat == 'fq', 'Invalid output format: %s' % outFormat
# checking the output file
if outFile is None:
c = 0
while True:
outFile = fq1Path + '_%s.%s.gz' % (c, outFormat)
if not os.path.isfile(outFile):
break
c += 1
else:
outFileDir = os.path.dirname(outFile)
assert os.path.basename(outFile) != '', 'Output file name is empty'
assert outFileDir == '' or os.path.isdir(outFileDir), 'Invalid output directory: %s' % outFileDir
outFile = outFile.strip()
if not outFile.endswith('.gz'):
outFile += '.gz'
print('The name of the output file was modified to:\n\t%s' % outFile)
# Looking for the hmmsearch binaries
if hmmsearchPath is None:
hmmsearchPath = os.popen("which hmmsearch").read().strip()
if hmmsearchPath != '':
print('This hmmsearch binary will be used:\n\t%s' % hmmsearchPath)
assert os.path.isfile(hmmsearchPath), 'Path for (hmmsearch) is invalid: %s' % hmmsearchPath
# creates a temporary working directory
if workingDir is None:
workingDir = tempfile.mkdtemp(prefix='snowball_')
assert os.path.isdir(workingDir), 'Cannot create temporary working directory (%s)' % workingDir
cleenUpTmpWorkingDir = True
print('Using temporary directory:\n\t%s' % workingDir)
else:
cleenUpTmpWorkingDir = False
assert os.path.isdir(workingDir), 'Working directory does not exist:\n\t%s' % workingDir
assert not os.listdir(workingDir), 'Working directory must be empty:\n\t%s' % workingDir
# set the number of processor cores to be used
comh.MAX_PROC = max(1, min(processors, mp.cpu_count()))
# set assembly parameters or use defaults
if pfamMinScore is not None:
comh.SAMPLES_PFAM_EVAN_MIN_SCORE = pfamMinScore
if pOverlap is not None:
comh.ASSEMBLY_POVERLAP = (pOverlap,)
if overlapLen is not None:
comh.ASSEMBLY_OVERLAP_LEN = (overlapLen,)
# creates a temporary directory for the sample strains
strainsDir = os.path.join(workingDir, 'strains')
if not os.path.isdir(strainsDir):
os.mkdir(strainsDir)
assert os.path.isdir(strainsDir), 'Cannot create temporary directory:\n\t%s' % strainsDir
os.symlink(fq1Path, os.path.join(strainsDir, '0_pair1.fq.gz'))
os.symlink(fq2Path, os.path.join(strainsDir, '0_pair2.fq.gz'))
# Start of the algorithm
print('Running on: %s (%s)' % (' '.join(platform.dist()), sys.platform))
print('Using %s processors' % comh.MAX_PROC)
print('Settings:\n\tRead length: %s\n\tInsert size: %s\n\tMin. overlap probability: %s\n\tMin. overlap length: %s'
'\n\tMin. HMM score: %s'
% (readLen, insertSize, comh.ASSEMBLY_POVERLAP[0], comh.ASSEMBLY_OVERLAP_LEN[0],
comh.SAMPLES_PFAM_EVAN_MIN_SCORE))
# file with joined consensus reads
fqJoinPath = os.path.join(strainsDir, '0_join.fq.gz')
# join paired-end reads
if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure)
print('Joining paired-end reads into consensus reads, loading reads from:\n\t%s\n\t%s' % (fq1Path, fq2Path))
r = fq.joinPairEnd([(fq1Path, fq2Path, fqJoinPath, readLen, insertSize, None, 60)],
minOverlap=comh.SAMPLES_PAIRED_END_JOIN_MIN_OVERLAP,
minOverlapIdentity=comh.SAMPLES_PAIRED_END_JOIN_MIN_OVERLAP_IDENTITY,
maxCpu=comh.MAX_PROC)
print("Filtered out: %s %% reads" % r)
# Translate consensus reads into protein sequences, run hmmsearch
if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure)
print("Translating reads to protein sequences")
# file with protein consensus read sequences
joinFastaProtGzip = os.path.join(strainsDir, '0_join_prot.fna.gz')
fq.readsToProt(fqJoinPath, joinFastaProtGzip, comh.TRANSLATION_TABLE)
print("Running HMMER (hmmsearch)")
domOut = os.path.join(strainsDir, '0_join_prot.domtblout')
joinFastaProt = joinFastaProtGzip[:-3]
cmd = 'zcat %s > %s;%s -o /dev/null --noali --domtblout %s -E 0.01 ' \
'--cpu %s %s %s;rm %s;gzip -f %s' % (joinFastaProtGzip, joinFastaProt, hmmsearchPath, domOut, comh.MAX_PROC,
profileHmmFile, joinFastaProt, joinFastaProt, domOut)
assert parallel.reportFailedCmd(parallel.runCmdSerial([parallel.TaskCmd(cmd, strainsDir)])) is None
# Assign consensus reads to individual gene domains
if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure)
print("Assigning consensus reads to gene domains")
hio.partitionReads(workingDir, comh.SAMPLES_PFAM_EVAN_MIN_SCORE, comh.SAMPLES_PFAM_EVAN_MIN_ACCURACY,
comh.SAMPLES_SHUFFLE_RAND_SEED, comh.SAMPLES_PFAM_PARTITIONED_DIR, True, False)
partitionedDir = os.path.join(workingDir, comh.SAMPLES_PFAM_PARTITIONED_DIR)
# Run Assembly
if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure)
print("Running Snowball assembly")
# collect tasks for each gene domain
taskList = []
assert os.path.isdir(partitionedDir), 'Temporary directory does not exist:\n\t%s' % partitionedDir
for f in os.listdir(partitionedDir):
fPath = os.path.join(partitionedDir, f)
if f.endswith('join.fq.gz') and os.path.isfile(fPath):
base = fPath[:-6]
inFq = fPath
inDomtblout = '%s_prot.domtblout.gz' % base
inProtFna = '%s_prot.fna.gz' % base
outPath = '%s_read_rec.pkl.gz' % base
taskList.append(parallel.TaskThread(hmain.buildSuperReads,
(inFq, inDomtblout, inProtFna, outPath,
comh.ASSEMBLY_CONSIDER_PROT_COMP,
comh.ASSEMBLY_ONLY_POVERLAP,
comh.ASSEMBLY_POVERLAP,
comh.ASSEMBLY_OVERLAP_LEN,
comh.ASSEMBLY_OVERLAP_ANNOT_LEN,
comh.ASSEMBLY_STOP_OVERLAP_MISMATCH,
comh.ASSEMBLY_MAX_LOOPS,
comh.TRANSLATION_TABLE)))
# run tasks in parallel
parallel.runThreadParallel(taskList, comh.MAX_PROC, keepRetValues=False)
# Creates the output file
if True: # to skip this step, set to False (e.g. resume processing after OS/HW failure)
print('Creating output file:\n\t%s' % outFile)
counter = 0
out = fq.WriteFq(outFile)
for f in os.listdir(partitionedDir):
fPath = os.path.join(partitionedDir, f)
if f.endswith('.pkl.gz') and os.path.isfile(fPath):
domName = f[2:-23]
for rec in hio.loadReadRec(fPath):
counter += 1
contigName = 'contig_%s_%s' % (counter, domName)
dnaSeq = rec.dnaSeq
# get the quality score string
if outAnnot or outFormat == 'fq':
qs = rec.qsArray.getQSStr(dnaSeq)
else:
qs = None
# get the contig annotations
if outAnnot:
assert qs is not None
codingStart = rec.annotStart
codingLen = rec.annotLen
posCov = ','.join(map(lambda x: str(int(x)), rec.getPosCovArray()))
annotStr = 'domName:%s|codingStart:%s|codingLen:%s|qs:%s|posCov:%s' % (domName, codingStart,
codingLen, qs, posCov)
else:
annotStr = ''
# write an entry to the output file
if outFormat == 'fq':
out.writeFqEntry('@' + contigName, dnaSeq, qs, annotStr)
else:
assert outFormat == 'fna'
if outAnnot:
annotStr = '|' + annotStr
out.write('>%s%s\n%s\n' % (contigName, annotStr, dnaSeq))
# close output file
out.close()
# Clean up the working directory
if cleenUpTmpWorkingDir:
# clean up the temporary directory
print('Cleaning up temporary directory')
assert os.path.isdir(workingDir), 'Directory to be cleaned does not exist:\n%s' % workingDir
shutil.rmtree(workingDir)
elif cleanUp:
# clean up the user defined working directory
if os.path.isdir(workingDir):
print('Cleaning up working directory:\n\t%s' % workingDir)
shutil.rmtree(os.path.join(workingDir, comh.SAMPLES_PFAM_PARTITIONED_DIR))
shutil.rmtree(strainsDir)
print('Done')
def _main():
"""
Main function of the master script.
"""
# Command line parameters
parser = argparse.ArgumentParser(
description = 'Snowball gene assembler for Metagenomes (version 1.2).',
epilog='This software is distributed under the GNU General Public License version 3 (http://www.gnu.org/licenses/).')
parser.add_argument('-f', '--fq-1-file', nargs=1, type=file, required=True,
help='FASTQ 1 file path containing first read-ends of Illumina paired-end reads).',
metavar='pair1.fq.gz',
dest='fq1File')
parser.add_argument('-s', '--fq-2-file', nargs=1, type=file, required=True,
help='FASTQ 2 file path containing second read-ends of Illumina paired-end reads).',
metavar='pair2.fq.gz',
dest='fq2File')
parser.add_argument('-m', '--profile-hmm-file', nargs=1, type=file, required=True,
help='Profile HMMs file containing models of individual gene domains '
'(this file is generated by the HMMER 3.0 software).',
metavar='profile.hmm',
dest='profileHmmFile')
parser.add_argument('-i', '--insert-size', nargs=1, type=int, required=True,
help='Mean insert size used for the library preparation (i.e. read generation).',
metavar='225',
dest='insertSize')
parser.add_argument('-r', '--read-length', nargs=1, type=int, required=False,
help='Read length of the read-ends (Default: read length will be derived from the input files).',
metavar='150',
dest='readLen')
parser.add_argument('-o', '--output-file', nargs=1, type=str, required=False,
help='Output FASTA or FASTQ file containing assembled contigs '
'(Default: the file name will be derived from the input file names).',
metavar='contigs.fna.gz',
dest='outFile')
parser.add_argument('-t', '--output-format', nargs=1, type=str, required=False,
choices=['fna', 'fq'],
help='Format of the output file, supported: fna, fq (Default: fna).',
metavar='fna',
dest='outFormat')
parser.add_argument('-w', '--working-directory', nargs=1, type=str, required=False,
help='Working directory (Default: a temporary working directory will be automatically '
'created and removed).',
metavar='wd',
dest='workingDir')
parser.add_argument('-e', '--hmmsearch-path', nargs=1, type=file, required=False,
help='Path to the HMMER hmmsearch command (Default: the version in the PATH will be used).',
metavar='/usr/bin/hmmsearch',
dest='hmmsearchPath')
parser.add_argument('-n', '--hmmsearch-min-score', nargs=1, type=int, required=False,
help='Minimum score for the reads to gene domains assignments (Default: 40).',
metavar='40',
dest='pfamMinScore')
parser.add_argument('-v', '--minimum-overlap-probability', nargs=1, type=float, required=False,
help='Minimum overlap probability parameter of the Snowball algorithm (Default: 0.8).',
metavar='0.8',
dest='pOverlap')
parser.add_argument('-l', '--min-overlap-length', nargs=1, type=float, required=False,
help='Minimum overlap length parameter of the Snowball algorithm (Default: 0.5).',
metavar='0.5',
dest='overlapLen')
parser.add_argument('-a', '--output-contig-annotation', action='store_true', required=False,
help='Store additional contig annotation along with the contigs.'
' (Default: no annotation is stored).',
dest='outAnnot')
parser.add_argument('-c', '--clean-up', action='store_true', required=False,
help='Clean up the working directory. If a temporary working directory is automatically created, '
'it will always be cleaned up. (Default: no clean up is performed).',
dest='cleanUp')
parser.add_argument('-p', '--processors', nargs=1, type=int, required=False,
help='Number of processors to be used (Default: all available processors will be used).',
metavar='60',
dest='processors')
args = parser.parse_args()
# Values that must be defined
fq1File = None
fq2File = None
profileHmmFile = None
insertSize = None
# Default values
outFormat = 'fna'
pfamMinScore = 40
pOverlap = 0.8
overlapLen = 0.5
outAnnot = False
cleanUp = False
processors = mp.cpu_count()
readLen = None
outFile = None
workingDir = None
hmmsearchPath = None
# reading arguments
if args.fq1File:
fq1File = normPath(args.fq1File[0].name)
if args.fq2File:
fq2File = normPath(args.fq2File[0].name)
if args.profileHmmFile:
profileHmmFile = normPath(args.profileHmmFile[0].name)
if args.insertSize:
insertSize = int(args.insertSize[0])
if args.readLen:
readLen = int(args.readLen[0])
if args.outFile:
outFile = normPath(args.outFile[0])
if args.outFormat:
outFormat = args.outFormat[0]
if args.workingDir:
workingDir = normPath(args.workingDir[0])
if args.hmmsearchPath:
hmmsearchPath = normPath(args.hmmsearchPath[0].name)
if args.pfamMinScore:
pfamMinScore = int(args.pfamMinScore[0])
if args.pOverlap:
pOverlap = float(args.pOverlap[0])
if args.overlapLen:
overlapLen = float(args.overlapLen[0])
if args.outAnnot:
outAnnot = args.outAnnot
if args.cleanUp:
cleanUp = args.cleanUp
if args.processors:
processors = int(args.processors[0])
# Printing for debugging.
if False: # set to True to print input parameters
print('fq1File: %s' % fq1File)
print('fq2File: %s' % fq2File)
print('profileHmmFile: %s' % profileHmmFile)
print('insertSize: %s' % insertSize)
print('readLen: %s' % readLen)
print('outFile: %s' % outFile)
print('outFormat: %s' % outFormat)
print('workingDir: %s' % workingDir)
print('hmmsearchPath: %s' % hmmsearchPath)
print('pfamMinScore: %s' % pfamMinScore)
print('pOverlap: %s' % pOverlap)
print('overlapLen: %s' % overlapLen)
print('outAnnot: %s' % outAnnot)
print('cleanUp: %s' % cleanUp)
print('processors: %s' % processors)
# Run Snowball
mainSnowball(fq1File, fq2File, profileHmmFile, insertSize,
readLen=readLen, outFile=outFile, outFormat=outFormat, workingDir=workingDir,
hmmsearchPath=hmmsearchPath, pfamMinScore=pfamMinScore, pOverlap=pOverlap, overlapLen=overlapLen,
outAnnot=outAnnot, cleanUp=cleanUp, processors=processors)
def normPath(path):
if os.path.isabs(path) or path.strip().startswith('~'):
return path
else:
return os.path.abspath(path)
# TESTS ---------------------------------------------------
def _test():
fq1File = '/home/igregor/Documents/work/release_snow/input/10_1_NZ_AIGN00000000_p1.fq.gz'
fq2File = '/home/igregor/Documents/work/release_snow/input/10_1_NZ_AIGN00000000_p2.fq.gz'
profileHmmFile = '/home/igregor/Documents/work/db/pfamV27/Pfam-A_and_Amphora2.hmm'
insertSize = 225
outFile = '/home/igregor/Documents/work/release_snow/out.fna'
outFormat = 'fna' # or 'fq'
workingDir = '/home/igregor/Documents/work/release_snow/working'
hmmsearchPath = '/home/igregor/Documents/work/tools/hmmer-3.0/binaries/hmmsearch'
mainSnowball(fq1File, fq2File, profileHmmFile, insertSize, readLen=None, outFile=outFile, outFormat=outFormat,
workingDir=workingDir, hmmsearchPath=hmmsearchPath, pfamMinScore=None, outAnnot=False, cleanUp=False,
processors=mp.cpu_count())
if __name__ == "__main__":
_main()
# _test()
| algbioi/snowball | algbioi/ga/run.py | Python | gpl-3.0 | 21,873 |
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module ProjectManagerApi
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
| alansalinas/ProjectManager-api | config/application.rb | Ruby | gpl-3.0 | 988 |
package edu.drexel.psal.anonymouth.engine;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import edu.drexel.psal.ANONConstants;
import edu.drexel.psal.anonymouth.helpers.ErrorHandler;
import edu.drexel.psal.jstylo.analyzers.WekaAnalyzer;
import edu.drexel.psal.jstylo.generics.Logger;
import edu.drexel.psal.jstylo.generics.Logger.LogOut;
import weka.core.Instance;
import weka.core.Instances;
/**
* Swaps original feature values out of the original feature vector of the documen to anonymize,
* and replaces them with potential target values of the feature in question.
* All of these swaps are tested against the trained classifier,
* and the ClusterGroup with target values that confused the classifier the most is returned.
*
* "Confused the classifier the most" means that the "other" authors (not the user) had ownership estimates
* with the lowest variance with respect to a single test instance, and that the user had a (low, less than random chance..?)
* @author Andrew W.E. McDonald
*
*/
public class FeatureSwapper {
private final String NAME = "( "+this.getClass().getName()+" ) - ";
WekaAnalyzer waz;
Instances toAnonymize;
ClusterGroup[] clusterGroups;
WekaResults[] wekaResultsArray;
ArrayList<String> toAnonymizeTitlesList;
Set<String> trainSetAuthors;
double bestCaseClassification = 1; // set it to worst case, and we'll update as it gets better.
public FeatureSwapper(ClusterGroup[] clusterGroups, DocumentMagician magician){
toAnonymize = magician.getToModifyDat();
toAnonymizeTitlesList = magician.getToModifyTitlesList();
trainSetAuthors = magician.getTrainSetAuthors();
waz = new WekaAnalyzer(ANONConstants.PATH_TO_CLASSIFIER);
this.clusterGroups = clusterGroups;
if (clusterGroups == null)
Logger.logln(NAME+"Damn.");
}
/**
* Will test the topN_ClusterGroupsToTest by swapping the centroid (target) values into the document to anonymize's
* Instance object, and testing the modified Instances against the original classifier.
*
* It will return the best ClusterGroup (which is the one that would provide the most anonymity).
*
* If "topN_ClusterGroupsToTest" is less than 1, or greater than the number of ClusterGroups available,
* all ClusterGroups will be tested.
* @param topN_ClusterGroupsToTest
* @return
*/
public ClusterGroup getBestClusterGroup(int topN_ClusterGroupsToTest){
int numClusterGroups;
if (topN_ClusterGroupsToTest <= 0 || topN_ClusterGroupsToTest > clusterGroups.length)
numClusterGroups = clusterGroups.length;
else
numClusterGroups = topN_ClusterGroupsToTest;
Instance alteredInstance = null;
double[] tempCG_centroids;
Attribute tempAttrib;
Iterator<String> keyIter;
int indexInInstance;
int numTopFeatures = DataAnalyzer.topAttributes.length;
wekaResultsArray = new WekaResults[numClusterGroups];
int i,j;
for(i = 0; i < numClusterGroups; i++){ // for each cluster group
Instances hopefullyAnonymizedInstances = new Instances(toAnonymize);
alteredInstance = hopefullyAnonymizedInstances.instance(0); // hardcoding in '0' because we only plan to have a single document (thus a single instance)
hopefullyAnonymizedInstances.delete(0);// deleting the original from the copy -- it will be replaced by an Instance with substituted values
tempCG_centroids = clusterGroups[i].getCentroids(); // these are the "target values" that will be substituted in
for( j = 0; j < numTopFeatures; j++){
// the attributes (features) in topAttributes are in the same order as in each ClusterGroup (clusterGroups[i]),
// AND in the same order as the centroids in the array returned by "clusterGroups[i].getCentroids()" above.
tempAttrib = DataAnalyzer.topAttributes[j];
indexInInstance = tempAttrib.getFeaturesOriginalInstancesIndexNumber();
alteredInstance.setValue(indexInInstance, tempCG_centroids[j]);
}
hopefullyAnonymizedInstances.add(alteredInstance);
Map<String,Map<String,Double>> wekaResultMap = waz.classifyWithPretrainedClassifier(hopefullyAnonymizedInstances, toAnonymizeTitlesList, trainSetAuthors);
keyIter = (wekaResultMap.keySet()).iterator();
System.out.println(wekaResultMap.keySet().toString()+" -- current cluster group num: "+i);
if (keyIter.hasNext()){
wekaResultsArray[i] = new WekaResults(wekaResultMap.get(keyIter.next()),i); // there should never be more that one key in this map. We only test one document.
}
else
ErrorHandler.fatalProcessingError(null);
}
Arrays.sort(wekaResultsArray);
/*
* Error check to make sure that Weka isn't being misused:
* if ALL of the representativeValue's are equal, then something is wrong.. because that means that all of the classifications were identical.
*/
boolean allEqual = true;
double lastValue = wekaResultsArray[0].representativeValue;
int numVals = wekaResultsArray.length;
for (i = 1; i < numVals; i++){
if (lastValue != wekaResultsArray[i].representativeValue){
allEqual = false;
break;
}
//System.out.println("representative: "+wekaResultsArray[i].representativeValue+" ==> "+clusterGroups[wekaResultsArray[i].respectiveIndexInClusterGroupArray].toString());
}
Logger.logln(NAME+"If all features are moved to their target values, the following classification will result: "+clusterGroups[wekaResultsArray[0].respectiveIndexInClusterGroupArray].toString());
if (allEqual && i != 1)
Logger.logln(NAME+"Oops! Weka must have been called incorrectly. All ClusterGroup representativeValue's are the same!\nThis is known to happen when the SMO is run without the '-M' flag.", LogOut.STDERR);
return clusterGroups[wekaResultsArray[0].respectiveIndexInClusterGroupArray];
}
}
/**
* Takes care of parsing the results from Weka, and calculates a representative value that indicates how favorable a given result is,
* with respect to the other results. Implements Comparable to allow for easy sorting via Arrays.sort(array).
* @author Andrew W.E. McDonald
*
*/
class WekaResults implements Comparable<WekaResults>{
ResultPair[] results;
ResultPair theUser;
int numOtherAuthors;
int respectiveIndexInClusterGroupArray;
double representativeValue;
public WekaResults(Map<String,Double> resultsMap, int indexInClusterGroupArray){
respectiveIndexInClusterGroupArray = indexInClusterGroupArray;
Set<String> keySet = resultsMap.keySet();
numOtherAuthors = keySet.size() - 1;
results = new ResultPair[numOtherAuthors];
Iterator<String> strIter = keySet.iterator();
String name;
double d;
int count = 0;
while(strIter.hasNext()){
name = strIter.next();
d = resultsMap.get(name);
if (name.equals(ANONConstants.DUMMY_NAME)){
theUser = new ResultPair(name, d);
continue;
}
results[count] = new ResultPair(name, d);
count++;
}
representativeValue = getAverageOfUserResultAndCalculatedVariance();
}
/**
* Calculates the variance among ONLY the "other" authors (not the actual author).
* (we want to pick the result with the lowest variance (meaning it was hard to tell who wrote the document)
*/
public double getVariance(){
int i;
double total = 0;
double average = 0;
for(i = 0; i < numOtherAuthors; i++)
total += results[i].value;
average = total/numOtherAuthors;
total = 0;
for(i = 0; i < numOtherAuthors; i++)
total += Math.pow((results[i].value - average),2); // sum the squares of each element minus the average.
return total/numOtherAuthors; // the variance.
}
/**
* This calculates the average between the variance of the other author's results (the degree of certainty that each other author wrote the document in question),
* and the degree of certainty that the user (who did write the document) wrote the document in question.
* This is done because it seemed to be the best way to factor in a low variance between other authors (meaning it's hard to tell if any of the other authors wrote the document),
* and the fact that we also want it to look as different from the author's writing as possible.
*
* Taking the average of these two numbers means that the ClusterGroup that we select will have a value as close to zero as possible returned from this function.
* @return
*/
public double getAverageOfUserResultAndCalculatedVariance(){
double variance = getVariance();
double total = theUser.value + variance;
return total/2;
}
@Override
public int compareTo(WekaResults wr) {
if(this.representativeValue < wr.representativeValue)
return -1;
else if(this.representativeValue > wr.representativeValue)
return 1;
else
return 0;
}
}
/**
* Small wrapper for the name and degree of certaintly returned by Weka, as a result of the classification.
* @author Andrew W.E. McDonald
*
*/
class ResultPair{
String name;
double value;
public ResultPair(String name, double value){
this.name = name;
this.value = value;
}
}
| jbdatko/pes | anonymouth/src/edu/drexel/psal/anonymouth/engine/FeatureSwapper.java | Java | gpl-3.0 | 8,994 |
/***********************************************************************
filename: CEGUIDirect3D11GeometryBuffer.cpp
created: Wed May 5 2010
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#define NOMINMAX
#include "CEGUIDirect3D11GeometryBuffer.h"
#include "CEGUIDirect3D11Texture.h"
#include "CEGUIRenderEffect.h"
#include "CEGUIVertex.h"
#include "CEGUIExceptions.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
Direct3D11GeometryBuffer::Direct3D11GeometryBuffer(Direct3D11Renderer& owner) :
d_owner(owner),
d_device(d_owner.getDirect3DDevice()),
d_activeTexture(0),
d_vertexBuffer(0),
d_bufferSize(0),
d_bufferSynched(false),
d_clipRect(0, 0, 0, 0),
d_translation(0, 0, 0),
d_rotation(0, 0, 0),
d_pivot(0, 0, 0),
d_effect(0),
d_matrixValid(false)
{
}
//----------------------------------------------------------------------------//
Direct3D11GeometryBuffer::~Direct3D11GeometryBuffer()
{
cleanupVertexBuffer();
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::draw() const
{
// setup clip region
D3D11_RECT clip;
clip.left = static_cast<LONG>(d_clipRect.d_left);
clip.top = static_cast<LONG>(d_clipRect.d_top);
clip.right = static_cast<LONG>(d_clipRect.d_right);
clip.bottom = static_cast<LONG>(d_clipRect.d_bottom);
d_device.d_context->RSSetScissorRects(1, &clip);
if (!d_bufferSynched)
syncHardwareBuffer();
// apply the transformations we need to use.
if (!d_matrixValid)
updateMatrix();
d_owner.setWorldMatrix(d_matrix);
// set our buffer as the vertex source.
const UINT stride = sizeof(D3DVertex);
const UINT offset = 0;
d_device.d_context->IASetVertexBuffers(0, 1, &d_vertexBuffer, &stride, &offset);
const int pass_count = d_effect ? d_effect->getPassCount() : 1;
for (int pass = 0; pass < pass_count; ++pass)
{
// set up RenderEffect
if (d_effect)
d_effect->performPreRenderFunctions(pass);
// draw the batches
size_t pos = 0;
BatchList::const_iterator i = d_batches.begin();
for ( ; i != d_batches.end(); ++i)
{
// Set Texture
d_owner.setCurrentTextureShaderResource(
const_cast<ID3D11ShaderResourceView*>((*i).first));
// Draw this batch
d_owner.bindTechniquePass(d_blendMode);
d_device.d_context->Draw((*i).second, pos);
pos += (*i).second;
}
}
// clean up RenderEffect
if (d_effect)
d_effect->performPostRenderFunctions();
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::setTranslation(const Vector3& v)
{
d_translation = v;
d_matrixValid = false;
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::setRotation(const Vector3& r)
{
d_rotation = r;
d_matrixValid = false;
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::setPivot(const Vector3& p)
{
d_pivot = p;
d_matrixValid = false;
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::setClippingRegion(const Rect& region)
{
d_clipRect.d_top = ceguimax(0.0f, PixelAligned(region.d_top));
d_clipRect.d_bottom = ceguimax(0.0f, PixelAligned(region.d_bottom));
d_clipRect.d_left = ceguimax(0.0f, PixelAligned(region.d_left));
d_clipRect.d_right = ceguimax(0.0f, PixelAligned(region.d_right));
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::appendVertex(const Vertex& vertex)
{
appendGeometry(&vertex, 1);
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::appendGeometry(const Vertex* const vbuff,
uint vertex_count)
{
const ID3D11ShaderResourceView* srv =
d_activeTexture ? d_activeTexture->getDirect3DShaderResourceView() : 0;
// create a new batch if there are no batches yet, or if the active texture
// differs from that used by the current batch.
if (d_batches.empty() || (srv != d_batches.back().first))
d_batches.push_back(BatchInfo(srv, 0));
// update size of current batch
d_batches.back().second += vertex_count;
// buffer these vertices
D3DVertex vd;
const Vertex* vs = vbuff;
for (uint i = 0; i < vertex_count; ++i, ++vs)
{
// copy vertex info the buffer, converting from CEGUI::Vertex to
// something directly usable by D3D as needed.
vd.x = vs->position.d_x;
vd.y = vs->position.d_y;
vd.z = vs->position.d_z;
vd.diffuse = vs->colour_val.getARGB();
vd.tu = vs->tex_coords.d_x;
vd.tv = vs->tex_coords.d_y;
d_vertices.push_back(vd);
}
d_bufferSynched = false;
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::setActiveTexture(Texture* texture)
{
d_activeTexture = static_cast<Direct3D11Texture*>(texture);
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::reset()
{
d_batches.clear();
d_vertices.clear();
d_activeTexture = 0;
}
//----------------------------------------------------------------------------//
Texture* Direct3D11GeometryBuffer::getActiveTexture() const
{
return d_activeTexture;
}
//----------------------------------------------------------------------------//
uint Direct3D11GeometryBuffer::getVertexCount() const
{
return d_vertices.size();
}
//----------------------------------------------------------------------------//
uint Direct3D11GeometryBuffer::getBatchCount() const
{
return d_batches.size();
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::setRenderEffect(RenderEffect* effect)
{
d_effect = effect;
}
//----------------------------------------------------------------------------//
RenderEffect* Direct3D11GeometryBuffer::getRenderEffect()
{
return d_effect;
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::updateMatrix() const
{
const D3DXVECTOR3 p(d_pivot.d_x, d_pivot.d_y, d_pivot.d_z);
const D3DXVECTOR3 t(d_translation.d_x,
d_translation.d_y,
d_translation.d_z);
D3DXQUATERNION r;
D3DXQuaternionRotationYawPitchRoll(&r,
D3DXToRadian(d_rotation.d_y),
D3DXToRadian(d_rotation.d_x),
D3DXToRadian(d_rotation.d_z));
D3DXMatrixTransformation(&d_matrix, 0, 0, 0, &p, &r, &t);
d_matrixValid = true;
}
//----------------------------------------------------------------------------//
const D3DXMATRIX* Direct3D11GeometryBuffer::getMatrix() const
{
if (!d_matrixValid)
updateMatrix();
return &d_matrix;
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::syncHardwareBuffer() const
{
const size_t vertex_count = d_vertices.size();
if (vertex_count > d_bufferSize)
{
cleanupVertexBuffer();
allocateVertexBuffer(vertex_count);
}
if (vertex_count > 0)
{
void* buff;
D3D11_MAPPED_SUBRESOURCE SubRes;
if (FAILED(d_device.d_context->Map(d_vertexBuffer,0,D3D11_MAP_WRITE_DISCARD, 0, &SubRes)))
CEGUI_THROW(RendererException(
"Direct3D11GeometryBuffer::syncHardwareBuffer: "
"failed to map buffer."));
buff=SubRes.pData;
std::memcpy(buff, &d_vertices[0], sizeof(D3DVertex) * vertex_count);
d_device.d_context->Unmap(d_vertexBuffer,0);
}
d_bufferSynched = true;
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::allocateVertexBuffer(const size_t count) const
{
D3D11_BUFFER_DESC buffer_desc;
buffer_desc.Usage = D3D11_USAGE_DYNAMIC;
buffer_desc.ByteWidth = count * sizeof(D3DVertex);
buffer_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
buffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
buffer_desc.MiscFlags = 0;
if (FAILED(d_device.d_device->CreateBuffer(&buffer_desc, 0, &d_vertexBuffer)))
CEGUI_THROW(RendererException(
"Direct3D11GeometryBuffer::allocateVertexBuffer:"
" failed to allocate vertex buffer."));
d_bufferSize = count;
}
//----------------------------------------------------------------------------//
void Direct3D11GeometryBuffer::cleanupVertexBuffer() const
{
if (d_vertexBuffer)
{
d_vertexBuffer->Release();
d_vertexBuffer = 0;
d_bufferSize = 0;
}
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
| cooljeanius/CEGUI | cegui/src/RendererModules/Direct3D11/CEGUIDirect3D11GeometryBuffer.cpp | C++ | gpl-3.0 | 10,922 |
# deprecated?
class HostControlWrapper(object):
def __init__(self):
self.id = None
self.idx = None
self.label = None
self.btn = None
self.tile_bg = None
self.host = None
| wackerl91/luna | resources/lib/model/hostcontrolwrapper.py | Python | gpl-3.0 | 222 |
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
class FoxAndWord {
public:
int howManyPairs(vector <string> V) {
int c = 0;
for(int i=0; i<V.size(); i++) {
for(int j=0; j<V.size(); j++) {
if(i != j) {
string a = V[i];
string b = V[j];
for(int k=0; k<a.size(); k++) {
if(a.compare(b) == 0) {
c++;
break;
}
a = a.substr(1) + a[0];
}
}
}
}
return c / 2;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, int p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
FoxAndWord *obj;
int answer;
obj = new FoxAndWord();
clock_t startTime = clock();
answer = obj->howManyPairs(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p1 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
vector <string> p0;
int p1;
{
// ----- test 0 -----
string t0[] = {"tokyo","kyoto"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 1;
all_right = KawigiEdit_RunTest(0, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 1 -----
string t0[] = {"aaaaa","bbbbb"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 0;
all_right = KawigiEdit_RunTest(1, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 2 -----
string t0[] = {"ababab","bababa","aaabbb"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 1;
all_right = KawigiEdit_RunTest(2, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 3 -----
string t0[] = {"eel","ele","lee"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 3;
all_right = KawigiEdit_RunTest(3, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 4 -----
string t0[] = {"aaa","aab","aba","abb","baa","bab","bba","bbb"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 6;
all_right = KawigiEdit_RunTest(4, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 5 -----
string t0[] = {"top","coder"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 0;
all_right = KawigiEdit_RunTest(5, p0, true, p1) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
| jhtan/cp | topCoder/SRM604div2/FoxAndWord.cpp | C++ | gpl-3.0 | 3,553 |
const UserAuthentication = function () {
let _userPool = new AmazonCognitoIdentity.CognitoUserPool(
window.auth.config.cognito
);
let _cognitoUser = _userPool.getCurrentUser();
const _getUser = function (email) {
if (!_cognitoUser) {
_cognitoUser = new AmazonCognitoIdentity.CognitoUser({
Username: email,
Pool: _userPool,
});
}
_cognitoUser.getSession(function () {});
return _cognitoUser;
};
const _buildAttributeList = function (
givenName,
familyName,
country,
industry,
contact
) {
let attributeList = [];
if (givenName !== undefined) {
const dataGivenName = {
Name: "given_name",
Value: givenName,
};
attributeList.push(
new AmazonCognitoIdentity.CognitoUserAttribute(dataGivenName)
);
}
if (familyName !== undefined) {
const dataFamilyName = {
Name: "family_name",
Value: familyName,
};
attributeList.push(
new AmazonCognitoIdentity.CognitoUserAttribute(dataFamilyName)
);
}
const dataLocale = {
Name: "locale",
Value: navigator.language,
};
attributeList.push(
new AmazonCognitoIdentity.CognitoUserAttribute(dataLocale)
);
if (country !== undefined) {
const datacountry = {
Name: "custom:country",
Value: country,
};
attributeList.push(
new AmazonCognitoIdentity.CognitoUserAttribute(datacountry)
);
}
if (industry !== undefined) {
const dataIndustry = {
Name: "custom:industry",
Value: industry,
};
attributeList.push(
new AmazonCognitoIdentity.CognitoUserAttribute(dataIndustry)
);
}
if (contact !== undefined) {
const dataContact = {
Name: "custom:contact",
Value: contact,
};
attributeList.push(
new AmazonCognitoIdentity.CognitoUserAttribute(dataContact)
);
}
return attributeList;
};
const _setCookie = function (name, value, expiry) {
const d = new Date();
d.setTime(d.getTime() + expiry * 24 * 60 * 60 * 1000);
let expires = "expires=" + d.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
};
const _getCookie = function (cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(";");
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === " ") {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
};
const _deleteCookie = function (name) {
document.cookie =
name + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
};
const _setUserCookie = function (userToken) {
_setCookie("aodnPortalUser", JSON.stringify(userToken), 365);
};
const _setGuestCookie = function () {
_setCookie("aodnPortalGuest", true, 1);
};
const _getUserCookie = function () {
const cookie = _getCookie("aodnPortalUser");
return cookie ? JSON.parse(cookie) : null;
};
const _getGuestCookie = function () {
const cookie = _getCookie("aodnPortalGuest");
return cookie ? true : null;
};
const _clearCookies = function () {
_deleteCookie("aodnPortalUser");
_deleteCookie("aodnPortalGuest");
};
return {
isGuest: function () {
return _getGuestCookie() !== null;
},
setAsGuest: function (callback) {
_setGuestCookie();
callback();
},
isSignedIn: function () {
const cookie = _getUserCookie();
return cookie !== null && _getUser(cookie.email) !== null;
},
signUp: function (
username,
password,
givenName,
familyName,
country,
industry,
contact,
callback
) {
const attributeList = _buildAttributeList(
givenName,
familyName,
country,
industry,
contact
);
_userPool.signUp(username, password, attributeList, null, callback);
},
setDetails: function (
givenName,
familyName,
country,
industry,
contact,
callback
) {
if (_cognitoUser) {
const attrList = _buildAttributeList(
givenName,
familyName,
country,
industry,
contact
);
_cognitoUser.updateAttributes(attrList, callback);
} else {
return {};
}
},
signIn: function (email, password, callback) {
_clearCookies();
const authenticationDetails =
new AmazonCognitoIdentity.AuthenticationDetails({
Username: email,
Password: password,
});
_getUser(email).authenticateUser(authenticationDetails, {
onSuccess: function (res) {
_setUserCookie({ email, token: res.accessToken.jwtToken });
callback(null);
},
onFailure: function (err) {
_cognitoUser = null;
callback(err);
},
});
},
getDetails: function (callback) {
_cognitoUser.getUserAttributes(function(err, result) {
if (err) {
callback(err, null);
} else {
// Build attrs into object
let userInfo = { name: _cognitoUser.username };
for (let k = 0; k < result.length; k++) {
userInfo[result[k].getName()] = result[k].getValue();
}
callback(null, userInfo);
}
});
},
signOut: function (callback) {
if (_cognitoUser && _cognitoUser.signInUserSession) {
_cognitoUser.signOut();
_cognitoUser = undefined;
_clearCookies();
callback(null, {});
}
},
delete: function (callback) {
_cognitoUser.deleteUser(function() {
_clearCookies();
callback();
});
},
changeUserPassword: function (oldPassword, newPassword, callback) {
if (_cognitoUser) {
_cognitoUser.changePassword(oldPassword, newPassword, callback);
} else {
callback({ name: "Error", message: "User is not signed in" }, null);
}
},
sendPasswordResetCode: function (userName, callback) {
_getUser(userName).forgotPassword({
onFailure: (err) => callback(err, null),
onSuccess: (result) => callback(null, result),
});
},
confirmPasswordReset: function (username, code, newPassword, callback) {
_getUser(username).confirmPassword(code, newPassword, {
onFailure: (err) => callback(err, null),
onSuccess: (result) => callback(null, result),
});
},
};
};
| aodn/aodn-portal | web-app/js/aws-cognito/UserAuthentication.js | JavaScript | gpl-3.0 | 6,716 |
package de.unijena.bioinf.fingerid;
import de.unijena.bioinf.fingerid.db.CustomDataSourceService;
import de.unijena.bioinf.sirius.gui.table.ActiveElementChangedListener;
import de.unijena.bioinf.sirius.gui.utils.WrapLayout;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class DBFilterPanel extends JPanel implements ActiveElementChangedListener<CompoundCandidate, Set<FingerIdData>>, CustomDataSourceService.DataSourceChangeListener {
private final List<FilterChangeListener> listeners = new LinkedList<>();
protected long bitSet;
protected List<JCheckBox> checkboxes;
private final AtomicBoolean isRefreshing = new AtomicBoolean(false);
public DBFilterPanel(CandidateList sourceList) {
setLayout(new WrapLayout(FlowLayout.LEFT, 5, 1));
this.checkboxes = new ArrayList<>(CustomDataSourceService.size());
for (CustomDataSourceService.Source source : CustomDataSourceService.sources()) {
checkboxes.add(new JCheckBox(source.name()));
}
addBoxes();
CustomDataSourceService.addListener(this);
sourceList.addActiveResultChangedListener(this);
}
public void addFilterChangeListener(FilterChangeListener listener) {
listeners.add(listener);
}
public void fireFilterChangeEvent() {
for (FilterChangeListener listener : listeners) {
listener.fireFilterChanged(bitSet);
}
}
protected void addBoxes() {
Collections.sort(checkboxes, new Comparator<JCheckBox>() {
@Override
public int compare(JCheckBox o1, JCheckBox o2) {
return o1.getText().toUpperCase().compareTo(o2.getText().toUpperCase());
}
});
this.bitSet = 0L;
for (final JCheckBox box : checkboxes) {
if (box.isSelected())
this.bitSet |= CustomDataSourceService.getSourceFromName(box.getText()).flag();
add(box);
box.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (!isRefreshing.get()) {
if (box.isSelected())
bitSet |= CustomDataSourceService.getSourceFromName(box.getText()).flag();
else
bitSet &= ~CustomDataSourceService.getSourceFromName(box.getText()).flag();
fireFilterChangeEvent();
}
}
});
}
}
protected void reset() {
isRefreshing.set(true);
bitSet = 0;
try {
for (JCheckBox checkbox : checkboxes) {
checkbox.setSelected(false);
}
} finally {
fireFilterChangeEvent();
isRefreshing.set(false);
}
}
public boolean toggle() {
setVisible(!isVisible());
return isVisible();
}
@Override
public void resultsChanged(Set<FingerIdData> datas, CompoundCandidate sre, List<CompoundCandidate> resultElements, ListSelectionModel selections) {
reset();
}
@Override
public void fireDataSourceChanged(Collection<String> changes) {
HashSet<String> changed = new HashSet<>(changes);
isRefreshing.set(true);
boolean c = false;
Iterator<JCheckBox> it = checkboxes.iterator();
while (it.hasNext()) {
JCheckBox checkbox = it.next();
if (changed.remove(checkbox.getText())) {
it.remove();
c = true;
}
}
for (String name : changed) {
checkboxes.add(new JCheckBox(name));
c = true;
}
if (c) {
removeAll();
addBoxes();
revalidate();
repaint();
fireFilterChangeEvent();
}
isRefreshing.set(false);
}
public interface FilterChangeListener extends EventListener {
void fireFilterChanged(long filterSet);
}
}
| boecker-lab/sirius_frontend | sirius_gui/src/main/java/de/unijena/bioinf/fingerid/DBFilterPanel.java | Java | gpl-3.0 | 4,224 |
<?php namespace DemocracyApps\CNP\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider {
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'DemocracyApps\CNP\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
//
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function($router)
{
require app_path('Http/routes.php');
});
}
}
| DemocracyApps/CNP | app/Providers/RouteServiceProvider.php | PHP | gpl-3.0 | 959 |
package com.ua.homework_7_2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ua.homework_7_1.hibernate.controllers.DishController;
import com.ua.homework_7_1.hibernate.controllers.EmployeeController;
import com.ua.homework_7_1.hibernate.controllers.OrderController;
import java.util.Arrays;
public class Main {
private EmployeeController employeeController;
private DishController dishController;
private OrderController orderController;
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
Main main = applicationContext.getBean(Main.class);
main.start();
}
public void init() {
if (reInit) {
preparedDishController.removeAll();
orderController.removeAll();
dishController.removeAll();
employeeController.removeAll();
storageController.removeAll();
ingredientController.removeAll();
ingredientController.initIngredients();
storageController.initStorage();
employeeController.initEmployee();
dishController.initDishes();
orderController.initOrders();
preparedDishController.initPreparedDishes();
}
}
private void start() {
employeeController.createEmployee();
dishController.createDish();
orderController.createOrder("John", Arrays.asList("Borch", "Deer"), 1);
orderController.createOrder("John", Arrays.asList("Soup", "Tekilla"), 2);
orderController.createOrder("John", Arrays.asList("Plov", "Rom"), 3);
orderController.printAllOrders();
}
public void setEmployeeController(EmployeeController employeeController) {
this.employeeController = employeeController;
}
public void setDishController(DishController dishController) {
this.dishController = dishController;
}
public void setOrderController(OrderController orderController) {
this.orderController = orderController;
}
}
| andrewzagor/goit | Enterprise_7_2/Main.java | Java | gpl-3.0 | 2,196 |
/**********************************************************
* Version $Id$
*********************************************************/
///////////////////////////////////////////////////////////
// //
// SAGA //
// //
// System for Automated Geoscientific Analyses //
// //
// Application Programming Interface //
// //
// Library: SAGA_API //
// //
//-------------------------------------------------------//
// //
// table_record.cpp //
// //
// Copyright (C) 2005 by Olaf Conrad //
// //
//-------------------------------------------------------//
// //
// This file is part of 'SAGA - System for Automated //
// Geoscientific Analyses'. //
// //
// 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, version 2.1 of the License. //
// //
// 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 program; if //
// not, write to the Free Software Foundation, Inc., //
// 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, //
// USA. //
// //
//-------------------------------------------------------//
// //
// contact: Olaf Conrad //
// Institute of Geography //
// University of Goettingen //
// Goldschmidtstr. 5 //
// 37077 Goettingen //
// Germany //
// //
// e-mail: oconrad@saga-gis.org //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
#include "table.h"
#include "table_value.h"
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
CSG_Table_Record::CSG_Table_Record(CSG_Table *pTable, int Index)
{
m_pTable = pTable;
m_Index = Index;
m_Flags = 0;
if( m_pTable && m_pTable->Get_Field_Count() > 0 )
{
m_Values = (CSG_Table_Value **)SG_Malloc(m_pTable->Get_Field_Count() * sizeof(CSG_Table_Value *));
for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++)
{
m_Values[iField] = _Create_Value(m_pTable->Get_Field_Type(iField));
}
}
else
{
m_Values = NULL;
}
}
//---------------------------------------------------------
CSG_Table_Record::~CSG_Table_Record(void)
{
if( is_Selected() )
{
m_pTable->Select(m_Index, true);
}
if( m_pTable->Get_Field_Count() > 0 )
{
for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++)
{
delete(m_Values[iField]);
}
SG_Free(m_Values);
}
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
CSG_Table_Value * CSG_Table_Record::_Create_Value(TSG_Data_Type Type)
{
switch( Type )
{
default:
case SG_DATATYPE_String: return( new CSG_Table_Value_String() );
case SG_DATATYPE_Date : return( new CSG_Table_Value_Date () );
case SG_DATATYPE_Color :
case SG_DATATYPE_Byte :
case SG_DATATYPE_Char :
case SG_DATATYPE_Word :
case SG_DATATYPE_Short :
case SG_DATATYPE_DWord :
case SG_DATATYPE_Int : return( new CSG_Table_Value_Int () );
case SG_DATATYPE_ULong :
case SG_DATATYPE_Long : return( new CSG_Table_Value_Long () );
case SG_DATATYPE_Float :
case SG_DATATYPE_Double: return( new CSG_Table_Value_Double() );
case SG_DATATYPE_Binary: return( new CSG_Table_Value_Binary() );
}
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CSG_Table_Record::_Add_Field(int add_Field)
{
if( add_Field < 0 )
{
add_Field = 0;
}
else if( add_Field >= m_pTable->Get_Field_Count() )
{
add_Field = m_pTable->Get_Field_Count() - 1;
}
m_Values = (CSG_Table_Value **)SG_Realloc(m_Values, m_pTable->Get_Field_Count() * sizeof(CSG_Table_Value *));
for(int iField=m_pTable->Get_Field_Count()-1; iField>add_Field; iField--)
{
m_Values[iField] = m_Values[iField - 1];
}
m_Values[add_Field] = _Create_Value(m_pTable->Get_Field_Type(add_Field));
return( true );
}
//---------------------------------------------------------
bool CSG_Table_Record::_Del_Field(int del_Field)
{
delete(m_Values[del_Field]);
for(int iField=del_Field; iField<m_pTable->Get_Field_Count(); iField++)
{
m_Values[iField] = m_Values[iField + 1];
}
m_Values = (CSG_Table_Value **)SG_Realloc(m_Values, m_pTable->Get_Field_Count() * sizeof(CSG_Table_Value *));
return( true );
}
//---------------------------------------------------------
int CSG_Table_Record::_Get_Field(const CSG_String &Field) const
{
if( Field.Length() )
{
for(int iField=0; iField<m_pTable->Get_Field_Count(); iField++)
{
if( !Field.Cmp(m_pTable->Get_Field_Name(iField)) )
{
return( iField );
}
}
}
return( -1 );
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
void CSG_Table_Record::Set_Selected(bool bOn)
{
if( bOn != is_Selected() )
{
if( bOn )
{
m_Flags |= SG_TABLE_REC_FLAG_Selected;
}
else
{
m_Flags &= ~SG_TABLE_REC_FLAG_Selected;
}
}
}
//---------------------------------------------------------
void CSG_Table_Record::Set_Modified(bool bOn)
{
if( bOn != is_Modified() )
{
if( bOn )
{
m_Flags |= SG_TABLE_REC_FLAG_Modified;
}
else
{
m_Flags &= ~SG_TABLE_REC_FLAG_Modified;
}
}
if( bOn )
{
m_pTable->Set_Modified();
}
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CSG_Table_Record::Set_Value (int iField, const CSG_Bytes &Value)
{
if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
{
if( m_Values[iField]->Set_Value(Value) )
{
Set_Modified(true);
m_pTable->Set_Update_Flag();
m_pTable->_Stats_Invalidate(iField);
return( true );
}
}
return( false );
}
bool CSG_Table_Record::Set_Value(const CSG_String &Field, const CSG_Bytes &Value)
{
return( Set_Value(_Get_Field(Field), Value) );
}
//---------------------------------------------------------
bool CSG_Table_Record::Set_Value(int iField, const CSG_String &Value)
{
if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
{
if( m_Values[iField]->Set_Value(Value) )
{
Set_Modified(true);
m_pTable->Set_Update_Flag();
m_pTable->_Stats_Invalidate(iField);
return( true );
}
}
return( false );
}
bool CSG_Table_Record::Set_Value(const CSG_String &Field, const CSG_String &Value)
{
return( Set_Value(_Get_Field(Field), Value) );
}
//---------------------------------------------------------
bool CSG_Table_Record::Set_Value(int iField, double Value)
{
if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
{
if( m_Values[iField]->Set_Value(Value) )
{
Set_Modified(true);
m_pTable->Set_Update_Flag();
m_pTable->_Stats_Invalidate(iField);
return( true );
}
}
return( false );
}
bool CSG_Table_Record::Set_Value(const CSG_String &Field, double Value)
{
return( Set_Value(_Get_Field(Field), Value) );
}
//---------------------------------------------------------
bool CSG_Table_Record::Add_Value(int iField, double Value)
{
if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
{
return( Set_Value(iField, asDouble(iField) + Value) );
}
return( false );
}
bool CSG_Table_Record::Add_Value(const CSG_String &Field, double Value)
{
return( Add_Value(_Get_Field(Field), Value) );
}
//---------------------------------------------------------
bool CSG_Table_Record::Mul_Value(int iField, double Value)
{
if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
{
return( Set_Value(iField, asDouble(iField) * Value) );
}
return( false );
}
bool CSG_Table_Record::Mul_Value(const CSG_String &Field, double Value)
{
return( Mul_Value(_Get_Field(Field), Value) );
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CSG_Table_Record::Set_NoData(int iField)
{
if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
{
switch( m_pTable->Get_Field_Type(iField) )
{
default:
case SG_DATATYPE_String:
if( !m_Values[iField]->Set_Value(SG_T("")) )
return( false );
break;
case SG_DATATYPE_Date:
case SG_DATATYPE_Color:
case SG_DATATYPE_Byte:
case SG_DATATYPE_Char:
case SG_DATATYPE_Word:
case SG_DATATYPE_Short:
case SG_DATATYPE_DWord:
case SG_DATATYPE_Int:
case SG_DATATYPE_ULong:
case SG_DATATYPE_Long:
case SG_DATATYPE_Float:
case SG_DATATYPE_Double:
if( !m_Values[iField]->Set_Value(m_pTable->Get_NoData_Value()) )
return( false );
break;
case SG_DATATYPE_Binary:
m_Values[iField]->asBinary().Destroy();
break;
}
Set_Modified(true);
m_pTable->Set_Update_Flag();
m_pTable->_Stats_Invalidate(iField);
return( true );
}
return( false );
}
bool CSG_Table_Record::Set_NoData(const CSG_String &Field)
{
return( Set_NoData(_Get_Field(Field)) );
}
//---------------------------------------------------------
bool CSG_Table_Record::is_NoData(int iField) const
{
if( iField >= 0 && iField < m_pTable->Get_Field_Count() )
{
switch( m_pTable->Get_Field_Type(iField) )
{
default:
case SG_DATATYPE_String:
return( m_Values[iField]->asString() == NULL );
case SG_DATATYPE_Date:
case SG_DATATYPE_Color:
case SG_DATATYPE_Byte:
case SG_DATATYPE_Char:
case SG_DATATYPE_Word:
case SG_DATATYPE_Short:
case SG_DATATYPE_DWord:
case SG_DATATYPE_Int:
case SG_DATATYPE_ULong:
case SG_DATATYPE_Long:
return( m_pTable->is_NoData_Value(m_Values[iField]->asInt()) );
case SG_DATATYPE_Float:
case SG_DATATYPE_Double:
return( m_pTable->is_NoData_Value(m_Values[iField]->asDouble()) );
case SG_DATATYPE_Binary:
return( m_Values[iField]->asBinary().Get_Count() == 0 );
}
}
return( true );
}
bool CSG_Table_Record::is_NoData(const CSG_String &Field) const
{
return( is_NoData(_Get_Field(Field)) );
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
const SG_Char * CSG_Table_Record::asString(int iField, int Decimals) const
{
return( iField >= 0 && iField < m_pTable->Get_Field_Count() ? m_Values[iField]->asString(Decimals) : NULL );
}
const SG_Char * CSG_Table_Record::asString(const CSG_String &Field, int Decimals) const
{
return( asString(_Get_Field(Field), Decimals) );
}
//---------------------------------------------------------
int CSG_Table_Record::asInt(int iField) const
{
return( iField >= 0 && iField < m_pTable->Get_Field_Count() ? m_Values[iField]->asInt() : 0 );
}
int CSG_Table_Record::asInt(const CSG_String &Field) const
{
return( asInt(_Get_Field(Field)) );
}
//---------------------------------------------------------
sLong CSG_Table_Record::asLong(int iField) const
{
return( iField >= 0 && iField < m_pTable->Get_Field_Count() ? m_Values[iField]->asLong() : 0 );
}
sLong CSG_Table_Record::asLong(const CSG_String &Field) const
{
return( asLong(_Get_Field(Field)) );
}
//---------------------------------------------------------
double CSG_Table_Record::asDouble(int iField) const
{
return( iField >= 0 && iField < m_pTable->Get_Field_Count() ? m_Values[iField]->asDouble() : 0.0 );
}
double CSG_Table_Record::asDouble(const CSG_String &Field) const
{
return( asDouble(_Get_Field(Field)) );
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CSG_Table_Record::Assign(CSG_Table_Record *pRecord)
{
if( pRecord )
{
int nFields = m_pTable->Get_Field_Count() < pRecord->m_pTable->Get_Field_Count()
? m_pTable->Get_Field_Count() : pRecord->m_pTable->Get_Field_Count();
for(int iField=0; iField<nFields; iField++)
{
*(m_Values[iField]) = *(pRecord->m_Values[iField]);
}
Set_Modified();
return( true );
}
return( false );
}
///////////////////////////////////////////////////////////
// //
// //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
| UoA-eResearch/saga-gis | saga-gis/src/saga_core/saga_api/table_record.cpp | C++ | gpl-3.0 | 14,927 |
Simpla CMS 2.3.8 = afa50d5f661d65b6c67ec7f0e80eee7d
| gohdan/DFC | known_files/hashes/simpla/design/js/codemirror/addon/hint/css-hint.js | JavaScript | gpl-3.0 | 52 |
import requests
from requests.auth import HTTPDigestAuth
import time
import json
import sys
class IMT550C():
def __init__(self):
params = self.configure()
self.uri = params["uri"]
self.ip = params["IP"]
self.user = params["username"]
self.password = params["password"]
self.sample_rate = params["sample_rate"]
self.points = [
{"name": "cooling_setpoint", "unit": "F", "data_type": "double",
"OID": "4.1.6", "range": (45.0,95.0), "access": 6,
"devtosmap": lambda x: x/10, "smaptodev": lambda x: x*10}, #thermSetbackCool
{"name": "fan_state", "unit": "Mode", "data_type": "long",
"OID": "4.1.4", "range": [0,1], "access": 4,
"devtosmap": lambda x: {0:0, 1:0, 2:1}[x], "smaptodev": lambda x: {x:x}[x]}, # thermFanState
{"name": "heating_setpoint", "unit": "F", "data_type": "double",
"OID": "4.1.5", "range": (45.0,95.0), "access": 6,
"devtosmap": lambda x: x/10, "smaptodev": lambda x: x*10}, #thermSetbackHeat
{"name": "mode", "unit": "Mode", "data_type": "long",
"OID": "4.1.1", "range": [0,1,2,3], "access": 6,
"devtosmap": lambda x: x-1, "smaptodev": lambda x: x+1}, # thermHvacMode
{"name": "override", "unit": "Mode", "data_type": "long",
"OID": "4.1.9", "range": [0,1], "access": 6,
"devtosmap": lambda x: {1:0, 3:1, 2:0}[x], "smaptodev": lambda x: {0:1, 1:3}[x]}, # hold/override
{"name": "relative_humidity", "unit": "%RH", "data_type": "double",
"OID": "4.1.14", "range": (0,95), "access": 0,
"devtosmap": lambda x: x, "smaptodev": lambda x: x}, #thermRelativeHumidity
{"name": "state", "unit": "Mode", "data_type": "long",
"OID": "4.1.2", "range": [0,1,2], "access": 4,
"devtosmap": lambda x: {1:0, 2:0, 3:1, 4:1, 5:1, 6:2, 7:2, 8:0, 9:0}[x],
"smaptodev": lambda x: {x:x}[x]}, # thermHvacState
{"name": "temperature", "unit": "F", "data_type": "double",
"OID": "4.1.13", "range": (-30.0,200.0), "access": 4,
"devtosmap": lambda x: x/10, "smaptodev": lambda x: x*10}, # thermAverageTemp
{"name": "fan_mode", "unit": "Mode", "data_type": "long",
"OID": "4.1.3", "range": [1,2,3], "access": 6,
"devtosmap": lambda x: x, "smaptodev": lambda x: x} # thermFanMode
]
def get_state(self):
data = {}
for p in self.points:
url = "http://%s/get?OID%s" % (self.ip, p["OID"])
r = requests.get(url, auth=HTTPDigestAuth(self.user, self.password))
val = r.content.split('=')[-1]
if p["data_type"] == "long":
data[p["name"]] = p["devtosmap"](long(val))
else:
data[p["name"]] = p["devtosmap"](float(val))
data["time"] = int(time.time()*1e9)
return data
def set_state(self, request):
for p in self.points:
key = p["name"]
if key in request:
payload = {"OID"+p["OID"]: int(p["smaptodev"](request[key])), "submit": "Submit"}
r = requests.get('http://'+self.ip+"/pdp/", auth=HTTPDigestAuth(self.user, self.password), params=payload)
if not r.ok:
print r.content
def configure(self):
params = None
with open("params.json") as f:
try:
params = json.loads(f.read())
except ValueError as e:
print "Invalid parameter file"
sys.exit(1)
return dict(params)
if __name__ == '__main__':
thermostat = IMT550C()
while True:
print thermostat.get_state()
print
| SoftwareDefinedBuildings/bw2-contrib | driver/imt550c/smap.py | Python | gpl-3.0 | 3,893 |
'use strict';
/**
* pratice Node.js project
*
* @author Mingyi Zheng <badb0y520@gmail.com>
*/
import {expect} from 'chai';
import {request} from '../test';
describe('user', function () {
it('signup', async function () {
try {
const ret = await request.post('/api/signup', {
name: 'test1',
password: '123456789',
});
throw new Error('should throws missing parameter "email" error');
} catch (err) {
expect(err.message).to.equal('email: missing parameter "email"');
}
{
const ret = await request.post('/api/signup', {
name: 'test1',
password: '123456789',
email: 'test1@example.com',
});
console.log(ret);
expect(ret.user.name).to.equal('test1');
expect(ret.user.email).to.equal('test1@example.com');
}
{
const ret = await request.post('/api/login', {
name: 'test1',
password: '123456789',
});
console.log(ret);
expect(ret.token).to.be.a('string');
}
});
});
| akin520/pratice-node-project | src/test/test_user.js | JavaScript | gpl-3.0 | 1,036 |
# nnmware(c)2012-2020
from __future__ import unicode_literals
from django import forms
from django.contrib.admin.widgets import AdminTimeWidget
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.utils.timezone import now
from django.utils.translation import gettext as _, get_language
from nnmware.apps.booking.models import Hotel, Room, Booking, Discount, DISCOUNT_SPECIAL
from nnmware.apps.booking.models import RequestAddHotel, DISCOUNT_NOREFUND, DISCOUNT_CREDITCARD, \
DISCOUNT_EARLY, DISCOUNT_LATER, DISCOUNT_PERIOD, DISCOUNT_PACKAGE, DISCOUNT_NORMAL, DISCOUNT_HOLIDAY, \
DISCOUNT_LAST_MINUTE
from nnmware.apps.money.models import Bill
from nnmware.core.fields import ReCaptchaField
from nnmware.core.forms import UserFromRequestForm
class LocaleNamedForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(LocaleNamedForm, self).__init__(*args, **kwargs)
if get_language() == 'ru':
name = self.instance.name
description = self.instance.description
else:
name = self.instance.name_en
description = self.instance.description_en
self.fields['name'] = forms.CharField(widget=forms.TextInput(attrs={'size': '25'}), initial=name)
self.fields['description'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'wide',
'rows': '5'}),
initial=description)
def save(self, commit=True):
if get_language() == 'ru':
self.instance.name = self.cleaned_data['name']
self.instance.description = self.cleaned_data['description']
else:
self.instance.name_en = self.cleaned_data['name']
self.instance.description_en = self.cleaned_data['description']
return super(LocaleNamedForm, self).save(commit=commit)
class CabinetInfoForm(UserFromRequestForm, LocaleNamedForm):
time_on = forms.CharField(widget=AdminTimeWidget(), required=False)
time_off = forms.CharField(widget=AdminTimeWidget(), required=False)
class Meta:
model = Hotel
fields = ('option', 'time_on', 'time_off')
def __init__(self, *args, **kwargs):
super(CabinetInfoForm, self).__init__(*args, **kwargs)
if get_language() == 'ru':
schema_transit = self.instance.schema_transit
paid_services = self.instance.paid_services
else:
schema_transit = self.instance.schema_transit_en
paid_services = self.instance.paid_services_en
self.fields['schema_transit'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'wide',
'rows': '5'}),
initial=schema_transit)
self.fields['paid_services'] = forms.CharField(required=False, widget=forms.Textarea(attrs={'class': 'wide',
'rows': '5'}),
initial=paid_services)
if not self._user.is_superuser:
self.fields['name'].widget.attrs['readonly'] = True
def clean_name(self):
if self._user.is_superuser:
return self.cleaned_data['name']
if get_language() == 'ru':
return self.instance.name
else:
return self.instance.name_en
def save(self, commit=True):
if get_language() == 'ru':
self.instance.schema_transit = self.cleaned_data['schema_transit']
self.instance.paid_services = self.cleaned_data['paid_services']
else:
self.instance.schema_transit_en = self.cleaned_data['schema_transit']
self.instance.paid_services_en = self.cleaned_data['paid_services']
return super(CabinetInfoForm, self).save(commit=commit)
class CabinetRoomForm(LocaleNamedForm):
class Meta:
model = Room
fields = ('option', 'typefood', 'surface_area')
widgets = {
'typefood': forms.RadioSelect(),
}
class CabinetEditBillForm(forms.ModelForm):
class Meta:
model = Bill
fields = ('date_billed', 'status', 'description_small', 'invoice_number', 'amount')
class RequestAddHotelForm(forms.ModelForm):
city = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
address = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
name = forms.CharField(widget=forms.TextInput(attrs={'size': '35'}))
email = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
phone = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
fax = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
contact_email = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
website = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
rooms_count = forms.CharField(required=False, widget=forms.TextInput(attrs={'size': '35'}))
class Meta:
model = RequestAddHotel
fields = ('city', 'address', 'name', 'email', 'phone', 'fax', 'contact_email',
'website', 'rooms_count', 'starcount')
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(RequestAddHotelForm, self).__init__(*args, **kwargs)
if not user.is_authenticated:
self.fields['recaptcha'] = ReCaptchaField(error_messages={'required': _('This field is required'),
'invalid': _('Answer is wrong')})
class UserCabinetInfoForm(UserFromRequestForm):
class Meta:
model = get_user_model()
fields = ('first_name', 'last_name', 'subscribe')
class BookingAddForm(UserFromRequestForm):
room_id = forms.CharField(max_length=30, required=False)
settlement = forms.CharField(max_length=30, required=False)
hid_method = forms.CharField(max_length=30, required=False)
class Meta:
model = Booking
fields = (
'from_date', 'to_date', 'first_name', 'middle_name', 'last_name', 'phone', 'email', 'guests', 'comment')
def clean_hid_method(self):
m = self.cleaned_data.get('hid_method')
if m:
raise forms.ValidationError(_("Spam."))
return None
def clean_phone(self):
phone = self.cleaned_data.get('phone')
if not phone:
raise forms.ValidationError(_("Phone is required"))
return phone
def clean_email(self):
email = self.cleaned_data.get('email')
if not email:
raise forms.ValidationError(_("Email is required"))
try:
validate_email(email)
except ValidationError as verr:
raise forms.ValidationError(_("Email is wrong"))
return email
def clean(self):
cleaned_data = super(BookingAddForm, self).clean()
if not self._user.is_authenticated:
email = cleaned_data.get('email')
if get_user_model().objects.filter(email=email).exists():
raise forms.ValidationError(_("Email already registered, please sign-in."))
return cleaned_data
class AddDiscountForm(LocaleNamedForm):
# TODO - Not used now(future)
class Meta:
model = Discount
fields = ('name', 'choice', 'time_on', 'time_off', 'days', 'at_price_days', 'percentage', 'apply_norefund',
'apply_creditcard', 'apply_package', 'apply_period')
def __init__(self, *args, **kwargs):
super(AddDiscountForm, self).__init__(*args, **kwargs)
self.fields['name'].required = False
def clean_choice(self):
choice = self.cleaned_data.get('choice')
if choice == 0:
raise forms.ValidationError(_("Discount not set"))
return choice
def clean_name(self):
name = self.cleaned_data.get('name')
if len(name.strip()) is 0:
name = _("New discount from ") + now().strftime("%d.%m.%Y")
return name
def clean(self):
cleaned_data = super(AddDiscountForm, self).clean()
choice = cleaned_data.get("choice")
need_del = []
if choice == DISCOUNT_NOREFUND or choice == DISCOUNT_CREDITCARD:
need_del = ['time_on', 'time_off', 'days', 'at_price_days', 'apply_norefund', 'apply_creditcard',
'apply_package', 'apply_period']
elif choice == DISCOUNT_EARLY:
need_del = ['time_on', 'time_off', 'at_price_days', 'apply_creditcard']
elif choice == DISCOUNT_LATER:
need_del = ['time_off', 'at_price_days']
elif choice == DISCOUNT_PERIOD:
need_del = ['time_on', 'time_off', 'at_price_days', 'apply_package', 'apply_period']
elif choice == DISCOUNT_PACKAGE:
need_del = ['time_on', 'time_off', 'apply_norefund', 'apply_creditcard']
elif choice == DISCOUNT_HOLIDAY or choice == DISCOUNT_SPECIAL or choice == DISCOUNT_NORMAL:
need_del = ['time_on', 'time_off', 'days', 'at_price_days', 'apply_package', 'apply_period']
elif choice == DISCOUNT_LAST_MINUTE:
need_del = ['days', 'at_price_days', 'apply_norefund', 'apply_creditcard', 'apply_package', 'apply_period']
for i in need_del:
del cleaned_data[i]
| nnmware/nnmware | apps/booking/forms.py | Python | gpl-3.0 | 9,755 |
/*
* Copyright (C) 2014 Hector Espert Pardo
*
* 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 utilidades;
import java.util.Random;
/**
*
* @author Hector Espert
*
*/
public class Aleatorios {
/**
* Genera un numero aleatorio entre dos numeros.
* @param min
* @param max
* @return int
*/
public static int entre(int min, int max) {
//Ordenar
if (min > max) {
int aux = min;
min = max;
max = aux;
}
Random aleatorio = new Random();
int numale;
do {
numale = aleatorio.nextInt(max);
if (aleatorio.nextBoolean()) {
numale = -numale;
}
} while (numale < min);
return numale;
}
/**
* Genera un numero aleatorio entre dos numeros.
* @param min
* @param max
* @return double
*/
public static double entre(double min, double max) {
//Ordenar
if (min > max) {
double aux = min;
min = max;
max = aux;
}
Random aleatorio = new Random();
int numale;
do {
numale = aleatorio.nextInt();
if (aleatorio.nextBoolean()) {
numale = -numale;
}
} while (numale < min && numale > max);
return numale;
}
/**
* Devuelve una matrix de enteros aleatorios.
* num es el tamaño de la matriz
* @param num
* @return
*/
public static int[] toMatriz(int num) {
int[] numeros = new int[num];
Random aleatorio = new Random();
for (int i = 0; i < numeros.length; i++) {
int numero = aleatorio.nextInt();
numeros[i] = numero;
}
return numeros;
}
/**
* Devuelve una matrix de enteros aleatorios de 0 a un valor.
* num es el tamaño de la matriz
* max es el valor maximo de los aleatorios.
* @param num
* @param max
* @return
*/
public static int[] toMatriz(int num, int max) {
int[] numeros = new int[num];
Random aleatorio = new Random();
for (int i = 0; i < numeros.length; i++) {
int numero = aleatorio.nextInt(max);
numeros[i] = numero;
}
return numeros;
}
/**
* Devuelve una matrix de enteros aleatorios entre dos valores.
* @param num
* @param min
* @param max
* @return
*/
public static int[] toMatrizEntre (int num, int min, int max) {
int[] numeros = new int[num];
//Ordenar
if (min > max) {
int aux = min;
min = max;
max = aux;
}
for (int i = 0; i < numeros.length; i++) {
numeros[i] = entre(min, max);
}
return numeros;
}
/**
* Devuelve una matriz multiplie con numeros aleatorios.
* @param num
* @return
*/
public static int[][] toMatrizMulti(int num) {
int[][] numeros = new int[num][num];
Random aleatorio = new Random();
for (int[] matriz : numeros) {
for (int i = 0; i < matriz.length; i++) {
matriz[i] = aleatorio.nextInt();
}
}
return numeros;
}
/**
* Devuelve una matriz
* @param num
* @param max
* @return
*/
public static int[][] toMatrizMulti(int num, int max) {
int[][] numeros = new int[num][num];
Random aleatorio = new Random();
for (int[] matriz : numeros) {
for (int i = 0; i < matriz.length; i++) {
matriz[i] = aleatorio.nextInt(max);
}
}
return numeros;
}
/**
*
* @param num
* @param min
* @param max
* @return
*/
public static int[][] toMatrizMultiEntre (int num, int min, int max) {
int[][] numeros = new int[num][num];
//Ordenar
if (min > max) {
int aux = min;
min = max;
max = aux;
}
for (int[] matriz : numeros) {
for (int i = 0; i < matriz.length; i++) {
matriz[i] = entre(min, max);
}
}
return numeros;
}
/**
* Devuelve un boolean aleatorio.
* @return
*/
public static boolean getBoolean() {
Random aleatorio = new Random();
return aleatorio.nextBoolean();
}
/**
* Devuelve un int aleatorio.
* @return
*/
public static int getInt() {
Random aleatorio = new Random();
return aleatorio.nextInt();
}
}
| cheste1/LibDAM | LibDAM/src/utilidades/Aleatorios.java | Java | gpl-3.0 | 6,150 |
// Copyright (C) 2009--2011, 2013, 2014 Jed Brown and Ed Bueler and Constantine Khroulev and David Maxwell
//
// This file is part of PISM.
//
// PISM 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.
//
// PISM 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 PISM; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
// The following are macros (instead of inline functions) so that error handling
// is less cluttered. They should be replaced with empty macros when in
// optimized mode.
#ifndef _FETOOLS_H_
#define _FETOOLS_H_
#include <petscmat.h>
#include "iceModelVec.hh" // to get PISMVector2
//! \file
//! \brief Classes for implementing the Finite Element Method on an IceGrid.
/*! \file
We assume that the reader has a basic understanding of the finite element method.
The following is a reminder of the method that also
gives the background for the how to implement it on an IceGrid with the tools in this
module.
The IceGrid domain \f$\Omega\f$ is decomposed into a grid of rectangular physical elements indexed by indices (i,j):
\verbatim
(0,1) (1,1)
---------
| | |
---------
| | |
---------
(0,0) (1,0)
\endverbatim
The index of an element corresponds with the index of its lower-left vertex in the grid.
The reference element is the square \f$[-1,1]\times[-1,1]\f$. For each physical element \f$E_{ij}\f$, there is an
map \f$F_{ij}\f$ from the reference element \f$R\f$ to \f$E_{ij}\f$.
In this implementation, the rectangles in the domain are all congruent, and the maps F_{ij} are all the same up
to a translation.
On the reference element, vertices are ordered as follows:
\verbatim
3 o---------o 2
| |
| |
| |
0 o---------o 1
\endverbatim
For each vertex \f$k\f$ there is an element basis function \f$\phi_k\f$ that is bilinear, equals 1 at
vertex \f$k\f$, and equals 0 at the remaining vertices.
For each node \f$(i',j')\f$ in the physical domain there is a basis function that equals 1 at
vertex \f$(i',j')\f$, equals zero at all other vertices, and that on element \f$(i,j)\f$
can be written as \f$\phi_k\circ F_{i,j}^{-1}\f$ for some index \f$k\f$.
A (scalar) finite element function \f$f\f$ on the domain is then a linear combination
\f[
f_h = \sum_{i,j} c_{ij}\psi_{ij}.
\f]
Let \f$G(w,\psi)\f$ denote the weak form of the PDE under consideration. For
example, for the scalar Poisson equation \f$-\Delta w = f\f$,
\f[
G(w,\psi) = \int_\Omega \nabla w \cdot \nabla \psi -f\psi\;dx.
\f]
In the continuous problem we seek to
find a trial function \f$w\f$ such that \f$G(w,\psi)=0\f$ for all suitable test
functions \f$\psi\f$. In the discrete problem, we seek a finite element function \f$w_h\f$
such that \f$G(w_h,\psi_{ij})=0\f$ for all suitable indices \f$(i,j)\f$.
For realistice problems, the integral given by \f$G\f$ cannot be evaluated exactly,
but is approximated with some \f$G_h\f$ that arises from numerical quadrature quadrature rule:
integration on an element \f$E\f$ is approximated with
\f[
\int_E f dx \approx \sum_{q} f(x_q) w_q
\f]
for certain points \f$x_q\f$ and weights \f$j_q\f$ (specific details are found in FEQuadrature).
The unknown \f$w_h\f$ is represented by an IceVec, \f$w_h=\sum_{ij} c_{ij} \psi_{ij}\f$ where
\f$c_{ij}\f$ are the coefficients of the vector. The solution of the finite element problem
requires the following computations:
-# Evaluation of the residuals \f$r_{ij} = G_h(w_h,\psi_{ij})\f$
-# Evaluation of the Jacobian matrix
\f[
J_{(ij)\;(kl)}=\frac{d}{dc_{kl}} G_h(w_h,\psi_{ij}).
\f]
Computations of these 'integrals' are done by adding up the contributions
from each element (an FEElementMap helps with iterating over the elements).
For a fixed element, there is a locally defined trial
function \f$\hat w_h\f$ (with 4 degrees of freedom in the scalar case) and
4 local test functions \f$\hat\psi_k\f$, one for each vertex.
The contribution to the integrals proceeds as follows (for concreteness
in the case of computing the residual):
- Extract from the global degrees of freedom \f$c\f$ defining \f$w_h\f$
the local degrees of freedom \f$d\f$ defining \f$\hat w_h\f$. (FEDOFMap)
- Evaluate the local trial function \f$w_h\f$ (values and derivatives as needed)
at the quadrature points \f$x_q\f$ (FEQuadrature)
- Evaluate the local test functions (again values and derivatives)
at the quadrature points. (FEQuadrature)
- Obtain the quadrature weights $j_q$ for the element (FEQuadrature)
- Compute the values of the integrand \f$g(\hat w_h,\psi_k)\f$
at each quadrature point (call these \f$g_{qk}\f$) and
form the weighted sums \f$y_k=\sum_{q} j_q g_{qk}\f$.
- Each sum \f$y_k\f$ is the contribution of the current element to
a residual entry \f$r_{ij}\f$, where local degree of freedom \f$k\f$
corresponds with global degree of freedom \f$(i,j)\f$. The
local contibutions now need to be added to the global residual vector (FEDOFMap).
Computation of the Jacobian is similar, except that there are now
multiple integrals per element (one for each local degree of freedom of
\f$\hat w_h\f$).
All of the above is a simplified description of what happens in practice.
The complications below treated by the following classes, and discussed
in their documentation:
- Ghost elements (as well as periodic boundary conditions): FEElementMap
- Dirichlet data: FEDOFMap
- Vector valued functions: (FEDOFMap, FEQuadrature)
The classes in this module are not intended
to be a fancy finite element package.
Their purpose is to clarify the steps that occur in the computation of
residuals and Jacobians in SSAFEM, and to isolate and consolodate
the hard steps so that they are not scattered about the code.
*/
//! Struct for gathering the value and derivative of a function at a point.
/*! Germ in meant in the mathematical sense, sort of. */
struct FEFunctionGerm
{
double val, //!< Function value.
dx, //!< Function deriviative with respect to x.
dy; //!< Function derivative with respect to y.
};
//! Struct for gathering the value and derivative of a vector valued function at a point.
/*! Germ in meant in the mathematical sense, sort of. */
struct FEVector2Germ
{
PISMVector2 val, //!< Function value.
dx, //!< Function deriviative with respect to x.
dy; //!< Function derivative with respect to y.
};
//! Computation of Q1 shape function values.
/*! The Q1 shape functions are bilinear functions. On a rectangular
element, there are four (FEShapeQ1::Nk) basis functions, each equal
to 1 at one vertex and equal to zero at the remainder.
The FEShapeQ1 class consolodates the computation of the values and
derivatives of these basis functions. */
class FEShapeQ1 {
public:
virtual ~FEShapeQ1() {}
//! Compute values and derivatives of the shape function supported at node 0
static void shape0(double x, double y, FEFunctionGerm *value)
{
value->val = (1-x)*(1-y)/4.;
value->dx = -(1-y)/4.;
value->dy = -(1-x)/4;
}
//! Compute values and derivatives of the shape function supported at node 1
static void shape1(double x, double y, FEFunctionGerm *value)
{
value->val = (1+x)*(1-y)/4.;
value->dx = (1-y)/4.;
value->dy = -(1+x)/4;
}
//! Compute values and derivatives of the shape function supported at node 2
static void shape2(double x, double y, FEFunctionGerm *value)
{
value->val = (1+x)*(1+y)/4.;
value->dx = (1+y)/4.;
value->dy = (1+x)/4;
}
//! Compute values and derivatives of the shape function supported at node 3
static void shape3(double x, double y, FEFunctionGerm *value)
{
value->val = (1-x)*(1+y)/4.;
value->dx = -(1+y)/4.;
value->dy = (1-x)/4;
}
//! The number of basis shape functions.
static const int Nk = 4;
//! A table of function pointers, one for each shape function.
typedef void (*ShapeFunctionSpec)(double,double,FEFunctionGerm*);
static const ShapeFunctionSpec shapeFunction[Nk];
//! Evaluate shape function \a k at (\a x,\a y) with values returned in \a germ.
virtual void eval(int k, double x, double y,FEFunctionGerm*germ){
shapeFunction[k](x,y,germ);
}
};
//! The mapping from global to local degrees of freedom.
/*! Computations of residual and Jacobian entries in the finite element method are
done by iterating of the elements and adding the various contributions from each element.
To do this, degrees of freedom from the global vector of unknowns must be remapped to
element-local degrees of freedom for the purposes of local computation,
(and the results added back again to the global residual and Jacobian arrays).
An FEDOFMap mediates the transfer between element-local and global degrees of freedom.
In this very concrete implementation, the global degrees of freedom are either
scalars (double's) or vectors (PISMVector2's), one per node in the IceGrid,
and the local degrees of freedom on the element are FEDOFMap::Nk (%i.e. four) scalars or vectors, one
for each vertex of the element.
The FEDOFMap is also (perhaps awkwardly) overloaded to also mediate transfering locally
computed contributions to residual and Jacobian matricies to their global
counterparts.
See also: \link FETools.hh FiniteElement/IceGrid background material\endlink.
*/
class FEDOFMap
{
public:
FEDOFMap()
{
m_i = m_j = 0;
PetscMemzero(m_row, Nk*sizeof(MatStencil));
PetscMemzero(m_col, Nk*sizeof(MatStencil));
};
virtual ~FEDOFMap() {};
virtual void extractLocalDOFs(int i, int j, double const*const*xg, double *x) const;
virtual void extractLocalDOFs(int i, int j, PISMVector2 const*const*xg, PISMVector2 *x) const;
virtual void extractLocalDOFs(double const*const*xg, double *x) const;
virtual void extractLocalDOFs(PISMVector2 const*const*xg, PISMVector2 *x) const;
virtual void reset(int i, int j, const IceGrid &g);
virtual void markRowInvalid(int k);
virtual void markColInvalid(int k);
void localToGlobal(int k, int *i, int *j);
virtual void addLocalResidualBlock(const PISMVector2 *y, PISMVector2 **yg);
virtual void addLocalResidualBlock(const double *y, double **yg);
virtual PetscErrorCode addLocalJacobianBlock(const double *K, Mat J);
virtual PetscErrorCode setJacobianDiag(int i, int j, const double *K, Mat J);
static const int Nk = 4; //<! The number of test functions defined on an element.
protected:
static const int kDofInvalid = PETSC_MIN_INT / 8; //!< Constant for marking invalid row/columns.
static const int kIOffset[Nk];
static const int kJOffset[Nk];
//! Indices of the current element (for updating residual/Jacobian).
int m_i, m_j;
//! Stencils for updating entries of the Jacobian matrix.
MatStencil m_row[Nk], m_col[Nk];
};
//! Manages iterating over element indices.
/*! When computing residuals and Jacobians, there is a loop over all the elements
in the IceGrid, and computations are done on each element. The IceGrid
has an underlying Petsc DA, and our processor does not own all of the nodes in the grid.
Therefore we should not perform computation on all of the elements. In general,
an element will have ghost (o) and real (*) vertices:
\verbatim
o---*---*---*---o
| | | | |
o---*---*---*---o
| | | | |
o---o---o---o---o
\endverbatim
The strategy is to do computations on this processor on every element that has
a vertex that is owned by this processor. But we only update entries in the
global residual and Jacobian matrices if the corresponding row corresponds to a
vertex that we own. In the worst case, where each vertex of an element is owned by
a different processor, the computations for that element will be repeated four times,
once for each processor.
This same strategy also correctly deals with periodic boundary conditions. The way Petsc deals
with periodic boundaries can be thought of as using a kind of ghost. So the rule still works:
compute on all elements containg a real vertex, but only update rows corresponding to that real vertex.
The calculation of what elements to index over needs to account for ghosts and the
presence or absense of periodic boundary conditions in the IceGrid. The FEElementMap performs
that computation for you (see FEElementMap::xs and friends).
See also: \link FETools.hh FiniteElement/IceGrid background material\endlink.
*/
class FEElementMap
{
public:
FEElementMap(const IceGrid &g);
/*!\brief The total number of elements to be iterated over. Useful for creating per-element storage.*/
int element_count()
{
return xm*ym;
}
/*!\brief Convert an element index (\a i,\a j) into a flattened (1-d) array index, with the first
element (\a i, \a j) to be iterated over corresponding to flattened index 0. */
int flatten(int i, int j)
{
return (i-xs)*ym+(j-ys);
}
int xs, //!< x-coordinate of the first element to loop over.
xm, //!< total number of elements to loop over in the x-direction.
ys, //!< y-coordinate of the first element to loop over.
ym, //!< total number of elements to loop over in the y-direction.
lxs, //!< x-index of the first local element.
lxm, //!< total number local elements in x direction.
lys, //!< y-index of the first local element.
lym; //!< total number local elements in y direction.
};
//! Numerical integration of finite element functions.
/*! The core of the finite element method is the computation of integrals over elements.
For nonlinear problems, or problems with non-constant coefficients (%i.e. any real problem)
the integration has to be done approximately:
\f[
\int_E f(x)\; dx \approx \sum_q f(x_q) w_q
\f]
for certain quadrature points \f$x_q\f$ and weights \f$w_q\f$. An FEQuadrature is used
to evaluate finite element functions at quadrature points, and to compute weights \f$w_q\f$
for a given element.
In this concrete implementation, the reference element \f$R\f$ is the square
\f$[-1,1]\times[-1,1]\f$. On a given element, nodes (o) and quadrature points (*)
are ordered as follows:
\verbatim
3 o------------------o 2
| 3 2 |
| * * |
| |
| |
| * * |
| 0 1 |
0 o------------------o 1
\endverbatim
So there are four quad points per element, which occur at \f$x,y=\pm 1/\sqrt{3}\f$. This corresponds to the tensor product
of Gaussian integration on an interval that is exact for cubic functions on the interval.
Integration on a physical element can be thought of as being done by change of variables. The quadrature weights need
to be modified, and the FEQuadrature takes care of this for you. Because all elements in an IceGrid are congruent, the
quadrature weights are the same for each element, and are computed upon initialization with an IceGrid.
See also: \link FETools.hh FiniteElement/IceGrid background material\endlink.
*/
class FEQuadrature
{
public:
static const int Nq = 4; //!< Number of quadrature points.
static const int Nk = 4; //!< Number of test functions on the element.
FEQuadrature();
void init(const IceGrid &g,double L=1.); // FIXME Allow a length scale to be specified.
const FEFunctionGerm (*testFunctionValues())[Nq];
const FEFunctionGerm *testFunctionValues(int q);
const FEFunctionGerm *testFunctionValues(int q,int k);
void computeTrialFunctionValues( const double *x, double *vals);
void computeTrialFunctionValues( const double *x, double *vals, double *dx, double *dy);
void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, double const*const*xg, double *vals);
void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, double const*const*xg,
double *vals, double *dx, double *dy);
void computeTrialFunctionValues( const PISMVector2 *x, PISMVector2 *vals);
void computeTrialFunctionValues( const PISMVector2 *x, PISMVector2 *vals, double (*Dv)[3]);
void computeTrialFunctionValues( const PISMVector2 *x, PISMVector2 *vals, PISMVector2 *dx, PISMVector2 *dy);
void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, PISMVector2 const*const*xg,
PISMVector2 *vals);
void computeTrialFunctionValues( int i, int j, const FEDOFMap &dof, PISMVector2 const*const*xg,
PISMVector2 *vals, double (*Dv)[3]);
void getWeightedJacobian(double *jxw);
//! The coordinates of the quadrature points on the reference element.
static const double quadPoints[Nq][2];
//! The weights for quadrature on the reference element.
static const double quadWeights[Nq];
protected:
//! The Jacobian determinant of the map from the reference element to the physical element.
double m_jacobianDet;
//! Shape function values (for each of \a Nq quadrature points, and each of \a Nk shape function )
FEFunctionGerm m_germs[Nq][Nk];
double m_tmpScalar[Nk];
PISMVector2 m_tmpVector[Nk];
};
class DirichletData {
public:
DirichletData();
~DirichletData();
PetscErrorCode init( IceModelVec2Int *indices, IceModelVec2V *values, double weight);
PetscErrorCode init( IceModelVec2Int *indices, IceModelVec2S *values, double weight);
PetscErrorCode init( IceModelVec2Int *indices);
void constrain( FEDOFMap &dofmap );
void update( FEDOFMap &dofmap, PISMVector2* x_e );
void update( FEDOFMap &dofmap, double* x_e );
void updateHomogeneous( FEDOFMap &dofmap, PISMVector2* x_e );
void updateHomogeneous( FEDOFMap &dofmap, double* x_e );
void fixResidual( PISMVector2 **x, PISMVector2 **r);
void fixResidual( double **x, double **r);
void fixResidualHomogeneous( PISMVector2 **r);
void fixResidualHomogeneous( double **r);
PetscErrorCode fixJacobian2V( Mat J);
PetscErrorCode fixJacobian2S( Mat J);
operator bool() {
return m_indices != NULL;
}
PetscErrorCode finish();
protected:
double m_indices_e[FEQuadrature::Nk];
IceModelVec2Int *m_indices;
IceModelVec *m_values;
double **m_pIndices;
void **m_pValues;
double m_weight;
};
#endif/* _FETOOLS_H_*/
| talbrecht/pism_pik06 | src/base/stressbalance/ssa/FETools.hh | C++ | gpl-3.0 | 18,810 |
/*
* Copyright (c) 2010-2014 Clark & Parsia, LLC. <http://www.clarkparsia.com>
*
* 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.complexible.stardog.plan.aggregates;
import java.io.File;
import com.complexible.common.protocols.server.Server;
import com.complexible.common.rdf.query.resultio.TextTableQueryResultWriter;
import com.complexible.stardog.Stardog;
import com.complexible.stardog.api.Connection;
import com.complexible.stardog.api.ConnectionConfiguration;
import com.complexible.stardog.api.admin.AdminConnection;
import com.complexible.stardog.api.admin.AdminConnectionConfiguration;
import com.complexible.stardog.protocols.snarl.SNARLProtocolConstants;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.resultio.QueryResultIO;
/**
* <p></p>
*
* @author Albert Meroño-Peñuela
* @since 1.0
* @version 1.0
*/
public class TestRAggregates {
private static Server SERVER = null;
private static final String DB = "testRAggregates";
@BeforeClass
public static void beforeClass() throws Exception {
SERVER = Stardog.buildServer()
.bind(SNARLProtocolConstants.EMBEDDED_ADDRESS)
.start();
final AdminConnection aConn = AdminConnectionConfiguration.toEmbeddedServer()
.credentials("admin", "admin")
.connect();
try {
if (aConn.list().contains(DB)) {
aConn.drop(DB);
}
aConn.memory(DB).create(new File("/Users/Albert/src/linked-edit-rules/data/people.ttl"));
}
finally {
aConn.close();
}
}
@AfterClass
public static void afterClass() {
if (SERVER != null) {
SERVER.stop();
}
}
@Test
public void TestMean() throws Exception {
final Connection aConn = ConnectionConfiguration.to(DB)
.credentials("admin", "admin")
.connect();
try {
final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
"PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
"PREFIX agg: <urn:aggregate> " +
"SELECT (agg:stardog:mean(?o) AS ?c) " +
"WHERE { ?s leri:height ?o } ";
System.out.println("Executing query: " + aQuery);
final TupleQueryResult aResult = aConn.select(aQuery).execute();
try {
System.out.println("Query result:");
while (aResult.hasNext()) {
System.out.println(aResult.next().getValue("c").stringValue());
}
}
finally {
aResult.close();
}
}
finally {
aConn.close();
}
}
// @Test
// public void TestMedian() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:median(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestMaxAggregate() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:max(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestMinAggregate() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:min(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestSd() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:sd(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestVar() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "PREFIX agg: <urn:aggregate> " +
// "SELECT (agg:stardog:var(?o) AS ?c) " +
// "WHERE { ?s leri:height ?o } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestAbs() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:abs(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestSqrt() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:sqrt(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestCeiling() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:ceiling(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestFloor() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:floor(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestTrunc() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:trunc(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestLog() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:log(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestLog10() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:log10(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestExp() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:exp(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestRound() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:round(stardog:sin(?o), 4) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestSignif() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:signif(stardog:sin(?o), 4) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestCos() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:cos(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestSin() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:sin(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestTan() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT ?c " +
// "WHERE { ?s leri:height ?o . BIND (stardog:tan(?o) AS ?c) } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
//
// @Test
// public void TestCov() throws Exception {
// final Connection aConn = ConnectionConfiguration.to(DB)
// .credentials("admin", "admin")
// .connect();
// try {
//
// final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
// "PREFIX sdmx-dimension: <http://purl.org/linked-data/sdmx/2009/dimension#> " +
// "PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
// "SELECT (stardog:cov(?height, ?age) AS ?c) " +
// "WHERE { ?s leri:height ?height ; sdmx-dimension:age ?age } ";
// System.out.println("Executing query: " + aQuery);
//
// final TupleQueryResult aResult = aConn.select(aQuery).execute();
//
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// System.out.println(aResult.next().getValue("c").stringValue());
// }
// }
// finally {
// aResult.close();
// }
// }
// finally {
// aConn.close();
// }
// }
@Test
public void TestPredict() throws Exception {
final Connection aConn = ConnectionConfiguration.to(DB)
.credentials("admin", "admin")
.connect();
try {
final String aQuery = "PREFIX stardog: <tag:stardog:api:> " +
"PREFIX sdmx-dimension: <http://purl.org/linked-data/sdmx/2009/dimension#> " +
"PREFIX leri: <http://lod.cedar-project.nl:8888/linked-edit-rules/resource/> " +
"SELECT (stardog:predict(?age) AS ?page) " +
"WHERE { ?s leri:height ?height . } ";
System.out.println("Executing query: " + aQuery);
final TupleQueryResult aResult = aConn.select(aQuery).execute();
//QueryResultIO.write(aResult, TextTableQueryResultWriter.FORMAT, System.out);
// try {
// System.out.println("Query result:");
// while (aResult.hasNext()) {
// try {
// System.out.println(aResult.next().getValue("page").stringValue());
// } catch (NullPointerException e) {
// System.out.println("NA");
// }
// }
// } catch (NullPointerException e) {
// System.err.println(e.getMessage());
// }
// finally {
// aResult.close();
// }
}
finally {
aConn.close();
}
}
}
| albertmeronyo/stardog-r | aggregates/test/src/com/complexible/stardog/plan/aggregates/TestRAggregates.java | Java | gpl-3.0 | 22,803 |
/*
* HelpCommand.java
*
* Copyright (C) 2002-2013 Takis Diakoumis
*
* 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 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.executequery.gui.console.commands;
import org.executequery.gui.console.Console;
import org.underworldlabs.util.SystemProperties;
/* ----------------------------------------------------------
* CVS NOTE: Changes to the CVS repository prior to the
* release of version 3.0.0beta1 has meant a
* resetting of CVS revision numbers.
* ----------------------------------------------------------
*/
/**
* This command displays command help.
* @author Romain Guy
*/
/**
* @author Takis Diakoumis
* @version $Revision: 160 $
* @date $Date: 2013-02-08 17:15:04 +0400 (Пт, 08 фев 2013) $
*/
public class HelpCommand extends Command {
private static final String COMMAND_NAME = "help";
public String getCommandName() {
return COMMAND_NAME;
}
public String getCommandSummary() {
return SystemProperties.getProperty("console", "console.help.command.help");
}
public boolean handleCommand(Console console, String command) {
if (command.equals(COMMAND_NAME)) {
console.help();
return true;
}
return false;
}
}
| Black-millenium/rdb-executequery | java/src/org/executequery/gui/console/commands/HelpCommand.java | Java | gpl-3.0 | 1,823 |
/*
* Copyright 2010 kk-electronic a/s.
*
* This file is part of KKPortal.
*
* KKPortal 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.
*
* KKPortal 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 KKPortal. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kk_electronic.kkportal.core.rpc.jsonformat;
@SuppressWarnings("serial")
public class UnableToDeserialize extends Exception {
public UnableToDeserialize(String string) {
super(string);
}
}
| kk-electronic/KKPortal | src/com/kk_electronic/kkportal/core/rpc/jsonformat/UnableToDeserialize.java | Java | gpl-3.0 | 950 |
/**
* Copyright 2015 Poznań Supercomputing and Networking Center
*
* Licensed under the GNU General Public License, Version 3.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.gnu.org/licenses/gpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package pl.psnc.synat.wrdz.ms.stats;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import pl.psnc.synat.wrdz.ms.entity.stats.DataFileFormatStat;
import pl.psnc.synat.wrdz.zmd.dto.format.DataFileFormatDto;
import pl.psnc.synat.wrdz.zmd.format.DataFileFormatBrowser;
/**
* Bean that handles data file format statistics.
*/
@SuppressWarnings("serial")
public abstract class DataFileFormatBean implements Serializable {
/** Data file format statistics. */
private List<DataFileFormatStat> stats;
/** Data file format information. */
private Map<String, DataFileFormatDto> formats;
/** Data file format browser. */
@EJB(name = "DataFileFormatBrowser")
private transient DataFileFormatBrowser formatBrowser;
/** When the statistics were computed. */
private Date computedOn;
/**
* Refreshes the currently cached statistics.
*/
public void refresh() {
stats = fetchStatistics();
computedOn = !stats.isEmpty() ? stats.get(0).getComputedOn() : null;
formats = new HashMap<String, DataFileFormatDto>();
for (DataFileFormatDto format : formatBrowser.getFormats()) {
formats.put(format.getPuid(), format);
}
}
/**
* Returns the currently cached statistics, refreshing them if necessary.
*
* @return statistics
*/
public List<DataFileFormatStat> getStatistics() {
if (stats == null) {
refresh();
}
return stats;
}
public Date getComputedOn() {
return computedOn;
}
/**
* Returns the map with format puids and their data.
*
* @return a <format puid, format data> map
*/
public Map<String, DataFileFormatDto> getFormats() {
if (formats == null) {
refresh();
}
return formats;
}
/**
* Fetches the statistics from database.
*
* @return the statistics
*/
protected abstract List<DataFileFormatStat> fetchStatistics();
}
| psnc-dl/darceo | wrdz/wrdz-ms/web/src/main/java/pl/psnc/synat/wrdz/ms/stats/DataFileFormatBean.java | Java | gpl-3.0 | 2,754 |
<?php
/*
Copyright (c) 2009-2017 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Legacy mode enabler
class F3
{
public static $fw;
/**
* Forward function calls to framework
*
* @return mixed
* @param $func callback
* @param $args array
**/
public static function __callstatic($func, array $args)
{
if (!self::$fw) {
self::$fw=Base::instance();
}
return call_user_func_array([self::$fw,$func], $args);
}
}
| vijinho/fatfree-core-psr2 | f3.php | PHP | gpl-3.0 | 1,213 |
#include "pointconversor.h"
#include "invalidconversorinput.h"
// TODO: implement human notation WIHTOUT double float (or any float).
// With float, there are some 64 bits numbers which cannot be represented
// because double float only really has 52 bits for mantissa.
PointConversor::PointConversor():
bits(0),
exponent(0),
sign(false),
normality(PointConversor::NORMAL)
{
}
// Raw input functions
PointConversor& PointConversor::inputHalfFloatRaw(uint16_t number)
{
return this->inputGenericFloatRaw(number, 10, 5);
}
PointConversor& PointConversor::inputSingleFloatRaw(float number)
{
union { float number; uint32_t bits; } bitCast { number };
return this->inputGenericFloatRaw(bitCast.bits, 23, 8);
}
PointConversor& PointConversor::inputDoubleFloatRaw(double number)
{
union { double number; uint64_t bits; } bitCast { number };
return this->inputGenericFloatRaw(bitCast.bits, 52, 11);
}
PointConversor& PointConversor::inputFixed8Raw(uint8_t number, int16_t pointPos, Signedness signedness)
{
return this->inputGenericFixedRaw(number, 8, pointPos, signedness);
}
PointConversor& PointConversor::inputFixed16Raw(uint16_t number, int16_t pointPos, Signedness signedness)
{
return this->inputGenericFixedRaw(number, 16, pointPos, signedness);
}
PointConversor& PointConversor::inputFixed32Raw(uint32_t number, int16_t pointPos, Signedness signedness)
{
return this->inputGenericFixedRaw(number, 32, pointPos, signedness);
}
PointConversor& PointConversor::inputFixed64Raw(uint64_t number, int16_t pointPos, Signedness signedness)
{
return this->inputGenericFixedRaw(number, 64, pointPos, signedness);
}
// String input functions
PointConversor& PointConversor::inputHalfFloat(QString const& number)
{
return this->inputGenericFloat(number, 10, 5);
}
PointConversor& PointConversor::inputSingleFloat(QString const& number)
{
return this->inputGenericFloat(number, 23, 8);
}
PointConversor& PointConversor::inputDoubleFloat(QString const& number)
{
return this->inputGenericFloat(number, 52, 11);
}
PointConversor& PointConversor::inputFixed8(QString const& number, Signedness signedness)
{
return this->inputGenericFixed(number, 8, signedness);
}
PointConversor& PointConversor::inputFixed16(QString const& number, Signedness signedness)
{
return this->inputGenericFixed(number, 16, signedness);
}
PointConversor& PointConversor::inputFixed32(QString const& number, Signedness signedness)
{
return this->inputGenericFixed(number, 32, signedness);
}
PointConversor& PointConversor::inputFixed64(QString const& number, Signedness signedness)
{
return this->inputGenericFixed(number, 64, signedness);
}
PointConversor& PointConversor::inputHumanNotation(QString const& number)
{
// For now, we are decoding human notation via double float. This means we
// are losing some precision, since double has only 52 bits of significant
// digits, and our class stores 64 bits of significant digits, but that's
// perhaps acceptable.
bool ok = true;
double asDoubleFloat = number.toDouble(&ok);
if (!ok) {
throw InvalidConversorInput("Número não está na notação humana adequada");
}
return this->inputDoubleFloatRaw(asDoubleFloat);
}
// Raw output functions
uint16_t PointConversor::outputHalfFloatRaw() const
{
return this->outputGenericFloatRaw(10, 5);
}
float PointConversor::outputSingleFloatRaw() const
{
uint32_t number = this->outputGenericFloatRaw(23, 8);
union { uint32_t bits; float number; } bitCast { number };
return bitCast.number;
}
double PointConversor::outputDoubleFloatRaw() const
{
uint64_t number = this->outputGenericFloatRaw(52, 11);
union { uint64_t bits; double number; } bitCast { number };
return bitCast.number;
}
uint8_t PointConversor::outputFixed8Raw(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixedRaw(8, pointPos, signedness);
}
uint16_t PointConversor::outputFixed16Raw(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixedRaw(16, pointPos, signedness);
}
uint32_t PointConversor::outputFixed32Raw(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixedRaw(32, pointPos, signedness);
}
uint64_t PointConversor::outputFixed64Raw(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixedRaw(64, pointPos, signedness);
}
QString PointConversor::outputHalfFloat() const
{
return this->outputGenericFloat(10, 5);
}
QString PointConversor::outputSingleFloat() const
{
return this->outputGenericFloat(23, 8);
}
QString PointConversor::outputDoubleFloat() const
{
return this->outputGenericFloat(52, 11);
}
// String output function
QString PointConversor::outputFixed8(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixed(8, pointPos, signedness);
}
QString PointConversor::outputFixed16(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixed(16, pointPos, signedness);
}
QString PointConversor::outputFixed32(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixed(32, pointPos, signedness);
}
QString PointConversor::outputFixed64(int16_t pointPos, Signedness signedness) const
{
return this->outputGenericFixed(64, pointPos, signedness);
}
QString PointConversor::outputHumanNotation() const
{
double asDoubleFloat = this->outputDoubleFloatRaw();
QString rendered = QString::number(asDoubleFloat, 'f', 50);
if (rendered.contains('.')) {
int trailingPos = rendered.length() - 1;
while (trailingPos > 2 && rendered[trailingPos] == '0') {
trailingPos--;
}
rendered.truncate(trailingPos + 1);
}
return rendered;
}
// Generic input functions
PointConversor& PointConversor::inputGenericFloatRaw(uint64_t number, uint16_t mantissaSize, uint16_t exponentSize)
{
uint64_t mantissaMask = 0;
int16_t exponentMask = 0;
uint64_t finalBit = 0;
validateFloatSpec(mantissaSize, exponentSize);
// Initialize here because mantissa size or exponent size might be invalid.
mantissaMask = ((uint64_t) 1 << mantissaSize) - 1;
exponentMask = ((uint64_t) 1 << exponentSize) - 1;
finalBit = ((uint64_t) 1 << mantissaSize);
// Sign is the last bit.
this->sign = number >> (exponentSize + mantissaSize);
// We store the mantissa bits (lower bits) as the significant bits.
this->bits = number & mantissaMask;
// Exponent is between the mantissa and the sign.
this->exponent = (number >> mantissaSize) & exponentMask;
if (this->exponent != exponentMask) {
// Exponent being `< maximum` exponent means it is normal.
if (this->exponent == 0) {
// But if the exponent is zero, it is actually subnormal.
this->exponent++;
} else {
// Otherwise, `0 < exponent < max` means it is really normal.
//
// There is an extra high bit, because a normal number is in this
// format:
//
// 1.xxxxxxx... * 2**e
//
// And this "1" is not stored, only the xxxxxx...
//
// So, we need to introduce it.
this->bits |= finalBit;
}
this->normality = PointConversor::NORMAL;
// The exponent uses an encoding which we need to translate to C++'s signed numbers.
this->exponent -= mantissaSize + (exponentMask >> 1);
} else if (this->bits == 0) {
// exponent == MAX and bits are zeroed, therefore, Infinity.
this->normality = PointConversor::INFINITY_NAN;
} else {
// exponent == MAX and bits not zeroed, therefore, regular NAN.
this->normality = PointConversor::NOT_A_NUMBER;
}
return *this;
}
PointConversor& PointConversor::inputGenericFixedRaw(uint64_t number, int16_t width, int16_t pointPos, Signedness signedness)
{
uint64_t signMask = 0;
uint64_t extendMask = 0;
validateFixedSpec(width, pointPos, signedness);
// Initialize here because width might be invalid.
//
// Last bit.
signMask = (uint64_t) 1 << (width - 1);
// Cut off extension mask, 0000....011111...1111
extendMask = ~((uint64_t) 0) >> (MAX_WIDTH - width);
// Fixed point is always normal.
this->normality = PointConversor::NORMAL;
switch (signedness) {
case UNSIGNED:
this->sign = false;
break;
case TWOS_COMPL:
this->sign = (number & signMask) != 0;
break;
}
// Bits b with point p means the number is b * 2**(-p)
this->exponent = -pointPos;
this->bits = number;
if (this->sign) {
// Complementing negativeness.
this->bits = (~this->bits + 1) & extendMask;
}
return *this;
}
PointConversor& PointConversor::inputGenericFloat(QString const &number, uint16_t mantissaSize, uint16_t exponentSize)
{
uint64_t numBits = 0;
bool hasChars = false;
int count = 0;
for (QChar numChar : number) {
if (numChar == '0' || numChar == '1') {
numBits <<= 1;
// By now we know it is zero or one.
numBits |= numChar.digitValue();
if (numBits != 0) {
// Only start to count when bits not zero because leading zeros are ignored.
count++;
}
if (count > mantissaSize + exponentSize + 1) {
// Note that count ignores leading zeros.
throw InvalidConversorInput("Entrada é muito grande");
}
hasChars = true;
} else if (numChar != ' ') {
// Space is ignored, but other chars are an error!
throw InvalidConversorInput("Entrada precisa conter apenas 0 ou 1");
}
}
if (!hasChars) {
throw InvalidConversorInput("Entrada não pode ser vazia");
}
return this->inputGenericFloatRaw(numBits, mantissaSize, exponentSize);
}
PointConversor& PointConversor::inputGenericFixed(QString const &number, int16_t width, Signedness signedness)
{
uint64_t numBits = 0;
bool hasChars = false;
bool pointFound = false;
int16_t pointPos = 0;
int count = 0;
for (QChar numChar : number) {
if (numChar == '0' || numChar == '1') {
numBits <<= 1;
// By now we know it is zero or one.
numBits |= numChar.digitValue();
if (numBits != 0 || pointFound) {
// Only start to count when bits not zero because leading zeros are ignored.
//
// However, once a point has been found, we cannot ignore anymore.
count++;
}
if (count > width && numChar != '0') {
// Note that count ignores leading zeros (before point!).
throw InvalidConversorInput("Entrada é muito grande");
}
hasChars = true;
} else if (numChar == '.') {
if (pointFound) {
throw InvalidConversorInput("Entrada pode conter apenas um ponto");
}
pointFound = true;
// Saves point position, because count still has to be incremented for overflow checks,
// and for knowing the total width.
pointPos = count;
} else if (numChar != ' ') {
// Space is ignored, but other chars are an error!
throw InvalidConversorInput("Entrada precisa conter apenas 0 ou 1 (ou ponto)");
}
}
if (!hasChars) {
throw InvalidConversorInput("Entrada não pode ser vazia");
}
if (!pointFound) {
throw InvalidConversorInput("O número em ponto fixo deve conter um ponto.");
}
if (pointPos > width || count - pointPos > width) {
throw InvalidConversorInput("O ponto não pode estar fora dos limites.");
}
// Actual point position is reversed because humans usually write numbers in big-endian:
// complement it with the found width to reverse it back..
return this->inputGenericFixedRaw(numBits, width, count - pointPos, signedness);
}
// Generic output functions
uint64_t PointConversor::outputGenericFloatRaw(uint16_t mantissaSize, uint16_t exponentSize) const
{
int16_t numExponent = 0;
uint64_t numBits = 0;
uint64_t number = 0;
uint64_t mantissaMask = 0;
int16_t exponentMask = 0;
uint64_t finalBit = 0;
bool subnormal = false;
uint64_t roundRight = 0;
// Initialize here because mantissa size or exponent size might be invalid.
validateFloatSpec(mantissaSize, exponentSize);
mantissaMask = ((uint64_t) 1 << mantissaSize) - 1;
exponentMask = ((uint64_t) 1 << exponentSize) - 1;
finalBit = (uint64_t) 1 << mantissaSize;
switch (this->normality) {
case PointConversor::NORMAL:
// Converts the C++'s signed integer representation of the exponent into float's one.
numExponent = this->exponent + (exponentMask >> 1) + mantissaSize;
numBits = this->bits;
// Try to normalize the number if too small. Remember "really" normal floats have an implicit bit,
// and that the significant bits they store are `xxxxx...` in the number `1.xxxxx... * 2**e`.
// This makes that 1 be in the correct position.
while (numBits < finalBit && numBits != 0) {
numBits <<= 1;
// Remember making an equivalent exponent.
numExponent -= 1;
}
// Same as the loop above, but in this case the number is too big.
while (numBits >= (finalBit << 1)) {
// If the last eliminated bit was 1, we might round the number later.
roundRight = numBits & 1;
numBits >>= 1;
// Remember making an equivalent exponent.
numExponent += 1;
}
if (numExponent <= 0) {
// In case the exponent is below zero, this will be subnormal...
while (numExponent < 0) {
numBits >>= 1;
numExponent += 1;
}
roundRight = numBits & 1;
// Subnormal numbers have an extra step on the exponent, so we must
// get rid off an extra bit to compensate.
numBits >>= 1;
}
// If it does not have final bit, it is subnormal. Important for below.
subnormal = (numBits & finalBit) == 0;
// Getting rid of that implicit "1".
numBits &= ~finalBit;
// Potentially rounding in the right.
numBits += roundRight;
// Tries to fit the exponent. Might fail and end up with infinity below.
while (numExponent > exponentMask && numBits < (finalBit >> 1)) {
numBits <<= 1;
numExponent -= 1;
}
if (subnormal && numBits == 0) {
// No final bit => subnormal.
numExponent = 0;
} else if (numExponent >= exponentMask) {
// Exponent too big? Then infinity.
numExponent = exponentMask;
numBits = 0;
}
break;
case PointConversor::INFINITY_NAN:
numExponent = exponentMask;
numBits = 0;
break;
case PointConversor::NOT_A_NUMBER:
numExponent = exponentMask;
// Could be any non-zero value.
numBits = 1;
break;
}
number = numBits & mantissaMask;
number |= (uint64_t) (numExponent & exponentMask) << mantissaSize;
number |= (uint64_t) this->sign << (mantissaSize + exponentSize);
return number;
}
uint64_t PointConversor::outputGenericFixedRaw(int16_t width, int16_t pointPos, Signedness signedness) const
{
uint64_t number = this->bits;
int16_t numExponent = this->exponent;
uint64_t finalBit = 0;
uint64_t mantissaMask = 0;
uint64_t digitsMask = 0;
uint64_t roundLeft = 0;
uint64_t roundRight = 0;
validateFixedSpec(width, pointPos, signedness);
// Initialize here because width might be invalid.
//
// 0000...01111..111111
digitsMask = ~((uint64_t) 0) >> (MAX_WIDTH - width);
// Gets final significant bit (except for sign).
switch (signedness) {
case UNSIGNED:
finalBit = (uint64_t) 1 << (width - 1);
break;
case TWOS_COMPL:
finalBit = (uint64_t) 1 << (width - 2);
break;
}
// Significant bits mask.
mantissaMask = (finalBit << 1) - 1;
switch (this->normality) {
case NORMAL:
// We need to normalize the exponent to the point position.
while (numExponent > -pointPos) {
// We might need to round the number in the left.
if (number >= finalBit) {
roundLeft = finalBit;
}
numExponent -= 1;
number <<= 1;
}
// If the exponent was not too big, it could be too small.
while (numExponent < -pointPos) {
// In this case, we might need to round by the right.
roundRight = (number & 1) != 0;
numExponent += 1;
number >>= 1;
}
if (number > mantissaMask) {
roundLeft = finalBit;
}
// Potential rounding at left position (most significant).
number |= roundLeft;
// Truncating the number.
number &= mantissaMask;
if (digitsMask != number) {
// But that's ok because we will round right (less significant) it here if required.
number += roundRight;
}
if (this->sign) {
switch (signedness) {
case UNSIGNED:
throw InvalidConversorInput("Formato de saída é sem sinal, mas entrada é negativa.");
case TWOS_COMPL:
// Complementing via 2's complement.
number = (~number + 1) & digitsMask;
break;
}
}
break;
case INFINITY_NAN:
// If infinity, let's just assign it to the greatest value (in magnitude).
number = mantissaMask;
if (this->sign) {
switch (signedness) {
case UNSIGNED:
throw InvalidConversorInput("Formato de saída é sem sinal, mas entrada é negativa.");
case TWOS_COMPL:
// Negative "infinity".
number = ((~number + 1) & digitsMask) - 1;
break;
}
}
break;
case NOT_A_NUMBER:
// NAN is invalid for fixed points. No way to represent?
throw InvalidConversorInput("Entrada é um NAN (Not A Number)");
}
return number;
}
QString PointConversor::outputGenericFloat(uint16_t mantissaSize, uint16_t exponentSize) const
{
uint64_t number = this->outputGenericFloatRaw(mantissaSize, exponentSize);
QString output;
// Simple dummy binary conversion loop :P
for (uint64_t i = mantissaSize + exponentSize + 1; i > 0; i--) {
uint64_t mask = (uint64_t) 1 << (i - 1);
output.append(number & mask ? '1' : '0');
}
return output;
}
QString PointConversor::outputGenericFixed(int16_t width, int16_t pointPos, Signedness signedness) const
{
uint64_t number = this->outputGenericFixedRaw(width, pointPos, signedness);
QString output;
// Before the point.
for (int i = width - 1; i >= pointPos; i--) {
if (i >= 0) {
// Regular bit conversion.
uint64_t mask = (uint64_t) 1 << (uint64_t) i;
output.append(number & mask ? '1' : '0');
} else {
// Append a trailing zero.
output.append('0');
}
}
// Point required because fixed-point format.
output.append('.');
// After the point.
for (int i = pointPos - 1; i >= 0; i--) {
if (i < width) {
// Regular bit conversion.
uint64_t mask = (uint64_t) 1 << (uint64_t) i;
output.append(number & mask ? '1' : '0');
} else {
// Append a trailing zero.
output.append('0');
}
}
return output;
}
// Validation functions
void PointConversor::validateFloatSpec(uint16_t mantissaSize, uint16_t exponentSize) const
{
if (mantissaSize < MIN_MANTISSA_SIZE) {
throw InvalidConversorInput(QString("Tamanho da mantissa não pode ser menor que ") + QString::number(MIN_MANTISSA_SIZE));
}
if (exponentSize < MIN_EXPONENT_SIZE) {
throw InvalidConversorInput(QString("Tamanho do expoente não pode ser menor que ") + QString::number(MIN_EXPONENT_SIZE));
}
if (mantissaSize + exponentSize > MAX_WIDTH - 1) {
throw InvalidConversorInput(
QString("É necessário um bit de sinal, mantissa e expoente juntos devem ser menor que ")
+ QString::number(MAX_WIDTH - 1));
}
}
void PointConversor::validateFixedSpec(int16_t width, int16_t pointPos, Signedness signedness) const
{
if (width < MIN_FIXED_WIDTH) {
throw InvalidConversorInput(QString("Largura não pode ser menor que ") + QString::number(MIN_FIXED_WIDTH));
}
if (width > MAX_WIDTH) {
throw InvalidConversorInput(QString("Largura não pode ser maior que ") + QString::number(MAX_WIDTH));
}
if (pointPos > width || pointPos < 0) {
throw InvalidConversorInput("Ponto fora da quantidade de bits disponíveis.");
}
if (pointPos > width || pointPos < 0) {
throw InvalidConversorInput("Ponto fora da quantidade de bits disponíveis.");
}
}
| petcomputacaoufrgs/hidracpp | src/core/pointconversor.cpp | C++ | gpl-3.0 | 21,532 |
import java.util.ArrayList;
/**
* Write a description of class StrengthPotion here.
*
* @author Jarom Kraus
* @version 2.23.16
*/
@SuppressWarnings("unchecked")
public class StrengthPotion extends Potion{
private ArrayList stats;
public StrengthPotion(String Name){
super(Name);
}
public void drinkStrengthPotion(){
System.out.println("You drink the strength potion and your strength is increased.");
}public ArrayList getStats(){
stats = new ArrayList();
stats.addAll(super.getStats());
return stats;
}
}
| jaromkraus/RPG | RPG/StrengthPotion.java | Java | gpl-3.0 | 577 |
package centralapp.views;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import centralapp.controlers.CentralApp;
/**
* The main window containing all the sub-views
*/
@SuppressWarnings("serial")
public class MainView extends JFrame {
private JTabbedPane tabbedPane;
/**
* Constructor of MainView
*
* @param controler The controlers associated to this view
*/
public MainView(CentralApp controler) {
//GTK theme
/*try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
} catch (Exception e) { }*/
//Ensure to exit the program and not only the window
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 600);
tabbedPane = new JTabbedPane();
getContentPane().add(tabbedPane);
//Just to test
//openCheckInOutTab();
//Set up events
addWindowListener(controler.new ExitEvent());
}
/**
* Add the panel in parameter as a tab of the main window
*
* @param name The tab's name
* @param tab The panel to add
*/
public void addTab(String name, JPanel tab){
tabbedPane.addTab(name, tab);
CentralApp.nbTab++;
}
/**
* Close a tab
*
* @param tabNb The tab id
*/
public void closeTab(int tabNb) {
tabbedPane.remove(tabNb);
}
} | Edroxis/DI3_Projet4_Pointeuse | src/centralapp/views/MainView.java | Java | gpl-3.0 | 1,273 |
from __future__ import print_function, division
INLINE_LABEL_STYLE = {
'display': 'inline-block',
}
GRAPH_GLOBAL_CONFIG = {
'displaylogo': False,
'modeBarButtonsToRemove': ['sendDataToCloud'],
}
AXIS_OPTIONS = ({
'label': 'linear',
'value': 'linear',
}, {
'label': 'log',
'value': 'log',
})
ERRORBAR_OPTIONS = ({
'label': 'True',
'value': True,
}, {
'label': 'False',
'value': False,
})
LINE_STYLE = {
'width': 1.0,
}
XLABEL = {
'linear': r'Scattering Vector, $q$ $(\text{\AA}^{-1})$',
'log': r'Scattering Vector, $q$ $(\text{\AA}^{-1}) (log scale)$',
'guinier': r'$q^2$ $(\text{\AA}^{-2})$',
'kratky': r'Scattering Vector, $q$ $(\text{\AA}^{-1})$',
'porod': r'$q^4$ $(\text{\AA}^{-4})$',
'pdf': r'pair distance ($\text{\AA}$)',
}
YLABEL = {
'linear': 'Intensity (arb. units.)',
'log': r'$\log(I)$',
'guinier': r'$\ln(I(q))$',
'kratky': r'$I(q) \cdot q^2$',
'porod': r'$I(q) \cdot q^4$',
'relative_diff': 'Relative Ratio (%)',
'absolute_diff': 'Absolute Difference (arb. units.)',
'error': 'Error',
'error_relative_diff': 'Error Relative Ratio (%)',
'pdf': 'P(r)',
}
TITLE = {
'sasprofile': 'Subtracted Profiles',
'guinier': 'Guinier Profiles',
'kratky': 'Kratky Profiles',
'porod': 'Porod Profiles',
'relative_diff': 'Relative Difference Profiles',
'absolute_diff': 'Absolute Difference Profiles',
'error': 'Error Profile',
'error_relative_diff': 'Error Relative Difference Profile',
'pdf': 'Pair-wise Distribution',
'fitting': 'P(r) Distribution Fitting',
}
| lqhuang/SAXS-tools | dashboard/layouts/style.py | Python | gpl-3.0 | 1,620 |
/*
* Copyright (C) 2020 <mark@makr.zone>
* inspired and based on work
* Copyright (C) 2011 Jason von Nieda <jason@vonnieda.org>
*
* This file is part of OpenPnP.
*
* OpenPnP 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.
*
* OpenPnP 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 OpenPnP. If not, see
* <http://www.gnu.org/licenses/>.
*
* For more information about OpenPnP visit http://openpnp.org
*/
package org.openpnp.machine.reference.axis.wizards;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import org.openpnp.gui.components.ComponentDecorators;
import org.openpnp.gui.support.AbstractConfigurationWizard;
import org.openpnp.spi.Axis;
import org.openpnp.spi.base.AbstractAxis;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.RowSpec;
@SuppressWarnings("serial")
public abstract class AbstractAxisConfigurationWizard extends AbstractConfigurationWizard {
protected final AbstractAxis axis;
protected JPanel panelProperties;
protected JLabel lblName;
protected JTextField name;
protected JLabel lblType;
protected JComboBox type;
public AbstractAxisConfigurationWizard(AbstractAxis axis) {
super();
this.axis = axis;
panelProperties = new JPanel();
panelProperties.setBorder(new TitledBorder(null, "Properties", TitledBorder.LEADING, TitledBorder.TOP, null, null));
contentPanel.add(panelProperties);
panelProperties.setLayout(new FormLayout(new ColumnSpec[] {
FormSpecs.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(70dlu;default)"),
FormSpecs.RELATED_GAP_COLSPEC,
FormSpecs.DEFAULT_COLSPEC,},
new RowSpec[] {
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,}));
lblType = new JLabel("Type");
panelProperties.add(lblType, "2, 2, right, default");
type = new JComboBox(Axis.Type.values());
panelProperties.add(type, "4, 2, fill, default");
lblName = new JLabel("Name");
panelProperties.add(lblName, "2, 4, right, default");
name = new JTextField();
panelProperties.add(name, "4, 4, fill, default");
name.setColumns(20);
}
protected AbstractAxis getAxis() {
return axis;
}
@Override
public void createBindings() {
addWrappedBinding(axis, "type", type, "selectedItem");
addWrappedBinding(axis, "name", name, "text");
ComponentDecorators.decorateWithAutoSelect(name);
}
}
| openpnp/openpnp | src/main/java/org/openpnp/machine/reference/axis/wizards/AbstractAxisConfigurationWizard.java | Java | gpl-3.0 | 3,328 |
package com.github.alexaegis.plane.poligons;
import com.github.alexaegis.plane.Point;
public abstract class RegularPolygon implements Polygon {
protected RegularPolygons type = null;
protected Point center = new Point(0, 0);
protected double edgeLength = 0; // length of the edges
protected double radius = 0; // the radius of the circumscribed circle
protected double apothem = 0; // the radius of the inscribed circle
protected double perimeter = 0;
RegularPolygon() {
}
@Override
public double getArea() {
return 0.5d * apothem * perimeter;
}
@Override
public double getPerimeter() {
return perimeter;
}
@Override
public Point getCenter() {
return new Point(center);
}
@Override
public double diffInPerimArea() {
return Math.abs(getArea() - getPerimeter());
}
@Override
public void show() {
System.out.println(toString());
}
@Override
public String toString() {
return "Regular Polygon{" +
"type = " + type.getName() +
", vertices = " + Integer.toString(type.getVertices() - 1) +
", center = " + center.toString() +
", edgeLength = " + edgeLength +
", radius = " + radius +
", apothem = " + apothem +
", area = " + getArea() +
", perimeter = " + perimeter +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RegularPolygon that = (RegularPolygon) o;
if (Double.compare(that.edgeLength, edgeLength) != 0) return false;
if (Double.compare(that.radius, radius) != 0) return false;
if (Double.compare(that.apothem, apothem) != 0) return false;
if (Double.compare(that.perimeter, perimeter) != 0) return false;
if (type != that.type) return false;
if (center != null ? !center.equals(that.center) : that.center != null) return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = type != null ? type.hashCode() : 0;
result = 31 * result + (center != null ? center.hashCode() : 0);
temp = Double.doubleToLongBits(edgeLength);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(radius);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(apothem);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(perimeter);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
} | AlexAegis/elte-progtech-1 | submission1/src/main/java/com/github/alexaegis/plane/poligons/RegularPolygon.java | Java | gpl-3.0 | 2,838 |
/*******************************************************************************
* HellFirePvP / Astral Sorcery 2017
*
* This project is licensed under GNU GENERAL PUBLIC LICENSE Version 3.
* The source code is available on github: https://github.com/HellFirePvP/AstralSorcery
* For further details, see the License file there.
******************************************************************************/
package hellfirepvp.astralsorcery.common.base;
import hellfirepvp.astralsorcery.common.constellation.effect.GenListEntries;
import hellfirepvp.astralsorcery.common.util.BlockStateCheck;
import hellfirepvp.astralsorcery.common.util.ItemUtils;
import hellfirepvp.astralsorcery.common.util.MiscUtils;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* This class is part of the Astral Sorcery Mod
* The complete source code for this mod can be found on github.
* Class: WorldMeltables
* Created by HellFirePvP
* Date: 31.10.2016 / 22:49
*/
public enum WorldMeltables implements MeltInteraction {
COBBLE( new BlockStateCheck.Block(Blocks.COBBLESTONE), Blocks.FLOWING_LAVA.getDefaultState(), 180),
STONE( new BlockStateCheck.Block(Blocks.STONE), Blocks.FLOWING_LAVA.getDefaultState(), 100),
OBSIDIAN( new BlockStateCheck.Block(Blocks.OBSIDIAN), Blocks.FLOWING_LAVA.getDefaultState(), 75),
NETHERRACK( new BlockStateCheck.Block(Blocks.NETHERRACK), Blocks.FLOWING_LAVA.getDefaultState(), 40),
NETHERBRICK(new BlockStateCheck.Block(Blocks.NETHER_BRICK), Blocks.FLOWING_LAVA.getDefaultState(), 60),
MAGMA( new BlockStateCheck.Block(Blocks.MAGMA), Blocks.FLOWING_LAVA.getDefaultState(), 1),
ICE( new BlockStateCheck.Block(Blocks.ICE), Blocks.FLOWING_WATER.getDefaultState(), 1),
FROSTED_ICE(new BlockStateCheck.Block(Blocks.FROSTED_ICE), Blocks.FLOWING_WATER.getDefaultState(), 1),
PACKED_ICE( new BlockStateCheck.Block(Blocks.PACKED_ICE), Blocks.FLOWING_WATER.getDefaultState(), 2);
private final BlockStateCheck meltableCheck;
private final IBlockState meltResult;
private final int meltDuration;
private WorldMeltables(BlockStateCheck meltableCheck, IBlockState meltResult, int meltDuration) {
this.meltableCheck = meltableCheck;
this.meltResult = meltResult;
this.meltDuration = meltDuration;
}
@Override
public boolean isMeltable(World world, BlockPos pos, IBlockState worldState) {
return meltableCheck.isStateValid(world, pos, worldState);
}
@Override
@Nullable
public IBlockState getMeltResultState() {
return meltResult;
}
@Override
@Nonnull
public ItemStack getMeltResultStack() {
return ItemStack.EMPTY;
}
@Override
public int getMeltTickDuration() {
return meltDuration;
}
@Nullable
public static MeltInteraction getMeltable(World world, BlockPos pos) {
IBlockState state = world.getBlockState(pos);
for (WorldMeltables melt : values()) {
if(melt.isMeltable(world, pos, state))
return melt;
}
ItemStack stack = ItemUtils.createBlockStack(state);
if(!stack.isEmpty()) {
ItemStack out = FurnaceRecipes.instance().getSmeltingResult(stack);
if(!out.isEmpty()) {
return new FurnaceRecipeInteraction(state, out);
}
}
return null;
}
public static class ActiveMeltableEntry extends GenListEntries.CounterListEntry {
public ActiveMeltableEntry(BlockPos pos) {
super(pos);
}
public boolean isValid(World world, boolean forceLoad) {
if(!forceLoad && !MiscUtils.isChunkLoaded(world, new ChunkPos(getPos()))) return true;
return getMeltable(world) != null;
}
public MeltInteraction getMeltable(World world) {
return WorldMeltables.getMeltable(world, getPos());
}
}
public static class FurnaceRecipeInteraction implements MeltInteraction {
private final ItemStack out;
private final BlockStateCheck.Meta matchInState;
public FurnaceRecipeInteraction(IBlockState inState, ItemStack outStack) {
this.matchInState = new BlockStateCheck.Meta(inState.getBlock(), inState.getBlock().getMetaFromState(inState));
this.out = outStack;
}
@Override
public boolean isMeltable(World world, BlockPos pos, IBlockState state) {
return matchInState.isStateValid(world, pos, state);
}
@Nullable
@Override
public IBlockState getMeltResultState() {
return ItemUtils.createBlockState(out);
}
@Nonnull
@Override
public ItemStack getMeltResultStack() {
return out;
}
}
}
| Saereth/AstralSorcery | src/main/java/hellfirepvp/astralsorcery/common/base/WorldMeltables.java | Java | gpl-3.0 | 5,184 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.3 on 2016-07-01 17:09
from __future__ import unicode_literals
from django.db import migrations
import django_fsm
class Migration(migrations.Migration):
dependencies = [
('invoice', '0002_billordering'),
]
operations = [
migrations.AlterField(
model_name='bill',
name='status',
field=django_fsm.FSMIntegerField(choices=[(0, 'building'), (1, 'valid'), (2, 'cancel'), (3, 'archive')], db_index=True, default=0, verbose_name='status'),
),
]
| Diacamma2/financial | diacamma/invoice/migrations/0003_bill_status.py | Python | gpl-3.0 | 568 |
package com.taobao.api.domain;
import java.util.List;
import com.taobao.api.TaobaoObject;
import com.taobao.api.internal.mapping.ApiField;
import com.taobao.api.internal.mapping.ApiListField;
/**
* 评价信息
*
* @author auto create
* @since 1.0, null
*/
public class RateInfo extends TaobaoObject {
private static final long serialVersionUID = 7494752753378247845L;
/**
* 评价信息
*/
@ApiListField("rate_list")
@ApiField("rate_item")
private List<RateItem> rateList;
public List<RateItem> getRateList() {
return this.rateList;
}
public void setRateList(List<RateItem> rateList) {
this.rateList = rateList;
}
}
| kuiwang/my-dev | src/main/java/com/taobao/api/domain/RateInfo.java | Java | gpl-3.0 | 692 |
from setuptools import setup, find_packages
DESCRIPTION = "Implementation of Huff et. al. (2011) Estimation of Recent Shared Ancestry "
LONG_DESCRIPTION = "`ersa` estimates the combined number of generations between pairs of " \
"individuals using a " \
"`Germline <http://www1.cs.columbia.edu/~gusev/germline/>`_ " \
"matchfile as input. It is an implementation of " \
"`Huff et. al. (2011) Maximum-Likelihood estimation of recent shared ancenstry (ERSA) <http://genome.cshlp.org/content/21/5/768.full>`_ " \
"and `Li et. al. (2014) Relationship Estimation from Whole-Genome Sequence Data <http://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1004144>`_ ."
NAME = "ersa"
AUTHOR = "Richard Munoz, Jie Yuan, Yaniv Erlich"
AUTHOR_EMAIL = "rmunoz@columbia.edu, jyuan@columbia.edu, yaniv@cs.columbia.edu"
MAINTAINER = "Richard Munoz"
MAINTAINER_EMAIL = "rmunoz@columbia.edu"
DOWNLOAD_URL = 'http://github.com/rmunoz12/ersa'
LICENSE = 'GNU General Public License v3 (GPLv3)'
VERSION = '1.1.2'
setup(name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
url=DOWNLOAD_URL,
download_url=DOWNLOAD_URL,
license=LICENSE,
packages=find_packages(),
test_suite='tests',
entry_points = {
"console_scripts": ['ersa = ersa.ersa:main']
},
install_requires=['sqlalchemy', 'inflect', 'pytest', 'scipy'],
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3 :: Only',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Bio-Informatics',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Sociology :: Genealogy']
)
| rmunoz12/ersa | setup.py | Python | gpl-3.0 | 2,290 |
/*
* Created: 31.03.2012
*
* Copyright (C) 2012 Victor Antonovich (v.antonovich@gmail.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package su.comp.bk.arch;
import android.content.res.Resources;
import android.os.Bundle;
import org.apache.commons.lang.ArrayUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import su.comp.bk.R;
import su.comp.bk.arch.cpu.Cpu;
import su.comp.bk.arch.io.Device;
import su.comp.bk.arch.io.KeyboardController;
import su.comp.bk.arch.io.PeripheralPort;
import su.comp.bk.arch.io.Sel1RegisterSystemBits;
import su.comp.bk.arch.io.SystemTimer;
import su.comp.bk.arch.io.Timer;
import su.comp.bk.arch.io.VideoController;
import su.comp.bk.arch.io.VideoControllerManager;
import su.comp.bk.arch.io.audio.AudioOutput;
import su.comp.bk.arch.io.audio.Ay8910;
import su.comp.bk.arch.io.audio.Covox;
import su.comp.bk.arch.io.audio.Speaker;
import su.comp.bk.arch.io.disk.FloppyController;
import su.comp.bk.arch.io.disk.IdeController;
import su.comp.bk.arch.io.disk.SmkIdeController;
import su.comp.bk.arch.io.memory.Bk11MemoryManager;
import su.comp.bk.arch.io.memory.SmkMemoryManager;
import su.comp.bk.arch.memory.BankedMemory;
import su.comp.bk.arch.memory.Memory;
import su.comp.bk.arch.memory.RandomAccessMemory;
import su.comp.bk.arch.memory.RandomAccessMemory.Type;
import su.comp.bk.arch.memory.ReadOnlyMemory;
import su.comp.bk.arch.memory.SegmentedMemory;
import su.comp.bk.arch.memory.SelectableMemory;
import su.comp.bk.util.FileUtils;
import timber.log.Timber;
/**
* BK001x computer implementation.
*/
public class Computer implements Runnable {
// State save/restore: Computer system uptime (in nanoseconds)
private static final String STATE_SYSTEM_UPTIME = Computer.class.getName() + "#sys_uptime";
// State save/restore: Computer RAM data
private static final String STATE_RAM_DATA = Computer.class.getName() + "#ram_data";
/** Bus error constant */
public final static int BUS_ERROR = -1;
// Computer configuration
private Configuration configuration;
// Memory table mapped by 4KB blocks
private final List<?>[] memoryTable = new List[16];
// List of created RandomAccessMemory instances
private final List<RandomAccessMemory> randomAccessMemoryList = new ArrayList<>();
// CPU implementation reference
private final Cpu cpu;
// Video controller reference
private VideoController videoController;
// Keyboard controller reference
private KeyboardController keyboardController;
// Peripheral port reference
private PeripheralPort peripheralPort;
// Audio outputs list
private List<AudioOutput> audioOutputs = new ArrayList<>();
// Floppy controller reference (<code>null</code> if no floppy controller attached)
private FloppyController floppyController;
/** BK0011 first banked memory block address */
public static final int BK0011_BANKED_MEMORY_0_ADDRESS = 040000;
/** BK0011 second banked memory block address */
public static final int BK0011_BANKED_MEMORY_1_ADDRESS = 0100000;
/** I/O registers space min start address */
public final static int IO_REGISTERS_MIN_ADDRESS = 0177000;
// I/O devices list
private final List<Device> deviceList = new ArrayList<>();
// I/O registers space addresses mapped to devices
private final List<?>[] deviceTable = new List[2048];
private boolean isRunning = false;
private boolean isPaused = true;
private Thread clockThread;
/** Amount of nanoseconds in one microsecond */
public static final long NANOSECS_IN_USEC = 1000L;
/** Amount of nanoseconds in one millisecond */
public static final long NANOSECS_IN_MSEC = 1000000L;
/** BK0010 clock frequency (in kHz) */
public final static int CLOCK_FREQUENCY_BK0010 = 3000;
/** BK0011 clock frequency (in kHz) */
public final static int CLOCK_FREQUENCY_BK0011 = 4000;
// Computer clock frequency (in kHz)
private int clockFrequency;
/** Uptime sync threshold (in nanoseconds) */
private static final long UPTIME_SYNC_THRESHOLD = (10L * NANOSECS_IN_MSEC);
// Last computer system uptime update timestamp (unix timestamp, in nanoseconds)
private long systemUptimeUpdateTimestamp;
// Computer system uptime since start (in nanoseconds)
private long systemUptime;
/** Uptime sync check interval (in nanoseconds) */
private static final long UPTIME_SYNC_CHECK_INTERVAL = (1L * NANOSECS_IN_MSEC);
// Computer system uptime sync check interval (in CPU ticks)
private long systemUptimeSyncCheckIntervalTicks;
// Last computer system uptime sync check timestamp (in CPU ticks)
private long systemUptimeSyncCheckTimestampTicks;
private final List<UptimeListener> uptimeListeners = new ArrayList<>();
// IDE controller reference (<code>null</code> if no IDE controller present)
private IdeController ideController;
/**
* Computer uptime updates listener.
*/
public interface UptimeListener {
void uptimeUpdated(long uptime);
}
public enum Configuration {
/** BK0010 - monitor only */
BK_0010_MONITOR,
/** BK0010 - monitor and Basic */
BK_0010_BASIC,
/** BK0010 - monitor, Focal and tests */
BK_0010_MSTD,
/** BK0010 with connected floppy drive controller (КНГМД) */
BK_0010_KNGMD(true),
/** BK0011M - MSTD block attached */
BK_0011M_MSTD(false, true),
/** BK0011M with connected floppy drive controller (КНГМД) */
BK_0011M_KNGMD(true, true),
/** BK0011M with connected SMK512 controller */
BK_0011M_SMK512(true, true);
private final boolean isFloppyControllerPresent;
private final boolean isMemoryManagerPresent;
Configuration() {
this(false, false);
}
Configuration(boolean isFloppyControllerPresent) {
this(isFloppyControllerPresent, false);
}
Configuration(boolean isFloppyControllerPresent, boolean isMemoryManagerPresent) {
this.isFloppyControllerPresent = isFloppyControllerPresent;
this.isMemoryManagerPresent = isMemoryManagerPresent;
}
/**
* Check is {@link FloppyController} present in this configuration.
* @return <code>true</code> if floppy controller present, <code>false</code> otherwise
*/
public boolean isFloppyControllerPresent() {
return isFloppyControllerPresent;
}
/**
* Check is BK-0011 {@link Bk11MemoryManager} present in configuration.
* @return <code>true</code> if memory manager present, <code>false</code> otherwise
*/
public boolean isMemoryManagerPresent() {
return isMemoryManagerPresent;
}
}
public static class MemoryRange {
private final int startAddress;
private final Memory memory;
private final int endAddress;
public MemoryRange(int startAddress, Memory memory) {
this.startAddress = startAddress;
this.memory = memory;
this.endAddress = startAddress + (memory.getSize() << 1) - 1;
}
public int getStartAddress() {
return startAddress;
}
public Memory getMemory() {
return memory;
}
public boolean isRelatedAddress(int address) {
return (address >= startAddress) && (address <= endAddress);
}
}
public Computer() {
this.cpu = new Cpu(this);
}
/**
* Configure this computer.
* @param resources Android resources object reference
* @param config computer configuration as {@link Configuration} value
* @throws Exception in case of error while configuring
*/
public void configure(Resources resources, Configuration config) throws Exception {
setConfiguration(config);
// Apply shared configuration
addDevice(new Sel1RegisterSystemBits(!config.isMemoryManagerPresent() ? 0100000 : 0140000));
keyboardController = new KeyboardController(this);
addDevice(keyboardController);
peripheralPort = new PeripheralPort();
addDevice(peripheralPort);
addDevice(new Timer());
// Apply computer specific configuration
if (!config.isMemoryManagerPresent()) {
// BK-0010 configurations
setClockFrequency(CLOCK_FREQUENCY_BK0010);
// Set RAM configuration
RandomAccessMemory workMemory = createRandomAccessMemory("WorkMemory",
020000, Type.K565RU6);
addMemory(0, workMemory);
RandomAccessMemory videoMemory = createRandomAccessMemory("VideoMemory",
020000, Type.K565RU6);
addMemory(040000, videoMemory);
// Add video controller
videoController = new VideoController(videoMemory);
addDevice(videoController);
// Set ROM configuration
addReadOnlyMemory(resources, 0100000, R.raw.monit10, "Monitor10");
switch (config) {
case BK_0010_BASIC:
addReadOnlyMemory(resources, 0120000, R.raw.basic10_1, "Basic10:1");
addReadOnlyMemory(resources, 0140000, R.raw.basic10_2, "Basic10:2");
addReadOnlyMemory(resources, 0160000, R.raw.basic10_3, "Basic10:3");
break;
case BK_0010_MSTD:
addReadOnlyMemory(resources, 0120000, R.raw.focal, "Focal");
addReadOnlyMemory(resources, 0160000, R.raw.tests, "MSTD10");
break;
case BK_0010_KNGMD:
addMemory(0120000, createRandomAccessMemory("ExtMemory", 020000, Type.K537RU10));
addReadOnlyMemory(resources, 0160000, R.raw.disk_327, "FloppyBios");
floppyController = new FloppyController(this);
addDevice(floppyController);
break;
default:
break;
}
} else {
// BK-0011 configurations
setClockFrequency(CLOCK_FREQUENCY_BK0011);
// Set RAM configuration
BankedMemory firstBankedMemory = new BankedMemory("BankedMemory0",
020000, Bk11MemoryManager.NUM_RAM_BANKS);
BankedMemory secondBankedMemory = new BankedMemory("BankedMemory1",
020000,
Bk11MemoryManager.NUM_RAM_BANKS + Bk11MemoryManager.NUM_ROM_BANKS);
for (int memoryBankIndex = 0; memoryBankIndex < Bk11MemoryManager.NUM_RAM_BANKS;
memoryBankIndex++) {
Memory memoryBank = createRandomAccessMemory("MemoryBank" + memoryBankIndex,
020000, Type.K565RU5);
firstBankedMemory.setBank(memoryBankIndex, memoryBank);
secondBankedMemory.setBank(memoryBankIndex, memoryBank);
}
addMemory(0, firstBankedMemory.getBank(6)); // Fixed RAM page at address 0
addMemory(BK0011_BANKED_MEMORY_0_ADDRESS, firstBankedMemory); // First banked memory window at address 040000
SelectableMemory selectableSecondBankedMemory = new SelectableMemory(
secondBankedMemory.getId(), secondBankedMemory, true);
addMemory(BK0011_BANKED_MEMORY_1_ADDRESS, selectableSecondBankedMemory); // Second banked memory window at address 0100000
// Set ROM configuration
secondBankedMemory.setBank(Bk11MemoryManager.NUM_RAM_BANKS, new ReadOnlyMemory(
"Basic11M:0", loadReadOnlyMemoryData(resources, R.raw.basic11m_0)));
secondBankedMemory.setBank(Bk11MemoryManager.NUM_RAM_BANKS + 1,
new ReadOnlyMemory("Basic11M:1/ExtBOS11M", loadReadOnlyMemoryData(resources,
R.raw.basic11m_1, R.raw.ext11m)));
ReadOnlyMemory bosRom = new ReadOnlyMemory("BOS11M",
loadReadOnlyMemoryData(resources, R.raw.bos11m));
SelectableMemory selectableBosRom = new SelectableMemory(bosRom.getId(), bosRom, true);
addMemory( 0140000, selectableBosRom);
switch (config) {
case BK_0011M_MSTD:
addReadOnlyMemory(resources, 0160000, R.raw.mstd11m, "MSTD11M");
break;
case BK_0011M_KNGMD:
addReadOnlyMemory(resources, 0160000, R.raw.disk_327, "FloppyBios");
floppyController = new FloppyController(this);
addDevice(floppyController);
break;
case BK_0011M_SMK512:
ReadOnlyMemory smkBiosRom = new ReadOnlyMemory("SmkBiosRom",
loadReadOnlyMemoryData(resources, R.raw.disk_smk512_v205));
SelectableMemory selectableSmkBiosRom0 = new SelectableMemory(
smkBiosRom.getId() + ":0", smkBiosRom, false);
SelectableMemory selectableSmkBiosRom1 = new SelectableMemory(
smkBiosRom.getId() + ":1", smkBiosRom, false);
addMemory(SmkMemoryManager.BIOS_ROM_0_START_ADDRESS, selectableSmkBiosRom0);
addMemory(SmkMemoryManager.BIOS_ROM_1_START_ADDRESS, selectableSmkBiosRom1);
RandomAccessMemory smkRam = createRandomAccessMemory("SmkRam",
SmkMemoryManager.MEMORY_TOTAL_SIZE, Type.K565RU5);
List<SegmentedMemory> smkRamSegments = new ArrayList<>(
SmkMemoryManager.NUM_MEMORY_SEGMENTS);
for (int i = 0; i < SmkMemoryManager.NUM_MEMORY_SEGMENTS; i++) {
SegmentedMemory smkRamSegment = new SegmentedMemory("SmkRamSegment" + i,
smkRam, SmkMemoryManager.MEMORY_SEGMENT_SIZE);
smkRamSegments.add(smkRamSegment);
addMemory(SmkMemoryManager.MEMORY_START_ADDRESS +
i * SmkMemoryManager.MEMORY_SEGMENT_SIZE * 2, smkRamSegment);
}
SmkMemoryManager smkMemoryManager = new SmkMemoryManager(smkRamSegments,
selectableSmkBiosRom0, selectableSmkBiosRom1);
smkMemoryManager.setSelectableBk11BosRom(selectableBosRom);
smkMemoryManager.setSelectableBk11SecondBankedMemory(selectableSecondBankedMemory);
addDevice(smkMemoryManager);
floppyController = new FloppyController(this);
addDevice(floppyController);
SmkIdeController smkIdeController = new SmkIdeController(this);
ideController = smkIdeController;
addDevice(smkIdeController);
break;
default:
break;
}
// Configure BK0011M memory manager
addDevice(new Bk11MemoryManager(firstBankedMemory, secondBankedMemory));
// Add video controller with palette/screen manager
BankedMemory videoMemory = new BankedMemory("VideoPagesMemory", 020000, 2);
videoMemory.setBank(0, firstBankedMemory.getBank(1));
videoMemory.setBank(1, firstBankedMemory.getBank(7));
videoController = new VideoController(videoMemory);
addDevice(videoController);
addDevice(new VideoControllerManager(videoController, videoMemory));
// Add system timer
SystemTimer systemTimer = new SystemTimer(this);
addDevice(systemTimer);
videoController.addFrameSyncListener(systemTimer);
}
// Notify video controller about computer time updates
addUptimeListener(videoController);
// Add audio outputs
addAudioOutput(new Speaker(this, config.isMemoryManagerPresent()));
addAudioOutput(new Covox(this));
addAudioOutput(new Ay8910(this));
}
/**
* Set computer configuration.
* @param config computer configuration as {@link Configuration} value
*/
public void setConfiguration(Configuration config) {
this.configuration = config;
}
/**
* Get computer configuration.
* @return computer configuration as {@link Configuration} value
*/
public Configuration getConfiguration() {
return this.configuration;
}
/**
* Create new {@link RandomAccessMemory} and add it to the RAM list for further saving/restoring.
* @param memoryId RAM identifier
* @param memorySize RAM size (in words)
* @param memoryType RAM type
* @return created {@link RandomAccessMemory} reference
*/
private RandomAccessMemory createRandomAccessMemory(String memoryId, int memorySize,
Type memoryType) {
RandomAccessMemory memory = new RandomAccessMemory(memoryId, memorySize, memoryType);
addToRandomAccessMemoryList(memory);
return memory;
}
private void addToRandomAccessMemoryList(RandomAccessMemory memory) {
randomAccessMemoryList.add(memory);
}
private List<RandomAccessMemory> getRandomAccessMemoryList() {
return randomAccessMemoryList;
}
/**
* Save computer state.
* @param outState {@link Bundle} to save state
*/
public void saveState(Bundle outState) {
// Save computer configuration
outState.putString(Configuration.class.getName(), getConfiguration().name());
// Save computer system uptime
outState.putLong(STATE_SYSTEM_UPTIME, getSystemUptime());
// Save RAM data
saveRandomAccessMemoryData(outState);
// Save CPU state
getCpu().saveState(outState);
// Save device states
for (Device device : deviceList) {
device.saveState(outState);
}
}
private void saveRandomAccessMemoryData(Bundle outState) {
List<RandomAccessMemory> randomAccessMemoryList = getRandomAccessMemoryList();
// Calculate total RAM data size (in bytes)
int totalDataSize = 0;
for (RandomAccessMemory memory: randomAccessMemoryList) {
totalDataSize += memory.getSize() * 2;
}
// Pack all RAM data into a single buffer
ByteBuffer dataBuf = ByteBuffer.allocate(totalDataSize);
ShortBuffer shortDataBuf = dataBuf.asShortBuffer();
for (RandomAccessMemory memory: randomAccessMemoryList) {
shortDataBuf.put(memory.getData(), 0, memory.getSize());
}
dataBuf.flip();
// Compress RAM data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
try (DeflaterOutputStream dos = new DeflaterOutputStream(baos, deflater)) {
dos.write(dataBuf.array());
} catch (IOException e) {
throw new IllegalStateException("Can't compress RAM data", e);
}
byte[] compressedData = baos.toByteArray();
outState.putByteArray(STATE_RAM_DATA, compressedData);
Timber.d("Saved RAM data: original %dKB, compressed %dKB",
totalDataSize / 1024, compressedData.length / 1024);
}
/**
* Restore computer state.
* @param inState {@link Bundle} to restore state
* @throws Exception in case of error while state restoring
*/
public void restoreState(Bundle inState) throws Exception {
// Restore computer system uptime
setSystemUptime(inState.getLong(STATE_SYSTEM_UPTIME));
// Initialize CPU and devices
cpu.initDevices(true);
// Restore RAM data
restoreRandomAccessMemoryData(inState);
// Restore CPU state
getCpu().restoreState(inState);
// Restore device states
for (Device device : deviceList) {
device.restoreState(inState);
}
}
private void restoreRandomAccessMemoryData(Bundle inState) {
byte[] compressedData = inState.getByteArray(STATE_RAM_DATA);
if (compressedData == null || compressedData.length == 0) {
throw new IllegalArgumentException("No RAM data to restore");
}
List<RandomAccessMemory> randomAccessMemoryList = getRandomAccessMemoryList();
// Calculate RAM memory data size (in bytes)
int totalDataSize = 0;
for (RandomAccessMemory memory: randomAccessMemoryList) {
totalDataSize += memory.getSize() * 2;
}
// Decompress RAM data
ByteArrayOutputStream baos = new ByteArrayOutputStream(totalDataSize);
ByteArrayInputStream bais = new ByteArrayInputStream(compressedData);
try (InflaterInputStream iis = new InflaterInputStream(bais)) {
FileUtils.writeFully(iis, baos);
} catch (IOException e) {
throw new IllegalArgumentException("Can't decompress RAM data", e);
}
// Check decompressed data
byte[] data = baos.toByteArray();
if (data.length != totalDataSize) {
throw new IllegalArgumentException(String.format("Invalid decompressed RAM " +
"data length: expected %d, got %d", totalDataSize, data.length));
}
// Restore RAM data
ByteBuffer dataBuf = ByteBuffer.wrap(data);
ShortBuffer shortDataBuf = dataBuf.asShortBuffer();
for (RandomAccessMemory memory: randomAccessMemoryList) {
short[] memoryData = new short[memory.getSize()];
shortDataBuf.get(memoryData);
memory.putData(memoryData);
}
}
public static Configuration getStoredConfiguration(Bundle inState) {
return (inState != null) ? Configuration.valueOf(inState.getString(
Configuration.class.getName())) : null;
}
/**
* Get clock frequency (in kHz)
* @return clock frequency
*/
public int getClockFrequency() {
return clockFrequency;
}
/**
* Set clock frequency (in kHz)
* @param clockFrequency clock frequency to set
*/
public void setClockFrequency(int clockFrequency) {
this.clockFrequency = clockFrequency;
systemUptimeSyncCheckIntervalTicks = nanosToCpuTime(UPTIME_SYNC_CHECK_INTERVAL);
}
private void addReadOnlyMemory(Resources resources, int address, int romDataResId, String romId)
throws IOException {
byte[] romData = loadReadOnlyMemoryData(resources, romDataResId);
addMemory(address, new ReadOnlyMemory(romId, romData));
}
/**
* Load ROM data from raw resources.
* @param resources {@link Resources} reference
* @param romDataResIds ROM raw resource IDs
* @return loaded ROM data
* @throws IOException in case of ROM data loading error
*/
private byte[] loadReadOnlyMemoryData(Resources resources, int... romDataResIds)
throws IOException {
byte[] romData = null;
for (int romDataResId : romDataResIds) {
romData = ArrayUtils.addAll(romData, loadRawResourceData(resources, romDataResId));
}
return romData;
}
/**
* Load data of raw resource.
* @param resources {@link Resources} reference
* @param resourceId raw resource ID
* @return read raw resource data
* @throws IOException in case of loading error
*/
private byte[] loadRawResourceData(Resources resources, int resourceId) throws IOException {
InputStream resourceDataStream = resources.openRawResource(resourceId);
byte[] resourceData = new byte[resourceDataStream.available()];
resourceDataStream.read(resourceData);
return resourceData;
}
/**
* Get {@link Cpu} reference.
* @return this <code>Computer</code> CPU object reference
*/
public Cpu getCpu() {
return cpu;
}
/**
* Get {@link VideoController} reference.
* @return video controller reference
*/
public VideoController getVideoController() {
return videoController;
}
/**
* Get {@link KeyboardController} reference.
* @return keyboard controller reference
*/
public KeyboardController getKeyboardController() {
return keyboardController;
}
/**
* Get {@link PeripheralPort} reference.
* @return peripheral port reference
*/
public PeripheralPort getPeripheralPort() {
return peripheralPort;
}
/**
* Get {@link FloppyController} reference.
* @return floppy controller reference or <code>null</code> if floppy controller is not present
*/
public FloppyController getFloppyController() {
return floppyController;
}
/**
* Get {@link IdeController} reference.
* @return IDE controller reference or <code>null</code> if IDE controller is not present
*/
public IdeController getIdeController() {
return ideController;
}
/**
* Get list of available {@link AudioOutput}s.
* @return audio outputs list
*/
public List<AudioOutput> getAudioOutputs() {
return audioOutputs;
}
/**
* Add {@link AudioOutput} device.
* @param audioOutput audio output device to add
*/
public void addAudioOutput(AudioOutput audioOutput) {
audioOutputs.add(audioOutput);
addDevice(audioOutput);
}
/**
* Set computer system uptime (in nanoseconds).
* @param systemUptime computer system uptime to set (in nanoseconds)
*/
public void setSystemUptime(long systemUptime) {
this.systemUptime = systemUptime;
}
/**
* Get computer system uptime (in nanoseconds).
* @return computer system uptime (in nanoseconds)
*/
public long getSystemUptime() {
return systemUptime;
}
/**
* Get computer time (in nanoseconds).
* @return current computer uptime
*/
public long getUptime() {
return cpuTimeToNanos(cpu.getTime());
}
/**
* Get computer time (in CPU ticks).
* @return current computer uptime
*/
public long getUptimeTicks() {
return cpu.getTime();
}
/**
* Add computer uptime updates listener.
* @param uptimeListener {@link UptimeListener} object reference to add
*/
public void addUptimeListener(UptimeListener uptimeListener) {
uptimeListeners.add(uptimeListener);
}
private void notifyUptimeListeners() {
long uptime = getUptime();
for (int i = 0; i < uptimeListeners.size(); i++) {
UptimeListener uptimeListener = uptimeListeners.get(i);
uptimeListener.uptimeUpdated(uptime);
}
}
/**
* Add memory (RAM/ROM) to address space.
* @param address address to add memory
* @param memory {@link Memory} to add
*/
public void addMemory(int address, Memory memory) {
int memoryStartBlock = address >> 12;
int memoryBlocksCount = memory.getSize() >> 11; // ((size << 1) >> 12)
if ((memory.getSize() & 03777) != 0) {
memoryBlocksCount++;
}
MemoryRange memoryRange = new MemoryRange(address, memory);
for (int i = 0; i < memoryBlocksCount; i++) {
int memoryBlockIdx = memoryStartBlock + i;
@SuppressWarnings("unchecked")
List<MemoryRange> memoryRanges = (List<MemoryRange>) memoryTable[memoryBlockIdx];
if (memoryRanges == null) {
memoryRanges = new ArrayList<>(1);
memoryTable[memoryBlockIdx] = memoryRanges;
}
memoryRanges.add(0, memoryRange);
}
}
/**
* Add I/O device to address space.
* @param device {@link Device} to add
*/
public void addDevice(Device device) {
deviceList.add(device);
int[] deviceAddresses = device.getAddresses();
for (int deviceAddress : deviceAddresses) {
int deviceTableIndex = (deviceAddress - IO_REGISTERS_MIN_ADDRESS) >> 1;
@SuppressWarnings("unchecked")
List<Device> addressDevices = (List<Device>) deviceTable[deviceTableIndex];
if (addressDevices == null) {
addressDevices = new ArrayList<>(1);
deviceTable[deviceTableIndex] = addressDevices;
}
addressDevices.add(device);
}
}
/**
* Check is given address is mapped to ROM area.
* @param address address to check
* @return <code>true</code> if given address is mapped to ROM area,
* <code>false</code> otherwise
*/
public boolean isReadOnlyMemoryAddress(int address) {
if (address >= 0) {
List<MemoryRange> memoryRanges = getMemoryRanges(address);
if (memoryRanges == null || memoryRanges.isEmpty()) {
return false;
}
for (MemoryRange memoryRange : memoryRanges) {
if (memoryRange != null && memoryRange.isRelatedAddress(address)
&& memoryRange.getMemory() instanceof ReadOnlyMemory) {
return true;
}
}
}
return false;
}
@SuppressWarnings("unchecked")
public List<MemoryRange> getMemoryRanges(int address) {
return (List<MemoryRange>) memoryTable[address >> 12];
}
@SuppressWarnings("unchecked")
private List<Device> getDevices(int address) {
return (List<Device>) deviceTable[(address - IO_REGISTERS_MIN_ADDRESS) >> 1];
}
/**
* Initialize bus devices state (on power-on cycle or RESET opcode).
* @param isHardwareReset true if bus initialization is initiated by hardware reset,
* false if it is initiated by RESET command
*/
public void initDevices(boolean isHardwareReset) {
for (Device device: deviceList) {
device.init(getCpu().getTime(), isHardwareReset);
}
}
/**
* Reset computer state.
*/
public void reset() {
pause();
synchronized (this) {
Timber.d("resetting computer");
getCpu().reset();
}
resume();
}
/**
* Read byte or word from memory or I/O device mapped to given address.
* @param isByteMode <code>true</code> to read byte, <code>false</code> to read word
* @param address address or memory location to read
* @return read memory or I/O device data or <code>BUS_ERROR</code> in case if given memory
* location is not mapped
*/
public int readMemory(boolean isByteMode, int address) {
int readValue = BUS_ERROR;
int wordAddress = address & 0177776;
// Check for memories at given address
List<MemoryRange> memoryRanges = getMemoryRanges(address);
if (memoryRanges != null) {
for (int i = 0, memoryRangesSize = memoryRanges.size(); i < memoryRangesSize; i++) {
MemoryRange memoryRange = memoryRanges.get(i);
if (memoryRange.isRelatedAddress(address)) {
int memoryReadValue = memoryRange.getMemory().read(
wordAddress - memoryRange.getStartAddress());
if (memoryReadValue != BUS_ERROR) {
readValue = memoryReadValue;
break;
}
}
}
}
// Check for I/O registers
if (address >= IO_REGISTERS_MIN_ADDRESS) {
List<Device> subdevices = getDevices(address);
if (subdevices != null) {
long cpuClock = getCpu().getTime();
for (int i = 0, subdevicesSize = subdevices.size(); i < subdevicesSize; i++) {
Device subdevice = subdevices.get(i);
// Read and combine subdevice state values in word mode
int subdeviceReadValue = subdevice.read(cpuClock, wordAddress);
if (subdeviceReadValue != BUS_ERROR) {
readValue = (readValue == BUS_ERROR)
? subdeviceReadValue
: readValue | subdeviceReadValue;
}
}
}
}
if (readValue != BUS_ERROR) {
if (isByteMode && (address & 1) != 0) {
// Extract high byte if byte mode read from odd address
readValue >>= 8;
}
readValue &= (isByteMode ? 0377 : 0177777);
}
return readValue;
}
/**
* Write byte or word to memory or I/O device mapped to given address.
* @param isByteMode <code>true</code> to write byte, <code>false</code> to write word
* @param address address or memory location to write
* @param value value (byte/word) to write to given address
* @return <code>true</code> if data successfully written or <code>false</code>
* in case if given memory location is not mapped
*/
public boolean writeMemory(boolean isByteMode, int address, int value) {
boolean isWritten = false;
if (isByteMode && (address & 1) != 0) {
value <<= 8;
}
// Check for memories at given address
List<MemoryRange> memoryRanges = getMemoryRanges(address);
if (memoryRanges != null) {
for (int i = 0, memoryRangesSize = memoryRanges.size(); i < memoryRangesSize; i++) {
MemoryRange memoryRange = memoryRanges.get(i);
if (memoryRange.isRelatedAddress(address)) {
if (memoryRange.getMemory().write(isByteMode,
address - memoryRange.getStartAddress(), value)) {
isWritten = true;
}
}
}
}
// Check for I/O registers
if (address >= IO_REGISTERS_MIN_ADDRESS) {
List<Device> devices = getDevices(address);
if (devices != null) {
long cpuClock = getCpu().getTime();
for (int i = 0, devicesSize = devices.size(); i < devicesSize; i++) {
Device device = devices.get(i);
if (device.write(cpuClock, isByteMode, address, value)) {
isWritten = true;
}
}
}
}
return isWritten;
}
/**
* Start computer.
*/
public synchronized void start() {
if (!isRunning) {
Timber.d("starting computer");
clockThread = new Thread(this, "ComputerClockThread");
isRunning = true;
clockThread.start();
// Waiting for emulation thread start
try {
this.wait();
} catch (InterruptedException e) {
// Do nothing
}
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.start();
}
} else {
throw new IllegalStateException("Computer is already running!");
}
}
/**
* Stop computer.
*/
public void stop() {
if (isRunning) {
Timber.d("stopping computer");
isRunning = false;
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.stop();
}
synchronized (this) {
this.notifyAll();
}
while (clockThread.isAlive()) {
try {
clockThread.join();
} catch (InterruptedException e) {
// Do nothing
}
}
} else {
throw new IllegalStateException("Computer is already stopped!");
}
}
public boolean isPaused() {
return isPaused;
}
/**
* Pause computer.
*/
public void pause() {
if (!isPaused) {
Timber.d("pausing computer");
isPaused = true;
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.pause();
}
}
}
/**
* Resume computer.
*/
public void resume() {
if (isPaused) {
Timber.d("resuming computer");
systemUptimeUpdateTimestamp = System.nanoTime();
systemUptimeSyncCheckTimestampTicks = getUptimeTicks();
isPaused = false;
synchronized (this) {
this.notifyAll();
}
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.resume();
}
}
}
/**
* Release computer resources.
*/
public void release() {
Timber.d("releasing computer");
for (AudioOutput audioOutput : audioOutputs) {
audioOutput.release();
}
if (floppyController != null) {
floppyController.unmountDiskImages();
}
if (ideController != null) {
ideController.detachDrives();
}
}
/**
* Get effective emulation clock frequency.
* @return effective emulation clock frequency (in kHz)
*/
public float getEffectiveClockFrequency() {
return (float) getCpu().getTime() * NANOSECS_IN_MSEC / getSystemUptime();
}
/**
* Get CPU time (converted from clock ticks to nanoseconds).
* @param cpuTime CPU time (in clock ticks) to convert
* @return CPU time in nanoseconds
*/
public long cpuTimeToNanos(long cpuTime) {
return cpuTime * NANOSECS_IN_MSEC / clockFrequency;
}
/**
* Get number of CPU clock ticks for given time in nanoseconds.
* @param nanosecs time (in nanoseconds) to convert to CPU ticks
* @return CPU ticks for given time
*/
public long nanosToCpuTime(long nanosecs) {
return nanosecs * clockFrequency / NANOSECS_IN_MSEC;
}
/**
* Check computer uptime is in sync with system time.
*/
private void checkUptimeSync() {
long uptimeTicks = getUptimeTicks();
if (uptimeTicks - systemUptimeSyncCheckTimestampTicks < systemUptimeSyncCheckIntervalTicks) {
return;
}
long systemTime = System.nanoTime();
systemUptime += systemTime - systemUptimeUpdateTimestamp;
systemUptimeUpdateTimestamp = systemTime;
systemUptimeSyncCheckTimestampTicks = uptimeTicks;
long uptimesDifference = getUptime() - systemUptime;
if (uptimesDifference >= UPTIME_SYNC_THRESHOLD) {
long uptimesDifferenceMillis = uptimesDifference / NANOSECS_IN_MSEC;
int uptimesDifferenceNanos = (int) (uptimesDifference % NANOSECS_IN_MSEC);
try {
this.wait(uptimesDifferenceMillis, uptimesDifferenceNanos);
} catch (InterruptedException e) {
// Do nothing
}
}
}
@Override
public void run() {
synchronized (this) {
Timber.d("computer started");
this.notifyAll();
while (isRunning) {
if (isPaused) {
Timber.d("computer paused");
while (isRunning && isPaused) {
try {
this.wait(100);
} catch (InterruptedException e) {
// Do nothing
}
}
Timber.d("computer resumed");
} else {
cpu.executeNextOperation();
notifyUptimeListeners();
checkUptimeSync();
}
}
}
Timber.d("computer stopped");
}
}
| 3cky/bkemu-android | app/src/main/java/su/comp/bk/arch/Computer.java | Java | gpl-3.0 | 40,937 |
//
// 1029Ca.cpp
// Problems
//
// Created by NicolasCardozo on 4/24/21.
// Copyright © 2021 NicolasCardozo. All rights reserved.
//
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
multiset<int> l, r;
pair<int, int> intervals[300010];
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> intervals[i].first >> intervals[i].second;
l.insert(intervals[i].first);
r.insert(intervals[i].second);
}
int best = 0;
for (int i = 0; i < n; ++i) {
l.erase(l.find(intervals[i].first));
r.erase(r.find(intervals[i].second));
best = max(best, *r.begin() - *l.rbegin());
l.insert(intervals[i].first);
r.insert(intervals[i].second);
}
cout << best << endl;
return 0;
}
| mua-uniandes/weekly-problems | codeforces/1029/1029Ca.cpp | C++ | gpl-3.0 | 800 |
package net.ddns.templex.commands;
import io.github.trulyfree.va.command.commands.TabbableCommand;
import io.github.trulyfree.va.daemon.Daemon;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.TabCompleteEvent;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TPAHereCommand extends TabbableCommand {
private final BaseComponent[] NO_ACTIVE_REQUESTS = new ComponentBuilder("You didn't have any active requests!").color(ChatColor.RED).create();
private final BaseComponent[] ALREADY_ACTIVE_REQUEST = new ComponentBuilder("You already have an active request!").color(ChatColor.RED).create();
private final BaseComponent[] TIMEOUT = new ComponentBuilder("Request timed out.").color(ChatColor.RED).create();
/**
* The set of currently active requests. This map is threadsafe.
*/
private final Map<ProxiedPlayer, ProxiedPlayer> requests;
/**
* The scheduler which manages request timeouts. Requests will timeout after 10 seconds.
*/
private final ScheduledExecutorService requestManager;
public TPAHereCommand() {
super("tpahere", "nonop");
this.requests = new ConcurrentHashMap<>();
requestManager = Executors.newSingleThreadScheduledExecutor();
}
@Override
public void execute(final CommandSender commandSender, String[] strings) {
if (!(commandSender instanceof ProxiedPlayer)) {
return;
}
ProxyServer proxy = ProxyServer.getInstance();
final ProxiedPlayer executor = (ProxiedPlayer) commandSender;
if (strings.length == 0) {
ProxiedPlayer target = null;
for (Map.Entry<ProxiedPlayer, ProxiedPlayer> entry : requests.entrySet()) {
if (entry.getValue().equals(executor)) {
target = entry.getKey();
break;
}
}
if (target == null) {
commandSender.sendMessage(NO_ACTIVE_REQUESTS);
} else {
requests.remove(target);
Daemon instance = Daemon.getInstanceNow();
if (instance == null) {
CommandUtil.daemonNotFound(commandSender);
return;
}
instance.submitCommands(Collections.singletonList(String.format("/tp %s %s", executor.getName(), target.getName())));
}
return;
}
if (requests.containsKey(executor)) {
commandSender.sendMessage(ALREADY_ACTIVE_REQUEST);
} else {
final ProxiedPlayer requested = proxy.getPlayer(strings[0]);
if (requested == null) {
commandSender.sendMessage(new ComponentBuilder(String.format("Didn't recognize the name %s.", strings[0])).color(ChatColor.RED).create());
} else {
commandSender.sendMessage(new ComponentBuilder(String.format("Request sent to %s", strings[0])).color(ChatColor.GREEN).create());
requested.sendMessage(new ComponentBuilder(String.format("%s requested that you TP to them! Type /tpahere to accept.", commandSender.getName())).color(ChatColor.GOLD).create());
requests.put(executor, requested);
requestManager.schedule(new Runnable() {
@Override
public void run() {
if (requests.remove(executor) != null) {
commandSender.sendMessage(TIMEOUT);
requested.sendMessage(new ComponentBuilder(String.format("Request from %s timed out.", commandSender.getName())).color(ChatColor.RED).create());
}
}
}, 10, TimeUnit.SECONDS);
}
}
}
@Override
public void handleTabCompleteEvent(TabCompleteEvent event) {
CommandUtil.pushAutocompletePlayers(event);
}
}
| TemplexMC/TemplexAdditions | src/main/java/net/ddns/templex/commands/TPAHereCommand.java | Java | gpl-3.0 | 4,347 |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-6 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose 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.
#
# Rose 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 Rose. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
import os
import time
import webbrowser
import pygtk
pygtk.require('2.0')
import gtk
import rose.config
import rose.config_editor.util
import rose.gtk.dialog
class NavPanelHandler(object):
"""Handles the navigation panel menu."""
def __init__(self, data, util, reporter, mainwindow,
undo_stack, redo_stack, add_config_func,
group_ops_inst, section_ops_inst, variable_ops_inst,
kill_page_func, reload_ns_tree_func, transform_default_func,
graph_ns_func):
self.data = data
self.util = util
self.reporter = reporter
self.mainwindow = mainwindow
self.undo_stack = undo_stack
self.redo_stack = redo_stack
self.group_ops = group_ops_inst
self.sect_ops = section_ops_inst
self.var_ops = variable_ops_inst
self._add_config = add_config_func
self.kill_page_func = kill_page_func
self.reload_ns_tree_func = reload_ns_tree_func
self._transform_default_func = transform_default_func
self._graph_ns_func = graph_ns_func
def add_dialog(self, base_ns):
"""Handle an add section dialog and request."""
if base_ns is not None and '/' in base_ns:
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
config_data = self.data.config[config_name]
if config_name == base_ns:
help_str = ''
else:
sections = self.data.helper.get_sections_from_namespace(
base_ns)
if sections == []:
help_str = subsp.replace('/', ':')
else:
help_str = sections[0]
help_str = help_str.split(':', 1)[0]
for config_section in (config_data.sections.now.keys() +
config_data.sections.latent.keys()):
if config_section.startswith(help_str + ":"):
help_str = help_str + ":"
else:
help_str = None
config_name = None
choices_help = self.data.helper.get_missing_sections(config_name)
config_names = [
n for n in self.data.config if not self.ask_is_preview(n)]
config_names.sort(lambda x, y: (y == config_name) - (x == config_name))
config_name, section = self.mainwindow.launch_add_dialog(
config_names, choices_help, help_str)
if config_name in self.data.config and section is not None:
self.sect_ops.add_section(config_name, section, page_launch=True)
def ask_is_preview(self, base_ns):
namespace = "/" + base_ns.lstrip("/")
try:
config_name = self.util.split_full_ns(self.data, namespace)[0]
config_data = self.data.config[config_name]
return config_data.is_preview
except KeyError:
print config_name
return False
def copy_request(self, base_ns, new_section=None, skip_update=False):
"""Handle a copy request for a section and its options."""
namespace = "/" + base_ns.lstrip("/")
sections = self.data.helper.get_sections_from_namespace(namespace)
if len(sections) != 1:
return False
section = sections.pop()
config_name = self.util.split_full_ns(self.data, namespace)[0]
config_data = self.data.config[config_name]
return self.group_ops.copy_section(config_name, section,
skip_update=skip_update)
def create_request(self):
"""Handle a create configuration request."""
if not any([v.config_type == rose.TOP_CONFIG_NAME
for v in self.data.config.values()]):
text = rose.config_editor.WARNING_APP_CONFIG_CREATE
title = rose.config_editor.WARNING_APP_CONFIG_CREATE_TITLE
rose.gtk.dialog.run_dialog(rose.gtk.dialog.DIALOG_TYPE_ERROR,
text, title)
return False
# Need an application configuration to be created.
root = os.path.join(self.data.top_level_directory,
rose.SUB_CONFIGS_DIR)
name, meta = self.mainwindow.launch_new_config_dialog(root)
if name is None:
return False
config_name = "/" + name
self._add_config(config_name, meta)
def ignore_request(self, base_ns, is_ignored):
"""Handle an ignore or enable section request."""
config_names = self.data.config.keys()
if base_ns is not None and '/' in base_ns:
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
prefer_name_sections = {
config_name:
self.data.helper.get_sections_from_namespace(base_ns)}
else:
prefer_name_sections = {}
config_sect_dict = {}
sorter = rose.config.sort_settings
for config_name in config_names:
config_data = self.data.config[config_name]
config_sect_dict[config_name] = []
sect_and_data = list(config_data.sections.now.items())
for v_sect in config_data.vars.now:
sect_data = config_data.sections.now[v_sect]
sect_and_data.append((v_sect, sect_data))
for section, sect_data in sect_and_data:
if section not in config_sect_dict[config_name]:
if sect_data.ignored_reason:
if is_ignored:
continue
if not is_ignored:
co = sect_data.metadata.get(rose.META_PROP_COMPULSORY)
if (not sect_data.ignored_reason or
co == rose.META_PROP_VALUE_TRUE):
continue
config_sect_dict[config_name].append(section)
config_sect_dict[config_name].sort(rose.config.sort_settings)
if config_name in prefer_name_sections:
prefer_name_sections[config_name].sort(
rose.config.sort_settings)
config_name, section = self.mainwindow.launch_ignore_dialog(
config_sect_dict, prefer_name_sections, is_ignored)
if config_name in self.data.config and section is not None:
self.sect_ops.ignore_section(config_name, section, is_ignored)
def edit_request(self, base_ns):
"""Handle a request for editing section comments."""
if base_ns is None:
return False
base_ns = "/" + base_ns.lstrip("/")
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
config_data = self.data.config[config_name]
sections = self.data.helper.get_sections_from_namespace(base_ns)
for section in list(sections):
if section not in config_data.sections.now:
sections.remove(section)
if not sections:
return False
if len(sections) > 1:
section = rose.gtk.dialog.run_choices_dialog(
rose.config_editor.DIALOG_LABEL_CHOOSE_SECTION_EDIT,
sections,
rose.config_editor.DIALOG_TITLE_CHOOSE_SECTION)
else:
section = sections[0]
if section is None:
return False
title = rose.config_editor.DIALOG_TITLE_EDIT_COMMENTS.format(section)
text = "\n".join(config_data.sections.now[section].comments)
finish = lambda t: self.sect_ops.set_section_comments(
config_name, section, t.splitlines())
rose.gtk.dialog.run_edit_dialog(text, finish_hook=finish, title=title)
def fix_request(self, base_ns):
"""Handle a request to auto-fix a configuration."""
if base_ns is None:
return False
base_ns = "/" + base_ns.lstrip("/")
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
self._transform_default_func(only_this_config=config_name)
def get_ns_metadata_and_comments(self, namespace):
"""Return metadata dict and comments list."""
namespace = "/" + namespace.lstrip("/")
metadata = {}
comments = ""
if namespace is None:
return metadata, comments
metadata = self.data.namespace_meta_lookup.get(namespace, {})
comments = self.data.helper.get_ns_comment_string(namespace)
return metadata, comments
def info_request(self, namespace):
"""Handle a request for namespace info."""
if namespace is None:
return False
config_name, subsp = self.util.split_full_ns(self.data, namespace)
config_data = self.data.config[config_name]
sections = self.data.helper.get_sections_from_namespace(namespace)
search_function = lambda i: self.search_request(namespace, i)
for section in sections:
sect_data = config_data.sections.now.get(section)
if sect_data is not None:
rose.config_editor.util.launch_node_info_dialog(
sect_data, "", search_function)
def graph_request(self, namespace):
"""Handle a graph request for namespace info."""
self._graph_ns_func(namespace)
def remove_request(self, base_ns):
"""Handle a delete section request."""
config_names = self.data.config.keys()
if base_ns is not None and '/' in base_ns:
config_name, subsp = self.util.split_full_ns(self.data, base_ns)
prefer_name_sections = {
config_name:
self.data.helper.get_sections_from_namespace(base_ns)}
else:
prefer_name_sections = {}
config_sect_dict = {}
sorter = rose.config.sort_settings
for config_name in config_names:
config_data = self.data.config[config_name]
config_sect_dict[config_name] = config_data.sections.now.keys()
config_sect_dict[config_name].sort(rose.config.sort_settings)
if config_name in prefer_name_sections:
prefer_name_sections[config_name].sort(
rose.config.sort_settings)
config_name, section = self.mainwindow.launch_remove_dialog(
config_sect_dict, prefer_name_sections)
if config_name in self.data.config and section is not None:
start_stack_index = len(self.undo_stack)
group = (
rose.config_editor.STACK_GROUP_DELETE + "-" + str(time.time()))
config_data = self.data.config[config_name]
sect_data = config_data.sections.now[section]
ns = sect_data.metadata["full_ns"]
variable_sorter = lambda v, w: rose.config.sort_settings(
v.metadata['id'], w.metadata['id'])
variables = list(config_data.vars.now.get(section, []))
variables.sort(variable_sorter)
variables.reverse()
for variable in variables:
self.var_ops.remove_var(variable)
self.sect_ops.remove_section(config_name, section)
for stack_item in self.undo_stack[start_stack_index:]:
stack_item.group = group
def search_request(self, namespace, setting_id):
"""Handle a search for an id (hyperlink)."""
config_name, subsp = self.util.split_full_ns(self.data, namespace)
self.var_ops.search_for_var(config_name, setting_id)
def popup_panel_menu(self, base_ns, event):
"""Popup a page menu on the navigation panel."""
if base_ns is None:
namespace = None
else:
namespace = "/" + base_ns.lstrip("/")
ui_config_string = """<ui> <popup name='Popup'>"""
actions = [('New', gtk.STOCK_NEW,
rose.config_editor.TREE_PANEL_NEW_CONFIG),
('Add', gtk.STOCK_ADD,
rose.config_editor.TREE_PANEL_ADD_GENERIC),
('Add section', gtk.STOCK_ADD,
rose.config_editor.TREE_PANEL_ADD_SECTION),
('Autofix', gtk.STOCK_CONVERT,
rose.config_editor.TREE_PANEL_AUTOFIX_CONFIG),
('Clone', gtk.STOCK_COPY,
rose.config_editor.TREE_PANEL_CLONE_SECTION),
('Edit', gtk.STOCK_EDIT,
rose.config_editor.TREE_PANEL_EDIT_SECTION),
('Enable', gtk.STOCK_YES,
rose.config_editor.TREE_PANEL_ENABLE_GENERIC),
('Enable section', gtk.STOCK_YES,
rose.config_editor.TREE_PANEL_ENABLE_SECTION),
('Graph', gtk.STOCK_SORT_ASCENDING,
rose.config_editor.TREE_PANEL_GRAPH_SECTION),
('Ignore', gtk.STOCK_NO,
rose.config_editor.TREE_PANEL_IGNORE_GENERIC),
('Ignore section', gtk.STOCK_NO,
rose.config_editor.TREE_PANEL_IGNORE_SECTION),
('Info', gtk.STOCK_INFO,
rose.config_editor.TREE_PANEL_INFO_SECTION),
('Help', gtk.STOCK_HELP,
rose.config_editor.TREE_PANEL_HELP_SECTION),
('URL', gtk.STOCK_HOME,
rose.config_editor.TREE_PANEL_URL_SECTION),
('Remove', gtk.STOCK_DELETE,
rose.config_editor.TREE_PANEL_REMOVE_GENERIC),
('Remove section', gtk.STOCK_DELETE,
rose.config_editor.TREE_PANEL_REMOVE_SECTION)]
url = None
help = None
is_empty = (not self.data.config)
if namespace is not None:
config_name = self.util.split_full_ns(self.data, namespace)[0]
if self.data.config[config_name].is_preview:
return False
cloneable = self.is_ns_duplicate(namespace)
is_top = (namespace in self.data.config.keys())
is_fixable = bool(self.get_ns_errors(namespace))
has_content = self.data.helper.is_ns_content(namespace)
is_unsaved = self.data.helper.get_config_has_unsaved_changes(
config_name)
ignored_sections = self.data.helper.get_ignored_sections(namespace)
enabled_sections = self.data.helper.get_ignored_sections(
namespace, get_enabled=True)
is_latent = self.data.helper.get_ns_latent_status(namespace)
latent_sections = self.data.helper.get_latent_sections(namespace)
metadata, comments = self.get_ns_metadata_and_comments(namespace)
if is_latent:
for i, section in enumerate(latent_sections):
action_name = "Add {0}".format(i)
ui_config_string += '<menuitem action="{0}"/>'.format(
action_name)
actions.append(
(action_name, gtk.STOCK_ADD,
rose.config_editor.TREE_PANEL_ADD_SECTION.format(
section.replace("_", "__")))
)
ui_config_string += '<separator name="addlatentsep"/>'
ui_config_string += '<menuitem action="Add"/>'
if cloneable:
ui_config_string += '<separator name="clonesep"/>'
ui_config_string += '<menuitem action="Clone"/>'
ui_config_string += '<separator name="ignoresep"/>'
ui_config_string += '<menuitem action="Enable"/>'
ui_config_string += '<menuitem action="Ignore"/>'
ui_config_string += '<separator name="infosep"/>'
if has_content:
ui_config_string += '<menuitem action="Info"/>'
ui_config_string += '<menuitem action="Edit"/>'
ui_config_string += '<separator name="graphsep"/>'
ui_config_string += '<menuitem action="Graph"/>'
url = metadata.get(rose.META_PROP_URL)
help = metadata.get(rose.META_PROP_HELP)
if url is not None or help is not None:
ui_config_string += '<separator name="helpsep"/>'
if url is not None:
ui_config_string += '<menuitem action="URL"/>'
if help is not None:
ui_config_string += '<menuitem action="Help"/>'
if not is_empty:
ui_config_string += """<separator name="removesep"/>"""
ui_config_string += """<menuitem action="Remove"/>"""
if is_fixable:
ui_config_string += """<separator name="sepauto"/>
<menuitem action="Autofix"/>"""
else:
ui_config_string += '<menuitem action="Add"/>'
ui_config_string += '<separator name="ignoresep"/>'
ui_config_string += '<menuitem action="Enable"/>'
ui_config_string += '<menuitem action="Ignore"/>'
if namespace is None or (is_top or is_empty):
ui_config_string += """<separator name="newconfigsep"/>
<menuitem action="New"/>"""
ui_config_string += """</popup> </ui>"""
uimanager = gtk.UIManager()
actiongroup = gtk.ActionGroup('Popup')
actiongroup.add_actions(actions)
uimanager.insert_action_group(actiongroup, pos=0)
uimanager.add_ui_from_string(ui_config_string)
if namespace is None or (is_top or is_empty):
new_item = uimanager.get_widget('/Popup/New')
new_item.connect("activate", lambda b: self.create_request())
new_item.set_sensitive(not is_empty)
add_item = uimanager.get_widget('/Popup/Add')
add_item.connect("activate", lambda b: self.add_dialog(namespace))
add_item.set_sensitive(not is_empty)
enable_item = uimanager.get_widget('/Popup/Enable')
enable_item.connect(
"activate", lambda b: self.ignore_request(namespace, False))
enable_item.set_sensitive(not is_empty)
ignore_item = uimanager.get_widget('/Popup/Ignore')
ignore_item.connect(
"activate", lambda b: self.ignore_request(namespace, True))
ignore_item.set_sensitive(not is_empty)
if namespace is not None:
if is_latent:
for i, section in enumerate(latent_sections):
action_name = "Add {0}".format(i)
add_item = uimanager.get_widget("/Popup/" + action_name)
add_item._section = section
add_item.connect(
"activate",
lambda b: self.sect_ops.add_section(
config_name, b._section))
if cloneable:
clone_item = uimanager.get_widget('/Popup/Clone')
clone_item.connect("activate",
lambda b: self.copy_request(namespace))
if has_content:
edit_item = uimanager.get_widget('/Popup/Edit')
edit_item.connect("activate",
lambda b: self.edit_request(namespace))
info_item = uimanager.get_widget('/Popup/Info')
info_item.connect("activate",
lambda b: self.info_request(namespace))
graph_item = uimanager.get_widget("/Popup/Graph")
graph_item.connect("activate",
lambda b: self.graph_request(namespace))
if is_unsaved:
graph_item.set_sensitive(False)
if help is not None:
help_item = uimanager.get_widget('/Popup/Help')
help_title = namespace.split('/')[1:]
help_title = rose.config_editor.DIALOG_HELP_TITLE.format(
help_title)
search_function = lambda i: self.search_request(namespace, i)
help_item.connect(
"activate",
lambda b: rose.gtk.dialog.run_hyperlink_dialog(
gtk.STOCK_DIALOG_INFO, help, help_title,
search_function))
if url is not None:
url_item = uimanager.get_widget('/Popup/URL')
url_item.connect(
"activate", lambda b: webbrowser.open(url))
if is_fixable:
autofix_item = uimanager.get_widget('/Popup/Autofix')
autofix_item.connect("activate",
lambda b: self.fix_request(namespace))
remove_section_item = uimanager.get_widget('/Popup/Remove')
remove_section_item.connect(
"activate", lambda b: self.remove_request(namespace))
menu = uimanager.get_widget('/Popup')
menu.popup(None, None, None, event.button, event.time)
return False
def is_ns_duplicate(self, namespace):
"""Lookup whether a page can be cloned, via the metadata."""
sections = self.data.helper.get_sections_from_namespace(namespace)
if len(sections) != 1:
return False
section = sections.pop()
config_name = self.util.split_full_ns(self.data, namespace)[0]
sect_data = self.data.config[config_name].sections.now.get(section)
if sect_data is None:
return False
return (sect_data.metadata.get(rose.META_PROP_DUPLICATE) ==
rose.META_PROP_VALUE_TRUE)
def get_ns_errors(self, namespace):
"""Count the number of errors in a namespace."""
config_name = self.util.split_full_ns(self.data, namespace)[0]
config_data = self.data.config[config_name]
sections = self.data.helper.get_sections_from_namespace(namespace)
errors = 0
for section in sections:
errors += len(config_data.sections.get_sect(section).error)
real_data, latent_data = self.data.helper.get_data_for_namespace(
namespace)
errors += sum([len(v.error) for v in real_data + latent_data])
return errors
def get_ns_ignored(self, base_ns):
"""Lookup the ignored status of a namespace's data."""
namespace = "/" + base_ns.lstrip("/")
return self.data.helper.get_ns_ignored_status(namespace)
def get_can_show_page(self, latent_status, ignored_status, has_error):
"""Lookup whether to display a page based on the data status."""
if has_error or (not ignored_status and not latent_status):
# Always show this.
return True
show_ignored = self.data.page_ns_show_modes[
rose.config_editor.SHOW_MODE_IGNORED]
show_user_ignored = self.data.page_ns_show_modes[
rose.config_editor.SHOW_MODE_USER_IGNORED]
show_latent = self.data.page_ns_show_modes[
rose.config_editor.SHOW_MODE_LATENT]
if latent_status:
if not show_latent:
# Latent page, no latent pages allowed.
return False
# Latent page, latent pages allowed (but may be ignored...).
if ignored_status:
if ignored_status == rose.config.ConfigNode.STATE_USER_IGNORED:
if show_ignored or show_user_ignored:
# This is an allowed user-ignored page.
return True
# This is a user-ignored page that isn't allowed.
return False
# This is a trigger-ignored page that may be allowed.
return show_ignored
# This is a latent page that isn't ignored, latent pages allowed.
return True
| kaday/rose | lib/python/rose/config_editor/nav_panel_menu.py | Python | gpl-3.0 | 24,642 |
package com.ebrightmoon.doraemonkit.ui.dialog;
/**
* Created by wanglikun on 2019/4/12
*/
public interface DialogListener {
boolean onPositive();
boolean onNegative();
void onCancel();
} | jinsedeyuzhou/NewsClient | doraemonkit/src/main/java/com/ebrightmoon/doraemonkit/ui/dialog/DialogListener.java | Java | gpl-3.0 | 203 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-11-30 03:32
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('administrador', '0011_auto_20171129_2215'),
]
operations = [
migrations.AlterField(
model_name='respuesta',
name='fecha',
field=models.DateTimeField(blank=True, default=datetime.datetime(2017, 11, 29, 22, 32, 35, 304385), null=True),
),
]
| adbetin/organico-cooperativas | administrador/migrations/0012_auto_20171129_2232.py | Python | gpl-3.0 | 548 |
/**
* @file Surface Component
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
import { ComponentRegistry } from "../globals.js";
import { defaults } from "../utils.js";
import Component from "./component.js";
/**
* Component wrapping a Surface object
* @class
* @extends Component
* @param {Stage} stage - stage object the component belongs to
* @param {Surface} surface - surface object to wrap
* @param {ComponentParameters} params - component parameters
*/
function SurfaceComponent( stage, surface, params ){
var p = params || {};
p.name = defaults( p.name, surface.name );
Component.call( this, stage, p );
this.surface = surface;
}
SurfaceComponent.prototype = Object.assign( Object.create(
Component.prototype ), {
constructor: SurfaceComponent,
/**
* Component type
* @alias SurfaceComponent#type
* @constant
* @type {String}
* @default
*/
type: "surface",
/**
* Add a new surface representation to the component
* @alias SurfaceComponent#addRepresentation
* @param {String} type - the name of the representation, one of:
* surface, dot.
* @param {SurfaceRepresentationParameters} params - representation parameters
* @return {RepresentationComponent} the created representation wrapped into
* a representation component object
*/
addRepresentation: function( type, params ){
return Component.prototype.addRepresentation.call(
this, type, this.surface, params
);
},
dispose: function(){
this.surface.dispose();
Component.prototype.dispose.call( this );
},
centerView: function( zoom ){
var center = this.surface.center;
if( zoom ){
zoom = this.surface.boundingBox.size().length();
}
this.viewer.centerView( zoom, center );
},
} );
ComponentRegistry.add( "surface", SurfaceComponent );
export default SurfaceComponent;
| deepchem/deepchem-gui | gui/static/ngl/src/component/surface-component.js | JavaScript | gpl-3.0 | 2,061 |
from django.db import models
from wagtail.core.models import Page
from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel
from wagtail.core.fields import StreamField
from wagtail.core import blocks
from wagtail.images.blocks import ImageChooserBlock
from test.anotherapp.models import HomePage
class AnotherTest(Page):
"""
This model is entirely NOT translated.
This could be normal for some kind of page that's individual to every
language.
"""
field_that_is_not_translated = models.CharField(max_length=255, null=True, blank=True)
content_panels = [
FieldPanel("field_that_is_not_translated"),
StreamFieldPanel("body"),
]
body = StreamField(
[
("heading", blocks.CharBlock(classname="full title")),
("paragraph", blocks.RichTextBlock()),
("image", ImageChooserBlock()),
],
verbose_name="body",
blank=True,
help_text="The main contents of the page",
)
def get_context(self, request):
context = super().get_context(request)
context['test'] = self.get_children().live()
return context
class Test(Page):
"""
This model is translated
"""
field_that_is_translated = models.CharField(max_length=255, null=True, blank=True)
field_that_is_not_translated = models.CharField(max_length=255, null=True, blank=True)
class InheritsFromHomePageTranslated(HomePage):
"""
This model is translated but inherits from a non-translated parent.
This could be normal for some kind of page that's individual to every
language.
"""
field_that_is_translated = models.CharField(max_length=255, null=True, blank=True)
field_that_is_not_translated = models.CharField(max_length=255, null=True, blank=True)
class InheritsFromPageTranslated(Page):
"""
This model is translated but inherits from a non-translated parent.
This could be normal for some kind of page that's individual to every
language.
"""
field_that_is_translated = models.CharField(max_length=255, null=True, blank=True)
field_that_is_not_translated = models.CharField(max_length=255, null=True, blank=True)
| benjaoming/django-modeltranslation-wagtail | test/transapp/models.py | Python | gpl-3.0 | 2,238 |
# daisy-extract
# Copyright (C) 2016 James Scholes
# This program is free software, licensed under the terms of the GNU General Public License (version 3 or later).
# See the file LICENSE for more details.
from collections import namedtuple
import argparse
import glob
import logging
import os
import platform
import shutil
import sys
from bs4 import BeautifulSoup
from natsort import natsorted
__version__ = '0.1'
is_windows = 'windows' in platform.system().lower()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
log_stream = logging.StreamHandler(sys.stdout)
log_stream.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
logger.addHandler(log_stream)
HTML_PARSER = 'html.parser'
NCC_FILENAME = 'NCC.HTML'
MASTER_SMIL_FILENAME = 'MASTER.SMIL'
SMIL_GLOB = '*.[sS][mM][iI][lL]'
BookMetadata = namedtuple('BookMetadata', ('authors', 'title'))
class InvalidDAISYBookError(Exception):
pass
class ExtractMetadataError(Exception):
pass
def main():
logger.info('daisy-extract version {0}'.format(__version__))
cli_args = parse_command_line()
if cli_args.debug:
logger.setLevel(logging.DEBUG)
encoding = getattr(cli_args, 'encoding', 'utf-8')
input_directory = os.path.abspath(cli_args.input_directory)
output_directory = os.path.abspath(cli_args.output_directory)
if not os.path.exists(input_directory) or not os.path.isdir(input_directory):
exit_with_error('{0} does not exist or is not a directory'.format(input_directory))
try:
metadata = create_metadata_object_from_ncc(find_ncc_path(input_directory), encoding=encoding)
except InvalidDAISYBookError as e:
exit_with_error('The contents of {0} don\'t seem to be a valid DAISY 2.02 book: {1}'.format(input_directory, str(e)))
except ExtractMetadataError as e:
exit_with_error(str(e))
output_directory = os.path.join(output_directory, make_safe_filename(metadata.authors), make_safe_filename(metadata.title))
logger.info('Extracting content of book: {0} by {1} from {2} to {3}'.format(metadata.title, metadata.authors, input_directory, output_directory))
source_audio_files = []
destination_audio_files = []
for doc in find_smil_documents(input_directory):
parsed_doc = parse_smil_document(doc, encoding=encoding)
try:
section_title = find_document_title(parsed_doc)
logger.debug('Found SMIL document: {0}'.format(section_title))
except ExtractMetadataError as e:
exit_with_error('Could not retrieve metadata from SMIL document ({0}): {1}'.format(file, str(e)))
section_audio_files = get_audio_filenames_from_smil(parsed_doc)
logger.debug('SMIL document spans {0} audio file(s)'.format(len(section_audio_files)))
for audio_file in section_audio_files:
source_audio_files.append((section_title, os.path.join(input_directory, audio_file)))
logger.info('Copying {0} audio files'.format(len(source_audio_files)))
try:
os.makedirs(output_directory)
logger.debug('Created directory: {0}'.format(output_directory))
except (FileExistsError, PermissionError):
pass
track_number = 1
for section_name, file_path in source_audio_files:
destination_filename = '{0:02d} - {1}.{2}'.format(track_number, make_safe_filename(section_name), os.path.splitext(file_path)[-1][1:].lower())
destination_path = os.path.join(output_directory, destination_filename)
logger.debug('Copying file: {0} to: {1}'.format(file_path, destination_path))
if is_windows:
destination_path = add_path_prefix(destination_path)
shutil.copyfile(file_path, destination_path)
destination_audio_files.append(os.path.split(destination_path)[-1])
track_number += 1
logger.info('Creating M3U playlist')
playlist_filename = '{0}.m3u'.format(make_safe_filename(metadata.title))
playlist_path = os.path.join(output_directory, playlist_filename)
logger.debug('M3U playlist path: {0}'.format(playlist_path))
if is_windows:
playlist_path = add_path_prefix(playlist_path)
with open(playlist_path, 'w', newline=None) as f:
f.write('\n'.join(destination_audio_files))
logger.info('Done!')
def parse_command_line():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input-directory', nargs='?', required=True)
parser.add_argument('-o', '--output-directory', nargs='?', required=True)
parser.add_argument('-e', '--encoding', nargs='?', required=False)
parser.add_argument('-d', '--debug', dest='debug', action='store_true', default=False, help='Enable debug logging')
args = parser.parse_args()
return args
def exit_with_error(message):
logger.error(message)
sys.exit(1)
def find_ncc_path(directory):
filenames = (NCC_FILENAME, NCC_FILENAME.lower())
for filename in filenames:
path = os.path.join(directory, filename)
if os.path.exists(path) and os.path.isfile(path):
logger.debug('Found NCC file: {0}'.format(path))
return path
raise InvalidDAISYBookError('Could not find NCC file')
def find_smil_documents(directory):
documents = list(filter(lambda smil: not smil.upper().endswith(MASTER_SMIL_FILENAME), glob.iglob(os.path.join(directory, SMIL_GLOB))))
if documents:
logger.debug('Found {0} SMIL documents in directory'.format(len(documents)))
return natsorted(documents)
else:
raise InvalidDAISYBookError('No SMIL documents found')
def create_metadata_object_from_ncc(ncc_path, encoding='utf-8'):
with open(ncc_path, 'r', encoding=encoding) as f:
ncc = BeautifulSoup(f, HTML_PARSER)
title_tag = ncc.find('meta', attrs={'name': 'dc:title'})
if title_tag is None:
raise ExtractMetadataError('The title of the DAISY book could not be found')
title = title_tag.attrs.get('content')
if not title:
raise ExtractMetadataError('The title of the DAISY book is blank')
creator_tags = ncc.find_all('meta', attrs={'name': 'dc:creator'})
if not creator_tags:
raise ExtractMetadataError('No authors are listed in the DAISY book')
authors = ', '.join([tag.attrs.get('content') for tag in creator_tags])
return BookMetadata(authors, title)
def parse_smil_document(path, encoding='utf-8'):
logger.debug('Parsing SMIL document: {0}'.format(os.path.split(path)[-1]))
with open(path, 'r', encoding=encoding) as f:
return BeautifulSoup(f, HTML_PARSER)
def find_document_title(doc):
title_tag = doc.find('meta', attrs={'name': 'title'})
if title_tag is None:
raise ExtractMetadataError('Unable to extract title from SMIL document')
title = title_tag.attrs.get('content')
if not title:
raise ExtractMetadataError('SMIL document has no title')
return title
def get_audio_filenames_from_smil(smil):
audio_files = [audio.attrs.get('src') for audio in smil.find_all('audio')]
unique_audio_files = []
for file in audio_files:
if file not in unique_audio_files:
unique_audio_files.append(file)
return tuple(unique_audio_files)
def add_path_prefix(path):
return '\\\\?\\{0}'.format(path)
def make_safe_filename(filename):
# strip out any disallowed chars and replace with underscores
disallowed_ascii = [chr(i) for i in range(0, 32)]
disallowed_chars = '<>:"/\\|?*^{0}'.format(''.join(disallowed_ascii))
translator = dict((ord(char), '_') for char in disallowed_chars)
safe_filename = filename.replace(': ', ' - ').translate(translator).rstrip('. ')
return safe_filename
if __name__ == '__main__':
main()
| jscholes/daisy-extract | extract.py | Python | gpl-3.0 | 7,728 |
package com.abada.trazability.datamatrix.decode;
/*
* #%L
* Contramed
* %%
* Copyright (C) 2013 Abada Servicios Desarrollo (investigacion@abadasoft.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/gpl-3.0.html>.
* #L%
*/
import com.abada.trazability.datamatrix.code.Codificar;
import com.abada.trazability.datamatrix.dato.DatosCodeDecode;
import com.abada.trazability.datamatrix.dato.DatosExponentePeso;
import com.abada.trazability.datamatrix.dato.DatosExponenteVolumen;
import com.abada.trazability.datamatrix.dato.ObjectPeso;
import com.abada.trazability.datamatrix.dato.ObjectVolumen;
import com.abada.trazability.datamatrix.exceptions.ExceptionCodeDecode;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*Decodificar una cadena en formato GS1
* @author maria
*/
public class DecodeImpl implements Decode {
private static final Log logger=LogFactory.getLog(DecodeImpl.class);
/**
* Metodo para codificar en forma legible por el humano un string que representa
* un formato GS1.
* @param ent
* @return map
*/
public Map<DatosCodeDecode, Object> decode(String ent) {
logger.debug("Entrada: "+ ent);
CompruebaDecode cd = new CompruebaDecode();
String sinparen = cd.quitaParentesis(ent);
String a;
if (sinparen.startsWith(Codificar.START_TAG)) {
a = sinparen.substring(3, sinparen.length());
} else {
a = sinparen;
}
Map<DatosCodeDecode, Object> cadenadeco = new HashMap<DatosCodeDecode, Object>();
/**
* Comprobamos que el tamaño del String de entrada es correcto, sino algun
* campo no estara bien codificado
* El tamaño correcto se corresponde con :
* GTIN n2+n14
* BATCH n2+X..20
* Expirate Date n2+n6 en formato YYMMDD
* Serial Number n2+X..20
* Wigeht n4+n6
* Dimension n4+n6
* En total tendremos 86 caracteres, teniendo en cuenta que se va a expresar el GTIN con 13 caracteres
*/
if (a.length() > 86) {
//new ExceptionCodeDecode("Cadena a decodificar incorrecta");
String cad = "The size of the chain is superior to the allowed one";
//FIXME falta lanzar la excepcion new ExceptionCodeDecode(cad);
} else {
String falta = "";
while (a.length() != 0) {
try {
if (a.substring(0, 1).equals(".")) {
return cadenadeco;
}
DatosCodeDecode dato = cd.recogecaso(a);
switch (dato) {
case EAN13:
//GTIN
falta = a.substring(16, a.length());
cadenadeco.put(dato.EAN13, a.substring(2, 16));
a = falta;
break;
case BATCH:
//BATCH
//La longitud Es variable a como maximo 20 caracteres
int maximalong = cd.comprobarLongitud(a.substring(2, a.length()), 20);
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == ('<') || (a.charAt(i) == '.')) {
if (a.charAt(i) == ('<')) {
falta = a.substring(maximalong + 2, a.length());
cadenadeco.put(dato.BATCH, a.substring(2, maximalong - 2));
break;
} else {
falta = a.substring(maximalong, a.length());
cadenadeco.put(dato.BATCH, a.substring(2, maximalong));
break;
}
}
}
a = falta;
break;
case EXPIRATEDATE:
//EXPIRATEDATE
falta = a.substring(8, a.length());
String fecha = a.substring(2, 8);
Calendar cal = cd.fechaCalendar(fecha);
cadenadeco.put(dato.EXPIRATEDATE, cal);
a = falta;
break;
case SERIALNUMBER:
//SerialNumber
//La longitud Es variable a como maximo 20 caracteres
int maxlong = cd.comprobarLongitud(a.substring(2, a.length()), 20);
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == ('<') || (a.charAt(i) == '.')) {
if (a.charAt(i) == ('<')) {
falta = a.substring(maxlong + 2, a.length());
cadenadeco.put(dato.SERIALNUMBER, a.substring(2, maxlong - 2));
break;
} else {
falta = a.substring(maxlong, a.length());
cadenadeco.put(dato.SERIALNUMBER, a.substring(2, maxlong));
break;
}
}
}
a = falta;
break;
case WEIGHT:
//Net weight, kilograms (Variable Measure Trade Item)
//Longitud fija de 6 caracteres, por eso al comprobar la cantidad de decimales
//que puede representar sera como maximo 5
ObjectPeso op = new ObjectPeso();
falta = falta = a.substring(10, a.length());
DatosExponentePeso caso = cd.recogeExpoPeso(a);
op.setExpo(caso);
String expop = cd.escribeExpoPeso(a, caso);
Double peso = Double.parseDouble(expop);
op.setValor(peso);
cadenadeco.put(dato.WEIGHT, op);
a = falta;
break;
case DIMENSION:
ObjectVolumen ov = new ObjectVolumen();
falta = falta = a.substring(10, a.length());
DatosExponenteVolumen volum = cd.recogeExpoVolumen(a);
ov.setExpo(volum);
String expov = cd.escribeExpoVolumen(a, volum);
Double volumen = Double.parseDouble(expov);
ov.setValor(volumen);
cadenadeco.put(dato.DIMENSION, ov);
a = falta;
break;
default:
break;
}
} catch (ExceptionCodeDecode ex) {
logger.error(ex);
}
}
}
return cadenadeco;
}
}
| abada-investigacion/contramed | trazability/trazability-datamatrix-utils/src/main/java/com/abada/trazability/datamatrix/decode/DecodeImpl.java | Java | gpl-3.0 | 8,180 |
# frozen_string_literal: true
class RenameTableCardExpenses < ActiveRecord::Migration[4.2]
def change
# noinspection RailsParamDefResolve
rename_table :card_expenses, :trip_expenses
end
end
| lssjbrolli/ctcadmin | db/migrate/20140809104441_rename_table_card_expenses.rb | Ruby | gpl-3.0 | 203 |
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 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.
*
* Applied Energistics 2 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 Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.core;
import net.minecraftforge.common.util.ForgeDirection;
import appeng.api.IAppEngApi;
import appeng.api.definitions.Blocks;
import appeng.api.definitions.Items;
import appeng.api.definitions.Materials;
import appeng.api.definitions.Parts;
import appeng.api.exceptions.FailedConnection;
import appeng.api.features.IRegistryContainer;
import appeng.api.networking.IGridBlock;
import appeng.api.networking.IGridConnection;
import appeng.api.networking.IGridNode;
import appeng.api.storage.IStorageHelper;
import appeng.core.api.ApiPart;
import appeng.core.api.ApiStorage;
import appeng.core.features.registries.RegistryContainer;
import appeng.me.GridConnection;
import appeng.me.GridNode;
import appeng.util.Platform;
public final class Api implements IAppEngApi
{
public static final Api INSTANCE = new Api();
private final ApiPart partHelper;
// private MovableTileRegistry MovableRegistry = new MovableTileRegistry();
private final IRegistryContainer registryContainer;
private final IStorageHelper storageHelper;
private final Materials materials;
private final Items items;
private final Blocks blocks;
private final Parts parts;
private final ApiDefinitions definitions;
private Api()
{
this.parts = new Parts();
this.blocks = new Blocks();
this.items = new Items();
this.materials = new Materials();
this.storageHelper = new ApiStorage();
this.registryContainer = new RegistryContainer();
this.partHelper = new ApiPart();
this.definitions = new ApiDefinitions( this.partHelper );
}
@Override
public IRegistryContainer registries()
{
return this.registryContainer;
}
@Override
public IStorageHelper storage()
{
return this.storageHelper;
}
@Override
public ApiPart partHelper()
{
return this.partHelper;
}
@Override
public Items items()
{
return this.items;
}
@Override
public Materials materials()
{
return this.materials;
}
@Override
public Blocks blocks()
{
return this.blocks;
}
@Override
public Parts parts()
{
return this.parts;
}
@Override
public ApiDefinitions definitions()
{
return this.definitions;
}
@Override
public IGridNode createGridNode( final IGridBlock blk )
{
if( Platform.isClient() )
{
throw new IllegalStateException( "Grid features for " + blk + " are server side only." );
}
return new GridNode( blk );
}
@Override
public IGridConnection createGridConnection( final IGridNode a, final IGridNode b ) throws FailedConnection
{
return new GridConnection( a, b, ForgeDirection.UNKNOWN );
}
}
| itachi1706/Applied-Energistics-2 | src/main/java/appeng/core/Api.java | Java | gpl-3.0 | 3,373 |
/*
Copyright (C) 2011 Jason von Nieda <jason@vonnieda.org>
This file is part of OpenPnP.
OpenPnP 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.
OpenPnP 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 OpenPnP. If not, see <http://www.gnu.org/licenses/>.
For more information about OpenPnP visit http://openpnp.org
*/
package org.openpnp.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.FocusTraversalPolicy;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Hashtable;
import java.util.Locale;
import java.util.concurrent.Callable;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import org.openpnp.ConfigurationListener;
import org.openpnp.gui.components.CameraPanel;
import org.openpnp.gui.support.Icons;
import org.openpnp.gui.support.MessageBoxes;
import org.openpnp.gui.support.NozzleItem;
import org.openpnp.model.Configuration;
import org.openpnp.model.LengthUnit;
import org.openpnp.model.Location;
import org.openpnp.spi.Camera;
import org.openpnp.spi.Head;
import org.openpnp.spi.Machine;
import org.openpnp.spi.MachineListener;
import org.openpnp.spi.Nozzle;
import org.openpnp.spi.PasteDispenser;
import org.openpnp.util.MovableUtils;
import com.google.common.util.concurrent.FutureCallback;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.RowSpec;
public class MachineControlsPanel extends JPanel {
private final JFrame frame;
private final CameraPanel cameraPanel;
private final Configuration configuration;
private Nozzle selectedNozzle;
private JTextField textFieldX;
private JTextField textFieldY;
private JTextField textFieldC;
private JTextField textFieldZ;
private JButton btnStartStop;
private JSlider sliderIncrements;
private JComboBox comboBoxNozzles;
private Color startColor = Color.green;
private Color stopColor = new Color(178, 34, 34);
private Color droNormalColor = new Color(0xBDFFBE);
private Color droEditingColor = new Color(0xF0F0A1);
private Color droWarningColor = new Color(0xFF5C5C);
private Color droSavedColor = new Color(0x90cce0);
private JogControlsPanel jogControlsPanel;
private JDialog jogControlsWindow;
private volatile double savedX = Double.NaN, savedY = Double.NaN, savedZ = Double.NaN, savedC = Double.NaN;
/**
* Create the panel.
*/
public MachineControlsPanel(Configuration configuration, JFrame frame, CameraPanel cameraPanel) {
this.frame = frame;
this.cameraPanel = cameraPanel;
this.configuration = configuration;
jogControlsPanel = new JogControlsPanel(configuration, this, frame);
createUi();
configuration.addListener(configurationListener);
jogControlsWindow = new JDialog(frame, "Jog Controls");
jogControlsWindow.setResizable(false);
jogControlsWindow.getContentPane().setLayout(new BorderLayout());
jogControlsWindow.getContentPane().add(jogControlsPanel);
}
/**
* @deprecated See {@link Machine#submit(Runnable)}
* @param runnable
*/
public void submitMachineTask(Runnable runnable) {
if (!Configuration.get().getMachine().isEnabled()) {
MessageBoxes.errorBox(getTopLevelAncestor(), "Machine Error", "Machine is not started.");
return;
}
Configuration.get().getMachine().submit(runnable);
}
public void setSelectedNozzle(Nozzle nozzle) {
selectedNozzle = nozzle;
comboBoxNozzles.setSelectedItem(selectedNozzle);
updateDros();
}
public Nozzle getSelectedNozzle() {
return selectedNozzle;
}
public PasteDispenser getSelectedPasteDispenser() {
try {
// TODO: We don't actually have a way to select a dispenser yet, so
// until we do we just return the first one.
return Configuration.get().getMachine().getHeads().get(0).getPasteDispensers().get(0);
}
catch (Exception e) {
return null;
}
}
public JogControlsPanel getJogControlsPanel() {
return jogControlsPanel;
}
private void setUnits(LengthUnit units) {
if (units == LengthUnit.Millimeters) {
Hashtable<Integer, JLabel> incrementsLabels = new Hashtable<Integer, JLabel>();
incrementsLabels.put(1, new JLabel("0.01"));
incrementsLabels.put(2, new JLabel("0.1"));
incrementsLabels.put(3, new JLabel("1.0"));
incrementsLabels.put(4, new JLabel("10"));
incrementsLabels.put(5, new JLabel("100"));
sliderIncrements.setLabelTable(incrementsLabels);
}
else if (units == LengthUnit.Inches) {
Hashtable<Integer, JLabel> incrementsLabels = new Hashtable<Integer, JLabel>();
incrementsLabels.put(1, new JLabel("0.001"));
incrementsLabels.put(2, new JLabel("0.01"));
incrementsLabels.put(3, new JLabel("0.1"));
incrementsLabels.put(4, new JLabel("1.0"));
incrementsLabels.put(5, new JLabel("10.0"));
sliderIncrements.setLabelTable(incrementsLabels);
}
else {
throw new Error("setUnits() not implemented for " + units);
}
updateDros();
}
public double getJogIncrement() {
if (configuration.getSystemUnits() == LengthUnit.Millimeters) {
return 0.01 * Math.pow(10, sliderIncrements.getValue() - 1);
}
else if (configuration.getSystemUnits() == LengthUnit.Inches) {
return 0.001 * Math.pow(10, sliderIncrements.getValue() - 1);
}
else {
throw new Error("getJogIncrement() not implemented for " + configuration.getSystemUnits());
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
homeAction.setEnabled(enabled);
goToZeroAction.setEnabled(enabled);
jogControlsPanel.setEnabled(enabled);
targetCameraAction.setEnabled(enabled);
targetToolAction.setEnabled(enabled);
}
public Location getCurrentLocation() {
if (selectedNozzle == null) {
return null;
}
Location l = selectedNozzle.getLocation();
l = l.convertToUnits(configuration.getSystemUnits());
return l;
}
public void updateDros() {
Location l = getCurrentLocation();
if (l == null) {
return;
}
double x, y, z, c;
x = l.getX();
y = l.getY();
z = l.getZ();
c = l.getRotation();
double savedX = this.savedX;
if (!Double.isNaN(savedX)) {
x -= savedX;
}
double savedY = this.savedY;
if (!Double.isNaN(savedY)) {
y -= savedY;
}
double savedZ = this.savedZ;
if (!Double.isNaN(savedZ)) {
z -= savedZ;
}
double savedC = this.savedC;
if (!Double.isNaN(savedC)) {
c -= savedC;
}
textFieldX.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), x));
textFieldY.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), y));
textFieldZ.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), z));
textFieldC.setText(String.format(Locale.US,configuration.getLengthDisplayFormat(), c));
}
private void createUi() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
ButtonGroup buttonGroup = new ButtonGroup();
JPanel panel = new JPanel();
add(panel);
panel.setLayout(new FormLayout(new ColumnSpec[] {
FormSpecs.RELATED_GAP_COLSPEC,
ColumnSpec.decode("default:grow"),},
new RowSpec[] {
FormSpecs.RELATED_GAP_ROWSPEC,
FormSpecs.DEFAULT_ROWSPEC,}));
comboBoxNozzles = new JComboBox();
comboBoxNozzles.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setSelectedNozzle(((NozzleItem) comboBoxNozzles.getSelectedItem()).getNozzle());
}
});
panel.add(comboBoxNozzles, "2, 2, fill, default");
JPanel panelDrosParent = new JPanel();
add(panelDrosParent);
panelDrosParent.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JPanel panelDros = new JPanel();
panelDrosParent.add(panelDros);
panelDros.setLayout(new BoxLayout(panelDros, BoxLayout.Y_AXIS));
JPanel panelDrosFirstLine = new JPanel();
panelDros.add(panelDrosFirstLine);
panelDrosFirstLine.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblX = new JLabel("X");
lblX.setFont(new Font("Lucida Grande", Font.BOLD, 24));
panelDrosFirstLine.add(lblX);
textFieldX = new JTextField();
textFieldX.setEditable(false);
textFieldX.setFocusTraversalKeysEnabled(false);
textFieldX.setSelectionColor(droEditingColor);
textFieldX.setDisabledTextColor(Color.BLACK);
textFieldX.setBackground(droNormalColor);
textFieldX.setFont(new Font("Lucida Grande", Font.BOLD, 24));
textFieldX.setText("0000.0000");
textFieldX.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
savedX = Double.NaN;
}
saveXAction.actionPerformed(null);
}
});
panelDrosFirstLine.add(textFieldX);
textFieldX.setColumns(6);
Component horizontalStrut = Box.createHorizontalStrut(15);
panelDrosFirstLine.add(horizontalStrut);
JLabel lblY = new JLabel("Y");
lblY.setFont(new Font("Lucida Grande", Font.BOLD, 24));
panelDrosFirstLine.add(lblY);
textFieldY = new JTextField();
textFieldY.setEditable(false);
textFieldY.setFocusTraversalKeysEnabled(false);
textFieldY.setSelectionColor(droEditingColor);
textFieldY.setDisabledTextColor(Color.BLACK);
textFieldY.setBackground(droNormalColor);
textFieldY.setFont(new Font("Lucida Grande", Font.BOLD, 24));
textFieldY.setText("0000.0000");
textFieldY.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
savedY = Double.NaN;
}
saveYAction.actionPerformed(null);
}
});
panelDrosFirstLine.add(textFieldY);
textFieldY.setColumns(6);
JButton btnTargetTool = new JButton(targetToolAction);
panelDrosFirstLine.add(btnTargetTool);
btnTargetTool.setToolTipText("Position the tool at the camera's current location.");
JPanel panelDrosSecondLine = new JPanel();
panelDros.add(panelDrosSecondLine);
panelDrosSecondLine.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblC = new JLabel("C");
lblC.setFont(new Font("Lucida Grande", Font.BOLD, 24));
panelDrosSecondLine.add(lblC);
textFieldC = new JTextField();
textFieldC.setEditable(false);
textFieldC.setFocusTraversalKeysEnabled(false);
textFieldC.setSelectionColor(droEditingColor);
textFieldC.setDisabledTextColor(Color.BLACK);
textFieldC.setBackground(droNormalColor);
textFieldC.setText("0000.0000");
textFieldC.setFont(new Font("Lucida Grande", Font.BOLD, 24));
textFieldC.setColumns(6);
textFieldC.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
savedC = Double.NaN;
}
saveCAction.actionPerformed(null);
}
});
panelDrosSecondLine.add(textFieldC);
Component horizontalStrut_1 = Box.createHorizontalStrut(15);
panelDrosSecondLine.add(horizontalStrut_1);
JLabel lblZ = new JLabel("Z");
lblZ.setFont(new Font("Lucida Grande", Font.BOLD, 24));
panelDrosSecondLine.add(lblZ);
textFieldZ = new JTextField();
textFieldZ.setEditable(false);
textFieldZ.setFocusTraversalKeysEnabled(false);
textFieldZ.setSelectionColor(droEditingColor);
textFieldZ.setDisabledTextColor(Color.BLACK);
textFieldZ.setBackground(droNormalColor);
textFieldZ.setText("0000.0000");
textFieldZ.setFont(new Font("Lucida Grande", Font.BOLD, 24));
textFieldZ.setColumns(6);
textFieldZ.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
savedZ = Double.NaN;
}
saveZAction.actionPerformed(null);
}
});
panelDrosSecondLine.add(textFieldZ);
JButton btnTargetCamera = new JButton(targetCameraAction);
panelDrosSecondLine.add(btnTargetCamera);
btnTargetCamera.setToolTipText("Position the camera at the tool's current location.");
JPanel panelIncrements = new JPanel();
add(panelIncrements);
sliderIncrements = new JSlider();
panelIncrements.add(sliderIncrements);
sliderIncrements.setMajorTickSpacing(1);
sliderIncrements.setValue(1);
sliderIncrements.setSnapToTicks(true);
sliderIncrements.setPaintLabels(true);
sliderIncrements.setPaintTicks(true);
sliderIncrements.setMinimum(1);
sliderIncrements.setMaximum(5);
JPanel panelStartStop = new JPanel();
add(panelStartStop);
panelStartStop.setLayout(new BorderLayout(0, 0));
btnStartStop = new JButton(startMachineAction);
btnStartStop.setFocusable(true);
btnStartStop.setForeground(startColor);
panelStartStop.add(btnStartStop);
btnStartStop.setFont(new Font("Lucida Grande", Font.BOLD, 48));
btnStartStop.setPreferredSize(new Dimension(160, 70));
setFocusTraversalPolicy(focusPolicy);
setFocusTraversalPolicyProvider(true);
}
private FocusTraversalPolicy focusPolicy = new FocusTraversalPolicy() {
@Override
public Component getComponentAfter(Container aContainer,
Component aComponent) {
return sliderIncrements;
}
@Override
public Component getComponentBefore(Container aContainer,
Component aComponent) {
return sliderIncrements;
}
@Override
public Component getDefaultComponent(Container aContainer) {
return sliderIncrements;
}
@Override
public Component getFirstComponent(Container aContainer) {
return sliderIncrements;
}
@Override
public Component getInitialComponent(Window window) {
return sliderIncrements;
}
@Override
public Component getLastComponent(Container aContainer) {
return sliderIncrements;
}
};
@SuppressWarnings("serial")
private Action stopMachineAction = new AbstractAction("STOP") {
@Override
public void actionPerformed(ActionEvent arg0) {
setEnabled(false);
Configuration.get().getMachine().submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
Configuration.get().getMachine().setEnabled(false);
return null;
}
}, new FutureCallback<Void>() {
@Override
public void onSuccess(Void result) {
setEnabled(true);
}
@Override
public void onFailure(Throwable t) {
MessageBoxes.errorBox(MachineControlsPanel.this, "Stop Failed", t.getMessage());
setEnabled(true);
}
}, true);
}
};
@SuppressWarnings("serial")
private Action startMachineAction = new AbstractAction("START") {
@Override
public void actionPerformed(ActionEvent arg0) {
setEnabled(false);
Configuration.get().getMachine().submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
Configuration.get().getMachine().setEnabled(true);
return null;
}
}, new FutureCallback<Void>() {
@Override
public void onSuccess(Void result) {
setEnabled(true);
}
@Override
public void onFailure(Throwable t) {
MessageBoxes.errorBox(MachineControlsPanel.this, "Start Failed", t.getMessage());
setEnabled(true);
}
}, true);
}
};
@SuppressWarnings("serial")
public Action goToZeroAction = new AbstractAction("Go To Zero") {
@Override
public void actionPerformed(ActionEvent arg0) {
submitMachineTask(new Runnable() {
public void run() {
try {
selectedNozzle.moveToSafeZ(1.0);
// Move to 0, 0, 0, 0.
selectedNozzle.moveTo(new Location(LengthUnit.Millimeters, 0, 0, 0, 0), 1.0);
}
catch (Exception e) {
e.printStackTrace();
MessageBoxes.errorBox(frame, "Go To Zero Failed", e);
}
}
});
}
};
@SuppressWarnings("serial")
public Action homeAction = new AbstractAction("Home") {
@Override
public void actionPerformed(ActionEvent arg0) {
submitMachineTask(new Runnable() {
public void run() {
try {
selectedNozzle.getHead().home();
}
catch (Exception e) {
e.printStackTrace();
MessageBoxes.errorBox(frame, "Homing Failed", e);
}
}
});
}
};
public Action showHideJogControlsWindowAction = new AbstractAction("Show Jog Controls") {
@Override
public void actionPerformed(ActionEvent arg0) {
if (jogControlsWindow.isVisible()) {
// Hide
jogControlsWindow.setVisible(false);
putValue(AbstractAction.NAME, "Show Jog Controls");
}
else {
// Show
jogControlsWindow.setVisible(true);
jogControlsWindow.pack();
int x = (int) getLocationOnScreen().getX();
int y = (int) getLocationOnScreen().getY();
x += (getSize().getWidth() / 2) - (jogControlsWindow.getSize().getWidth() / 2);
y += getSize().getHeight();
jogControlsWindow.setLocation(x, y);
putValue(AbstractAction.NAME, "Hide Jog Controls");
}
}
};
@SuppressWarnings("serial")
public Action raiseIncrementAction = new AbstractAction("Raise Jog Increment") {
@Override
public void actionPerformed(ActionEvent arg0) {
sliderIncrements.setValue(Math.min(sliderIncrements.getMaximum(), sliderIncrements.getValue() + 1));
}
};
@SuppressWarnings("serial")
public Action lowerIncrementAction = new AbstractAction("Lower Jog Increment") {
@Override
public void actionPerformed(ActionEvent arg0) {
sliderIncrements.setValue(Math.max(sliderIncrements.getMinimum(), sliderIncrements.getValue() - 1));
}
};
@SuppressWarnings("serial")
public Action targetToolAction = new AbstractAction(null, Icons.centerTool) {
@Override
public void actionPerformed(ActionEvent arg0) {
final Location location = cameraPanel.getSelectedCameraLocation();
final Nozzle nozzle = getSelectedNozzle();
submitMachineTask(new Runnable() {
public void run() {
try {
MovableUtils.moveToLocationAtSafeZ(nozzle, location, 1.0);
}
catch (Exception e) {
MessageBoxes.errorBox(frame, "Move Failed", e);
}
}
});
}
};
@SuppressWarnings("serial")
public Action targetCameraAction = new AbstractAction(null, Icons.centerCamera) {
@Override
public void actionPerformed(ActionEvent arg0) {
final Camera camera = cameraPanel.getSelectedCamera();
if (camera == null) {
return;
}
final Location location = getSelectedNozzle().getLocation();
submitMachineTask(new Runnable() {
public void run() {
try {
MovableUtils.moveToLocationAtSafeZ(camera, location, 1.0);
}
catch (Exception e) {
MessageBoxes.errorBox(frame, "Move Failed", e);
}
}
});
}
};
@SuppressWarnings("serial")
public Action saveXAction = new AbstractAction(null) {
@Override
public void actionPerformed(ActionEvent arg0) {
if (Double.isNaN(savedX)) {
textFieldX.setBackground(droSavedColor);
savedX = getCurrentLocation().getX();
}
else {
textFieldX.setBackground(droNormalColor);
savedX = Double.NaN;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
};
@SuppressWarnings("serial")
public Action saveYAction = new AbstractAction(null) {
@Override
public void actionPerformed(ActionEvent arg0) {
if (Double.isNaN(savedY)) {
textFieldY.setBackground(droSavedColor);
savedY = getCurrentLocation().getY();
}
else {
textFieldY.setBackground(droNormalColor);
savedY = Double.NaN;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
};
@SuppressWarnings("serial")
public Action saveZAction = new AbstractAction(null) {
@Override
public void actionPerformed(ActionEvent arg0) {
if (Double.isNaN(savedZ)) {
textFieldZ.setBackground(droSavedColor);
savedZ = getCurrentLocation().getZ();
}
else {
textFieldZ.setBackground(droNormalColor);
savedZ = Double.NaN;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
};
@SuppressWarnings("serial")
public Action saveCAction = new AbstractAction(null) {
@Override
public void actionPerformed(ActionEvent arg0) {
if (Double.isNaN(savedC)) {
textFieldC.setBackground(droSavedColor);
savedC = getCurrentLocation().getRotation();
}
else {
textFieldC.setBackground(droNormalColor);
savedC = Double.NaN;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
};
private MachineListener machineListener = new MachineListener.Adapter() {
@Override
public void machineHeadActivity(Machine machine, Head head) {
EventQueue.invokeLater(new Runnable() {
public void run() {
updateDros();
}
});
}
@Override
public void machineEnabled(Machine machine) {
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
setEnabled(true);
}
@Override
public void machineEnableFailed(Machine machine, String reason) {
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
}
@Override
public void machineDisabled(Machine machine, String reason) {
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
setEnabled(false);
}
@Override
public void machineDisableFailed(Machine machine, String reason) {
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
}
};
private ConfigurationListener configurationListener = new ConfigurationListener.Adapter() {
@Override
public void configurationComplete(Configuration configuration) {
Machine machine = configuration.getMachine();
if (machine != null) {
machine.removeListener(machineListener);
}
for (Head head : machine.getHeads()) {
for (Nozzle nozzle : head.getNozzles()) {
comboBoxNozzles.addItem(new NozzleItem(nozzle));
}
}
setSelectedNozzle(((NozzleItem) comboBoxNozzles.getItemAt(0)).getNozzle());
setUnits(configuration.getSystemUnits());
machine.addListener(machineListener);
btnStartStop.setAction(machine.isEnabled() ? stopMachineAction : startMachineAction);
btnStartStop.setForeground(machine.isEnabled() ? stopColor : startColor);
setEnabled(machine.isEnabled());
}
};
}
| TinWhiskers/openpnp | src/main/java/org/openpnp/gui/MachineControlsPanel.java | Java | gpl-3.0 | 25,064 |
(function() {
'use strict';
angular
.module('weatheropendataApp')
.config(stateConfig);
stateConfig.$inject = ['$stateProvider'];
function stateConfig($stateProvider) {
$stateProvider.state('register', {
parent: 'account',
url: '/register',
data: {
authorities: [],
pageTitle: 'register.title'
},
views: {
'content@': {
templateUrl: 'app/account/register/register.html',
controller: 'RegisterController',
controllerAs: 'vm'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('register');
return $translate.refresh();
}]
}
});
}
})();
| hackathinho/open-clean-energy | backend-weather/src/main/webapp/app/account/register/register.state.js | JavaScript | gpl-3.0 | 993 |
/*
* MindmapsDB - A Distributed Semantic Database
* Copyright (C) 2016 Mindmaps Research Ltd
*
* MindmapsDB 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.
*
* MindmapsDB 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 MindmapsDB. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package io.mindmaps.graql;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import io.mindmaps.MindmapsTransaction;
import io.mindmaps.core.model.Concept;
import io.mindmaps.graql.internal.parser.GraqlLexer;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.Token;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* An autocomplete result suggesting keywords, types and variables that the user may wish to type
*/
public class Autocomplete {
private final ImmutableSet<String> candidates;
private final int cursorPosition;
/**
* @param transaction the transaction to find types in
* @param query the query to autocomplete
* @param cursorPosition the cursor position in the query
* @return an autocomplete object containing potential candidates and cursor position to autocomplete from
*/
public static Autocomplete create(MindmapsTransaction transaction, String query, int cursorPosition) {
return new Autocomplete(transaction, query, cursorPosition);
}
/**
* @return all candidate autocomplete words
*/
public Set<String> getCandidates() {
return candidates;
}
/**
* @return the cursor position that autocompletions should start from
*/
public int getCursorPosition() {
return cursorPosition;
}
/**
* @param transaction the transaction to find types in
* @param query the query to autocomplete
* @param cursorPosition the cursor position in the query
*/
private Autocomplete(MindmapsTransaction transaction, String query, int cursorPosition) {
Optional<? extends Token> optToken = getCursorToken(query, cursorPosition);
candidates = ImmutableSet.copyOf(findCandidates(transaction, query, optToken));
this.cursorPosition = findCursorPosition(cursorPosition, optToken);
}
/**
* @param transaction the transaction to find types in
* @param query a graql query
* @param optToken the token the cursor is on in the query
* @return a set of potential autocomplete words
*/
private static Set<String> findCandidates(MindmapsTransaction transaction, String query, Optional<? extends Token> optToken) {
Set<String> allCandidates = Stream.of(getKeywords(), getTypes(transaction), getVariables(query))
.flatMap(Function.identity()).collect(Collectors.toSet());
return optToken.map(
token -> {
Set<String> candidates = allCandidates.stream()
.filter(candidate -> candidate.startsWith(token.getText()))
.collect(Collectors.toSet());
if (candidates.size() == 1 && candidates.iterator().next().equals(token.getText())) {
return Sets.newHashSet(" ");
} else {
return candidates;
}
}
).orElse(allCandidates);
}
/**
* @param cursorPosition the current cursor position
* @param optToken the token the cursor is on in the query
* @return the new cursor position to start autocompleting from
*/
private int findCursorPosition(int cursorPosition, Optional<? extends Token> optToken) {
return optToken
.filter(token -> !candidates.contains(" "))
.map(Token::getStartIndex)
.orElse(cursorPosition);
}
/**
* @return all Graql keywords
*/
private static Stream<String> getKeywords() {
HashSet<String> keywords = new HashSet<>();
for (int i = 1; GraqlLexer.VOCABULARY.getLiteralName(i) != null; i ++) {
String name = GraqlLexer.VOCABULARY.getLiteralName(i);
keywords.add(name.replaceAll("'", ""));
}
return keywords.stream();
}
/**
* @param transaction the transaction to find types in
* @return all type IDs in the ontology
*/
private static Stream<String> getTypes(MindmapsTransaction transaction) {
return transaction.getMetaType().instances().stream().map(Concept::getId);
}
/**
* @param query a graql query
* @return all variable names occurring in the query
*/
private static Stream<String> getVariables(String query) {
List<? extends Token> allTokens = getTokens(query);
if (allTokens.size() > 0) allTokens.remove(allTokens.size() - 1);
return allTokens.stream()
.filter(t -> t.getType() == GraqlLexer.VARIABLE)
.map(Token::getText);
}
/**
* @param query a graql query
* @param cursorPosition the cursor position in the query
* @return the token at the cursor position in the given graql query
*/
private static Optional<? extends Token> getCursorToken(String query, int cursorPosition) {
if (query == null) return Optional.empty();
return getTokens(query).stream()
.filter(t -> t.getStartIndex() <= cursorPosition && t.getStopIndex() >= cursorPosition - 1)
.findFirst();
}
/**
* @param query a graql query
* @return a list of tokens from running the lexer on the query
*/
private static List<? extends Token> getTokens(String query) {
ANTLRInputStream input = new ANTLRInputStream(query);
GraqlLexer lexer = new GraqlLexer(input);
// Ignore syntax errors
lexer.removeErrorListeners();
lexer.addErrorListener(new BaseErrorListener());
return lexer.getAllTokens();
}
}
| duckofyork/mindmapsdb | mindmaps-graql/src/main/java/io/mindmaps/graql/Autocomplete.java | Java | gpl-3.0 | 6,589 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Camel : GamePiece {
public override List<GridCell>GetMovementCells(GameGrid grid, GridCell cell)
{
return grid.GetLeapCells(cell, 3, 1);
}
public override List<GridCell>GetAttackCells(GameGrid grid, GridCell cell)
{
return GetMovementCells(grid, cell);
}
}
| matthewvroman/single-player-chess | Assets/Scripts/GamePieces/Camel.cs | C# | gpl-3.0 | 365 |
package org.betonquest.betonquest.objectives;
import lombok.CustomLog;
import org.betonquest.betonquest.BetonQuest;
import org.betonquest.betonquest.Instruction;
import org.betonquest.betonquest.api.Condition;
import org.betonquest.betonquest.api.Objective;
import org.betonquest.betonquest.api.QuestEvent;
import org.betonquest.betonquest.conditions.ChestItemCondition;
import org.betonquest.betonquest.events.ChestTakeEvent;
import org.betonquest.betonquest.exceptions.InstructionParseException;
import org.betonquest.betonquest.exceptions.ObjectNotFoundException;
import org.betonquest.betonquest.exceptions.QuestRuntimeException;
import org.betonquest.betonquest.id.NoID;
import org.betonquest.betonquest.utils.PlayerConverter;
import org.betonquest.betonquest.utils.location.CompoundLocation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.InventoryHolder;
/**
* Requires the player to put items in the chest. Items can optionally NOT
* disappear once the chest is closed.
*/
@SuppressWarnings("PMD.CommentRequired")
@CustomLog
public class ChestPutObjective extends Objective implements Listener {
private final Condition chestItemCondition;
private final QuestEvent chestTakeEvent;
private final CompoundLocation loc;
public ChestPutObjective(final Instruction instruction) throws InstructionParseException {
super(instruction);
template = ObjectiveData.class;
// extract location
loc = instruction.getLocation();
final String location = instruction.current();
final String items = instruction.next();
try {
chestItemCondition = new ChestItemCondition(new Instruction(instruction.getPackage(), new NoID(instruction.getPackage()), "chestitem " + location + " " + items));
} catch (InstructionParseException | ObjectNotFoundException e) {
throw new InstructionParseException("Could not create inner chest item condition: " + e.getMessage(), e);
}
if (instruction.hasArgument("items-stay")) {
chestTakeEvent = null;
} else {
try {
chestTakeEvent = new ChestTakeEvent(new Instruction(instruction.getPackage(), new NoID(instruction.getPackage()), "chesttake " + location + " " + items));
} catch (final ObjectNotFoundException e) {
throw new InstructionParseException("Could not create inner chest take event: " + e.getMessage(), e);
}
}
}
@SuppressWarnings("PMD.CyclomaticComplexity")
@EventHandler(ignoreCancelled = true)
public void onChestClose(final InventoryCloseEvent event) {
if (!(event.getPlayer() instanceof Player)) {
return;
}
final String playerID = PlayerConverter.getID((Player) event.getPlayer());
if (!containsPlayer(playerID)) {
return;
}
try {
final Location targetChestLocation = loc.getLocation(playerID);
final Block block = targetChestLocation.getBlock();
if (!(block.getState() instanceof InventoryHolder)) {
final World world = targetChestLocation.getWorld();
LOG.warn(instruction.getPackage(),
String.format("Error in '%s' chestput objective: Block at location x:%d y:%d z:%d in world '%s' isn't a chest!",
instruction.getID().getFullID(),
targetChestLocation.getBlockX(),
targetChestLocation.getBlockY(),
targetChestLocation.getBlockZ(),
world == null ? "null" : world.getName()));
return;
}
final InventoryHolder chest = (InventoryHolder) block.getState();
if (!chest.equals(event.getInventory().getHolder())) {
return;
}
if (chestItemCondition.handle(playerID) && checkConditions(playerID)) {
completeObjective(playerID);
if (chestTakeEvent != null) {
chestTakeEvent.handle(playerID);
}
}
} catch (final QuestRuntimeException e) {
LOG.warn(instruction.getPackage(), "Error while handling '" + instruction.getID() + "' objective: " + e.getMessage(), e);
}
}
@Override
public void start() {
Bukkit.getPluginManager().registerEvents(this, BetonQuest.getInstance());
}
@Override
public void stop() {
HandlerList.unregisterAll(this);
}
@Override
public String getDefaultDataInstruction() {
return "";
}
@Override
public String getProperty(final String name, final String playerID) {
return "";
}
}
| Co0sh/BetonQuest | src/main/java/org/betonquest/betonquest/objectives/ChestPutObjective.java | Java | gpl-3.0 | 5,067 |
/************************************************************************
* Virtual Whiteboard System Based on Image Processing
* Main file
*
* Author: Alankar Kotwal <alankarkotwal13@gmail.com>
************************************************************************/
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <sstream>
#include <string>
#include "path.hpp"
using namespace cv;
int main() {
std::stringstream configPath;
configPath<<REPO_ROOT<<"/config/config.xml";
boost::property_tree::ptree config;
boost::property_tree::read_xml(configPath.str(), config);
VideoCapture cap(config.get<int>("whiteboard.capture.captureNo"));
Mat frame;
cap >> frame;
Mat draw = Mat::zeros(frame.rows, frame.cols, CV_8UC3);
namedWindow("Drawing", WINDOW_AUTOSIZE);
Moments mom;
Point cen, oldCen;
int xC, yC;
bool first=1;
char key;
while(1) {
boost::property_tree::read_xml(configPath.str(), config);
cap >> frame;
Mat channels[3];
split(frame, channels);
Mat red = channels[2]; // OpenCV follows BGR
threshold(red, red, config.get<int>("whiteboard.imgproc.threshold"), config.get<int>("whiteboard.imgproc.maxVal"), THRESH_BINARY);
mom = moments(red, true);
xC = mom.m10 / mom.m00;
yC = mom.m01 / mom.m00;
Scalar color(config.get<int>("whiteboard.rendering.b"), config.get<int>("whiteboard.rendering.g"), config.get<int>("whiteboard.rendering.r"));
if(mom.m00 > config.get<int>("whiteboard.imgproc.minPixelNo")) {
oldCen.x = cen.x;
oldCen.y = cen.y;
cen.x = xC;
cen.y = yC;
if(config.get<string>("whiteboard.rendering.mode") == "circles") {
circle(draw, cen, config.get<int>("whiteboard.rendering.lineWidth"), color, 0, 8, 0);
}
else if(config.get<string>("whiteboard.rendering.mode") == "lines" && first == 0) {
line(draw, oldCen, cen, color, config.get<int>("whiteboard.rendering.lineWidth"), 8, 0);
}
first = 0;
}
else {
first = 1;
}
imshow("Drawing", draw);
key = waitKey(1);
if(key == 'r') {
draw = Mat::zeros(frame.rows, frame.cols, CV_8UC3);
}
}
return 0;
}
| alankarkotwal/lvp-whiteboard | code/opencv/Whiteboard.cpp | C++ | gpl-3.0 | 2,252 |
/**
* File ./src/main/java/de/lemo/dms/db/mapping/CourseAssignmentMining.java
* Lemo-Data-Management-Server for learning analytics.
* Copyright (C) 2013
* Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff
*
* 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
* 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/>.
**/
/**
* File ./main/java/de/lemo/dms/db/mapping/CourseAssignmentMining.java
* Date 2013-01-24
* Project Lemo Learning Analytics
*/
package de.lemo.dms.db.mapping;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import de.lemo.dms.db.mapping.abstractions.ICourseLORelation;
import de.lemo.dms.db.mapping.abstractions.ICourseRatedObjectAssociation;
import de.lemo.dms.db.mapping.abstractions.ILearningObject;
import de.lemo.dms.db.mapping.abstractions.IMappingClass;
import de.lemo.dms.db.mapping.abstractions.IRatedObject;
/**
* This class represents the relationship between the courses and assignments.
* @author Sebastian Schwarzrock
*/
@Entity
@Table(name = "course_assignment")
public class CourseAssignmentMining implements ICourseLORelation, IMappingClass, ICourseRatedObjectAssociation {
private long id;
private CourseMining course;
private AssignmentMining assignment;
private Long platform;
@Override
public boolean equals(final IMappingClass o)
{
if (!(o instanceof CourseAssignmentMining)) {
return false;
}
if ((o.getId() == this.getId()) && (o instanceof CourseAssignmentMining)) {
return true;
}
return false;
}
@Override
public int hashCode() {
return (int) id;
}
/**
* standard getter for the attribut course
*
* @return a course in which the quiz is used
*/
@Override
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="course_id")
public CourseMining getCourse() {
return this.course;
}
/**
* standard setter for the attribut course
*
* @param course
* a course in which the quiz is used
*/
public void setCourse(final CourseMining course) {
this.course = course;
}
/**
* parameterized setter for the attribut course
*
* @param course
* the id of a course in which the quiz is used
* @param courseMining
* a list of new added courses, which is searched for the course with the id submitted in the course
* parameter
* @param oldCourseMining
* a list of course in the miningdatabase, which is searched for the course with the id submitted in the
* course parameter
*/
public void setCourse(final long course, final Map<Long, CourseMining> courseMining,
final Map<Long, CourseMining> oldCourseMining) {
if (courseMining.get(course) != null)
{
this.course = courseMining.get(course);
courseMining.get(course).addCourseAssignment(this);
}
if ((this.course == null) && (oldCourseMining.get(course) != null))
{
this.course = oldCourseMining.get(course);
oldCourseMining.get(course).addCourseAssignment(this);
}
}
/**
* standard getter for the attribut assignment
*
* @return the quiz which is used in the course
*/
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="assignment_id")
public AssignmentMining getAssignment() {
return this.assignment;
}
/**
* standard setter for the attribut assignment
*
* @param assignment
* the assignment which is used in the course
*/
public void setAssignment(final AssignmentMining assignment) {
this.assignment = assignment;
}
/**
* parameterized setter for the attribut assignment
*
* @param id
* the id of the quiz in which the action takes place
* @param assignmentMining
* a list of new added quiz, which is searched for the quiz with the qid and qtype submitted in the other
* parameters
* @param oldAssignmentMining
* a list of quiz in the miningdatabase, which is searched for the quiz with the qid and qtype submitted
* in the other parameters
*/
public void setAssignment(final long assignment, final Map<Long, AssignmentMining> assignmentMining,
final Map<Long, AssignmentMining> oldAssignmentMining) {
if (assignmentMining.get(assignment) != null)
{
this.assignment = assignmentMining.get(assignment);
assignmentMining.get(assignment).addCourseAssignment(this);
}
if ((this.assignment == null) && (oldAssignmentMining.get(assignment) != null))
{
this.assignment = oldAssignmentMining.get(assignment);
oldAssignmentMining.get(assignment).addCourseAssignment(this);
}
}
/**
* standard setter for the attribut id
*
* @param id
* the identifier for the assoziation between course and assignment
*/
public void setId(final long id) {
this.id = id;
}
/**
* standard getter for the attribut id
*
* @return the identifier for the assoziation between course and assignment
*/
@Override
@Id
public long getId() {
return this.id;
}
@Column(name="platform")
public Long getPlatform() {
return this.platform;
}
public void setPlatform(final Long platform) {
this.platform = platform;
}
@Override
@Transient
public IRatedObject getRatedObject() {
return this.assignment;
}
@Override
@Transient
public Long getPrefix() {
return this.assignment.getPrefix();
}
@Override
@Transient
public ILearningObject getLearningObject() {
return this.getAssignment();
}
} | LemoProject/lemo2 | src/main/java/de/lemo/dms/db/mapping/CourseAssignmentMining.java | Java | gpl-3.0 | 6,152 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html
"""
class Countries_Tajikistan():
'''Class that manages this specific menu context.'''
def open(self, plugin, menu):
menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels",
"Events", "Live", "Movies", "Sports", "TVShows"],
countries=["Tajikistan"])) | xbmcmegapack/plugin.video.megapack.dev | resources/lib/menus/home_countries_tajikistan.py | Python | gpl-3.0 | 1,117 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Migration_modifica_coluna_hologated_null extends CI_Migration {
public function up() {
$this->dbforge->modify_column('selection_process_user_subscription', [
'homologated' => ['type' => 'tinyint(1)', 'null' => TRUE, 'default' => NULL]
]);
}
public function down() {
$this->dbforge->modify_column('selection_process_user_subscription', [
'homologated' => ['type' => 'tinyint(1)', 'null' => FALSE, 'default' => FALSE]
]);
}
} | Sistema-Integrado-Gestao-Academica/SiGA | application/migrations/162_modifica_coluna_hologated_null.php | PHP | gpl-3.0 | 581 |
/**
* initSession
*
* @module :: Policy
* @description :: make sure all session related values are properly setup
*
*/
module.exports = function(req, res, next) {
// make sure the appdev session obj is created.
req.session.appdev = req.session.appdev || ADCore.session.default();
// if this is a socket request, then initialize the socket info:
if (req.isSocket) {
ADCore.socket.init(req);
}
// ok, our session is properly setup.
next();
};
| appdevdesigns/appdev-core | api/policies/initSession.js | JavaScript | gpl-3.0 | 500 |
/*
* Copyright (C) 2013 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 android.media.cts;
import android.app.Presentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.SurfaceTexture;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaCodec;
import android.media.MediaCodec.BufferInfo;
import android.media.MediaCodecInfo;
import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCodecInfo.CodecProfileLevel;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Parcel;
import android.test.AndroidTestCase;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Size;
import android.view.Display;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.media.cts.R;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Tests to check if MediaCodec encoding works with composition of multiple virtual displays
* The test also tries to destroy and create virtual displays repeatedly to
* detect any issues. The test itself does not check the output as it is already done in other
* tests.
*/
public class EncodeVirtualDisplayWithCompositionTest extends AndroidTestCase {
private static final String TAG = "EncodeVirtualDisplayWithCompositionTest";
private static final boolean DBG = true;
private static final String MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC;
private static final long DEFAULT_WAIT_TIMEOUT_MS = 3000;
private static final long DEFAULT_WAIT_TIMEOUT_US = 3000000;
private static final int COLOR_RED = makeColor(100, 0, 0);
private static final int COLOR_BLUE = makeColor(0, 100, 0);
private static final int COLOR_GREEN = makeColor(0, 0, 100);
private static final int COLOR_GREY = makeColor(100, 100, 100);
private static final int BITRATE_1080p = 20000000;
private static final int BITRATE_720p = 14000000;
private static final int BITRATE_800x480 = 14000000;
private static final int BITRATE_DEFAULT = 10000000;
private static final int IFRAME_INTERVAL = 10;
private static final int MAX_NUM_WINDOWS = 3;
private static Handler sHandlerForRunOnMain = new Handler(Looper.getMainLooper());
private Surface mEncodingSurface;
private OutputSurface mDecodingSurface;
private volatile boolean mCodecConfigReceived = false;
private volatile boolean mCodecBufferReceived = false;
private EncodingHelper mEncodingHelper;
private MediaCodec mDecoder;
private final ByteBuffer mPixelBuf = ByteBuffer.allocateDirect(4);
private volatile boolean mIsQuitting = false;
private Throwable mTestException;
private VirtualDisplayPresentation mLocalPresentation;
private RemoteVirtualDisplayPresentation mRemotePresentation;
private ByteBuffer[] mDecoderInputBuffers;
/** event listener for test without verifying output */
private EncoderEventListener mEncoderEventListener = new EncoderEventListener() {
@Override
public void onCodecConfig(ByteBuffer data, MediaCodec.BufferInfo info) {
mCodecConfigReceived = true;
}
@Override
public void onBufferReady(ByteBuffer data, MediaCodec.BufferInfo info) {
mCodecBufferReceived = true;
}
@Override
public void onError(String errorMessage) {
fail(errorMessage);
}
};
/* TEST_COLORS static initialization; need ARGB for ColorDrawable */
private static int makeColor(int red, int green, int blue) {
return 0xff << 24 | (red & 0xff) << 16 | (green & 0xff) << 8 | (blue & 0xff);
}
public void testVirtualDisplayRecycles() throws Exception {
doTestVirtualDisplayRecycles(3);
}
public void testRendering800x480Locally() throws Throwable {
Log.i(TAG, "testRendering800x480Locally");
if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
runTestRenderingInSeparateThread(800, 480, false, false);
} else {
Log.i(TAG, "SKIPPING testRendering800x480Locally(): codec not supported");
}
}
public void testRenderingMaxResolutionLocally() throws Throwable {
Log.i(TAG, "testRenderingMaxResolutionLocally");
Size maxRes = checkMaxConcurrentEncodingDecodingResolution();
if (maxRes == null) {
Log.i(TAG, "SKIPPING testRenderingMaxResolutionLocally(): codec not supported");
} else {
Log.w(TAG, "Trying resolution " + maxRes);
runTestRenderingInSeparateThread(maxRes.getWidth(), maxRes.getHeight(), false, false);
}
}
public void testRendering800x480Remotely() throws Throwable {
Log.i(TAG, "testRendering800x480Remotely");
if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
runTestRenderingInSeparateThread(800, 480, true, false);
} else {
Log.i(TAG, "SKIPPING testRendering800x480Remotely(): codec not supported");
}
}
public void testRenderingMaxResolutionRemotely() throws Throwable {
Log.i(TAG, "testRenderingMaxResolutionRemotely");
Size maxRes = checkMaxConcurrentEncodingDecodingResolution();
if (maxRes == null) {
Log.i(TAG, "SKIPPING testRenderingMaxResolutionRemotely(): codec not supported");
} else {
Log.w(TAG, "Trying resolution " + maxRes);
runTestRenderingInSeparateThread(maxRes.getWidth(), maxRes.getHeight(), true, false);
}
}
public void testRendering800x480RemotelyWith3Windows() throws Throwable {
Log.i(TAG, "testRendering800x480RemotelyWith3Windows");
if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
runTestRenderingInSeparateThread(800, 480, true, true);
} else {
Log.i(TAG, "SKIPPING testRendering800x480RemotelyWith3Windows(): codec not supported");
}
}
public void testRendering800x480LocallyWith3Windows() throws Throwable {
Log.i(TAG, "testRendering800x480LocallyWith3Windows");
if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
runTestRenderingInSeparateThread(800, 480, false, true);
} else {
Log.i(TAG, "SKIPPING testRendering800x480LocallyWith3Windows(): codec not supported");
}
}
/**
* Run rendering test in a separate thread. This is necessary as {@link OutputSurface} requires
* constructing it in a non-test thread.
* @param w
* @param h
* @throws Exception
*/
private void runTestRenderingInSeparateThread(final int w, final int h,
final boolean runRemotely, final boolean multipleWindows) throws Throwable {
mTestException = null;
Thread renderingThread = new Thread(new Runnable() {
public void run() {
try {
doTestRenderingOutput(w, h, runRemotely, multipleWindows);
} catch (Throwable t) {
t.printStackTrace();
mTestException = t;
}
}
});
renderingThread.start();
renderingThread.join(60000);
assertTrue(!renderingThread.isAlive());
if (mTestException != null) {
throw mTestException;
}
}
private void doTestRenderingOutput(int w, int h, boolean runRemotely, boolean multipleWindows)
throws Throwable {
if (DBG) {
Log.i(TAG, "doTestRenderingOutput for w:" + w + " h:" + h);
}
try {
mIsQuitting = false;
mDecoder = MediaCodec.createDecoderByType(MIME_TYPE);
MediaFormat decoderFormat = MediaFormat.createVideoFormat(MIME_TYPE, w, h);
mDecodingSurface = new OutputSurface(w, h);
mDecoder.configure(decoderFormat, mDecodingSurface.getSurface(), null, 0);
mDecoder.start();
mDecoderInputBuffers = mDecoder.getInputBuffers();
mEncodingHelper = new EncodingHelper();
mEncodingSurface = mEncodingHelper.startEncoding(w, h,
new EncoderEventListener() {
@Override
public void onCodecConfig(ByteBuffer data, BufferInfo info) {
if (DBG) {
Log.i(TAG, "onCodecConfig l:" + info.size);
}
handleEncodedData(data, info);
}
@Override
public void onBufferReady(ByteBuffer data, BufferInfo info) {
if (DBG) {
Log.i(TAG, "onBufferReady l:" + info.size);
}
handleEncodedData(data, info);
}
@Override
public void onError(String errorMessage) {
fail(errorMessage);
}
private void handleEncodedData(ByteBuffer data, BufferInfo info) {
if (mIsQuitting) {
if (DBG) {
Log.i(TAG, "ignore data as test is quitting");
}
return;
}
int inputBufferIndex = mDecoder.dequeueInputBuffer(DEFAULT_WAIT_TIMEOUT_US);
if (inputBufferIndex < 0) {
if (DBG) {
Log.i(TAG, "dequeueInputBuffer returned:" + inputBufferIndex);
}
return;
}
assertTrue(inputBufferIndex >= 0);
ByteBuffer inputBuffer = mDecoderInputBuffers[inputBufferIndex];
inputBuffer.clear();
inputBuffer.put(data);
mDecoder.queueInputBuffer(inputBufferIndex, 0, info.size,
info.presentationTimeUs, info.flags);
}
});
GlCompositor compositor = new GlCompositor();
if (DBG) {
Log.i(TAG, "start composition");
}
compositor.startComposition(mEncodingSurface, w, h, multipleWindows ? 3 : 1);
if (DBG) {
Log.i(TAG, "create display");
}
Renderer renderer = null;
if (runRemotely) {
mRemotePresentation = new RemoteVirtualDisplayPresentation(getContext(),
compositor.getWindowSurface(multipleWindows? 1 : 0), w, h);
mRemotePresentation.connect();
mRemotePresentation.start();
renderer = mRemotePresentation;
} else {
mLocalPresentation = new VirtualDisplayPresentation(getContext(),
compositor.getWindowSurface(multipleWindows? 1 : 0), w, h);
mLocalPresentation.createVirtualDisplay();
mLocalPresentation.createPresentation();
renderer = mLocalPresentation;
}
if (DBG) {
Log.i(TAG, "start rendering and check");
}
renderColorAndCheckResult(renderer, w, h, COLOR_RED);
renderColorAndCheckResult(renderer, w, h, COLOR_BLUE);
renderColorAndCheckResult(renderer, w, h, COLOR_GREEN);
renderColorAndCheckResult(renderer, w, h, COLOR_GREY);
mIsQuitting = true;
if (runRemotely) {
mRemotePresentation.disconnect();
} else {
mLocalPresentation.dismissPresentation();
mLocalPresentation.destroyVirtualDisplay();
}
compositor.stopComposition();
} finally {
if (mEncodingHelper != null) {
mEncodingHelper.stopEncoding();
mEncodingHelper = null;
}
if (mDecoder != null) {
mDecoder.stop();
mDecoder.release();
mDecoder = null;
}
if (mDecodingSurface != null) {
mDecodingSurface.release();
mDecodingSurface = null;
}
}
}
private static final int NUM_MAX_RETRY = 120;
private static final int IMAGE_WAIT_TIMEOUT_MS = 1000;
private void renderColorAndCheckResult(Renderer renderer, int w, int h,
int color) throws Exception {
BufferInfo info = new BufferInfo();
for (int i = 0; i < NUM_MAX_RETRY; i++) {
renderer.doRendering(color);
int bufferIndex = mDecoder.dequeueOutputBuffer(info, DEFAULT_WAIT_TIMEOUT_US);
if (DBG) {
Log.i(TAG, "decoder dequeueOutputBuffer returned " + bufferIndex);
}
if (bufferIndex < 0) {
continue;
}
mDecoder.releaseOutputBuffer(bufferIndex, true);
if (mDecodingSurface.checkForNewImage(IMAGE_WAIT_TIMEOUT_MS)) {
mDecodingSurface.drawImage();
if (checkSurfaceFrameColor(w, h, color)) {
Log.i(TAG, "color " + Integer.toHexString(color) + " matched");
return;
}
} else if(DBG) {
Log.i(TAG, "no rendering yet");
}
}
fail("Color did not match");
}
private boolean checkSurfaceFrameColor(int w, int h, int color) {
// Read a pixel from the center of the surface. Might want to read from multiple points
// and average them together.
int x = w / 2;
int y = h / 2;
GLES20.glReadPixels(x, y, 1, 1, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, mPixelBuf);
int r = mPixelBuf.get(0) & 0xff;
int g = mPixelBuf.get(1) & 0xff;
int b = mPixelBuf.get(2) & 0xff;
int redExpected = (color >> 16) & 0xff;
int greenExpected = (color >> 8) & 0xff;
int blueExpected = color & 0xff;
if (approxEquals(redExpected, r) && approxEquals(greenExpected, g)
&& approxEquals(blueExpected, b)) {
return true;
}
Log.i(TAG, "expected 0x" + Integer.toHexString(color) + " got 0x"
+ Integer.toHexString(makeColor(r, g, b)));
return false;
}
/**
* Determines if two color values are approximately equal.
*/
private static boolean approxEquals(int expected, int actual) {
final int MAX_DELTA = 4;
return Math.abs(expected - actual) <= MAX_DELTA;
}
private static final int NUM_CODEC_CREATION = 5;
private static final int NUM_DISPLAY_CREATION = 10;
private static final int NUM_RENDERING = 10;
private void doTestVirtualDisplayRecycles(int numDisplays) throws Exception {
Size maxSize = getMaxSupportedEncoderSize();
if (maxSize == null) {
Log.i(TAG, "no codec found, skipping");
return;
}
VirtualDisplayPresentation[] virtualDisplays = new VirtualDisplayPresentation[numDisplays];
for (int i = 0; i < NUM_CODEC_CREATION; i++) {
mCodecConfigReceived = false;
mCodecBufferReceived = false;
if (DBG) {
Log.i(TAG, "start encoding");
}
EncodingHelper encodingHelper = new EncodingHelper();
mEncodingSurface = encodingHelper.startEncoding(maxSize.getWidth(), maxSize.getHeight(),
mEncoderEventListener);
GlCompositor compositor = new GlCompositor();
if (DBG) {
Log.i(TAG, "start composition");
}
compositor.startComposition(mEncodingSurface, maxSize.getWidth(), maxSize.getHeight(),
numDisplays);
for (int j = 0; j < NUM_DISPLAY_CREATION; j++) {
if (DBG) {
Log.i(TAG, "create display");
}
for (int k = 0; k < numDisplays; k++) {
virtualDisplays[k] =
new VirtualDisplayPresentation(getContext(),
compositor.getWindowSurface(k),
maxSize.getWidth()/numDisplays, maxSize.getHeight());
virtualDisplays[k].createVirtualDisplay();
virtualDisplays[k].createPresentation();
}
if (DBG) {
Log.i(TAG, "start rendering");
}
for (int k = 0; k < NUM_RENDERING; k++) {
for (int l = 0; l < numDisplays; l++) {
virtualDisplays[l].doRendering(COLOR_RED);
}
// do not care how many frames are actually rendered.
Thread.sleep(1);
}
for (int k = 0; k < numDisplays; k++) {
virtualDisplays[k].dismissPresentation();
virtualDisplays[k].destroyVirtualDisplay();
}
compositor.recreateWindows();
}
if (DBG) {
Log.i(TAG, "stop composition");
}
compositor.stopComposition();
if (DBG) {
Log.i(TAG, "stop encoding");
}
encodingHelper.stopEncoding();
assertTrue(mCodecConfigReceived);
assertTrue(mCodecBufferReceived);
}
}
interface EncoderEventListener {
public void onCodecConfig(ByteBuffer data, MediaCodec.BufferInfo info);
public void onBufferReady(ByteBuffer data, MediaCodec.BufferInfo info);
public void onError(String errorMessage);
}
private class EncodingHelper {
private MediaCodec mEncoder;
private volatile boolean mStopEncoding = false;
private EncoderEventListener mEventListener;
private int mW;
private int mH;
private Thread mEncodingThread;
private Surface mEncodingSurface;
private Semaphore mInitCompleted = new Semaphore(0);
Surface startEncoding(int w, int h, EncoderEventListener eventListener) {
mStopEncoding = false;
mW = w;
mH = h;
mEventListener = eventListener;
mEncodingThread = new Thread(new Runnable() {
@Override
public void run() {
try {
doEncoding();
} catch (Exception e) {
e.printStackTrace();
mEventListener.onError(e.toString());
}
}
});
mEncodingThread.start();
try {
if (DBG) {
Log.i(TAG, "wait for encoder init");
}
mInitCompleted.acquire();
if (DBG) {
Log.i(TAG, "wait for encoder done");
}
} catch (InterruptedException e) {
fail("should not happen");
}
return mEncodingSurface;
}
void stopEncoding() {
try {
mStopEncoding = true;
mEncodingThread.join();
} catch(InterruptedException e) {
// just ignore
} finally {
mEncodingThread = null;
}
}
private void doEncoding() throws Exception {
final int TIMEOUT_USEC_NORMAL = 1000000;
MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mW, mH);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
int bitRate = BITRATE_DEFAULT;
if (mW == 1920 && mH == 1080) {
bitRate = BITRATE_1080p;
} else if (mW == 1280 && mH == 720) {
bitRate = BITRATE_720p;
} else if (mW == 800 && mH == 480) {
bitRate = BITRATE_800x480;
}
format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
format.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
String codecName = null;
if ((codecName = mcl.findEncoderForFormat(format)) == null) {
throw new RuntimeException("encoder "+ MIME_TYPE + " not support : " + format.toString());
}
mEncoder = MediaCodec.createByCodecName(codecName);
mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mEncodingSurface = mEncoder.createInputSurface();
mEncoder.start();
mInitCompleted.release();
if (DBG) {
Log.i(TAG, "starting encoder");
}
try {
ByteBuffer[] encoderOutputBuffers = mEncoder.getOutputBuffers();
MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
while (!mStopEncoding) {
int index = mEncoder.dequeueOutputBuffer(info, TIMEOUT_USEC_NORMAL);
if (DBG) {
Log.i(TAG, "encoder dequeOutputBuffer returned " + index);
}
if (index >= 0) {
if ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
Log.i(TAG, "codec config data");
ByteBuffer encodedData = encoderOutputBuffers[index];
encodedData.position(info.offset);
encodedData.limit(info.offset + info.size);
mEventListener.onCodecConfig(encodedData, info);
mEncoder.releaseOutputBuffer(index, false);
} else if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
Log.i(TAG, "EOS, stopping encoding");
break;
} else {
ByteBuffer encodedData = encoderOutputBuffers[index];
encodedData.position(info.offset);
encodedData.limit(info.offset + info.size);
mEventListener.onBufferReady(encodedData, info);
mEncoder.releaseOutputBuffer(index, false);
}
} else if (index == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED){
Log.i(TAG, "output buffer changed");
encoderOutputBuffers = mEncoder.getOutputBuffers();
}
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
mEncoder.stop();
mEncoder.release();
mEncoder = null;
mEncodingSurface.release();
mEncodingSurface = null;
}
}
}
/**
* Handles composition of multiple SurfaceTexture into a single Surface
*/
private class GlCompositor implements SurfaceTexture.OnFrameAvailableListener {
private Surface mSurface;
private int mWidth;
private int mHeight;
private volatile int mNumWindows;
private GlWindow mTopWindow;
private Thread mCompositionThread;
private Semaphore mStartCompletionSemaphore;
private Semaphore mRecreationCompletionSemaphore;
private Looper mLooper;
private Handler mHandler;
private InputSurface mEglHelper;
private int mGlProgramId = 0;
private int mGluMVPMatrixHandle;
private int mGluSTMatrixHandle;
private int mGlaPositionHandle;
private int mGlaTextureHandle;
private float[] mMVPMatrix = new float[16];
private TopWindowVirtualDisplayPresentation mTopPresentation;
private static final String VERTEX_SHADER =
"uniform mat4 uMVPMatrix;\n" +
"uniform mat4 uSTMatrix;\n" +
"attribute vec4 aPosition;\n" +
"attribute vec4 aTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"void main() {\n" +
" gl_Position = uMVPMatrix * aPosition;\n" +
" vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
"}\n";
private static final String FRAGMENT_SHADER =
"#extension GL_OES_EGL_image_external : require\n" +
"precision mediump float;\n" +
"varying vec2 vTextureCoord;\n" +
"uniform samplerExternalOES sTexture;\n" +
"void main() {\n" +
" gl_FragColor = texture2D(sTexture, vTextureCoord);\n" +
"}\n";
void startComposition(Surface surface, int w, int h, int numWindows) throws Exception {
mSurface = surface;
mWidth = w;
mHeight = h;
mNumWindows = numWindows;
mCompositionThread = new Thread(new CompositionRunnable());
mStartCompletionSemaphore = new Semaphore(0);
mCompositionThread.start();
waitForStartCompletion();
}
void stopComposition() {
try {
if (mLooper != null) {
mLooper.quit();
mCompositionThread.join();
}
} catch (InterruptedException e) {
// don't care
}
mCompositionThread = null;
mSurface = null;
mStartCompletionSemaphore = null;
}
Surface getWindowSurface(int windowIndex) {
return mTopPresentation.getSurface(windowIndex);
}
void recreateWindows() throws Exception {
mRecreationCompletionSemaphore = new Semaphore(0);
Message msg = mHandler.obtainMessage(CompositionHandler.DO_RECREATE_WINDOWS);
mHandler.sendMessage(msg);
if(!mRecreationCompletionSemaphore.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS,
TimeUnit.MILLISECONDS)) {
fail("recreation timeout");
}
mTopPresentation.waitForSurfaceReady(DEFAULT_WAIT_TIMEOUT_MS);
}
@Override
public void onFrameAvailable(SurfaceTexture surface) {
if (DBG) {
Log.i(TAG, "onFrameAvailable " + surface);
}
GlWindow w = mTopWindow;
if (w != null) {
w.markTextureUpdated();
requestUpdate();
} else {
Log.w(TAG, "top window gone");
}
}
private void requestUpdate() {
Thread compositionThread = mCompositionThread;
if (compositionThread == null || !compositionThread.isAlive()) {
return;
}
Message msg = mHandler.obtainMessage(CompositionHandler.DO_RENDERING);
mHandler.sendMessage(msg);
}
private int loadShader(int shaderType, String source) throws GlException {
int shader = GLES20.glCreateShader(shaderType);
checkGlError("glCreateShader type=" + shaderType);
GLES20.glShaderSource(shader, source);
GLES20.glCompileShader(shader);
int[] compiled = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
Log.e(TAG, "Could not compile shader " + shaderType + ":");
Log.e(TAG, " " + GLES20.glGetShaderInfoLog(shader));
GLES20.glDeleteShader(shader);
shader = 0;
}
return shader;
}
private int createProgram(String vertexSource, String fragmentSource) throws GlException {
int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0) {
return 0;
}
int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0) {
return 0;
}
int program = GLES20.glCreateProgram();
checkGlError("glCreateProgram");
if (program == 0) {
Log.e(TAG, "Could not create program");
}
GLES20.glAttachShader(program, vertexShader);
checkGlError("glAttachShader");
GLES20.glAttachShader(program, pixelShader);
checkGlError("glAttachShader");
GLES20.glLinkProgram(program);
int[] linkStatus = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != GLES20.GL_TRUE) {
Log.e(TAG, "Could not link program: ");
Log.e(TAG, GLES20.glGetProgramInfoLog(program));
GLES20.glDeleteProgram(program);
program = 0;
}
return program;
}
private void initGl() throws GlException {
mEglHelper = new InputSurface(mSurface);
mEglHelper.makeCurrent();
mGlProgramId = createProgram(VERTEX_SHADER, FRAGMENT_SHADER);
mGlaPositionHandle = GLES20.glGetAttribLocation(mGlProgramId, "aPosition");
checkGlError("glGetAttribLocation aPosition");
if (mGlaPositionHandle == -1) {
throw new RuntimeException("Could not get attrib location for aPosition");
}
mGlaTextureHandle = GLES20.glGetAttribLocation(mGlProgramId, "aTextureCoord");
checkGlError("glGetAttribLocation aTextureCoord");
if (mGlaTextureHandle == -1) {
throw new RuntimeException("Could not get attrib location for aTextureCoord");
}
mGluMVPMatrixHandle = GLES20.glGetUniformLocation(mGlProgramId, "uMVPMatrix");
checkGlError("glGetUniformLocation uMVPMatrix");
if (mGluMVPMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uMVPMatrix");
}
mGluSTMatrixHandle = GLES20.glGetUniformLocation(mGlProgramId, "uSTMatrix");
checkGlError("glGetUniformLocation uSTMatrix");
if (mGluSTMatrixHandle == -1) {
throw new RuntimeException("Could not get attrib location for uSTMatrix");
}
Matrix.setIdentityM(mMVPMatrix, 0);
Log.i(TAG, "initGl w:" + mWidth + " h:" + mHeight);
GLES20.glViewport(0, 0, mWidth, mHeight);
float[] vMatrix = new float[16];
float[] projMatrix = new float[16];
// max window is from (0,0) to (mWidth - 1, mHeight - 1)
float wMid = mWidth / 2f;
float hMid = mHeight / 2f;
// look from positive z to hide windows in lower z
Matrix.setLookAtM(vMatrix, 0, wMid, hMid, 5f, wMid, hMid, 0f, 0f, 1.0f, 0.0f);
Matrix.orthoM(projMatrix, 0, -wMid, wMid, -hMid, hMid, 1, 10);
Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, vMatrix, 0);
createWindows();
}
private void createWindows() throws GlException {
mTopWindow = new GlWindow(this, 0, 0, mWidth, mHeight);
mTopWindow.init();
mTopPresentation = new TopWindowVirtualDisplayPresentation(mContext,
mTopWindow.getSurface(), mWidth, mHeight, mNumWindows);
mTopPresentation.createVirtualDisplay();
mTopPresentation.createPresentation();
((TopWindowPresentation) mTopPresentation.getPresentation()).populateWindows();
}
private void cleanupGl() {
if (mTopPresentation != null) {
mTopPresentation.dismissPresentation();
mTopPresentation.destroyVirtualDisplay();
mTopPresentation = null;
}
if (mTopWindow != null) {
mTopWindow.cleanup();
mTopWindow = null;
}
if (mEglHelper != null) {
mEglHelper.release();
mEglHelper = null;
}
}
private void doGlRendering() throws GlException {
if (DBG) {
Log.i(TAG, "doGlRendering");
}
mTopWindow.updateTexImageIfNecessary();
GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glUseProgram(mGlProgramId);
GLES20.glUniformMatrix4fv(mGluMVPMatrixHandle, 1, false, mMVPMatrix, 0);
mTopWindow.onDraw(mGluSTMatrixHandle, mGlaPositionHandle, mGlaTextureHandle);
checkGlError("window draw");
if (DBG) {
final IntBuffer pixels = IntBuffer.allocate(1);
GLES20.glReadPixels(mWidth / 2, mHeight / 2, 1, 1,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, pixels);
Log.i(TAG, "glReadPixels returned 0x" + Integer.toHexString(pixels.get(0)));
}
mEglHelper.swapBuffers();
}
private void doRecreateWindows() throws GlException {
mTopPresentation.dismissPresentation();
mTopPresentation.destroyVirtualDisplay();
mTopWindow.cleanup();
createWindows();
mRecreationCompletionSemaphore.release();
}
private void waitForStartCompletion() throws Exception {
if (!mStartCompletionSemaphore.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS,
TimeUnit.MILLISECONDS)) {
fail("start timeout");
}
mStartCompletionSemaphore = null;
mTopPresentation.waitForSurfaceReady(DEFAULT_WAIT_TIMEOUT_MS);
}
private class CompositionRunnable implements Runnable {
@Override
public void run() {
try {
Looper.prepare();
mLooper = Looper.myLooper();
mHandler = new CompositionHandler();
initGl();
// init done
mStartCompletionSemaphore.release();
Looper.loop();
} catch (GlException e) {
e.printStackTrace();
fail("got gl exception");
} finally {
cleanupGl();
mHandler = null;
mLooper = null;
}
}
}
private class CompositionHandler extends Handler {
private static final int DO_RENDERING = 1;
private static final int DO_RECREATE_WINDOWS = 2;
@Override
public void handleMessage(Message msg) {
try {
switch(msg.what) {
case DO_RENDERING: {
doGlRendering();
} break;
case DO_RECREATE_WINDOWS: {
doRecreateWindows();
} break;
}
} catch (GlException e) {
//ignore as this can happen during tearing down
}
}
}
private class GlWindow {
private static final int FLOAT_SIZE_BYTES = 4;
private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES;
private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0;
private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3;
private int mBlX;
private int mBlY;
private int mWidth;
private int mHeight;
private int mTextureId = 0; // 0 is invalid
private volatile SurfaceTexture mSurfaceTexture;
private volatile Surface mSurface;
private FloatBuffer mVerticesData;
private float[] mSTMatrix = new float[16];
private AtomicInteger mNumTextureUpdated = new AtomicInteger(0);
private GlCompositor mCompositor;
/**
* @param blX X coordinate of bottom-left point of window
* @param blY Y coordinate of bottom-left point of window
* @param w window width
* @param h window height
*/
public GlWindow(GlCompositor compositor, int blX, int blY, int w, int h) {
mCompositor = compositor;
mBlX = blX;
mBlY = blY;
mWidth = w;
mHeight = h;
int trX = blX + w;
int trY = blY + h;
float[] vertices = new float[] {
// x, y, z, u, v
mBlX, mBlY, 0, 0, 0,
trX, mBlY, 0, 1, 0,
mBlX, trY, 0, 0, 1,
trX, trY, 0, 1, 1
};
Log.i(TAG, "create window " + this + " blX:" + mBlX + " blY:" + mBlY + " trX:" +
trX + " trY:" + trY);
mVerticesData = ByteBuffer.allocateDirect(
vertices.length * FLOAT_SIZE_BYTES)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVerticesData.put(vertices).position(0);
}
/**
* initialize the window for composition. counter-part is cleanup()
* @throws GlException
*/
public void init() throws GlException {
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
mTextureId = textures[0];
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId);
checkGlError("glBindTexture mTextureID");
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_S,
GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GLES20.GL_TEXTURE_WRAP_T,
GLES20.GL_CLAMP_TO_EDGE);
checkGlError("glTexParameter");
mSurfaceTexture = new SurfaceTexture(mTextureId);
mSurfaceTexture.setDefaultBufferSize(mWidth, mHeight);
mSurface = new Surface(mSurfaceTexture);
mSurfaceTexture.setOnFrameAvailableListener(mCompositor);
}
public void cleanup() {
mNumTextureUpdated.set(0);
if (mTextureId != 0) {
int[] textures = new int[] {
mTextureId
};
GLES20.glDeleteTextures(1, textures, 0);
}
GLES20.glFinish();
if (mSurface != null) {
mSurface.release();
mSurface = null;
}
if (mSurfaceTexture != null) {
mSurfaceTexture.release();
mSurfaceTexture = null;
}
}
/**
* make texture as updated so that it can be updated in the next rendering.
*/
public void markTextureUpdated() {
mNumTextureUpdated.incrementAndGet();
}
/**
* update texture for rendering if it is updated.
*/
public void updateTexImageIfNecessary() {
int numTextureUpdated = mNumTextureUpdated.getAndDecrement();
if (numTextureUpdated > 0) {
if (DBG) {
Log.i(TAG, "updateTexImageIfNecessary " + this);
}
mSurfaceTexture.updateTexImage();
mSurfaceTexture.getTransformMatrix(mSTMatrix);
}
if (numTextureUpdated < 0) {
fail("should not happen");
}
}
/**
* draw the window. It will not be drawn at all if the window is not visible.
* @param uSTMatrixHandle shader handler for the STMatrix for texture coordinates
* mapping
* @param aPositionHandle shader handle for vertex position.
* @param aTextureHandle shader handle for texture
*/
public void onDraw(int uSTMatrixHandle, int aPositionHandle, int aTextureHandle) {
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mTextureId);
mVerticesData.position(TRIANGLE_VERTICES_DATA_POS_OFFSET);
GLES20.glVertexAttribPointer(aPositionHandle, 3, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mVerticesData);
GLES20.glEnableVertexAttribArray(aPositionHandle);
mVerticesData.position(TRIANGLE_VERTICES_DATA_UV_OFFSET);
GLES20.glVertexAttribPointer(aTextureHandle, 2, GLES20.GL_FLOAT, false,
TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mVerticesData);
GLES20.glEnableVertexAttribArray(aTextureHandle);
GLES20.glUniformMatrix4fv(uSTMatrixHandle, 1, false, mSTMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
}
public SurfaceTexture getSurfaceTexture() {
return mSurfaceTexture;
}
public Surface getSurface() {
return mSurface;
}
}
}
static void checkGlError(String op) throws GlException {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
Log.e(TAG, op + ": glError " + error);
throw new GlException(op + ": glError " + error);
}
}
public static class GlException extends Exception {
public GlException(String msg) {
super(msg);
}
}
private interface Renderer {
void doRendering(final int color) throws Exception;
}
private static class VirtualDisplayPresentation implements Renderer {
protected final Context mContext;
protected final Surface mSurface;
protected final int mWidth;
protected final int mHeight;
protected VirtualDisplay mVirtualDisplay;
protected TestPresentationBase mPresentation;
private final DisplayManager mDisplayManager;
VirtualDisplayPresentation(Context context, Surface surface, int w, int h) {
mContext = context;
mSurface = surface;
mWidth = w;
mHeight = h;
mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
}
void createVirtualDisplay() {
runOnMainSync(new Runnable() {
@Override
public void run() {
mVirtualDisplay = mDisplayManager.createVirtualDisplay(
TAG, mWidth, mHeight, 200, mSurface,
DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY |
DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION);
}
});
}
void destroyVirtualDisplay() {
runOnMainSync(new Runnable() {
@Override
public void run() {
mVirtualDisplay.release();
}
});
}
void createPresentation() {
runOnMainSync(new Runnable() {
@Override
public void run() {
mPresentation = doCreatePresentation();
mPresentation.show();
}
});
}
protected TestPresentationBase doCreatePresentation() {
return new TestPresentation(mContext, mVirtualDisplay.getDisplay());
}
TestPresentationBase getPresentation() {
return mPresentation;
}
void dismissPresentation() {
runOnMainSync(new Runnable() {
@Override
public void run() {
mPresentation.dismiss();
}
});
}
@Override
public void doRendering(final int color) throws Exception {
runOnMainSync(new Runnable() {
@Override
public void run() {
mPresentation.doRendering(color);
}
});
}
}
private static class TestPresentationBase extends Presentation {
public TestPresentationBase(Context outerContext, Display display) {
// This theme is required to prevent an extra view from obscuring the presentation
super(outerContext, display,
android.R.style.Theme_Holo_Light_NoActionBar_TranslucentDecor);
getWindow().setType(WindowManager.LayoutParams.TYPE_PRIVATE_PRESENTATION);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LOCAL_FOCUS_MODE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
}
public void doRendering(int color) {
// to be implemented by child
}
}
private static class TestPresentation extends TestPresentationBase {
private ImageView mImageView;
public TestPresentation(Context outerContext, Display display) {
super(outerContext, display);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageView = new ImageView(getContext());
mImageView.setImageDrawable(new ColorDrawable(COLOR_RED));
mImageView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
setContentView(mImageView);
}
public void doRendering(int color) {
if (DBG) {
Log.i(TAG, "doRendering " + Integer.toHexString(color));
}
mImageView.setImageDrawable(new ColorDrawable(color));
}
}
private static class TopWindowPresentation extends TestPresentationBase {
private FrameLayout[] mWindowsLayout = new FrameLayout[MAX_NUM_WINDOWS];
private CompositionTextureView[] mWindows = new CompositionTextureView[MAX_NUM_WINDOWS];
private final int mNumWindows;
private final Semaphore mWindowWaitSemaphore = new Semaphore(0);
public TopWindowPresentation(int numWindows, Context outerContext, Display display) {
super(outerContext, display);
mNumWindows = numWindows;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DBG) {
Log.i(TAG, "TopWindowPresentation onCreate, numWindows " + mNumWindows);
}
setContentView(R.layout.composition_layout);
mWindowsLayout[0] = (FrameLayout) findViewById(R.id.window0);
mWindowsLayout[1] = (FrameLayout) findViewById(R.id.window1);
mWindowsLayout[2] = (FrameLayout) findViewById(R.id.window2);
}
public void populateWindows() {
runOnMain(new Runnable() {
public void run() {
for (int i = 0; i < mNumWindows; i++) {
mWindows[i] = new CompositionTextureView(getContext());
mWindows[i].setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mWindowsLayout[i].setVisibility(View.VISIBLE);
mWindowsLayout[i].addView(mWindows[i]);
mWindows[i].startListening();
}
mWindowWaitSemaphore.release();
}
});
}
public void waitForSurfaceReady(long timeoutMs) throws Exception {
mWindowWaitSemaphore.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
for (int i = 0; i < mNumWindows; i++) {
if(!mWindows[i].waitForSurfaceReady(timeoutMs)) {
fail("surface wait timeout");
}
}
}
public Surface getSurface(int windowIndex) {
Surface surface = mWindows[windowIndex].getSurface();
assertNotNull(surface);
return surface;
}
}
private static class TopWindowVirtualDisplayPresentation extends VirtualDisplayPresentation {
private final int mNumWindows;
TopWindowVirtualDisplayPresentation(Context context, Surface surface, int w, int h,
int numWindows) {
super(context, surface, w, h);
assertNotNull(surface);
mNumWindows = numWindows;
}
void waitForSurfaceReady(long timeoutMs) throws Exception {
((TopWindowPresentation) mPresentation).waitForSurfaceReady(timeoutMs);
}
Surface getSurface(int windowIndex) {
return ((TopWindowPresentation) mPresentation).getSurface(windowIndex);
}
protected TestPresentationBase doCreatePresentation() {
return new TopWindowPresentation(mNumWindows, mContext, mVirtualDisplay.getDisplay());
}
}
private static class RemoteVirtualDisplayPresentation implements Renderer {
/** argument: Surface, int w, int h, return none */
private static final int BINDER_CMD_START = IBinder.FIRST_CALL_TRANSACTION;
/** argument: int color, return none */
private static final int BINDER_CMD_RENDER = IBinder.FIRST_CALL_TRANSACTION + 1;
private final Context mContext;
private final Surface mSurface;
private final int mWidth;
private final int mHeight;
private IBinder mService;
private final Semaphore mConnectionWait = new Semaphore(0);
private final ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mService = arg1;
mConnectionWait.release();
}
public void onServiceDisconnected(ComponentName arg0) {
//ignore
}
};
RemoteVirtualDisplayPresentation(Context context, Surface surface, int w, int h) {
mContext = context;
mSurface = surface;
mWidth = w;
mHeight = h;
}
void connect() throws Exception {
Intent intent = new Intent();
intent.setClassName("android.media.cts",
"android.media.cts.RemoteVirtualDisplayService");
mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
if (!mConnectionWait.tryAcquire(DEFAULT_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
fail("cannot bind to service");
}
}
void disconnect() {
mContext.unbindService(mConnection);
}
void start() throws Exception {
Parcel parcel = Parcel.obtain();
mSurface.writeToParcel(parcel, 0);
parcel.writeInt(mWidth);
parcel.writeInt(mHeight);
mService.transact(BINDER_CMD_START, parcel, null, 0);
}
@Override
public void doRendering(int color) throws Exception {
Parcel parcel = Parcel.obtain();
parcel.writeInt(color);
mService.transact(BINDER_CMD_RENDER, parcel, null, 0);
}
}
private static Size getMaxSupportedEncoderSize() {
final Size[] standardSizes = new Size[] {
new Size(1920, 1080),
new Size(1280, 720),
new Size(720, 480),
new Size(352, 576)
};
MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
for (Size sz : standardSizes) {
MediaFormat format = MediaFormat.createVideoFormat(
MIME_TYPE, sz.getWidth(), sz.getHeight());
format.setInteger(MediaFormat.KEY_FRAME_RATE, 15); // require at least 15fps
if (mcl.findEncoderForFormat(format) != null) {
return sz;
}
}
return null;
}
/**
* Check maximum concurrent encoding / decoding resolution allowed.
* Some H/Ws cannot support maximum resolution reported in encoder if decoder is running
* at the same time.
* Check is done for 4 different levels: 1080p, 720p, 800x480, 480p
* (The last one is required by CDD.)
*/
private Size checkMaxConcurrentEncodingDecodingResolution() {
if (isConcurrentEncodingDecodingSupported(1920, 1080, BITRATE_1080p)) {
return new Size(1920, 1080);
} else if (isConcurrentEncodingDecodingSupported(1280, 720, BITRATE_720p)) {
return new Size(1280, 720);
} else if (isConcurrentEncodingDecodingSupported(800, 480, BITRATE_800x480)) {
return new Size(800, 480);
} else if (isConcurrentEncodingDecodingSupported(720, 480, BITRATE_DEFAULT)) {
return new Size(720, 480);
}
Log.i(TAG, "SKIPPING test: concurrent encoding and decoding is not supported");
return null;
}
private boolean isConcurrentEncodingDecodingSupported(int w, int h, int bitRate) {
MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
MediaFormat testFormat = MediaFormat.createVideoFormat(MIME_TYPE, w, h);
testFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
testFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
if (mcl.findDecoderForFormat(testFormat) == null
|| mcl.findEncoderForFormat(testFormat) == null) {
return false;
}
MediaCodec decoder = null;
OutputSurface decodingSurface = null;
MediaCodec encoder = null;
Surface encodingSurface = null;
try {
decoder = MediaCodec.createDecoderByType(MIME_TYPE);
MediaFormat decoderFormat = MediaFormat.createVideoFormat(MIME_TYPE, w, h);
decodingSurface = new OutputSurface(w, h);
decodingSurface.makeCurrent();
decoder.configure(decoderFormat, decodingSurface.getSurface(), null, 0);
decoder.start();
MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, w, h);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
format.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
encoder = MediaCodec.createEncoderByType(MIME_TYPE);;
encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
encodingSurface = encoder.createInputSurface();
encoder.start();
encoder.stop();
decoder.stop();
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "This H/W does not support w:" + w + " h:" + h);
return false;
} finally {
if (encodingSurface != null) {
encodingSurface.release();
}
if (encoder != null) {
encoder.release();
}
if (decoder != null) {
decoder.release();
}
if (decodingSurface != null) {
decodingSurface.release();
}
}
return true;
}
private static void runOnMain(Runnable runner) {
sHandlerForRunOnMain.post(runner);
}
private static void runOnMainSync(Runnable runner) {
SyncRunnable sr = new SyncRunnable(runner);
sHandlerForRunOnMain.post(sr);
sr.waitForComplete();
}
private static final class SyncRunnable implements Runnable {
private final Runnable mTarget;
private boolean mComplete;
public SyncRunnable(Runnable target) {
mTarget = target;
}
public void run() {
mTarget.run();
synchronized (this) {
mComplete = true;
notifyAll();
}
}
public void waitForComplete() {
synchronized (this) {
while (!mComplete) {
try {
wait();
} catch (InterruptedException e) {
//ignore
}
}
}
}
}
}
| wiki2014/Learning-Summary | alps/cts/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTest.java | Java | gpl-3.0 | 59,181 |
#include "MapState.hpp"
namespace states {
MapState::MapState(engine::Engine& engine)
: GameState(engine), renderer(engine, world), saveFileHandler(engine), pauseState(engine, world, renderer) {
suspended = false;
};
void MapState::init() {
world::PerspectiveState initialPerspective;
initialPerspective.fovy = 45.f;
initialPerspective.aspect = engine.getWindowHandler().getViewportRatio();
initialPerspective.zNear = 0.1f;
initialPerspective.zFar = 10000.f;
data::CameraState initialCamera;
initialCamera.lookAt = glm::vec3();
initialCamera.distance = 80;
initialCamera.rotationAroundX = M_PI / 4.f;
initialCamera.rotationAroundY = 0;
world.getCamera().init(initialPerspective, initialCamera);
world.init();
city.name = "Warsaw";
city.people = 57950;
city.money = 445684;
world.getMap().setCurrentCity(&city);
createNewWorld();
geometry.init(engine, world);
init_brushes();
tree_shape = std::make_shared<geometry::Circle>(0.20f);
if (!renderer.init()) {
engine.stop();
return;
}
setCurrentAction(MapStateAction::PLACE_BUILDING);
this->pole_a = std::make_shared<data::PowerLinePole>(glm::vec2(5, 5));
this->pole_b = std::make_shared<data::PowerLinePole>(glm::vec2(5, 10));
this->pole_c = std::make_shared<data::PowerLinePole>(glm::vec2(5, 15));
world.getMap().add_power_pole(pole_a);
world.getMap().add_power_pole(pole_b);
world.getMap().add_power_pole(pole_c);
world.getMap().add_power_cable(std::make_shared<data::PowerLineCable>(*pole_a, *pole_b));
world.getMap().add_power_cable(std::make_shared<data::PowerLineCable>(*pole_b, *pole_c));
world.getTimer().start();
};
void MapState::init_brushes() noexcept {
tree_brush =
std::make_unique<input::Brush>(data::Position<float>(), TREE_BRUSH_RADIUS_NORMAL, TREE_BRUSH_BORDER_WIDTH);
tree_brush->set_base_colors(glm::vec4(1, 1, 1, 0.05f), glm::vec4(1, 1, 1, 0.4f));
tree_brush->set_active_colors(glm::vec4(1, 1, 0, 0.1f), glm::vec4(1, 1, 0, 0.4f));
}
void MapState::cleanup() {
renderer.cleanup();
world.cleanup();
}
void MapState::update(std::chrono::milliseconds delta) {
if (rmbPressed) {
handleMapDragging(delta);
}
if (rotatingClockwise) {
handleRotatingAroundY(delta, true);
}
if (rotatingCounterClockwise) {
handleRotatingAroundY(delta, false);
}
if (rotatingUpwards) {
handleRotatingAroundX(delta, true);
}
if (rotatingDownwards) {
handleRotatingAroundX(delta, false);
}
glm::ivec2 selectionEnd;
if (geometry.hitField(engine.getWindowHandler().getMousePositionNormalized(), selectionEnd)) {
if (!selection->isSelecting()) {
selection->from(selectionEnd);
}
selection->to(selectionEnd);
}
if (selection->isSelecting() && MapStateAction::PLACE_BUILDING == currentAction) {
glm::vec2 selection_size = selection->getTo() - selection->getFrom() + glm::ivec2(1, 1);
auto to_add_shape = std::make_shared<geometry::AABB>(glm::vec2(), selection_size);
auto colliders = collides_with(data::CollisionLayer::BUILDINGS);
geometry::Collidable to_add(data::CollisionLayer::BUILDINGS, colliders, to_add_shape, selection->getFrom());
if (!world.get_collision_space().if_collides(to_add)) {
selection->markValid();
} else {
selection->markInvalid();
}
}
if (MapStateAction::PLACE_ROAD == currentAction && selection->isSelecting()) {
data::Position from(selection->getFrom());
data::Position to(selection->getTo());
// FIXME(kantoniak): What if chunk in the middle is not active in the scene? Is it allowed.
bool chunk_exists = world.getMap().chunkExists(from.getChunk()) && world.getMap().chunkExists(to.getChunk());
if (!chunk_exists) {
selection->markInvalid();
} else {
geometry::Collidable::ptr candidate = selection_to_AABB(*selection, data::CollisionLayer::ROADS);
if (!world.get_collision_space().if_collides(*candidate)) {
selection->markValid();
} else {
selection->markInvalid();
}
}
}
if (currentAction == MapStateAction::PLACE_TREES) {
glm::vec3 hitpoint;
if (geometry.hitGround(engine.getWindowHandler().getMousePositionNormalized(), hitpoint)) {
tree_brush->set_center(glm::vec2(hitpoint.x, hitpoint.z));
if (tree_brush->get_radius() > TREE_BRUSH_RADIUS_SINGLE && tree_brush->is_active()) {
if (glm::distance(saved_tree_brush_hitpoint, tree_brush->get_center().getGlobal()) > 2.f) {
saved_tree_brush_hitpoint = tree_brush->get_center().getGlobal();
insert_trees_from_brush();
}
}
}
}
if (MapStateAction::PLACE_POWER_LINES == currentAction) {
this->current_tool->update();
}
// TODO(kantoniak): Remove temporary poles
float angle = (world.getTimer().get_turn_number() / 12.f) * M_PI * 2.f;
glm::vec2 pos_delta(cos(angle), sin(angle));
pole_a->set_translation(glm::vec2(5, 5) + pos_delta * 2.f);
pole_c->set_translation(glm::vec2(5, 15) + -pos_delta * 2.f);
float mid_angle = (fmod(world.getTimer().get_turn_number(), 24.f) / 24.f) * M_PI * 2.f;
pole_b->set_rotation(mid_angle);
pole_a->set_rotation(2 * M_PI - mid_angle);
world.update(delta);
};
void MapState::render() {
renderer.prepareFrame();
if (current_tool) {
this->current_tool->pre_render(renderer);
}
renderer.renderWorld(*selection, current_brush, current_tool);
#ifdef _DEBUG
renderer.renderWorldDebug();
renderer.renderDebug();
#endif
renderer.flushWorld();
engine.getDebugInfo().onRenderWorldEnd();
engine.getUI().startFrame();
renderer.renderUI();
#ifdef _DEBUG
renderer.renderDebugUI();
#endif
engine.getUI().endFrame();
renderer.sendFrame();
};
void MapState::onKey(int key, int, int action, int mods) {
// TODO(kantoniak): Refactor MapState::onKey by the end of march. If it's April you can start laughing now :)
if (key == GLFW_KEY_MINUS && action != GLFW_RELEASE) {
world.getCamera().zoom(-5);
}
if (key == GLFW_KEY_EQUAL && action != GLFW_RELEASE) {
world.getCamera().zoom(5);
}
// Rotation around Y
if (key == GLFW_KEY_Q && action == GLFW_PRESS) {
rotatingClockwise = true;
} else if (key == GLFW_KEY_Q && action == GLFW_RELEASE) {
rotatingClockwise = false;
}
if (key == GLFW_KEY_E && action == GLFW_PRESS) {
rotatingCounterClockwise = true;
} else if (key == GLFW_KEY_E && action == GLFW_RELEASE) {
rotatingCounterClockwise = false;
}
// Rotation around X
if (key == GLFW_KEY_HOME && action == GLFW_PRESS) {
rotatingUpwards = true;
} else if (key == GLFW_KEY_HOME && action == GLFW_RELEASE) {
rotatingUpwards = false;
}
if (key == GLFW_KEY_END && action == GLFW_PRESS) {
rotatingDownwards = true;
} else if (key == GLFW_KEY_END && action == GLFW_RELEASE) {
rotatingDownwards = false;
}
if (key == GLFW_KEY_N && action == GLFW_PRESS) {
engine.getSettings().rendering.renderNormals = !engine.getSettings().rendering.renderNormals;
engine.getLogger().debug(std::string("Normals view: %s"),
(engine.getSettings().rendering.renderNormals ? "on" : "off"));
}
if (key == GLFW_KEY_M && action == GLFW_PRESS) {
engine.getLogger().debug("Road nodes debug: %s",
(engine.getSettings().rendering.renderRoadNodesAsMarkers ? "on" : "off"));
engine.getSettings().rendering.renderRoadNodesAsMarkers = !engine.getSettings().rendering.renderRoadNodesAsMarkers;
renderer.markTileDataForUpdate();
}
if (key == GLFW_KEY_G && action == GLFW_PRESS) {
engine.getSettings().world.showGrid = !engine.getSettings().world.showGrid;
}
if (mods == GLFW_MOD_CONTROL) {
if (GLFW_KEY_1 <= key && key <= GLFW_KEY_9 && action == GLFW_PRESS) {
newBuildingHeight = key - GLFW_KEY_1 + 1;
}
} else {
if (GLFW_KEY_1 <= key && key <= GLFW_KEY_1 + world.getTimer().getMaxSpeed() - 1 && action == GLFW_PRESS) {
world.getTimer().setSpeed(key - GLFW_KEY_1 + 1);
world.getTimer().start();
}
}
if (key == GLFW_KEY_GRAVE_ACCENT && action == GLFW_PRESS) {
world.getTimer().pause();
}
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
switchToPauseState();
}
if (key == GLFW_KEY_Z && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_BUILDING);
}
if (key == GLFW_KEY_X && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_ZONE);
}
if (key == GLFW_KEY_C && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_ROAD);
}
if (key == GLFW_KEY_V && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_TREES);
}
if (key == GLFW_KEY_B && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::BULDOZE);
}
if (key == GLFW_KEY_N && action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) {
this->createNewWorld();
}
if (key == GLFW_KEY_S && action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) {
saveFileHandler.createSave(world);
}
if (key == GLFW_KEY_L && action == GLFW_RELEASE && mods == GLFW_MOD_CONTROL) {
world.get_collision_space().clear();
world.getMap().cleanup();
saveFileHandler.loadSave(world);
renderer.markTileDataForUpdate();
renderer.markBuildingDataForUpdate();
}
// Power lines
if (key == GLFW_KEY_P && action == GLFW_PRESS) {
setCurrentAction(MapStateAction::PLACE_POWER_LINES);
}
if (currentAction == MapStateAction::PLACE_TREES) {
switch (action) {
case GLFW_PRESS: {
if (key == GLFW_KEY_LEFT_ALT) {
tree_brush->set_radius(TREE_BRUSH_RADIUS_SINGLE);
renderer.mark_brush_dirty();
}
if (key == GLFW_KEY_LEFT_CONTROL) {
tree_brush->set_radius(TREE_BRUSH_RADIUS_SMALL);
renderer.mark_brush_dirty();
}
if (key == GLFW_KEY_LEFT_SHIFT) {
tree_brush->set_radius(TREE_BRUSH_RADIUS_BIG);
renderer.mark_brush_dirty();
}
break;
}
case GLFW_RELEASE: {
if (key != GLFW_KEY_LEFT_ALT && key != GLFW_KEY_LEFT_SHIFT && key != GLFW_KEY_LEFT_CONTROL) {
break;
}
if (tree_brush->get_radius() != TREE_BRUSH_RADIUS_NORMAL) {
tree_brush->set_radius(TREE_BRUSH_RADIUS_NORMAL);
renderer.mark_brush_dirty();
}
break;
}
}
}
}
void MapState::onMouseButton(int button, int action, int mods) {
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
selection->start(selection->getFrom());
} else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {
selection->stop();
if (MapStateAction::PLACE_BUILDING == currentAction) {
glm::ivec2 size = selection->getTo() - selection->getFrom() + glm::ivec2(1, 1);
auto to_add = std::make_shared<data::Building>();
to_add->width = size.x;
to_add->length = size.y;
to_add->level = newBuildingHeight;
to_add->x = selection->getFrom().x;
to_add->y = selection->getFrom().y;
auto to_add_shape = std::make_shared<geometry::AABB>(glm::vec2(), glm::vec2(size.x, size.y));
auto colliders = collides_with(data::CollisionLayer::BUILDINGS);
to_add->body = std::make_shared<geometry::Collidable>(data::CollisionLayer::BUILDINGS, colliders, to_add_shape,
selection->getFrom());
if (!world.get_collision_space().if_collides(*to_add->body)) {
// Delete colliding trees
auto collidables = world.get_collision_space().find_colliding_with(*to_add->body);
delete_collidables(collidables);
// Insert building
to_add->body->set_user_data(to_add.get());
world.get_collision_space().insert(to_add->body);
world.getMap().add_building(to_add);
renderer.markBuildingDataForUpdate();
}
}
if (MapStateAction::PLACE_ROAD == currentAction && selection->isValid()) {
geometry::Collidable::ptr candidate = selection_to_AABB(*selection, data::CollisionLayer::ROADS);
if (!world.get_collision_space().if_collides(*candidate)) {
// Delete colliding trees
auto collidables = world.get_collision_space().find_colliding_with(*candidate);
delete_collidables(collidables);
// Create and insert roads
auto* s = static_cast<input::LineSelection*>(selection.get());
const std::vector<input::LineSelection> selections = s->divideByChunk();
std::vector<data::Road> roads;
for (auto& selection : selections) {
geometry::Collidable::ptr road_body = selection_to_AABB(selection, data::CollisionLayer::ROADS);
world.get_collision_space().insert(road_body);
roads.emplace_back(selection.getSelected(), road_body);
}
world.getMap().addRoads(roads);
renderer.markTileDataForUpdate();
}
}
if (MapStateAction::BULDOZE == currentAction) {
// FIXME(kantoniak): Remove roads on buildozer
geometry::Collidable::ptr selection_phantom = selection_to_AABB(*selection, data::CollisionLayer::NONE);
geometry::Collidable::layer_key to_delete = data::CollisionLayer::BUILDINGS | data::CollisionLayer::TREES;
auto collidables = world.get_collision_space().collisions_with(*selection_phantom, to_delete);
delete_collidables(collidables);
renderer.markBuildingDataForUpdate();
}
}
if (button == GLFW_MOUSE_BUTTON_RIGHT) {
if (action == GLFW_PRESS) {
rmbPressed = true;
dragStart = engine.getWindowHandler().getMousePosition();
} else {
rmbPressed = false;
}
}
if (current_brush && button == GLFW_MOUSE_BUTTON_LEFT) {
if (action == GLFW_PRESS) {
current_brush->set_active(true);
glm::vec3 hitpoint;
if (geometry.hitGround(engine.getWindowHandler().getMousePositionNormalized(), hitpoint)) {
saved_tree_brush_hitpoint = glm::vec2(hitpoint.x, hitpoint.z);
if (current_brush->get_radius() == TREE_BRUSH_RADIUS_SINGLE) {
insert_trees_around(saved_tree_brush_hitpoint, {glm::vec2()});
} else {
insert_trees_from_brush();
}
}
} else if (action == GLFW_RELEASE) {
current_brush->set_active(false);
}
renderer.mark_brush_dirty();
}
if (current_tool) {
current_tool->on_mouse_button(button, action, mods);
}
}
void MapState::onScroll(double, double yoffset) {
world.getCamera().zoom(yoffset * 5);
}
void MapState::onWindowFocusChange(int focused) {
if (!focused) {
switchToPauseState();
}
}
void MapState::onWindowResize(int width, int height) {
world.getCamera().updateAspect(width / (float)height);
}
geometry::Collidable::ptr MapState::selection_to_AABB(const input::Selection& selection,
data::CollisionLayer layer) const noexcept {
glm::vec2 selection_size = selection.getTo() - selection.getFrom() + glm::ivec2(1, 1);
auto to_add_shape = std::make_shared<geometry::AABB>(glm::vec2(), selection_size);
geometry::Collidable::layer_key colliders = collides_with(static_cast<data::CollisionLayer>(layer));
return std::make_shared<geometry::Collidable>(layer, colliders, to_add_shape, selection.getFrom());
}
void MapState::delete_collidables(const std::vector<geometry::Collidable::ptr>& collidables) noexcept {
// TODO(kantoniak): Allow for reuse with different tools
for (auto& collidable : collidables) {
if (collidable->get_user_data() != nullptr) {
switch (collidable->get_layer_key()) {
case data::CollisionLayer::BUILDINGS: {
const data::Building& building = *static_cast<data::Building*>(collidable->get_user_data());
world.getMap().remove_building(building);
break;
}
case data::CollisionLayer::TREES: {
const data::Tree& tree = *static_cast<data::Tree*>(collidable->get_user_data());
world.getMap().remove_tree(tree);
break;
}
}
}
world.get_collision_space().remove(*collidable);
}
}
data::Tree::ptr MapState::create_random_tree(const data::Position<float>& position,
geometry::Collidable::ptr tree_body) noexcept {
const auto type = static_cast<data::Tree::Type>(rand() % data::Tree::TREE_TYPE_COUNT);
const float age = 100.f * static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
const float rotation = 2.f * M_PI * static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
return std::make_shared<data::Tree>(type, position, rotation, age, tree_body);
}
void MapState::insert_trees_from_brush() noexcept {
static const float tree_density = 2.5f;
const float brush_radius = current_brush->get_radius();
size_t point_count = tree_density * brush_radius * brush_radius;
std::vector<glm::vec2> points = geometry.distribute_in_circle(point_count, brush_radius, 3.f);
insert_trees_around(saved_tree_brush_hitpoint, points);
}
void MapState::insert_trees_around(const glm::vec2& center, const std::vector<glm::vec2>& points) noexcept {
for (auto& point : points) {
const glm::vec2 tree_center(center + point);
// Skip trees outside chunks
// FIXME(kantoniak): This should handle when there are multiple chunks on the board
if (tree_center.x < 0 || data::Chunk::SIDE_LENGTH < tree_center.x || tree_center.y < 0 ||
data::Chunk::SIDE_LENGTH < tree_center.y) {
continue;
}
auto colliders = collides_with(data::CollisionLayer::TREES);
auto collidable_ptr =
std::make_shared<geometry::Collidable>(data::CollisionLayer::TREES, colliders, tree_shape, tree_center);
if (!world.get_collision_space().if_collides(*collidable_ptr)) {
auto tree_ptr = create_random_tree(tree_center, collidable_ptr);
collidable_ptr->set_user_data(tree_ptr.get());
world.get_collision_space().insert(collidable_ptr);
world.getMap().add_tree(tree_ptr);
}
}
}
void MapState::createNewWorld() {
world.getMap().cleanup();
const glm::ivec2 mapSize = glm::ivec2(1, 1);
for (int x = 0; x < mapSize.x; x++) {
for (int y = 0; y < mapSize.y; y++) {
world.getMap().createChunk(glm::ivec2(x, y));
}
}
}
void MapState::createRandomWorld() {
/*const glm::ivec2 mapSize = glm::ivec2(2, 2);
for (int x = 0; x < mapSize.x; x++) {
for (int y = 0; y < mapSize.y; y++) {
world.getMap().createChunk(glm::ivec2(x, y));
}
}
for (int x = 0; x < mapSize.x; x++) {
for (int y = 0; y < mapSize.y; y++) {
auto chunkPos = glm::ivec2(x, y);
int lotX = 0;
for (int i = 2; i < 11; i++) {
data::Lot lot;
lot.position.setLocal(glm::ivec2(lotX + 2, 2), chunkPos);
lot.size = glm::ivec2(i, 6);
switch (i % 4) {
case 0:
lot.direction = data::Direction::N;
break;
case 1:
lot.direction = data::Direction::S;
break;
case 2:
lot.direction = data::Direction::W;
break;
case 3:
lot.direction = data::Direction::E;
break;
}
world.getMap().addLot(lot);
lotX += 1 + i;
}
}
}
// TEST road division
renderer.markTileDataForUpdate();
constexpr unsigned int minBuildingSide = 2;
constexpr unsigned int maxBuildingSideDifference = 3;
constexpr unsigned int minBuildingHeight = 1;
constexpr unsigned int maxBuildingHeightDifference = 6;
constexpr unsigned int maxCollisionTries = 20;
const unsigned int buildingCount =
(mapSize.x * mapSize.y) * (data::Chunk::SIDE_LENGTH * data::Chunk::SIDE_LENGTH / 4) * 0.02f;
for (unsigned int i = 0; i < buildingCount; i++) {
data::buildings::Building test;
for (unsigned int i = 0; i < maxCollisionTries; i++) {
test.width = rand() % maxBuildingSideDifference + minBuildingSide;
test.length = rand() % maxBuildingSideDifference + minBuildingSide;
test.level = rand() % maxBuildingHeightDifference + minBuildingHeight;
test.x = rand() % (data::Chunk::SIDE_LENGTH * mapSize.x - test.width + 1);
test.y = rand() % (data::Chunk::SIDE_LENGTH * mapSize.y - test.length + 1);
if (!geometry.checkCollisions(test)) {
world.getMap().addBuilding(test);
break;
}
}
}*/
}
void MapState::setCurrentAction(MapStateAction action) {
currentAction = action;
renderer.setLeftMenuActiveIcon(currentAction - MapStateAction::PLACE_BUILDING);
// Reset brush, selection and tool
engine.getSettings().rendering.renderSelection = false;
current_brush = nullptr;
renderer.mark_brush_dirty();
this->current_tool.reset();
switch (action) {
case MapStateAction::PLACE_BUILDING:
engine.getSettings().rendering.renderSelection = true;
selection = std::make_unique<input::Selection>();
selection->setColors(glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 0, 0, 0.4f));
break;
case MapStateAction::PLACE_ZONE:
break;
case MapStateAction::PLACE_POWER_LINES: {
auto tool_ptr = std::make_shared<input::PowerLineTool>(engine.getWindowHandler(), world,
renderer.get_model_manager(), geometry, current_brush);
this->current_tool = tool_ptr;
this->current_brush = tool_ptr->get_brush_ptr();
break;
}
case MapStateAction::PLACE_ROAD:
engine.getSettings().rendering.renderSelection = true;
selection = std::make_unique<input::LineSelection>(1);
selection->setColors(glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 1, 0.f, 0.4f), glm::vec4(1, 0, 0, 0.4f));
break;
case MapStateAction::PLACE_TREES:
current_brush = tree_brush;
tree_brush->set_center(glm::vec2(10, 10));
renderer.mark_brush_dirty();
break;
case MapStateAction::BULDOZE:
engine.getSettings().rendering.renderSelection = true;
selection = std::make_unique<input::Selection>();
selection->setColors(glm::vec4(1, 0.f, 0.f, 0.2f), glm::vec4(1, 0.f, 0.f, 0.6f), glm::vec4(1, 0, 0, 1.f));
break;
}
}
void MapState::handleMapDragging(std::chrono::milliseconds delta) {
const glm::vec2 mousePosition = engine.getWindowHandler().getMousePosition();
const glm::vec2 dragDelta = mousePosition - dragStart;
float dragSpeed = 0.2f * delta.count() / 1000.f;
world.getCamera().move(dragSpeed * glm::vec3(dragDelta.x, 0.f, dragDelta.y));
}
void MapState::handleRotatingAroundY(std::chrono::milliseconds delta, bool clockwise) {
float rotationDelta = M_PI * delta.count() / 1000.f;
float modifier = (clockwise ? 1.f : -1.f);
world.getCamera().rotateAroundY(rotationDelta * modifier);
}
void MapState::handleRotatingAroundX(std::chrono::milliseconds delta, bool upwards) {
float rotationDelta = M_PI * delta.count() / 1000.f;
float modifier = (upwards ? 1.f : -1.f);
world.getCamera().rotateAroundX(rotationDelta * modifier);
}
void MapState::switchToPauseState() {
engine.pushState(pauseState);
}
} | kantoniak/konstruisto | src/states/MapState.cpp | C++ | gpl-3.0 | 22,882 |
from core.testcases import APIModelViewSetTestCase, ModelViewSetTestCase, get_permissions_from_compact
from authentication.models import User, UserType
class UserViewSetTestCase(APIModelViewSetTestCase):
model = User
permissions = get_permissions_from_compact({
'list': '...a', # Only admin can list
'retrieve': '.u.a', # Only user and admin can retrieve
# 'update': '.u.a', # TODO Only user and admin can update ??
})
def create_object(self, user: User=None) -> User:
return self.users['user']
class UserTypeViewSetTestCase(ModelViewSetTestCase):
model = UserType
permissions = get_permissions_from_compact({
'list': 'puoa', # Everyone can list
'retrieve': 'puoa', # Everyone can retrieve
'create': '...a', # Only admin can create
'update': '...a', # Only admin can update
'delete': '...a', # Only admin can delete
})
# TODO Test user retrieval from API
| simde-utc/woolly-api | authentication/tests.py | Python | gpl-3.0 | 999 |
Monster = ring.create([AbstractIcon], {
constructor: function()
{
this.sprite = objPhaser.add.sprite(0, 0, Constants.ASSET_MONSTER);
this.sprite.animations.add("fly");
this.sprite.animations.play("fly", 3, true);
this.type = Constants.ASSET_MONSTER;
this.anim = 0;
this.sinchange = 0;
},
update: function(gamespeed)
{
this.$super(gamespeed);
/*this.anim++;
if (this.anim % Constants.MONSTER_LEVITATE_SPEED == 0)
{
this.sinchange++;
this.sprite.y += Math.round(Math.sin(this.sinchange) * Constants.MONSTER_LEVITATE_ACCELERATION);
}*/
},
toString: function()
{
return "Monster";
}
}); | gfrymer/GGJ2015-BSAS-Duality | src/entities/Monster.js | JavaScript | gpl-3.0 | 629 |
function direction(dir, neg) {
if (dir == 'x') {
return function (num) {
num = num == null ? 1 : num;
return new Tile(this.x + (neg ? -num : num), this.y);
};
}
return function (num) {
num = num == null ? 1 : num;
return new Tile(this.x, this.y + (neg ? -num : num));
};
}
var Tile = new Class({
initialize: function (x, y, layer) {
this.width = GetTileWidth();
this.height = GetTileHeight();
if (arguments.length > 1) {
this.layer = [layer, GetPersonLayer(Arq.config.player)].pick();
this.id = GetTile(x, y, this.layer);
this.x = x;
this.y = y;
this.pixelX = this.width * x;
this.pixelY = this.height * y;
}
else
this.id = x;
this.name = GetTileName(this.id);
},
north: direction('y', true),
south: direction('y'),
east: direction('x'),
west: direction('x', true),
place: function (person) {
SetPersonX(person, this.pixelX + this.width / 2);
SetPersonY(person, this.pixelY + this.height / 2);
return this;
},
set: function (tile) {
if (typeof tile == 'string')
tile = Tile.name(tile);
SetTile(this.x, this.y, this.layer, typeof tile == 'number' ? tile : tile.id);
return this;
}
});
function creator(create) {
return function (x, y, layer) {
if (arguments.length == 1) {
var coords = x;
x = coords.x;
y = coords.y;
}
return create(x, y, layer);
};
}
Tile.id = function (id) new Tile(id);
Tile.name = function (name) {
var n = GetNumTiles();
while (n--) {
if (GetTileName(n) == name)
return Tile.id(n);
}
};
Tile.tile = creator(function (x, y, layer) new Tile(x, y, layer));
Tile.pixels = creator(function (x, y, layer) new Tile(Math.floor(x / GetTileWidth()), Math.floor(y / GetTileHeight()), layer));
Tile.under = function (person) Tile.pixels(GetPersonX(person), GetPersonY(person), GetPersonLayer(person));
Tile.current = function () Tile.under(Arq.config.player);
exports.Tile = Tile;
| alpha123/Arq | tile.js | JavaScript | gpl-3.0 | 2,213 |
<?php
namespace ModulusContent\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ItensMenu
*
* @ORM\Table(name="itens_menu")
* @ORM\Entity(repositoryClass="ModulusContent\Repository\ItensMenu")
*/
class ItensMenu
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="label", type="string", length=100, nullable=false)
*/
private $label;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=100, nullable=false)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="url", type="string", length=255, nullable=true)
*/
private $url;
/**
* @var integer
*
* @ORM\Column(name="ordem", type="integer", nullable=false)
*/
private $ordem;
/**
* @var \Menu
*
* @ORM\ManyToOne(targetEntity="Menu")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="menu_id", referencedColumnName="id")
* })
*/
private $menu;
/**
* @var \ItensMenu
*
* @ORM\ManyToOne(targetEntity="ItensMenu")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="parent_item_menu_id", referencedColumnName="id")
* })
*/
private $parentItemMenu;
/**
* @var \SiteContent
*
* @ORM\ManyToOne(targetEntity="SiteContent")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="site_content_id", referencedColumnName="id")
* })
*/
private $siteContent;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set label
*
* @param string $label
* @return ItensMenu
*/
public function setLabel($label)
{
$this->label = $label;
return $this;
}
/**
* Get label
*
* @return string
*/
public function getLabel()
{
return $this->label;
}
/**
* Set title
*
* @param string $title
* @return ItensMenu
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set url
*
* @param string $url
* @return ItensMenu
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set ordem
*
* @param integer $ordem
* @return ItensMenu
*/
public function setOrdem($ordem)
{
$this->ordem = $ordem;
return $this;
}
/**
* Get ordem
*
* @return integer
*/
public function getOrdem()
{
return $this->ordem;
}
/**
* Set menu
*
* @param \Menu $menu
* @return ItensMenu
*/
public function setMenu(Menu $menu = null)
{
$this->menu = $menu;
return $this;
}
/**
* Get menu
*
* @return \Menu
*/
public function getMenu()
{
return $this->menu;
}
/**
* Set parentItemMenu
*
* @param \ItensMenu $parentItemMenu
* @return ItensMenu
*/
public function setParentItemMenu(ItensMenu $parentItemMenu = null)
{
$this->parentItemMenu = $parentItemMenu;
return $this;
}
/**
* Get parentItemMenu
*
* @return \ItensMenu
*/
public function getParentItemMenu()
{
return $this->parentItemMenu;
}
/**
* Set siteContent
*
* @param \SiteContent $siteContent
* @return ItensMenu
*/
public function setSiteContent(SiteContent $siteContent = null)
{
$this->siteContent = $siteContent;
return $this;
}
/**
* Get siteContent
*
* @return \SiteContent
*/
public function getSiteContent()
{
return $this->siteContent;
}
}
| ZF2-Modulus/ModulusContent | src/ModulusContent/Entity/ItensMenu.php | PHP | gpl-3.0 | 4,282 |
// TinyXML2Demo.cpp : ¶¨Òå¿ØÖÆÌ¨Ó¦ÓóÌÐòµÄÈë¿Úµã¡£
//
#include "stdafx.h"
#include "tinyxml2.h"
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include <time.h>
using namespace std;
using namespace tinyxml2;
const char* NODE_XML = "Node.xml";
const char* NODE_ACG_H = "../AcgDemo/NodeAcg.h";
template<class TData>
string DebugData(const TData& data)
{
ostringstream oss;
oss << data;
return oss.str();
}
template<class TData>
string DebugData(const vector<TData>& dataVec)
{
ostringstream oss;
for each (const TData& data in dataVec)
{
oss << data << " ";
}
return oss.str();
}
template<class TData1, class TData2>
string DebugData(const map<TData1, TData2>& dataMap)
{
ostringstream oss;
for each (pair<TData1, TData2> data in dataMap)
{
oss << "[" << DebugData(data.first) << " " << DebugData(data.second) << "]";
}
return oss.str();
}
void DebugElement(FILE* fp, const char* pszSpace, const char* pszPrefix, const char* pszName, const char* pszType, bool bPrintName)
{
if (bPrintName)
fprintf(fp, "%soss << \"%s:\"", pszSpace, pszName);
else
fprintf(fp, "%soss", pszSpace);
if (!strncmp(pszType, "Ms", 2))
{
fprintf(fp, " << DebugClass(%s%s);\n", pszPrefix, pszName);
}
else if (!strncmp(pszType, "vector", 6))
{
fprintf(fp, " << \"[ \";\n");
char pszVecType[64] = { 0 };
const char* pszLT = strchr(pszType, '<');
const char* pszGT = strrchr(pszType, '>');
strncpy_s(pszVecType, 64, pszLT + 1, pszGT - pszLT - 1);
fprintf(fp, "%sfor_each(%s%s.begin(), %s%s.end(), [&oss](const %s& data)->void\n", pszSpace, pszPrefix, pszName, pszPrefix, pszName, pszVecType);
fprintf(fp, "%s{\n", pszSpace);
char pszNewSpace[1024] = { 0 };
strncpy_s(pszNewSpace, 1024, pszSpace, strlen(pszSpace));
strcat_s(pszNewSpace, 1024, " ");
DebugElement(fp, pszNewSpace, "", "data", pszVecType, false);
fprintf(fp, "%s});\n", pszSpace);
fprintf(fp, "%soss << \"] \";\n", pszSpace);
}
else if (!strncmp(pszType, "map", 3))
{
fprintf(fp, " << \"{ \";\n");
char keyType[64] = { 0 };
char valType[64] = { 0 };
char pairType[64] = { 0 };
const char* pszLT = strchr(pszType, '<');
const char* pszComma = strchr(pszType, ',');
const char* pszGT = strrchr(pszType, '>');
strncpy_s(keyType, 64, pszLT + 1, pszComma - pszLT - 1);
strncpy_s(valType, 64, pszComma + 1, pszGT - pszComma - 1);
strncpy_s(pairType, 64, pszLT + 1, pszGT - pszLT - 1);
fprintf(fp, "%sfor_each(%s%s.begin(), %s%s.end(), [&oss](const pair<%s>& data)->void\n", pszSpace, pszPrefix, pszName, pszPrefix, pszName, pairType);
fprintf(fp, "%s{\n", pszSpace);
char pszNewSpace[1024] = { 0 };
strncpy_s(pszNewSpace, 1024, pszSpace, strlen(pszSpace));
strcat_s(pszNewSpace, 1024, " ");
fprintf(fp, "%soss << \"[ \";\n", pszNewSpace);
DebugElement(fp, pszNewSpace, "", "data.first", keyType, false);
DebugElement(fp, pszNewSpace, "", "data.second", valType, false);
fprintf(fp, "%soss << \"]\";\n", pszNewSpace);
fprintf(fp, "%s});\n", pszSpace);
fprintf(fp, "%soss << \" } \";\n", pszSpace);
}
else
{
fprintf(fp, " << %s%s << \" \";\n", pszPrefix, pszName);
}
}
//string DebugClass(MsUserInfoLite& mb)
//{
// ostringstream oss;
//
// oss << DebugData(mb.roleId) << " " << DebugData(mb.roleName);
//
// return oss.str();
//}
void AutoGenClass()
{
FILE* fp;
fopen_s(&fp, NODE_ACG_H, "w");
if (!fp)
{
printf("error open file %s\n", NODE_ACG_H);
return;
}
XMLDocument *pDoc = new XMLDocument();
XMLError errorId = pDoc->LoadFile(NODE_XML);
if (errorId != XML_SUCCESS)
{
fclose(fp);
printf("error load xml: %d %s\n", errorId, NODE_XML);
return;
}
XMLElement* pRoot = pDoc->RootElement();
XMLElement* pCppText = pRoot->FirstChildElement("CppText");
fprintf(fp, "%s\n", pCppText->GetText());
XMLElement* pMessage = pRoot->FirstChildElement("Message");
while (pMessage)
{
const char* pszName = pMessage->Attribute("name");
const char* pszBase = pMessage->Attribute("base");
fprintf(fp, "class Ms%s", pszName);
if (pszBase)
fprintf(fp, " : public Ms%s", pszBase);
fprintf(fp, "\n");
fprintf(fp, "{\n");
fprintf(fp, "public:\n");
fprintf(fp, " Ms%s(){}\n", pszName);
fprintf(fp, "\npublic:\n");
XMLElement* pVar = pMessage->FirstChildElement("Var");
while (pVar)
{
const char* pszName = pVar->Attribute("name");
const char* pszType = pVar->Attribute("type");
fprintf(fp, " %s %s;\n", pszType, pszName);
pVar = pVar->NextSiblingElement();
}
fprintf(fp, "};\n\n\n");
pMessage = pMessage->NextSiblingElement();
}
fclose(fp);
}
void AutoGenDebugClass()
{
FILE* fp;
fopen_s(&fp, NODE_ACG_H, "a");
if (!fp)
{
printf("error open file: %s\n", NODE_ACG_H);
return;
}
XMLDocument *pDoc = new XMLDocument();
XMLError errorId = pDoc->LoadFile(NODE_XML);
if (errorId != XML_SUCCESS)
{
fclose(fp);
printf("error load xml: %d %s\n", errorId, NODE_XML);
return;
}
XMLElement* pRoot = pDoc->RootElement();
XMLElement* pMessage = pRoot->FirstChildElement("Message");
while (pMessage)
{
const char* pszName = pMessage->Attribute("name");
const char* pszBase = pMessage->Attribute("base");
fprintf(fp, "string DebugClass(const class Ms%s& mb)\n", pszName);
fprintf(fp, "{\n");
char pszSpace[1024] = " ";
fprintf(fp, "%sostringstream oss;\n", pszSpace);
fprintf(fp, "%soss << \"{ \";\n", pszSpace);
if (pszBase)
{
fprintf(fp, "%soss << \"Ms%s: \" << DebugClass(static_cast<const Ms%s&>(mb));\n", pszSpace, pszBase, pszBase);
}
XMLElement* pVar = pMessage->FirstChildElement("Var");
while (pVar)
{
const char* pszName = pVar->Attribute("name");
const char* pszType = pVar->Attribute("type");
DebugElement(fp, pszSpace, "mb.", pszName, pszType, true);
pVar = pVar->NextSiblingElement();
}
fprintf(fp, "%soss << \"} \";\n", pszSpace);
fprintf(fp, "%sreturn oss.str();\n", pszSpace);
fprintf(fp, "}\n");
pMessage = pMessage->NextSiblingElement();
}
fclose(fp);
}
int main()
{
//printf("/\\");
//printf("\n");
if ((void)0, 0)
{
printf("i am void 0\n");
}
else
{
printf("i am not void 0\n");
}
AutoGenClass();
AutoGenDebugClass();
//FILE* fp;
//fopen_s(&fp, "../AcgDemo/NodeAcg.h", "a");
//XMLDocument *pDoc = new XMLDocument();
//XMLError errorId = pDoc->LoadFile(NODE_XML);
//if (errorId != XML_SUCCESS)
//{
// fclose(fp);
// printf("error load xml: %d %s\n", errorId, NODE_XML);
// system("pause");
// return 0;
//}
//XMLElement* pRoot = pDoc->RootElement();
//XMLElement* pMessage = pRoot->FirstChildElement("Message");
//while (pMessage)
//{
// const char* pszName = pMessage->Attribute("name");
// const char* pszBase = pMessage->Attribute("base");
// fprintf(fp, "string DebugClass(class Ms%s& mb)\n", pszName);
// fprintf(fp, "{\n");
// fprintf(fp, " ostringstream oss;\n");
// XMLElement* pVar = pMessage->FirstChildElement("Var");
// while (pVar)
// {
// const char* pszName = pVar->Attribute("name");
// const char* pszType = pVar->Attribute("type");
// DebugElement(fp, "mb.", pszName, pszType);
// //if( !strncmp(pszType, "Ms", 2) )
// // printf(" oss << DebugClass(mb.%s);\n", pszName);
// //else if( !strncmp(pszType, "vector", 6))
// //else
// // printf(" oss << DebugData(mb.%s);\n", pszName);
// pVar = pVar->NextSiblingElement();
// }
// fprintf(fp, " return oss.str();\n");
// fprintf(fp, "}\n");
//
// pMessage = pMessage->NextSiblingElement();
//}
//while (pMessage)
//{
// const char* pszName = pMessage->Attribute("name");
// const char* pszBase = pMessage->Attribute("base");
// XMLElement* pVar = pMessage->FirstChildElement("Var");
// while (pVar)
// {
// printf("var name:%s type:%s\n", pVar->Attribute("name"), pVar->Attribute("type"));
// pVar = pVar->NextSiblingElement();
// }
// pMessage = pMessage->NextSiblingElement();
//}
//int nNum = 1;
//printf("debug 1: %s\n", DebugData(nNum).c_str());
//vector<int> numVec;
//numVec.push_back(1);
//numVec.push_back(1);
//numVec.push_back(3);
//printf("debug vector: %s\n", DebugData(numVec).c_str());
//map<int, int> numMap;
//numMap[1] = 1;
//numMap[2] = 2;
//numMap[3] = 3;
//printf("debug map: %s\n", DebugData(numMap).c_str());
//fclose(fp);
system("pause");
return 0;
}
| windpenguin/TinyXML2Demo | TinyXML2Demo/TinyXML2Demo.cpp | C++ | gpl-3.0 | 8,301 |
class Deputy < User
has_many :users, :through => :substitutions, :dependent => :restrict, :inverse_of => :deputies
end
| informatom/qm | app/models/deputy.rb | Ruby | gpl-3.0 | 121 |
/*
Copyright (C) 2016 Julien Le Fur
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/>.
*/
var CST = require('../../constants.js');
var fs = require('fs');
var util = require('util');
function execute(args,options,input,ctx,callback){
if(ctx[CST.OBJ.TEMPLATE]==undefined){
return callback(new Error(util.format(CST.MSG_ERR.TEMPLATE_NOT_EXIST,args[CST.OBJ.TEMPLATE])));
}
var template=`./${config.get('simusPath')}/${args[CST.OBJ.SERVICE]}/${args[CST.OBJ.API]}/${args[CST.OBJ.TEMPLATE]}`;
fs.unlink(template, (err)=>{
if(err)
return callback(new Error(util.format(CST.MSG_ERR.TEMPLATE_DELETE,args[CST.OBJ.TEMPLATE])));
else{
return callback(null,args,options,input,ctx);
}
});
}
module.exports = execute
| Ju-Li-An/gs_engine | lib/dataAccess/fs/template/delete.js | JavaScript | gpl-3.0 | 1,386 |
<?php
/*
* TreeChecker: Error recognition for genealogical trees
*
* Copyright (C) 2014 Digital Humanities Lab, Faculty of Humanities, Universiteit Utrecht
* Corry Gellatly <corry.gellatly@gmail.com>
* Martijn van der Klis <M.H.vanderKlis@uu.nl>
*
* Class that defines an event details object
*
* Derived from webtrees: Web based Family History software
* Copyright (C) 2014 webtrees development team.
*
* 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/>.
*/
if (!defined('WT_WEBTREES')) {
header('HTTP/1.0 403 Forbidden');
exit;
}
class WT_Fact {
private $fact_id = null; // Unique identifier for this fact
private $parent = null; // The GEDCOM record from which this fact is taken.
private $gedcom = null; // The raw GEDCOM data for this fact
private $tag = null; // The GEDCOM tag for this record
private $is_old = false; // Is this a pending record?
private $is_new = false; // Is this a pending record?
private $date = null; // The WT_Date object for the "2 DATE ..." attribute
private $place = null; // The WT_Place object for the "2 PLAC ..." attribute
private $lati = null; // The WT_Lati object for the "2 LATI ..." attribute
private $long = null; // The WT_Long object for the "2 LONG ..." attribute
// Temporary(!) variables that are used by other scripts
public $temp = null; // Timeline controller
public $sortOrder = 0; // sort_facts()
// Create an event objects from a gedcom fragment.
// We need the parent object (to check privacy) and a (pseudo) fact ID to
// identify the fact within the record.
public function __construct($gedcom, WT_GedcomRecord $parent, $fact_id) {
if (preg_match('/^1 ('.WT_REGEX_TAG.')/', $gedcom, $match)) {
$this->gedcom = $gedcom;
$this->parent = $parent;
$this->fact_id = $fact_id;
$this->tag = $match[1];
} else {
// TODO need to rewrite code that passes dummy data to this function
//throw new Exception('Invalid GEDCOM data passed to WT_Fact::_construct('.$gedcom.')');
}
}
// Get the value of level 1 data in the fact
// Allow for multi-line values
public function getValue() {
if (preg_match('/^1 (?:' . $this->tag . ') ?(.*(?:(?:\n2 CONT ?.*)*))/', $this->gedcom, $match)) {
return preg_replace("/\n2 CONT ?/", "\n", $match[1]);
} else {
return null;
}
}
// Get the record to which this fact links
public function getTarget() {
$xref = trim($this->getValue(), '@');
switch ($this->tag) {
case 'FAMC':
case 'FAMS':
return WT_Family::getInstance($xref, $this->getParent()->getGedcomId());
case 'HUSB':
case 'WIFE':
case 'CHIL':
return WT_Individual::getInstance($xref, $this->getParent()->getGedcomId());
case 'SOUR':
return WT_Source::getInstance($xref, $this->getParent()->getGedcomId());
case 'OBJE':
return WT_Media::getInstance($xref, $this->getParent()->getGedcomId());
case 'REPO':
return WT_Repository::getInstance($xref, $this->getParent()->getGedcomId());
case 'NOTE':
return WT_Note::getInstance($xref, $this->getParent()->getGedcomId());
default:
return WT_GedcomRecord::getInstance($xref, $this->getParent()->getGedcomId());
}
}
// Get the value of level 2 data in the fact
public function getAttribute($tag) {
if (preg_match('/\n2 (?:' . $tag . ') ?(.*(?:(?:\n3 CONT ?.*)*)*)/', $this->gedcom, $match)) {
return preg_replace("/\n3 CONT ?/", "\n", $match[1]);
} else {
return null;
}
}
// Do the privacy rules allow us to display this fact to the current user
public function canShow($access_level=WT_USER_ACCESS_LEVEL) {
// TODO - use the privacy settings for $this->gedcom_id, not the default gedcom.
global $person_facts, $global_facts;
// // Does this record have an explicit RESN?
// if (strpos($this->gedcom, "\n2 RESN confidential")) {
// return WT_PRIV_NONE >= $access_level;
// }
// if (strpos($this->gedcom, "\n2 RESN privacy")) {
// return WT_PRIV_USER >= $access_level;
// }
// if (strpos($this->gedcom, "\n2 RESN none")) {
// return true;
// }
//
// // Does this record have a default RESN?
// $xref = $this->parent->getXref();
// if (isset($person_facts[$xref][$this->tag])) {
// return $person_facts[$xref][$this->tag] >= $access_level;
// }
// if (isset($global_facts[$this->tag])) {
// return $global_facts[$this->tag] >= $access_level;
// }
// No restrictions - it must be public
return true;
}
// Check whether this fact is protected against edit
public function canEdit() {
// Managers can edit anything
// Members cannot edit RESN, CHAN and locked records
return
$this->parent->canEdit() && !$this->isOld() && (
WT_USER_GEDCOM_ADMIN ||
WT_USER_CAN_EDIT && strpos($this->gedcom, "\n2 RESN locked")===false && $this->getTag()!='RESN' && $this->getTag()!='CHAN'
);
}
// The place where the event occured.
public function getPlace() {
if ($this->place === null) {
$this->place = new WT_Place($this->getAttribute('PLAC'), $this->getParent()->getGedcomId());
}
return $this->place;
}
// The latitude where the event occured.
public function getLati() {
if ($this->lati === null) {
$this->lati = new WT_Place($this->getAttribute('LATI'), $this->getParent()->getGedcomId());
}
return $this->lati;
}
// The longitude where the event occured.
public function getLong() {
if ($this->long === null) {
$this->long = new WT_Place($this->getAttribute('LONG'), $this->getParent()->getGedcomId());
}
return $this->long;
}
// We can call this function many times, especially when sorting,
// so keep a copy of the date.
public function getDate() {
if ($this->date === null) {
$this->date = new WT_Date($this->getAttribute('DATE'));
}
return $this->date;
}
// The raw GEDCOM data for this fact
public function getGedcom() {
return $this->gedcom;
}
// Unique identifier for the fact
public function getFactId() {
return $this->fact_id;
}
// What sort of fact is this?
public function getTag() {
return $this->tag;
}
// Used to convert a real fact (e.g. BIRT) into a close-relative’s fact (e.g. _BIRT_CHIL)
public function setTag($tag) {
$this->tag = $tag;
}
// The Person/Family record where this WT_Fact came from
public function getParent() {
return $this->parent;
}
public function getLabel() {
switch($this->tag) {
case 'EVEN':
case 'FACT':
if ($this->getAttribute('TYPE')) {
// Custom FACT/EVEN - with a TYPE
return WT_I18N::translate(WT_Filter::escapeHtml($this->getAttribute('TYPE')));
}
// no break - drop into next case
default:
return WT_Gedcom_Tag::getLabel($this->tag, $this->parent);
}
}
// Is this a pending edit?
public function setIsOld() {
$this->is_old = true;
$this->is_new = false;
}
public function isOld() {
return $this->is_old;
}
public function setIsNew() {
$this->is_new = true;
$this->is_old = false;
}
public function isNew() {
return $this->is_new;
}
// Source citations linked to this fact
public function getCitations() {
preg_match_all('/\n(2 SOUR @(' . WT_REGEX_XREF . ')@(?:\n[3-9] .*)*)/', $this->getGedcom(), $matches, PREG_SET_ORDER);
$citations = array();
foreach ($matches as $match) {
$source = WT_Source::getInstance($match[2], $this->getParent()->getGedcomId());
if ($source->canShow()) {
$citations[] = $match[1];
}
}
return $citations;
}
// Notes (inline and objects) linked to this fact
public function getNotes() {
$notes = array();
preg_match_all('/\n2 NOTE ?(.*(?:\n3.*)*)/', $this->getGedcom(), $matches);
foreach ($matches[1] as $match) {
$note = preg_replace("/\n3 CONT ?/", "\n", $match);
if (preg_match('/@(' . WT_REGEX_XREF . ')@/', $note, $nmatch)) {
$note = WT_Note::getInstance($nmatch[1], $this->getParent()->getGedcomId());
if ($note && $note->canShow()) {
// A note object
$notes[] = $note;
}
} else {
// An inline note
$notes[] = $note;
}
}
return $notes;
}
// Media objects linked to this fact
public function getMedia() {
$media = array();
preg_match_all('/\n2 OBJE @(' . WT_REGEX_XREF . ')@/', $this->getGedcom(), $matches);
foreach ($matches[1] as $match) {
$obje = WT_Media::getInstance($match, $this->getParent()->getGedcomId());
if ($obje->canShow()) {
$media[] = $obje;
}
}
return $media;
}
// A one-line summary of the fact - for charts, etc.
public function summary() {
global $SHOW_PARENTS_AGE;
$attributes = array();
$target = $this->getTarget();
if ($target) {
$attributes[] = $target->getFullName();
} else {
$value = $this->getValue();
if ($value && $value!='Y') {
$attributes[] = '<span dir="auto">' . WT_Filter::escapeHtml($value) . '</span>';
}
$date = $this->getDate();
if ($this->getTag() == 'BIRT' && $SHOW_PARENTS_AGE && $this->getParent() instanceof WT_Individual) {
$attributes[] = $date->display() . format_parents_age($this->getParent(), $date);
} else {
$attributes[] = $date->display();
}
$place = $this->getPlace()->getShortName();
if ($place) {
$attributes[] = $place;
}
}
$html = WT_Gedcom_Tag::getLabelValue($this->getTag(), implode(' — ', $attributes), $this->getParent());
if ($this->isNew()) {
return '<div class="new">' . $html . '</div>';
} elseif ($this->isOld()) {
return '<div class="old">' . $html . '</div>';
} else {
return $html;
}
}
// Display an icon for this fact.
// Icons are held in a theme subfolder. Not all themes provide icons.
public function Icon() {
$icon = 'images/facts/' . $this->getTag() . '.png';
$dir = substr(WT_CSS_URL, strlen(WT_STATIC_URL));
if (file_exists($dir . $icon)) {
return '<img src="' . WT_CSS_URL . $icon . '" title="' . WT_Gedcom_Tag::getLabel($this->getTag()) . '">';
} elseif (file_exists($dir . 'images/facts/NULL.png')) {
// Spacer image - for alignment - until we move to a sprite.
return '<img src="' . WT_CSS_URL . 'images/facts/NULL.png">';
} else {
return '';
}
}
/**
* Static Helper functions to sort events
*
* @param WT_Fact $a Fact one
* @param WT_Fact $b Fact two
*
* @return integer
*/
public static function CompareDate(WT_Fact $a, WT_Fact $b)
{
if ($a->getDate()->isOK() && $b->getDate()->isOK()) {
// If both events have dates, compare by date
$ret = WT_Date::Compare($a->getDate(), $b->getDate());
if ($ret == 0) {
// If dates are the same, compare by fact type
$ret = self::CompareType($a, $b);
// If the fact type is also the same, retain the initial order
if ($ret == 0) {
$ret = $a->sortOrder - $b->sortOrder;
}
}
return $ret;
} else {
// One or both events have no date - retain the initial order
return $a->sortOrder - $b->sortOrder;
}
}
/**
* Static method to compare two events by their type.
*
* @param WT_Fact $a Fact one
* @param WT_Fact $b Fact two
*
* @return integer
*/
public static function CompareType(WT_Fact $a, WT_Fact $b) {
global $factsort;
if (empty($factsort)) {
$factsort = array_flip(
array(
'BIRT',
'_HNM',
'ALIA', '_AKA', '_AKAN',
'ADOP', '_ADPF', '_ADPF',
'_BRTM',
'CHR', 'BAPM',
'FCOM',
'CONF',
'BARM', 'BASM',
'EDUC',
'GRAD',
'_DEG',
'EMIG', 'IMMI',
'NATU',
'_MILI', '_MILT',
'ENGA',
'MARB', 'MARC', 'MARL', '_MARI', '_MBON',
'MARR', 'MARR_CIVIL', 'MARR_RELIGIOUS', 'MARR_PARTNERS', 'MARR_UNKNOWN', '_COML',
'_STAT',
'_SEPR',
'DIVF',
'MARS',
'_BIRT_CHIL',
'DIV', 'ANUL',
'_BIRT_', '_MARR_', '_DEAT_','_BURI_', // other events of close relatives
'CENS',
'OCCU',
'RESI',
'PROP',
'CHRA',
'RETI',
'FACT', 'EVEN',
'_NMR', '_NMAR', 'NMR',
'NCHI',
'WILL',
'_HOL',
'_????_',
'DEAT',
'_FNRL', 'CREM', 'BURI', '_INTE',
'_YART',
'_NLIV',
'PROB',
'TITL',
'COMM',
'NATI',
'CITN',
'CAST',
'RELI',
'SSN', 'IDNO',
'TEMP',
'SLGC', 'BAPL', 'CONL', 'ENDL', 'SLGS',
'ADDR', 'PHON', 'EMAIL', '_EMAIL', 'EMAL', 'FAX', 'WWW', 'URL', '_URL',
'FILE', // For media objects
'AFN', 'REFN', '_PRMN', 'REF', 'RIN', '_UID',
'OBJE', 'NOTE', 'SOUR',
'CHAN', '_TODO',
)
);
}
// Facts from same families stay grouped together
// Keep MARR and DIV from the same families from mixing with events from other FAMs
// Use the original order in which the facts were added
if (($a->parent instanceof WT_Family)
&& ($b->parent instanceof WT_Family)
&& ($a->parent !== $b->parent)
) {
return $a->sortOrder - $b->sortOrder;
}
$atag = $a->getTag();
$btag = $b->getTag();
// Events not in the above list get mapped onto one that is.
if (!array_key_exists($atag, $factsort)) {
if (preg_match('/^(_(BIRT|MARR|DEAT|BURI)_)/', $atag, $match)) {
$atag = $match[1];
} else {
$atag = "_????_";
}
}
if (!array_key_exists($btag, $factsort)) {
if (preg_match('/^(_(BIRT|MARR|DEAT|BURI)_)/', $btag, $match)) {
$btag = $match[1];
} else {
$btag = "_????_";
}
}
// - Don't let dated after DEAT/BURI facts sort non-dated facts before DEAT/BURI
// - Treat dated after BURI facts as BURI instead
if (($a->getAttribute('DATE') != null)
&& ($factsort[$atag] > $factsort['BURI'])
&& ($factsort[$atag] < $factsort['CHAN'])
) {
$atag = 'BURI';
}
if (($b->getAttribute('DATE') != null)
&& ($factsort[$btag] > $factsort['BURI'])
&& ($factsort[$btag] < $factsort['CHAN'])
) {
$btag = 'BURI';
}
$ret = $factsort[$atag] - $factsort[$btag];
// If facts are the same then put dated facts before non-dated facts
if ($ret == 0) {
if (($a->getAttribute('DATE') != null)
&& ($b->getAttribute('DATE') == null)
) {
return -1;
}
if (($b->getAttribute('DATE') != null)
&& ($a->getAttribute('DATE')==null)
) {
return 1;
}
// If no sorting preference, then keep original ordering
$ret = $a->sortOrder - $b->sortOrder;
}
return $ret;
}
// Allow native PHP functions such as array_unique() to work with objects
public function __toString() {
return $this->fact_id . '@' . $this->parent->getXref();
}
}
| cgeltly/treechecker | app/models/webtrees/Fact.php | PHP | gpl-3.0 | 14,911 |
import Palabra from '../../models/palabras'
import { GROUP_ID } from '../../config'
/**
* Obtiene el ranking de palabras más usadas.
* @param {*} msg
*/
const ranking = async msg => {
if(msg.chat.id !== GROUP_ID) return;
try {
let palabras = await Palabra.find({}).sort('-amount').exec();
if (palabras.length >= 3) {
await msg.reply.text(
`${palabras[0].palabra} (${palabras[0].amount} veces), ` +
`${palabras[1].palabra} (${palabras[1].amount} veces), ` +
`${palabras[2].palabra} (${palabras[2].amount} veces)`
);
} else if (palabras.length === 2) {
await msg.reply.text(
`${palabras[0].palabra} (${palabras[0].amount} veces), ` +
`${palabras[1].palabra} (${palabras[1].amount} veces)`
);
} else if (palabras.length === 1) {
await msg.reply.text(
`${palabras[0].palabra} (${palabras[0].amount} veces)`
);
} else {
await msg.reply.text('Hablen más por favor');
}
return 0;
} catch (err) {
console.error(err.message || err);
return;
}
};
export default bot => bot.on(['/ranking'], ranking) | jesusgn90/etsiit-moderator | lib/lib/estadisticas/estadisticas.js | JavaScript | gpl-3.0 | 1,257 |
package de.randi2.core.unit.model.randomization;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import de.randi2.model.TreatmentArm;
import de.randi2.model.Trial;
import de.randi2.model.randomization.UrnDesignConfig;
import de.randi2.randomization.RandomizationAlgorithm;
import de.randi2.testUtility.utility.AbstractDomainTest;
public class UrnDesignConfigTest extends AbstractDomainTest<UrnDesignConfig> {
UrnDesignConfig conf;
public UrnDesignConfigTest(){
super(UrnDesignConfig.class);
}
@Test
public void testTrial_null(){
conf = new UrnDesignConfig();
conf.setTrial(null);
assertNull(conf.getTrial());
}
@Test
public void testTrial_withEmptyRandomizationConfig(){
conf = new UrnDesignConfig();
Trial trial = new Trial();
assertNull(trial.getRandomizationConfiguration());
conf.setTrial(trial);
assertEquals(trial, conf.getTrial());
assertEquals(conf, trial.getRandomizationConfiguration());
}
@Test
public void testTrial_withRandomizationConfig(){
conf = new UrnDesignConfig();
Trial trial = new Trial();
trial.setRandomizationConfiguration(new UrnDesignConfig());
assertNotNull(trial.getRandomizationConfiguration());
conf.setTrial(trial);
assertEquals(trial, conf.getTrial());
assertFalse(conf.equals(trial.getRandomizationConfiguration()));
}
@Test
public void testGetAlgortihm_withSeed(){
conf = new UrnDesignConfig(1234);
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertNotNull(algorithm);
assertEquals(1234, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
}
@Test
public void testGetAlgortihm_withoutSeed(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertNotNull(algorithm);
assertEquals(Long.MIN_VALUE, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgorithm_withSeed(){
conf = new UrnDesignConfig(1234);
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(1234, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithm();
assertEquals(1234, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgortihm_withoutSeed(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(Long.MIN_VALUE, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithm();
assertEquals(Long.MIN_VALUE, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgorithmWithNextSeed(){
conf = new UrnDesignConfig(1234);
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(1234, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithmWithNextSeed();
assertEquals(1234+10000, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgorithmWithNextSeed_withoutSeed(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(Long.MIN_VALUE, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithmWithNextSeed();
assertEquals(Long.MIN_VALUE, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testResetAlgorithmNewSeed(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
RandomizationAlgorithm<?> algorithm = conf.getAlgorithm();
assertEquals(Long.MIN_VALUE, algorithm.getSeed());
assertEquals(algorithm, conf.getAlgorithm());
conf.resetAlgorithm(123);
assertEquals(123, conf.getAlgorithm().getSeed());
assertNotSame(algorithm, conf.getAlgorithm());
}
@Test
public void testCountReplacedBalls(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
conf.setCountReplacedBalls(10);
assertEquals(10, conf.getCountReplacedBalls());
}
@Test
public void testInitializeCountBalls(){
conf = new UrnDesignConfig();
conf.setTrial(new Trial());
conf.setInitializeCountBalls(10);
assertEquals(10, conf.getInitializeCountBalls());
}
@Test
public void testTempData(){
conf = new UrnDesignConfig();
conf.setTempData(null);
assertNotNull(conf.getTempData());
}
@Test
public void testTrialHasOnlyTwoArms(){
conf = new UrnDesignConfig();
Trial trial = new Trial();
Set<TreatmentArm> arms = new HashSet<TreatmentArm>();
TreatmentArm arm1 = new TreatmentArm();
arm1.setName("arm1");
arms.add(arm1);
trial.setTreatmentArms(arms);
conf.setTrial(trial);
assertInvalid(conf);
TreatmentArm arm2 = new TreatmentArm();
arm2.setName("arm2");
arms.add(arm2);
trial.setTreatmentArms(arms);
conf.setTrial(trial);
assertValid(conf);
}
} | randi2/randi2 | src/test/java/de/randi2/core/unit/model/randomization/UrnDesignConfigTest.java | Java | gpl-3.0 | 5,309 |
# from mainsite.models import Web_Region
context = {'title': 'my static title',
'description': 'my static description',
'data': 'my static data',
}
def get_context(request):
# region_list = Web_Region.objects.values_list('region_name', flat=True)
context.update({'data': 'my dynamic data'})
return context | sstacha/uweb-vagrant | files/docroot/files/test.data.py | Python | gpl-3.0 | 364 |
var Octopi = function(words) {
this.uid = 0;
this.tree = {$$: []};
this.table = {};
words = (words || []);
for (var i = 0; i < words.length; i++)
this.add(words[i]);
};
/**
* Take serialized Octopi data as string and initialize the Octopi object
* @param json String The serialized Octopi trie
*/
Octopi.load = function(json){
var oct = new Octopi();
var o = JSON.parse(json);
oct.uid = o.uid;
oct.tree = o.tree;
oct.table = o.table;
return oct;
}
Octopi.prototype = {
constructor: Octopi,
/**
* Add a new element to the trie
* @param key String prefix to look up
* @param data Object returned by trie
*/
add: function(key, data) {
var id = ++this.uid;
var sub = this.tree;
this.table[id] = data || key;
sub.$$.push(id);
for (var i = 0; i < key.length; i++) {
var c = key[i];
sub = sub[c] || (sub[c] = {$$:[]});
sub.$$.push(id);
}
},
/**
* Return the list of elements in the trie for a given query
* @param key String The prefix to lookup
*/
get: function(key) {
var sub = this.tree;
var tbl = this.table;
for (var i = 0; i < key.length; i++)
if (!(sub = sub[key[i]]))
return [];
return sub.$$.map(function(id) {
return tbl[id];
});
},
/**
* Serialize the Octopi trie as string
*
* @return String
*/
serialize: function(){
var o = { uid: this.uid,
tree: this.tree,
table: this.table
}
return JSON.stringify(o);
}
};
//Search core code
var trie_data = AUTOCOMPLETE_PLUGIN_REPLACE;
var Autocomplete = function() {
this.oct = new Octopi();
};
Autocomplete.prototype = {
load_data: function(data) {
for (var i = 0; data[i]; i++) {
var info = {
'w': data[i][0],
'd': data[i][1],
's': data[i][2]
}
this.oct.add(data[i][0], info)
}
},
get: function(str) {
// Fixme: cleanup malicious input
var candidates = this.oct.get(str);
return candidates.sort(function(a,b){
return (a.s < b.s) ? 1: -1;
}
);
}
};
// Export needed functions/data to the global context
window.Autocomplete = Autocomplete;
window.trie_data = trie_data;
| ebursztein/SiteFab | plugins/site/rendering/autocomplete/autocomplete.js | JavaScript | gpl-3.0 | 2,263 |
<?php
namespace at\eisisoft\partywithme\api;
/**
* Created by PhpStorm.
* User: Florian
* Date: 05.03.2016
* Time: 09:11
*/
use at\eisisoft\partywithme as pwm;
use function at\eisisoft\partywithme\api\fetchEvents;
use function at\eisisoft\partywithme\api\toJSON;
require_once "../hidden/partials/jsonHeader.php";
$fbLogin = isFbLogin();
$sql = file_get_contents(resolveFileRelativeToHidden("resources/sql/api/allevents.sql"));
if (fetchEvents($fbLogin)) {
try {
$connection = pwm\MySQLHelper::getConnection();
$pstmt = $connection->prepare($sql);
$pstmt->bindValue(":userId", $fbLogin[FB_USER_ID_KEY], \PDO::PARAM_STR);
toJSON($pstmt);;
} catch (\PDOException $e) {
echo "[]";
}
}
?> | reisi007/Party-With-Me | api/listEvents.php | PHP | gpl-3.0 | 743 |
(function() {
var billerModule = angular.module('billerModule');
billerModule.filter('offset', function() {
return function(input, start) {
start = parseInt(start, 10);
return input != null ? input.slice(start) : [];
};
});
billerModule.directive('billRecalculationInfo', function() {
return {
restrict : 'AE',
templateUrl : 'html/bills/bill-recalculation-info.html',
controller : ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http) {
$scope.init = function() {
$scope.itemsPerPage = 10;
$scope.pageCurrentBills = 0;
$scope.pageNonExistingBills = 0;
};
$scope.setCurrentBillsPage = function(value) {
$scope.pageCurrentBills = value;
};
$scope.setNonExistingBillsPage = function(value) {
$scope.pageNonExistingBills = value;
};
$scope.init();
}],
require : '^ngModel',
replace : 'true',
scope : {
entity : '=ngModel'
}
};
});
billerModule.controller('BillRecalculationCtrl', [ '$scope', '$rootScope', '$routeParams', '$http', 'dialogs', function($scope, $rootScope, $routeParams, $http, dialogs) {
$scope.init = function() {
$scope.modes = [
{ id: 'byStore', label:'Por establecimiento' },
{ id: 'byCompany', label:'Por operador' },
{ id: 'allBills', label:'Todos' }
];
$scope.months = [
{ id: '1', label: "Enero"}, { id: '2', label: "Febrero"}, { id: '3', label: "Marzo"}, { id: '4', label: "Abril"},
{ id: '5', label: "Mayo"}, { id: '6', label: "Junio"}, { id: '7', label: "Julio"}, { id: '8', label: "Agosto"},
{ id: '9', label: "Septiembre"}, { id: '10', label: "Octubre"}, { id: '11', label: "Noviembre"}, { id: '12', label: "Diciembre"},
];
$scope.options = { mode: $scope.modes[0]};
};
$scope.prepareBill = function() {
$http.get('rest/recalculation/prepare/bill', {
params: {
y: $scope.options.year,
m: $scope.options.month != null ? $scope.options.month.id : null,
s: $scope.options.store != null && $scope.options.mode.id == 'byStore' ? $scope.options.store.id : null,
c: $scope.options.company != null && $scope.options.mode.id == 'byCompany' ? $scope.options.company.id : null
}
}).success(function(data) {
$scope.message = data;
$scope.prepareResult = data.payload;
});
};
$scope.cancelBillRecalculation = function() {
$scope.prepareResult = null;
};
$scope.executeBillRecalculation = function() {
var dlg = dialogs.confirm('Confirmacion','Desea recalcular la factura? Los ajustes manuales se perderan');
dlg.result.then(function(btn){
$scope.message = {code: 200, info: ['billRecalculation.inProgress']};
$scope.isLoading = true;
$scope.prepareResult.recalculateLiquidation = $scope.recalculateLiquidation;
$http.post('rest/recalculation/execute/bill', $scope.prepareResult
).success(function(data) {
$scope.message = data;
$scope.results = data.payload;
$scope.isLoading = false;
});
});
};
$scope.init();
}]);
})();
| labcabrera/biller | biller-web/src/main/webapp/js/controllers/bill-recalculation-ctrl.js | JavaScript | gpl-3.0 | 3,019 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.12.22 at 06:47:20 AM EET
//
package bias.extension.DashBoard.xmlb;
import jakarta.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the bias.extension.DashBoard.xmlb package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: bias.extension.DashBoard.xmlb
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Frames }
*
*/
public Frames createFrames() {
return new Frames();
}
/**
* Create an instance of {@link Frame }
*
*/
public Frame createFrame() {
return new Frame();
}
}
| kion/Bias | src/bias/extension/DashBoard/xmlb/ObjectFactory.java | Java | gpl-3.0 | 1,528 |
<?php
/**
* TrcIMPLAN Sitio Web - Retrospectiva y estado actual del empleo en Torreón y la Zona Metropolitana de La Laguna
*
* Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.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 TrcIMPLANSitioWeb
*/
namespace Blog;
/**
* Clase RestrospectivaEstadoActualEmpleo
*/
class RestrospectivaEstadoActualEmpleo extends \Base\PublicacionSchemaBlogPosting {
/**
* Constructor
*/
public function __construct() {
// Ejecutar constructor en el padre
parent::__construct();
// Título, autor y fecha
$this->nombre = 'Retrospectiva y estado actual del empleo en Torreón y la ZML';
$this->autor = 'Lic. Rodrigo González Morales';
$this->fecha = '2014-09-26T08:05';
// El nombre del archivo a crear
$this->archivo = 'retrospectiva-estado-actual-empleo';
// La descripción y claves dan información a los buscadores y redes sociales
$this->descripcion = 'El empleo es uno de los principales indicadores, que muestra el desempeño económico de una ciudad, región o país. Desde hace 9 años Torreón y la Zona Metropolitana de la Laguna se habían separado a la alza de la media nacional.';
$this->claves = 'IMPLAN, Torreon, Empleo';
// Ruta al archivo HTML con el contenido
$this->contenido_archivo_html = 'lib/Blog/RestrospectivaEstadoActualEmpleo.html';
// Para el Organizador
$this->categorias = array('Empleo');
$this->fuentes = array();
$this->regiones = array();
} // constructor
} // Clase RestrospectivaEstadoActualEmpleo
?>
| TRCIMPLAN/trcimplan.github.io | lib/Blog/RestrospectivaEstadoActualEmpleo.php | PHP | gpl-3.0 | 2,450 |
package org.betonquest.betonquest.conditions;
import org.betonquest.betonquest.Instruction;
import org.betonquest.betonquest.api.Condition;
import org.betonquest.betonquest.exceptions.InstructionParseException;
import org.betonquest.betonquest.utils.PlayerConverter;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import java.util.Locale;
@SuppressWarnings("PMD.CommentRequired")
public class RideCondition extends Condition {
private EntityType vehicle;
private boolean any;
public RideCondition(final Instruction instruction) throws InstructionParseException {
super(instruction, true);
final String name = instruction.next();
if ("any".equalsIgnoreCase(name)) {
any = true;
} else {
try {
vehicle = EntityType.valueOf(name.toUpperCase(Locale.ROOT));
} catch (final IllegalArgumentException e) {
throw new InstructionParseException("Entity type " + name + " does not exist.", e);
}
}
}
@Override
protected Boolean execute(final String playerID) {
final Entity entity = PlayerConverter.getPlayer(playerID).getVehicle();
return entity != null && (any || entity.getType() == vehicle);
}
}
| Co0sh/BetonQuest | src/main/java/org/betonquest/betonquest/conditions/RideCondition.java | Java | gpl-3.0 | 1,282 |
//
// StateUtils.cs
//
// Author:
// Willem Van Onsem <vanonsem.willem@gmail.com>
//
// Copyright (c) 2014 Willem Van Onsem
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using NUtils.Collections;
namespace NUtils.Automata {
/// <summary>
/// Utility functions for <see cref="T:IState`2"/> instances.
/// </summary>
public static class StateUtils {
#region Blankets
/// <summary>
/// Calculate the blanket of the given <see cref="T:IState`2"/> for the given <paramref name="blankettag"/>.
/// </summary>
/// <returns>The blanket.</returns>
/// <param name="state">Current.</param>
/// <param name="blankettag">Blankettag.</param>
/// <typeparam name="TStateTag">The 1st type parameter.</typeparam>
/// <typeparam name="TEdgeTag">The 2nd type parameter.</typeparam>
/// <remarks>
/// <para>A blanket is the set of states that can be reached by applying zero, one or more times the given tag onto the given state.</para>
/// <para>Each state is included in its own blanket.</para>
/// <para>The algorithm avoids loops by storing the already visited states.</para>
/// <para>The order of the blanken is unique depth-first.</para>
/// </remarks>
public static IEnumerable<IState<TStateTag,TEdgeTag>> GetBlanket<TStateTag,TEdgeTag> (this IState<TStateTag,TEdgeTag> state, TEdgeTag blankettag) {
yield return state;
IState<TStateTag,TEdgeTag> current;
Queue<IState<TStateTag,TEdgeTag>> todo = new Queue<IState<TStateTag, TEdgeTag>> ();
HashSet<IState<TStateTag,TEdgeTag>> seen = new HashSet<IState<TStateTag, TEdgeTag>> ();
seen.Add (state);
todo.Enqueue (state);
while (todo.Count > 0x00) {
current = todo.Dequeue ();
foreach (IState<TStateTag,TEdgeTag> target in current.TaggedEdges(blankettag).SelectMany ((x => x.ResultingStates))) {
if (seen.Add (target)) {
yield return target;
todo.Enqueue (target);
}
}
}
}
#endregion
}
}
| KommuSoft/NUtils | NUtils/Automata/StateUtils.cs | C# | gpl-3.0 | 2,615 |
#!/usr/bin/python
"""
DES-CHAN: A Framework for Channel Assignment Algorithms for Testbeds
This module provides a class to represent network graphs and conflict graphs.
Authors: Matthias Philipp <mphilipp@inf.fu-berlin.de>,
Felix Juraschek <fjuraschek@gmail.com>
Copyright 2008-2013, Freie Universitaet Berlin (FUB). All rights reserved.
These sources were developed at the Freie Universitaet Berlin,
Computer Systems and Telematics / Distributed, embedded Systems (DES) group
(http://cst.mi.fu-berlin.de, http://www.des-testbed.net)
-------------------------------------------------------------------------------
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see http://www.gnu.org/licenses/ .
--------------------------------------------------------------------------------
For further information and questions please use the web site
http://www.des-testbed.net
"""
import re
import sys
class Graph:
def __init__(self, vertices=[]):
# initialize internal data structures
self.values = dict()
self.distances = dict()
# set vertex names and distances
for vertex in vertices:
self.add_vertex(vertex)
def add_vertex(self, new_vertex):
"""Adds the given vertex to the graph.
"""
# do nothing if vertex already exists
if new_vertex in self.get_vertices():
return
# otherwise set up data structures for new vertex
self.values[new_vertex] = dict()
self.distances[new_vertex] = dict()
for old_vertex in self.get_vertices():
self.set_edge_value((old_vertex, new_vertex), None, False)
self.set_distance(old_vertex, new_vertex, sys.maxint)
# distance to itself is 0
self.set_distance(new_vertex, new_vertex, 0)
def remove_vertex(self, vertex):
"""Removes the given vertex from the graph.
"""
del self.values[vertex]
del self.distances[vertex]
for v in self.get_vertices():
del self.values[v][vertex]
del self.distances[v][vertex]
def get_vertices(self):
"""Returns a list that contains all vertices of the graph.
"""
return set(self.values.keys())
def set_edge_value(self, edge, value, update=True):
"""Sets the value of the given edge. The edge is represented by a tuple
of two vertices.
"""
v1, v2 = edge
self.values[v1][v2] = value
# we implement an undirected graph
self.values[v2][v1] = value
# update distance information
# None, "", False, and 0 correspond to no edge
if value:
self.set_distance(v1, v2, 1)
# other shortest paths may have changed
if update:
self.update_distances()
def set_distance(self, v1, v2, d):
"""Sets the distance between the two vertices.
"""
self.distances[v1][v2] = d
# we implement an undirected graph
self.distances[v2][v1] = d
def get_edge_value(self, edge):
"""Returns the value of the given edge. The edge is represented by a tuple
of two vertices.
"""
v1, v2 = edge
return self.values[v1][v2]
def get_distance(self, v1, v2):
"""Returns the distance between v1 and v2.
"""
return self.distances[v1][v2]
def get_edges(self, get_all=False):
"""Returns a dictionary that contains all edges as keys and the
corresponding edge values as values. Only edges that have a value are
returned. By default the graph is assumed to be undirected. If the
optional parameter get_all is True, all vertices are returned.
"""
edges = dict()
remaining_vertices = self.get_vertices()
for v1 in self.get_vertices():
for v2 in remaining_vertices:
value = self.get_edge_value((v1, v2))
# None, "", False, and 0 correspond to no edge
if value:
edges[(v1, v2)] = value
# graph is assumed to be undirected, therefore discard
# duplicate edges if not explicitly requested
if not get_all:
remaining_vertices.remove(v1)
return edges
def merge(self, graph):
"""Merges the current graph with the specified graph. The new graph
contains the union of both vertex sets and the corresponding edge
values.
"""
# add missing vertices
for vertex in graph.get_vertices() - self.get_vertices():
self.add_vertex(vertex)
# set edge values
for edge, edge_value in graph.get_edges().items():
self.set_edge_value(edge, edge_value, False)
self.update_distances()
def get_adjacency_matrix(self):
"""Returns the graph's adjacency matrix as a formatted string.
"""
vertices = self.values.keys()
maxlen = 4
# get maximum length of vertex names for proper layout
for vertex in vertices:
if len(str(vertex)) > maxlen:
maxlen = len(str(vertex))
# print column heads
matrix = "".rjust(maxlen) + " |"
for vertex in vertices:
matrix += " " + str(vertex).rjust(maxlen) + " |"
# print without trailing |
matrix = matrix[:-1] + "\n"
# generate row separator
matrix += "-" * maxlen + "-+"
for i in range(len(vertices)):
matrix += "-" + "-" * maxlen + "-+"
# print without trailing +
matrix = matrix[:-1] + "\n"
# print rows
for v1 in vertices:
matrix += str(v1).ljust(maxlen) + " |"
for v2 in vertices:
matrix += " " + self._get_edge_value_as_text((v1, v2)).rjust(maxlen) + " |"
# print without trailing |
matrix = matrix[:-1] + "\n"
return matrix
def get_graphviz(self, label=""):
"""Returns a string representation of the graph in the dot language from
the graphviz project.
"""
left_vertices = set(self.values.keys())
graph = "Graph G {\n"
if label != "":
graph += "\tgraph [label = \"%s\", labelloc=t]\n" % label
for v1 in self.values.keys():
for v2 in left_vertices:
if self.get_edge_value((v1, v2)):
graph += "\t\"" + str(v1) + "\" -- \"" + str(v2) + "\" "
graph += "[label = \"" + str(self.get_edge_value((v1, v2))) + "\"]\n"
# undirected graph, therefore discard double connections
left_vertices.remove(v1)
graph += "}\n"
return graph
def write_to_file(self, file_name, use_graphviz=False):
"""Writes a textual representation of the graph to the specified file.
If the optional parameter use_graphviz is True, the graph is represented
in the dot language from the graphviz project.
"""
file = open(file_name, 'w')
if use_graphviz:
file.write(self.get_graphviz())
else:
file.write(self.get_adjacency_matrix())
file.close()
def read_from_dotfile(self, file_name):
"""Reads the graph from a graphviz dot file.
"""
file = open(file_name, 'r')
# clear current data
self.__init__()
# match following lines
# "t9-035" -- "t9-146" [label = "1"]
edge_re = re.compile('\s*"(.+)" -- "(.+)" \[label = "(.+)"\]')
for line in file:
edge_ma = edge_re.match(line)
if edge_ma:
v1 = edge_ma.group(1)
v2 = edge_ma.group(2)
value = edge_ma.group(3)
self.add_vertex(v1)
self.add_vertex(v2)
self.set_edge_value((v1, v2), value, False)
file.close()
self.update_distances()
def read_from_file(self, file_name):
"""Reads the graph from a file containing an adjacency matrix as
generated by get_adjacency_matrix() or write_to_file(). The dot format
is not supported.
"""
file = open(file_name, 'r')
# line counter
i = 0;
vertices = list()
for line in file:
i += 1
# first line contains the vertex names
if i == 1:
# first element is empty, therefore discard it
for vertex in line.split("|")[1:]:
vertices.append(vertex.strip())
# clear current data and set new vertices
self.__init__(vertices)
if i > 2:
row = line.split("|")
# first element is the vertex name
v1 = row[0].strip()
# remaining elements are edge values
row = row[1:]
for v2 in vertices:
value = row[vertices.index(v2)].strip()
if value == '':
value = None
self.set_edge_value((v1, v2), value, False)
file.close()
self.update_distances()
def update_distances(self):
"""Updates the distance matrix with the number of hops between all
vertex pairs.
"""
# Floyd Warshall algorithm
# calculate all shortest paths
for k in self.get_vertices():
remaining_vertices = self.get_vertices()
for v1 in self.get_vertices():
for v2 in remaining_vertices:
d = min(self.get_distance(v1, v2),
self.get_distance(v1, k) + self.get_distance(k, v2))
self.set_distance(v1, v2, d)
remaining_vertices.remove(v1)
def get_neighbors(self, vertex):
"""Returns a set that contains all direct neighbors of the given vertex.
"""
neighbors = set()
for v1, v2 in self.get_edges().keys():
if v1 == vertex:
neighbors.add(v2)
elif v2 == vertex:
neighbors.add(v1)
return neighbors
def copy(self):
"""Returns a new Graph object that contains the same vertices and edges.
"""
remaining_vertices = self.get_vertices()
g = Graph(list(remaining_vertices))
for v1 in self.get_vertices():
for v2 in remaining_vertices:
g.set_edge_value((v1, v2), self.get_edge_value((v1, v2)))
g.set_distance(v1, v2, self.get_distance(v1, v2))
remaining_vertices.remove(v1)
return g
def copy_fast(self):
"""Returns a new Graph object that contains the same vertices and edges.
"""
remaining_vertices = self.get_vertices()
g = Graph(list(remaining_vertices))
e = self.get_edges()
for (v1, v2), chans in self.get_edges().iteritems():
g.set_edge_value((v1,v2), self.get_edge_value((v1, v2)), update=False)
g.set_distance(v1, v2, self.get_distance(v1, v2))
return g
def _get_edge_value_as_text(self, edge):
"""Returns a textual representation of the value of the given edge. The
edge is represented by a tuple of two vertices.
"""
v1, v2 = edge
if not self.values[v1][v2]:
return ""
else:
return str(self.values[v1][v2])
class ConflictGraphVertex:
def __init__(self, conflict_graph, nw_graph_edge):
self.conflict_graph = conflict_graph
self.nw_graph_edge = nw_graph_edge
self.channels = None
def __str__(self):
return "%s_%s" % (self.nw_graph_edge)
def get_channel(self):
"""Returns the channel of the link in the network graph that corresponds
to this vertex.
"""
return int(self.conflict_graph.network_graph.get_edge_value(self.nw_graph_edge))
def set_channel(self, channel):
"""Sets the channel in the network graph and computes the resulting
conflict graph.
"""
# update network graph
self.conflict_graph.network_graph.set_edge_value(self.nw_graph_edge,
str(channel))
# update conflict graph
# NOTE the change: We do not have to recalculate ALL edges, just the onces
# adjacent to the changed one are enough! gives us O(n) instead of O(n*n)
self.conflict_graph.update_edge(self)
# self.conflict_graph.update_edges()
def get_nw_graph_neighbor(self, node_name):
"""Returns the neigbor in the network graph corresponding to the link.
"""
if node_name not in self.nw_graph_edge:
return None
if self.nw_graph_edge[0] == node_name:
return self.nw_graph_edge[1]
else:
return self.nw_graph_edge[0]
class ConflictGraph(Graph):
def __init__(self, network_graph, interference_model):
# store the original network graph for later reference
self.network_graph = network_graph
self.interference_model = interference_model
vertices = set()
# each edge in the network graph corresponds to a vertex in the conflict
# graph
for edge in network_graph.get_edges().keys():
vertices.add(ConflictGraphVertex(self, edge))
# call constructor of the super-class with new vertex set
Graph.__init__(self, vertices)
# set edges according to interference model
self.update_edges()
def update_edges(self):
"""Updates all edges of the ConflictGraph regarding the current channel
assignment and the applied interference model.
"""
remaining_vertices = self.get_vertices()
for v1 in self.get_vertices():
for v2 in remaining_vertices:
# get edge value according to the interference model
value = self.interference_model.get_interference(self.network_graph,
v1.nw_graph_edge,
v2.nw_graph_edge)
self.set_edge_value((v1, v2), value, False)
# graph is undirected
remaining_vertices.remove(v1)
def update_edge(self, cg_vertex):
"""Updates all edges that are adjacent to the supplied cg_vertex.
"""
remaining_vertices = self.get_vertices()
for v2 in self.get_vertices():
# get edge value according to the interference model
value = self.interference_model.get_interference(self.network_graph,
cg_vertex.nw_graph_edge,
v2.nw_graph_edge)
self.set_edge_value((cg_vertex, v2), value, False)
def get_vertices_for_node(self, node_name):
"""Returns a set containing all vertices that correspond to links that
are incident to the given node.
"""
vertices = set()
for vertex in self.get_vertices():
if vertex.nw_graph_edge[0] == node_name or \
vertex.nw_graph_edge[1] == node_name:
vertices.add(vertex)
return vertices
def get_vertex(self, node1, node2):
"""Returns the vertex that corresponds to the link between the two given
node names, or None, if such vertex does not exist.
"""
for vertex in self.get_vertices():
if (vertex.nw_graph_edge[0] == node1 and \
vertex.nw_graph_edge[1] == node2) or \
(vertex.nw_graph_edge[0] == node2 and \
vertex.nw_graph_edge[1] == node1):
return vertex
return None
def get_interference_sum(self):
"""Returns the overall interference which is calculated by summing up
all edge values.
"""
sum = 0
for value in self.get_edges().values():
sum += value
return sum
def get_vertex_names(self):
vertex_names = set()
for vertex in self.get_vertices():
vertex_names.add(str(vertex))
return vertex_names
def update(self, network_graph):
old_edges = self.network_graph.get_edges()
new_edges = network_graph.get_edges()
# do nothing if graphs are equal
if new_edges == old_edges:
return
old_edges_keys = set(old_edges.keys())
new_edges_keys = set(new_edges.keys())
# assign new network graph
self.network_graph = network_graph
# update conflict graph
for new_edge in new_edges_keys - old_edges_keys:
# create a new conflict graph vertex for each new network graph edge
self.add_vertex(ConflictGraphVertex(self, new_edge))
for obsolete_edge in old_edges_keys - new_edges_keys:
# remove conflict graph vertices for obsolete edges
self.remove_vertex(self.get_vertex(obsolete_edge[0],
obsolete_edge[1]))
self.update_edges()
# this only runs if the module was *not* imported
if __name__ == '__main__':
g = Graph(["a", "b", "c", "d", "e"])
g.set_edge_value(("a", "b"), 40)
g.set_edge_value(("b", "c"), 40)
g.set_edge_value(("c", "d"), 40)
g.set_edge_value(("d", "e"), 40)
print g.get_adjacency_matrix()
| des-testbed/des_chan | graph.py | Python | gpl-3.0 | 18,151 |
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
dist: {
options: {
style: 'compressed'
},
files: {
'assets/css/global.css': 'src/sass/global.scss'
}
}
},
concat: {
options: {
separator: ';'
},
dist: {
src: ['src/js/**.js'],
dest: 'assets/js/global.js'
}
},
uglify: {
my_target: {
files: {
'assets/js/global.min.js': ['assets/js/global.js']
}
}
},
autoprefixer: {
options: {
map: true,
browsers: ['Last 8 versions', 'IE > 7', '> 1%']
},
css: {
src: 'assets/css/*.css'
}
},
watch: {
sass: {
files: ['src/sass/**/*.scss'],
tasks: ['sass', 'autoprefixer']
},
js: {
files: ['src/js/**/*.js'],
tasks: ['concat', 'uglify']
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['sass', 'autoprefixer', 'concat', 'uglify']);
}; | Treenity/bbpress-wp-support | gruntfile.js | JavaScript | gpl-3.0 | 1,604 |
package it.kytech.skywars;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Vector;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import it.kytech.skywars.MessageManager.PrefixType;
import it.kytech.skywars.commands.AddWall;
import it.kytech.skywars.commands.CreateArena;
import it.kytech.skywars.commands.DelArena;
import it.kytech.skywars.commands.Disable;
import it.kytech.skywars.commands.Enable;
import it.kytech.skywars.commands.ForceStart;
import it.kytech.skywars.commands.Join;
import it.kytech.skywars.commands.Leave;
import it.kytech.skywars.commands.LeaveQueue;
import it.kytech.skywars.commands.ListArenas;
import it.kytech.skywars.commands.ListPlayers;
import it.kytech.skywars.commands.Reload;
import it.kytech.skywars.commands.ResetSpawns;
import it.kytech.skywars.commands.SetLobbySpawn;
import it.kytech.skywars.commands.SetLobbyWall;
import it.kytech.skywars.commands.SetSpawn;
import it.kytech.skywars.commands.Spectate;
import it.kytech.skywars.commands.SubCommand;
import it.kytech.skywars.commands.Teleport;
import it.kytech.skywars.commands.Vote;
public class CommandHandler implements CommandExecutor {
private Plugin plugin;
private HashMap < String, SubCommand > commands;
private HashMap < String, Integer > helpinfo;
private MessageManager msgmgr = MessageManager.getInstance();
public CommandHandler(Plugin plugin) {
this.plugin = plugin;
commands = new HashMap < String, SubCommand > ();
helpinfo = new HashMap < String, Integer > ();
loadCommands();
loadHelpInfo();
}
private void loadCommands() {
commands.put("createarena", new CreateArena());
commands.put("join", new Join());
commands.put("addwall", new AddWall());
commands.put("setspawn", new SetSpawn());
commands.put("getcount", new ListArenas());
commands.put("disable", new Disable());
commands.put("start", new ForceStart());
commands.put("enable", new Enable());
commands.put("vote", new Vote());
commands.put("leave", new Leave());
commands.put("setlobbyspawn", new SetLobbySpawn());
commands.put("setlobbywall", new SetLobbyWall());
commands.put("resetspawns", new ResetSpawns());
commands.put("delarena", new DelArena());
commands.put("spectate", new Spectate());
commands.put("lq", new LeaveQueue());
commands.put("leavequeue", new LeaveQueue());
commands.put("list", new ListPlayers());
commands.put("tp", new Teleport());
commands.put("reload", new Reload());
commands.put("reload", new Reload());
}
private void loadHelpInfo() {
//you can do this by iterating thru the hashmap from a certian index btw instead of using a new hashmap,
//plus, instead of doing three differnet ifs, just iterate thru and check if the value == the page
helpinfo.put("createarena", 3);
helpinfo.put("join", 1);
helpinfo.put("addwall", 3);
helpinfo.put("setspawn", 3);
helpinfo.put("getcount", 3);
helpinfo.put("disable", 2);
helpinfo.put("start", 2);
helpinfo.put("enable", 2);
helpinfo.put("vote", 1);
helpinfo.put("leave", 1);
helpinfo.put("setlobbyspawn", 3);
helpinfo.put("resetspawns", 3);
helpinfo.put("delarena", 3);
helpinfo.put("flag", 3);
helpinfo.put("spectate", 1);
helpinfo.put("lq", 1);
helpinfo.put("leavequeue", 1);
helpinfo.put("list", 1);
}
@Override
public boolean onCommand(CommandSender sender, Command cmd1, String commandLabel, String[] args) {
PluginDescriptionFile pdfFile = plugin.getDescription();
if (!(sender instanceof Player)) {
msgmgr.logMessage(PrefixType.WARNING, "Only in-game players can use SurvivalGames commands! ");
return true;
}
Player player = (Player) sender;
if (SkyWars.config_todate == false) {
msgmgr.sendMessage(PrefixType.WARNING, "The config file is out of date. Please tell an administrator to reset the config.", player);
return true;
}
if (SkyWars.dbcon == false) {
msgmgr.sendMessage(PrefixType.WARNING, "Could not connect to server. Plugin disabled.", player);
return true;
}
if (cmd1.getName().equalsIgnoreCase("skywar")) {
if (args == null || args.length < 1) {
msgmgr.sendMessage(PrefixType.INFO, "Version " + pdfFile.getVersion() + " by Double0negative", player);
msgmgr.sendMessage(PrefixType.INFO, "Type /sw help <player | staff | admin> for command information", player);
return true;
}
if (args[0].equalsIgnoreCase("help")) {
if (args.length == 1) {
help(player, 1);
}
else {
if (args[1].toLowerCase().startsWith("player")) {
help(player, 1);
return true;
}
if (args[1].toLowerCase().startsWith("staff")) {
help(player, 2);
return true;
}
if (args[1].toLowerCase().startsWith("admin")) {
help(player, 3);
return true;
}
else {
msgmgr.sendMessage(PrefixType.WARNING, args[1] + " is not a valid page! Valid pages are Player, Staff, and Admin.", player);
}
}
return true;
}
String sub = args[0];
Vector < String > l = new Vector < String > ();
l.addAll(Arrays.asList(args));
l.remove(0);
args = (String[]) l.toArray(new String[0]);
if (!commands.containsKey(sub)) {
msgmgr.sendMessage(PrefixType.WARNING, "Command doesn't exist.", player);
msgmgr.sendMessage(PrefixType.INFO, "Type /sw help for command information", player);
return true;
}
try {
commands.get(sub).onCommand(player, args);
} catch (Exception e) {
e.printStackTrace();
msgmgr.sendFMessage(PrefixType.ERROR, "error.command", player, "command-["+sub+"] "+Arrays.toString(args));
msgmgr.sendMessage(PrefixType.INFO, "Type /sw help for command information", player);
}
return true;
}
return false;
}
public void help (Player p, int page) {
if (page == 1) {
p.sendMessage(ChatColor.BLUE + "------------ " + msgmgr.pre + ChatColor.DARK_AQUA + " Player Commands" + ChatColor.BLUE + " ------------");
}
if (page == 2) {
p.sendMessage(ChatColor.BLUE + "------------ " + msgmgr.pre + ChatColor.DARK_AQUA + " Staff Commands" + ChatColor.BLUE + " ------------");
}
if (page == 3) {
p.sendMessage(ChatColor.BLUE + "------------ " + msgmgr.pre + ChatColor.DARK_AQUA + " Admin Commands" + ChatColor.BLUE + " ------------");
}
for (String command : commands.keySet()) {
try{
if (helpinfo.get(command) == page) {
msgmgr.sendMessage(PrefixType.INFO, commands.get(command).help(p), p);
}
}catch(Exception e){}
}
/*for (SubCommand v : commands.values()) {
if (v.permission() != null) {
if (p.hasPermission(v.permission())) {
msgmgr.sendMessage(PrefixType.INFO1, v.help(p), p);
} else {
msgmgr.sendMessage(PrefixType.WARNING, v.help(p), p);
}
} else {
msgmgr.sendMessage(PrefixType.INFO, v.help(p), p);
}
}*/
}
} | hitech95/SkyWars | src/main/java/it/kytech/skywars/CommandHandler.java | Java | gpl-3.0 | 7,097 |
package com.cole.somecraft.proxy;
public interface IProxy
{
}
| ClarmonkGaming/SomeCraftReboot | src/main/java/com/cole/somecraft/proxy/IProxy.java | Java | gpl-3.0 | 63 |
/*
* //******************************************************************
* //
* // Copyright 2016 Samsung Electronics All Rights Reserved.
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
* //
* // 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.iotivity.cloud.ciserver.resources;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.iotivity.cloud.base.device.CoapDevice;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.device.IRequestChannel;
import org.iotivity.cloud.base.device.IResponseEventHandler;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.base.exception.ServerException.NotFoundException;
import org.iotivity.cloud.base.exception.ServerException.PreconditionFailedException;
import org.iotivity.cloud.base.protocols.IRequest;
import org.iotivity.cloud.base.protocols.IResponse;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.coap.CoapResponse;
import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.resource.Resource;
import org.iotivity.cloud.ciserver.Constants;
import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapDevicePool;
import org.iotivity.cloud.util.Cbor;
/**
*
* This class provides a set of APIs to send requests about message to another
* device
*
*/
public class DiResource extends Resource {
private CoapDevicePool mDevicePool = null;
public DiResource(CoapDevicePool devicePool) {
super(Arrays.asList(Constants.REQ_DEVICE_ID));
mDevicePool = devicePool;
addQueryHandler(
Arrays.asList(Constants.RS_INTERFACE + "="
+ Constants.LINK_INTERFACE),
this::onLinkInterfaceRequestReceived);
}
private IRequestChannel getTargetDeviceChannel(IRequest request)
throws ServerException {
List<String> uriPathSegment = request.getUriPathSegments();
if (uriPathSegment.size() < 2) {
throw new PreconditionFailedException();
}
String deviceId = uriPathSegment.get(1);
CoapDevice targetDevice = (CoapDevice) mDevicePool
.queryDevice(deviceId);
if (targetDevice == null) {
throw new NotFoundException();
}
// Do request and receive response
return targetDevice.getRequestChannel();
}
private String extractTargetUriPath(IRequest request) {
List<String> uriPathSegment = request.getUriPathSegments();
// Remove prefix path
uriPathSegment.remove(0);
uriPathSegment.remove(0);
StringBuilder uriPath = new StringBuilder();
for (String path : uriPathSegment) {
uriPath.append("/" + path);
}
return uriPath.toString();
}
private IResponse convertReponseUri(IResponse response, String di) {
String convertedUri = new String();
CoapResponse coapResponse = (CoapResponse) response;
if (coapResponse.getUriPath().isEmpty() == false) {
convertedUri = "/di/" + di + "/" + coapResponse.getUriPath();
}
return MessageBuilder.modifyResponse(response, convertedUri, null,
null);
}
/**
*
* This class provides a set of APIs to handling message contains link
* interface.
*
*/
class LinkInterfaceHandler implements IResponseEventHandler {
private Cbor<List<HashMap<String, Object>>> mCbor = new Cbor<>();
private String mTargetDI = null;
private Device mSrcDevice = null;
public LinkInterfaceHandler(String targetDI, Device srcDevice) {
mTargetDI = targetDI;
mSrcDevice = srcDevice;
}
private void convertHref(List<HashMap<String, Object>> linkPayload) {
for (HashMap<String, Object> link : linkPayload) {
link.put("href", "/di/" + mTargetDI + link.get("href"));
}
}
@Override
public void onResponseReceived(IResponse response) {
List<HashMap<String, Object>> linkPayload = null;
if (response.getStatus() == ResponseStatus.CONTENT) {
linkPayload = mCbor.parsePayloadFromCbor(response.getPayload(),
ArrayList.class);
if (linkPayload == null) {
throw new BadRequestException("payload is null");
}
convertHref(linkPayload);
}
mSrcDevice.sendResponse(MessageBuilder.modifyResponse(
convertReponseUri(response, mTargetDI),
ContentFormat.APPLICATION_CBOR, linkPayload != null
? mCbor.encodingPayloadToCbor(linkPayload) : null));
}
}
/**
* API for handling optional method for handling packet contains link
* interface.
*
* @param srcDevice
* device information contains response channel
* @param request
* received request to relay
*/
public void onLinkInterfaceRequestReceived(Device srcDevice,
IRequest request) throws ServerException {
IRequestChannel requestChannel = getTargetDeviceChannel(request);
if (requestChannel == null) {
throw new NotFoundException();
}
String deviceId = request.getUriPathSegments().get(1);
requestChannel.sendRequest(
MessageBuilder.modifyRequest(request,
extractTargetUriPath(request), null, null, null),
new LinkInterfaceHandler(deviceId, srcDevice));
}
class DefaultResponseHandler implements IResponseEventHandler {
private String mTargetDI = null;
private Device mSrcDevice = null;
public DefaultResponseHandler(String targetDI, Device srcDevice) {
mTargetDI = targetDI;
mSrcDevice = srcDevice;
}
@Override
public void onResponseReceived(IResponse response) {
mSrcDevice.sendResponse(convertReponseUri(response, mTargetDI));
}
}
@Override
public void onDefaultRequestReceived(Device srcDevice, IRequest request)
throws ServerException {
// Find proper request channel using di in URI path field.
IRequestChannel requestChannel = getTargetDeviceChannel(request);
if (requestChannel == null) {
throw new NotFoundException();
}
String deviceId = request.getUriPathSegments().get(1);
requestChannel.sendRequest(
MessageBuilder.modifyRequest(request,
extractTargetUriPath(request), null, null, null),
new DefaultResponseHandler(deviceId, srcDevice));
}
} | kadasaikumar/iotivity-1.2.1 | cloud/interface/src/main/java/org/iotivity/cloud/ciserver/resources/DiResource.java | Java | gpl-3.0 | 7,727 |
<?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/>.
/**
* Repeat event collection tests.
*
* @package core_calendar
* @copyright 2017 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once($CFG->dirroot . '/calendar/lib.php');
use core_calendar\local\event\entities\event;
use core_calendar\local\event\entities\repeat_event_collection;
use core_calendar\local\event\proxies\coursecat_proxy;
use core_calendar\local\event\proxies\std_proxy;
use core_calendar\local\event\value_objects\event_description;
use core_calendar\local\event\value_objects\event_times;
use core_calendar\local\event\factories\event_factory_interface;
/**
* Repeat event collection tests.
*
* @copyright 2017 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class core_calendar_repeat_event_collection_testcase extends advanced_testcase {
/**
* Test that creating a repeat collection for a parent that doesn't
* exist throws an exception.
*/
public function test_no_parent_collection() {
$this->resetAfterTest(true);
$parentid = 123122131;
$factory = new core_calendar_repeat_event_collection_event_test_factory();
$this->expectException('\core_calendar\local\event\exceptions\no_repeat_parent_exception');
$collection = new repeat_event_collection($parentid, null, $factory);
}
/**
* Test that an empty collection is valid.
*/
public function test_empty_collection() {
$this->resetAfterTest(true);
$this->setAdminUser();
$event = $this->create_event([
// This causes the code to set the repeat id on this record
// but not create any repeat event records.
'repeat' => 1,
'repeats' => 0
]);
$parentid = $event->id;
$factory = new core_calendar_repeat_event_collection_event_test_factory();
// Event collection with no repeats.
$collection = new repeat_event_collection($parentid, null, $factory);
$this->assertEquals($parentid, $collection->get_id());
$this->assertEquals(0, $collection->get_num());
$this->assertNull($collection->getIterator()->next());
}
/**
* Test that a collection with values behaves correctly.
*/
public function test_values_collection() {
$this->resetAfterTest(true);
$this->setAdminUser();
$factory = new core_calendar_repeat_event_collection_event_test_factory();
$event = $this->create_event([
// This causes the code to set the repeat id on this record
// but not create any repeat event records.
'repeat' => 1,
'repeats' => 0
]);
$parentid = $event->id;
$repeats = [];
for ($i = 1; $i < 4; $i++) {
$record = $this->create_event([
'name' => sprintf('repeat %d', $i),
'repeatid' => $parentid
]);
// Index by name so that we don't have to rely on sorting
// when doing the comparison later.
$repeats[$record->name] = $record;
}
// Event collection with no repeats.
$collection = new repeat_event_collection($parentid, null, $factory);
$this->assertEquals($parentid, $collection->get_id());
$this->assertEquals(count($repeats), $collection->get_num());
foreach ($collection as $index => $event) {
$name = $event->get_name();
$this->assertEquals($repeats[$name]->name, $name);
}
}
/**
* Helper function to create calendar events using the old code.
*
* @param array $properties A list of calendar event properties to set
* @return calendar_event
*/
protected function create_event($properties = []) {
$record = new \stdClass();
$record->name = 'event name';
$record->eventtype = 'global';
$record->repeat = 0;
$record->repeats = 0;
$record->timestart = time();
$record->timeduration = 0;
$record->timesort = 0;
$record->type = 1;
$record->courseid = 0;
$record->categoryid = 0;
foreach ($properties as $name => $value) {
$record->$name = $value;
}
$event = new calendar_event($record);
return $event->create($record, false);
}
}
/**
* Test event factory.
*
* @copyright 2017 Ryan Wyllie <ryan@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class core_calendar_repeat_event_collection_event_test_factory implements event_factory_interface {
public function create_instance(\stdClass $dbrow) {
$identity = function($id) {
return $id;
};
return new event(
$dbrow->id,
$dbrow->name,
new event_description($dbrow->description, $dbrow->format),
new coursecat_proxy($dbrow->categoryid),
new std_proxy($dbrow->courseid, $identity),
new std_proxy($dbrow->groupid, $identity),
new std_proxy($dbrow->userid, $identity),
new repeat_event_collection($dbrow->id, null, $this),
new std_proxy($dbrow->instance, $identity),
$dbrow->type,
new event_times(
(new \DateTimeImmutable())->setTimestamp($dbrow->timestart),
(new \DateTimeImmutable())->setTimestamp($dbrow->timestart + $dbrow->timeduration),
(new \DateTimeImmutable())->setTimestamp($dbrow->timesort ? $dbrow->timesort : $dbrow->timestart),
(new \DateTimeImmutable())->setTimestamp($dbrow->timemodified)
),
!empty($dbrow->visible),
new std_proxy($dbrow->subscriptionid, $identity)
);
}
}
| eSrem/moodle | calendar/tests/repeat_event_collection_test.php | PHP | gpl-3.0 | 6,590 |
/*
Copyright 2015 Rudolf Fiala
This file is part of Alpheus AFP Parser.
Alpheus AFP Parser 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.
Alpheus AFP Parser 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 Alpheus AFP Parser. If not, see <http://www.gnu.org/licenses/>
*/
package com.mgz.afp.modca;
import com.mgz.afp.base.IRepeatingGroup;
import com.mgz.afp.base.RepeatingGroupWithTriplets;
import com.mgz.afp.base.StructuredFieldBaseRepeatingGroups;
import com.mgz.afp.exceptions.AFPParserException;
import com.mgz.afp.parser.AFPParserConfiguration;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* MO:DCA, page 293.<br> <br> The Map Page Overlay structured field maps local identifiers to page
* overlay names.
*/
public class MPO_MapPageOverlay extends StructuredFieldBaseRepeatingGroups {
@Override
public void decodeAFP(byte[] sfData, int offset, int length, AFPParserConfiguration config) throws AFPParserException {
int actualLength = getActualLength(sfData, offset, length);
int pos = 0;
while (pos < actualLength) {
MPO_RepeatinGroup rg = new MPO_RepeatinGroup();
rg.decodeAFP(sfData, offset + pos, actualLength - pos, config);
addRepeatingGroup(rg);
pos += rg.getRepeatingGroupLength();
}
}
@Override
public void writeAFP(OutputStream os, AFPParserConfiguration config) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (IRepeatingGroup rg : repeatingGroups) rg.writeAFP(baos, config);
writeFullStructuredField(os, baos.toByteArray());
}
public static class MPO_RepeatinGroup extends RepeatingGroupWithTriplets {
}
}
| quike/alpheusafpparser | src/main/java/com/mgz/afp/modca/MPO_MapPageOverlay.java | Java | gpl-3.0 | 2,124 |
//
//
// Generated by StarUML(tm) C++ Add-In
//
// @ Project : Untitled
// @ File Name : StaticData.cpp
// @ Date : 2017/9/29
// @ Author : ouo
//
//
#include "StaticData.h"
StaticData StaticData::sharedStaticData() {
}
viod StaticData::purge() {
}
int StaticData::intValueFormKey(std::string key) {
}
char StaticData::stringValueFromKey(std::string key) {
}
float StaticData::floatValueFromKey(std::string key) {
}
bool StaticData::booleanFromKey(std::string key) {
}
cocos2d::CCPoint StaticData::pointFromKey(std::string key) {
}
cocos2d::CCRect StaticData::rectFromKey(std::string key) {
}
cocos2d::CCSize StaticData::sizeFromKey(std::string key) {
}
bool StaticData::init() {
}
StaticData::~StaticData() {
}
StaticData::StaticData() {
}
| ouopoi/StaticData | StaticData/StaticData.cpp | C++ | gpl-3.0 | 835 |