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 |
|---|---|---|---|---|---|
package enhanced.portals.client.gui.elements;
import java.util.List;
import enhanced.base.client.gui.BaseGui;
import enhanced.base.client.gui.elements.BaseElement;
import enhanced.core.Reference.ECMod;
import enhanced.portals.portal.GlyphIdentifier;
import net.minecraft.util.ResourceLocation;
public class ElementGlyphDisplay extends BaseElement {
GlyphIdentifier id;
public ElementGlyphDisplay(BaseGui gui, int x, int y, GlyphIdentifier i) {
super(gui, x, y, 162, 18);
id = i;
}
public void setIdentifier(GlyphIdentifier i) {
id = i;
}
@Override
public void addTooltip(List<String> list) {
}
@Override
protected void drawContent() {
parent.getMinecraft().renderEngine.bindTexture(new ResourceLocation(ECMod.ID, "textures/gui/player_inventory.png"));
drawTexturedModalRect(posX, posY, 7, 7, sizeX, sizeY);
parent.getMinecraft().renderEngine.bindTexture(ElementGlyphSelector.glyphs);
if (id != null && id.size() > 0)
for (int i = 0; i < 9; i++) {
if (i >= id.size())
break;
int glyph = id.get(i), X2 = i % 9 * 18, X = glyph % 9 * 18, Y = glyph / 9 * 18;
drawTexturedModalRect(posX + X2, posY, X, Y, 18, 18);
}
}
@Override
public void update() {
}
}
| enhancedportals/enhancedportals | src/main/java/enhanced/portals/client/gui/elements/ElementGlyphDisplay.java | Java | lgpl-3.0 | 1,367 |
/**
* Class ReloadRemoteOrder
* Sending remote order for background reload
* Creation: May, 06, 2011
* @author Ludovic APVRILLE
* @see
*/
import java.io.*;
import java.net.*;
public class ReloadRemoteOrder {
public static final int DEFAULT_PORT = 9362;
public static void main(String[] args) throws Exception{
byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);
String sendData = "reload background";
byte [] buf = sendData.getBytes();
DatagramPacket sendPacket = new DatagramPacket(buf, buf.length, addr, ReloadRemoteOrder.DEFAULT_PORT);
DatagramSocket serverSocket = new DatagramSocket(9876);
serverSocket.send(sendPacket);
}
} // End of class ReloadRemoteOrder
| LudooduL/crocbar | src/ReloadRemoteOrder.java | Java | lgpl-3.0 | 823 |
/*
* Neurpheus - Morfological Analyser
*
* Copyright (C) 2006 Jakub Strychowski
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*/
package org.neurpheus.nlp.morphology.inflection;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import org.neurpheus.core.io.DataOutputStreamPacker;
import org.neurpheus.nlp.morphology.VowelCharacters;
import org.neurpheus.nlp.morphology.VowelCharactersImpl;
/**
* Represents a core pattern which is a common part of some cores covered by this pattern.
*
* @author Jakub Strychowski
*/
public class CorePattern implements Serializable {
/** Unique serialization identifier of this class. */
static final long serialVersionUID = 770608060903220741L;
/** Holds the pattern template. */
private String pattern;
/** Holds the number of cores covered by this pattern. */
private int coveredCoresCount;
/** Holds the weight of this pattern in a morphological analysis process. */
private int weight;
/**
* Creates a new instance of CorePattern.
*/
public CorePattern() {
}
/**
* Returns a template of this pattern.
*
* @return A common fragment of cores.
*/
public String getPattern() {
return pattern;
}
/**
* Sets a new template for this code pattern.
*
* @param newPattern The new value of the template of this core pattern.
*/
public void setPattern(final String newPattern) {
this.pattern = newPattern;
}
/**
* Returns a number of cores covered by this core pattern.
*
* @return The number of covered cores.
*/
public int getCoveredCoresCount() {
return coveredCoresCount;
}
/**
* Sets the number of cores covered by this core pattern.
*
* @param newCoveredCoresCount The new number of covered cores.
*/
public void setCoveredCoresCount(final int newCoveredCoresCount) {
this.coveredCoresCount = newCoveredCoresCount;
}
/**
* Returns the weight value which is used by a morphological analysis process.
*
* @return The weight of this core pattern.
*/
public int getWeight() {
return weight;
}
/**
* Sets the weight value which is used by morphological analysis process.
*
* @param newWeight The new value of this core pattern weight.
*/
public void setWeight(final int newWeight) {
this.weight = newWeight;
}
/**
* Compares twis object with other core pattern.
*
* @param o The core pattern with which compare to.
*
* @return <code>0</code> if core patterns are equal, <code>-1</code> if this core pattern
* is before the given core pattern, and <code>1</code> if this core pattern
* is after the given core pattern.
*/
public int compareTo(final Object o) {
CorePattern p = (CorePattern) o;
return getPattern().compareTo(p.getPattern());
}
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hashtables such as those provided by
* <code>java.util.HashMap</code>.
*
* @return a hash code value for this object.
*/
public int hashCode() {
super.hashCode();
return getPattern().hashCode();
}
/**
* Indicates whether some other object is "equal to" this core pattern.
*
* @param obj The reference object with which to compare.
* @return <code>true</code> if this object is the same as the obj
* argument; <code>false</code> otherwise.
*/
public boolean equals(final Object obj) {
return compareTo(obj) == 0;
}
/**
* Prints this core pattern.
*
* @param out The output stream where this object should be printed.
*/
public void print(final PrintStream out) {
out.print(pattern);
out.print('(');
out.print(weight);
out.print(')');
}
/**
* Checks if a given core matches this core pattern.
*
* @param core The core to check.
* @param vowels The object representing vowels of a language of the core.
*
* @return <code>true</code> if this core pattern covers the given core.
*/
public boolean matches(final String core, final VowelCharacters vowels) {
if (pattern == null) {
return core == null;
}
if (pattern.length() > core.length()) {
return false;
}
char[] ca = core.toCharArray();
char[] pa = pattern.toCharArray();
int cix = ca.length - 1;
for (int pix = pa.length - 1; pix >= 0; pix--, cix--) {
if (ca[cix] != pa[pix]) {
char c = pa[pix];
if (c == vowels.getVowelSign() && Character.isLetter(ca[cix])) {
if (!vowels.isVowel(ca[cix])) {
return false;
}
} else if (c == vowels.getConsonantSign() && Character.isLetter(ca[cix])) {
if (vowels.isVowel(ca[cix])) {
return false;
}
} else {
return false;
}
}
}
return true;
}
/**
* Removes from the given collection all cores covered by this core pattern.
*
* @param cores The collection of cores which should be filtered.
* @param vowels The object representing vowels of a language of cores.
*/
public void removeCoveredCores(final Collection cores, final VowelCharacters vowels) {
boolean containsVowel = false;
boolean containsConsonant = false;
int minCoreLength = Integer.MAX_VALUE;
for (Iterator it = cores.iterator(); it.hasNext();) {
String core = (String) it.next();
if (core.equals("%inn%") && pattern.equals("inn%")) {
core = core + "";
}
if (matches(core, vowels)) {
int clen = core.length();
if (core.startsWith("%")) {
clen--;
}
if (clen < minCoreLength) {
minCoreLength = clen;
}
it.remove();
// check if core contains a vowel or a consonant at the position of
// a character where core pattern starts
if (pattern.length() < core.length()) {
char c = core.charAt(core.length() - pattern.length() - 1);
if (vowels.isVowel(c)) {
containsVowel = true;
} else {
containsConsonant = true;
}
}
}
}
if (pattern.length() < minCoreLength) {
if (containsVowel && !containsConsonant) {
pattern = vowels.getVowelSign() + pattern;
} else if (containsConsonant && !containsVowel) {
pattern = vowels.getConsonantSign() + pattern;
}
}
}
/**
* Reads this object data from the given input stream.
*
* @param in The input stream where this IPB is stored.
*
* @throws IOException if any read error occurred.
* @throws ClassNotFoundException if this object cannot be instantied.
*/
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
pattern = pattern.intern();
}
public void write(final DataOutputStream out) throws IOException {
DataOutputStreamPacker.writeString(pattern, out);
DataOutputStreamPacker.writeInt(coveredCoresCount, out);
DataOutputStreamPacker.writeInt(weight, out);
}
public void read(final DataInputStream in) throws IOException {
pattern = DataOutputStreamPacker.readString(in);
coveredCoresCount = DataOutputStreamPacker.readInt(in);
weight = DataOutputStreamPacker.readInt(in);
}
}
| Neurpheus/manalyser | src/main/java/org/neurpheus/nlp/morphology/inflection/CorePattern.java | Java | lgpl-3.0 | 8,839 |
package ch.idsia.blip.core.learn.solver.ps;
import ch.idsia.blip.core.utils.ParentSet;
public class NullProvider implements Provider {
@Override
public ParentSet[][] getParentSets() {
return null;
}
}
| mauro-idsia/blip | core/src/main/java/ch/idsia/blip/core/learn/solver/ps/NullProvider.java | Java | lgpl-3.0 | 226 |
package org.cdisc.ns.odm.v1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ArchiveLayoutRef complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ArchiveLayoutRef">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{http://www.cdisc.org/ns/odm/v1.3}ArchiveLayoutRefElementExtension" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attGroup ref="{http://www.cdisc.org/ns/odm/v1.3}ArchiveLayoutRefAttributeExtension"/>
* <attGroup ref="{http://www.cdisc.org/ns/odm/v1.3}ArchiveLayoutRefAttributeDefinition"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArchiveLayoutRef")
public class ArchiveLayoutRef {
@XmlAttribute(name = "ArchiveLayoutOID", required = true)
protected String archiveLayoutOID;
/**
* Gets the value of the archiveLayoutOID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getArchiveLayoutOID() {
return archiveLayoutOID;
}
/**
* Sets the value of the archiveLayoutOID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArchiveLayoutOID(String value) {
this.archiveLayoutOID = value;
}
}
| chb/i2b2-ssr | data_import/InformClient/src/main/java/org/cdisc/ns/odm/v1/ArchiveLayoutRef.java | Java | lgpl-3.0 | 1,726 |
<?php
include_once("templates/admin/BeanListPage.php");
include_once("beans/FAQSectionsBean.php");
include_once("beans/FAQItemsBean.php");
class FAQItemsListPage extends BeanListPage
{
public function __construct()
{
parent::__construct();
$sections = new FAQSectionsBean();
$bean = new FAQItemsBean();
$qry = $bean->query();
$qry->select->from.= " fi LEFT JOIN faq_sections fs ON fs.fqsID = fi.fqsID ";
$qry->select->fields()->set("fi.fID", "fs.section_name", "fi.question", "fi.answer");
$this->setIterator($qry);
$this->setListFields(array("section_name"=>"Section", "question"=>"Question", "answer"=>"Answer"));
$this->setBean($bean);
}
protected function initPage()
{
parent::initPage();
$menu = array(new MenuItem("Sections", "sections/list.php"));
$this->getPage()->setPageMenu($menu);
}
} | yodor/sparkbox | lib/templates/admin/FAQItemsListPage.php | PHP | lgpl-3.0 | 923 |
package sinhika.bark.handlers;
public interface IThingHelper
{
public abstract void init(); // end init
public abstract String getName(int index);
public abstract String getCapName(int index);
public abstract String getTypeName(int index);
public abstract int getItemID(int index);
public abstract void setItemID(int index, int id);
public abstract String getLocalizationTag(int index);
public abstract String getTexture(int index);
public abstract int size();
}
| Sinhika/SinhikaSpices | common/sinhika/bark/handlers/IThingHelper.java | Java | lgpl-3.0 | 518 |
/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.admin.patch.impl;
import org.alfresco.repo.admin.patch.AbstractPatch;
import org.alfresco.service.cmr.admin.PatchException;
/**
* Notifies the user that the patch about to be run is no longer supported and an incremental upgrade
* path must be followed.
*
* @author Derek Hulley
* @since 2.1.5
*/
public class NoLongerSupportedPatch extends AbstractPatch
{
private static final String ERR_USE_INCREMENTAL_UPGRADE = "patch.NoLongerSupportedPatch.err.use_incremental_upgrade";
private String lastSupportedVersion;
public NoLongerSupportedPatch()
{
}
public void setLastSupportedVersion(String lastSupportedVersion)
{
this.lastSupportedVersion = lastSupportedVersion;
}
@Override
protected void checkProperties()
{
super.checkProperties();
checkPropertyNotNull(lastSupportedVersion, "lastSupportedVersion");
}
@Override
protected String applyInternal() throws Exception
{
throw new PatchException(
ERR_USE_INCREMENTAL_UPGRADE,
super.getId(),
lastSupportedVersion,
lastSupportedVersion);
}
}
| loftuxab/community-edition-old | projects/repository/source/java/org/alfresco/repo/admin/patch/impl/NoLongerSupportedPatch.java | Java | lgpl-3.0 | 2,016 |
package org.ddialliance.ddieditor.ui.view;
import java.util.List;
import org.apache.xmlbeans.XmlObject;
import org.ddialliance.ddieditor.model.conceptual.ConceptualElement;
import org.ddialliance.ddieditor.model.conceptual.ConceptualType;
import org.ddialliance.ddieditor.model.lightxmlobject.CustomType;
import org.ddialliance.ddieditor.model.lightxmlobject.LightXmlObjectType;
import org.ddialliance.ddieditor.model.resource.DDIResourceType;
import org.ddialliance.ddieditor.model.resource.StorageType;
import org.ddialliance.ddieditor.persistenceaccess.maintainablelabel.MaintainableLightLabelQueryResult;
import org.ddialliance.ddieditor.ui.editor.Editor;
import org.ddialliance.ddieditor.ui.util.LanguageUtil;
import org.ddialliance.ddieditor.util.LightXmlObjectUtil;
import org.ddialliance.ddiftp.util.DDIFtpException;
import org.ddialliance.ddiftp.util.Translator;
import org.ddialliance.ddiftp.util.log.Log;
import org.ddialliance.ddiftp.util.log.LogFactory;
import org.ddialliance.ddiftp.util.log.LogType;
import org.ddialliance.ddiftp.util.xml.XmlBeansUtil;
import org.eclipse.jface.viewers.LabelProvider;
/**
* Tree Label Provider
*/
class TreeLabelProvider extends LabelProvider {
private static Log log = LogFactory.getLog(LogType.SYSTEM,
TreeLabelProvider.class);
@Override
public String getText(Object element) {
// LightXmlObjectType
if (element instanceof LightXmlObjectType) {
LightXmlObjectType lightXmlObject = (LightXmlObjectType) element;
if (lightXmlObject.getElement().equals("Variable")) {
StringBuilder result = new StringBuilder();
// name
for (CustomType cus : LightXmlObjectUtil.getCustomListbyType(
lightXmlObject, "Name")) {
result.append(XmlBeansUtil.getTextOnMixedElement(cus));
}
// label
try {
String l = XmlBeansUtil
.getTextOnMixedElement((XmlObject) XmlBeansUtil
.getDefaultLangElement(lightXmlObject
.getLabelList()));
if (l != null && !l.equals("")) {
result.append(" ");
result.append(l);
}
} catch (Exception e) {
Editor.showError(e, getClass().getName());
}
if (result.length() == 0) {
result.append(lightXmlObject.getElement() + ": "
+ lightXmlObject.getId());
}
return result.toString();
}
if (lightXmlObject.getLabelList().size() > 0) {
try {
Object obj = XmlBeansUtil.getLangElement(
LanguageUtil.getDisplayLanguage(),
lightXmlObject.getLabelList());
return XmlBeansUtil.getTextOnMixedElement((XmlObject) obj);
} catch (DDIFtpException e) {
Editor.showError(e, getClass().getName());
}
} else {
// No label specified - use ID instead:
return lightXmlObject.getElement() + ": "
+ lightXmlObject.getId();
}
}
// DDIResourceType
else if (element instanceof DDIResourceType) {
return ((DDIResourceType) element).getOrgName();
}
// StorageType
else if (element instanceof StorageType) {
return ((StorageType) element).getId();
}
// ConceptualType
else if (element instanceof ConceptualType) {
return Translator.trans(((ConceptualType) element).name());
}
// ConceptualElement
else if (element instanceof ConceptualElement) {
List<org.ddialliance.ddieditor.model.lightxmlobject.LabelType> labels = ((ConceptualElement) element)
.getValue().getLabelList();
if (!labels.isEmpty()) {
return XmlBeansUtil
.getTextOnMixedElement(((ConceptualElement) element)
.getValue().getLabelList().get(0));
} else {
return ((ConceptualElement) element).getValue().getId();
}
}
// MaintainableLightLabelQueryResult
else if (element instanceof MaintainableLightLabelQueryResult) {
try {
return ((MaintainableLightLabelQueryResult) element)
.getTargetLabel();
} catch (DDIFtpException e) {
Editor.showError(e, getClass().getName());
}
return "";
}
// java.util.List
else if (element instanceof List<?>) {
if (!((List<?>) element).isEmpty()) {
Object obj = ((List<?>) element).get(0);
// light xml objects
if (obj instanceof LightXmlObjectType) {
String label = ((LightXmlObjectType) obj).getElement();
return label;
}
} else {
DDIFtpException e = new DDIFtpException("Empty list",
new Throwable());
Editor.showError(e, getClass().getName());
}
}
// guard
else {
if (log.isWarnEnabled()) {
DDIFtpException e = new DDIFtpException(element.getClass()
.getName() + "is not supported", new Throwable());
Editor.showError(e, getClass().getName());
}
}
return new String();
}
}
| DdiEditor/ddieditor-ui | src/org/ddialliance/ddieditor/ui/view/TreeLabelProvider.java | Java | lgpl-3.0 | 4,630 |
// Catalano Imaging Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2014
// diego.catalano at live.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Imaging.Filters;
import Catalano.Imaging.FastBitmap;
import Catalano.Imaging.IBaseInPlace;
/**
* Difference of Gaussians is a feature enhancement algorithm that involves the subtraction of one blurred version of an original image from another.
* @author Diego Catalano
*/
public class DifferenceOfGaussian implements IBaseInPlace{
private int windowSize1 = 3, windowSize2 = 5;
private double sigma1 = 1.4D, sigma2 = 1.4D;
/**
* Get first sigma value.
* @return Sigma value.
*/
public double getSigma1() {
return sigma1;
}
/**
* Set first sigma value.
* @param sigma Sigma value.
*/
public void setSigma1(double sigma) {
this.sigma1 = Math.max( 0.5, Math.min( 5.0, sigma ) );
}
/**
* Get second sigma value.
* @return Sigma value.
*/
public double getSigma2() {
return sigma2;
}
/**
* Set second sigma value.
* @param sigma Sigma value.
*/
public void setSigma2(double sigma) {
this.sigma2 = Math.max( 0.5, Math.min( 5.0, sigma ) );
}
/**
* Get first window size.
* @return Window size value.
*/
public int getWindowSize1() {
return windowSize1;
}
/**
* Set first window size.
* @param size Window size value.
*/
public void setWindowSize1(int size) {
this.windowSize1 = Math.max( 3, Math.min( 21, size | 1 ) );
}
/**
* Get second window size.
* @return Window size value.
*/
public int getWindowSize2() {
return windowSize2;
}
/**
* Set second window size.
* @param size Window size value.
*/
public void setWindowSize2(int size) {
this.windowSize2 = Math.max( 3, Math.min( 21, size | 1 ) );
}
/**
* Initialize a new instance of the DifferenceOfGaussian class.
*/
public DifferenceOfGaussian() {}
/**
* Initialize a new instance of the DifferenceOfGaussian class.
* @param windowSize1 First window size.
* @param windowSize2 Second window size.
*/
public DifferenceOfGaussian(int windowSize1, int windowSize2) {
this.windowSize1 = windowSize1;
this.windowSize2 = windowSize2;
}
/**
* Initialize a new instance of the DifferenceOfGaussian class.
* @param windowSize1 First window size.
* @param windowSize2 Second window size.
* @param sigma Sigma value for both images.
*/
public DifferenceOfGaussian(int windowSize1, int windowSize2, double sigma) {
this.windowSize1 = windowSize1;
this.windowSize2 = windowSize2;
this.sigma1 = Math.max( 0.5, Math.min( 5.0, sigma ) );
}
/**
* Initialize a new instance of the DifferenceOfGaussian class.
* @param windowSize1 First window size.
* @param windowSize2 Second window size.
* @param sigma First sigma value.
* @param sigma2 Second sigma value.
*/
public DifferenceOfGaussian(int windowSize1, int windowSize2, double sigma, double sigma2) {
this.windowSize1 = windowSize1;
this.windowSize2 = windowSize2;
this.sigma1 = Math.max( 0.5, Math.min( 5.0, sigma ) );
this.sigma2 = Math.max( 0.5, Math.min( 5.0, sigma2 ) );
}
@Override
public void applyInPlace(FastBitmap fastBitmap) {
FastBitmap b = new FastBitmap(fastBitmap);
GaussianBlur gauss = new GaussianBlur(sigma1, windowSize1);
gauss.applyInPlace(b);
gauss.setSize(windowSize2);
gauss.setSigma(sigma2);
gauss.applyInPlace(fastBitmap);
Subtract sub = new Subtract(b);
sub.applyInPlace(fastBitmap);
b.recycle();
}
}
| accord-net/java | Catalano.Android.Image/src/Catalano/Imaging/Filters/DifferenceOfGaussian.java | Java | lgpl-3.0 | 4,825 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* 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, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import { shallow } from 'enzyme';
import * as React from 'react';
import StatPendingTime, { Props } from '../StatPendingTime';
it('should render correctly', () => {
expect(shallowRender()).toMatchSnapshot();
});
it('should not render', () => {
expect(shallowRender({ pendingCount: undefined }).type()).toBeNull();
expect(shallowRender({ pendingCount: 0 }).type()).toBeNull();
expect(shallowRender({ pendingTime: undefined }).type()).toBeNull();
});
it('should not render when pending time is too small', () => {
expect(
shallowRender({ pendingTime: 0 })
.find('.emphasised-measure')
.exists()
).toBe(false);
expect(
shallowRender({ pendingTime: 900 })
.find('.emphasised-measure')
.exists()
).toBe(false);
});
function shallowRender(props: Partial<Props> = {}) {
return shallow(<StatPendingTime pendingCount={5} pendingTime={15420} {...props} />);
}
| SonarSource/sonarqube | server/sonar-web/src/main/js/apps/background-tasks/components/__tests__/StatPendingTime-test.tsx | TypeScript | lgpl-3.0 | 1,747 |
var default_window_options = {
autoOpen: false,
width: 750,
height: 450,
modal: true,
resizable: false
};
function applyNotificationStyles() {
$('.error').each(function() {
$(this).addClass('ui-state-error ui-corner-all');
$(this).prepend('<span class="ui-icon ui-icon-alert"></span>');
});
$('.notification').each(function() {
$(this).addClass('ui-state-highlight ui-corner-all');
$(this).prepend('<span class="ui-icon ui-icon-info"></span>');
});
}
$(function() {
// Hard-coded paths aren't great... Maybe re-work this in the future
var divider = "url('" + media_url + "img/navigation_divider.png')";
$('#navigation ul.menu li:has(ul.submenu)').hover(function() {
$(this).addClass('has-submenu');
$(this).children('a.menu-link').css('background-image', 'none');
$(this).prev('li').children('a.menu-link').css('background-image', 'none');
$(this).children('ul').show();
}, function() {
$(this).removeClass('has-submenu');
$(this).children('a.menu-link').css('background-image', divider);
$(this).prev('li').children('a.menu-link').css('background-image', divider);
$(this).children('ul').hide();
});
$('#navigation ul.submenu a').click(function() {
$(this).parents('ul.submenu').hide();
});
// Style form buttons
$('input[type=button], input[type=submit], input[type=reset]').button();
// Style error and notification messages
applyNotificationStyles();
});
| mariajosefrancolugo/osp | osp/media/js/base.js | JavaScript | lgpl-3.0 | 1,553 |
package io.robe.admin.hibernate.entity;
import org.junit.FixMethodOrder;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
/**
* Created by recep on 30/09/16.
*/
@FixMethodOrder
public class MenuTest {
Menu entity = new Menu();
@Test
public void getText() throws Exception {
entity.setText("Text");
assertEquals("Text", entity.getText());
}
@Test
public void getPath() throws Exception {
entity.setPath("Path");
assertEquals("Path", entity.getPath());
}
@Test
public void getIndex() throws Exception {
entity.setIndex(3);
assertEquals(3, entity.getIndex());
}
@Test
public void getParentOid() throws Exception {
entity.setParentOid("12345678901234567890123456789012");
assertEquals("12345678901234567890123456789012", entity.getParentOid());
}
@Test
public void getModule() throws Exception {
entity.setModule("Module");
assertEquals("Module", entity.getModule());
}
@Test
public void getIcon() throws Exception {
entity.setIcon("Icon");
assertEquals("Icon", entity.getIcon());
}
}
| robeio/robe | robe-admin/src/test/java/io/robe/admin/hibernate/entity/MenuTest.java | Java | lgpl-3.0 | 1,192 |
<?php
/**
* @package wa-apps/photos/api/v1
*/
class photosPhotoRotateMethod extends waAPIMethod
{
protected $method = 'POST';
public function execute()
{
$id = $this->post('id', true);
$photo_model = new photosPhotoModel();
$photo = $photo_model->getById($id);
$clockwise = waRequest::post('clockwise', null, 1);
if (!is_numeric($clockwise)) {
$clockwise = strtolower(trim($clockwise));
$clockwise = $clockwise === 'false' ? 0 : 1;
}
if ($photo) {
try {
$photo_model = new photosPhotoModel();
$photo_model->rotate($id, $clockwise);
} catch (waException $e) {
throw new waAPIException('server_error', $e->getMessage(), 500);
}
$this->response = true;
} else {
throw new waAPIException('invalid_request', 'Photo not found', 404);
}
}
} | SergeR/webasyst-framework | wa-apps/photos/api/v1/photos.photo.rotate.method.php | PHP | lgpl-3.0 | 978 |
import math,re,sys,os,time
import random as RD
import time
try:
import netCDF4 as NC
except:
print("You no install netCDF4 for python")
print("So I do not import netCDF4")
try:
import numpy as NP
except:
print("You no install numpy")
print("Do not import numpy")
class GRIDINFORMATER:
"""
This object is the information of the input gridcells/array/map.
Using
.add_an_element to add an element/gridcell
.add_an_geo_element to add an element/gridcell
.create_resample_lat_lon to create a new map of lat and lon for resampling
.create_resample_map to create resample map as ARR_RESAMPLE_MAP
.create_reference_map to create ARR_REFERENCE_MAP to resample target map.
.export_reference_map to export ARR_REFERENCE_MAP into netCDF4 format
"""
STR_VALUE_INIT = "None"
NUM_VALUE_INIT = -9999.9
NUM_NULL = float("NaN")
ARR_RESAMPLE_X_LIM = []
ARR_RESAMPLE_Y_LIM = []
# FROM WRF: module_cam_shr_const_mod.f90
NUM_CONST_EARTH_R = 6.37122E6
NUM_CONST_PI = 3.14159265358979323846
def __init__(self, name="GRID", ARR_LAT=[], ARR_LON=[], NUM_NT=1, DIMENSIONS=2 ):
self.STR_NAME = name
self.NUM_DIMENSIONS = DIMENSIONS
self.NUM_LAST_INDEX = -1
self.ARR_GRID = []
self.NUM_NT = NUM_NT
self.ARR_LAT = ARR_LAT
self.ARR_LON = ARR_LON
self.ARR_RESAMPLE_MAP_PARA = { "EDGE": {"N" :-999, "S":-999, "E":-999, "W":-999 } }
if len(ARR_LAT) != 0 and len(ARR_LON) != 0:
NUM_ARR_NY_T1 = len(ARR_LAT)
NUM_ARR_NY_T2 = len(ARR_LON)
Y_T2 = len(ARR_LON)
NUM_ARR_NX_T1 = len(ARR_LAT[0])
NUM_ARR_NX_T2 = len(ARR_LON[0])
self.NUM_NX = NUM_ARR_NX_T1
self.NUM_NY = NUM_ARR_NY_T1
if NUM_ARR_NY_T1 - NUM_ARR_NY_T2 + NUM_ARR_NX_T1 - NUM_ARR_NX_T2 != 0:
print("The gridcell of LAT is {0:d}&{1:d}, and LON is {2:d}&{3:d} are not match"\
.format(NUM_ARR_NY_T1,NUM_ARR_NY_T2,NUM_ARR_NX_T1,NUM_ARR_NX_T2))
def index_map(self, ARR_IN=[], NUM_IN_NX=0, NUM_IN_NY=0):
if len(ARR_IN) == 0:
self.INDEX_MAP = [[ self.NUM_NULL for i in range(self.NUM_NX)] for j in range(self.NUM_NY)]
NUM_ALL_INDEX = len(self.ARR_GRID)
for n in range(NUM_ALL_INDEX):
self.INDEX_MAP[self.ARR_GRID[n]["INDEX_J"]][self.ARR_GRID[n]["INDEX_I"]] =\
self.ARR_GRID[n]["INDEX"]
else:
MAP_INDEX = [[ self.NUM_NULL for i in range(NUM_IN_NX)] for j in range(NUM_IN_NY)]
NUM_ALL_INDEX = len(ARR_IN)
for n in range(NUM_ALL_INDEX):
MAP_INDEX[ARR_IN[n]["INDEX_J"]][ARR_IN[n]["INDEX_I"]] = ARR_IN[n]["INDEX"]
return MAP_INDEX
def add_an_element(self, ARR_GRID, NUM_INDEX=0, STR_VALUE=STR_VALUE_INIT, NUM_VALUE=NUM_VALUE_INIT ):
""" Adding an element to an empty array """
OBJ_ELEMENT = {"INDEX" : NUM_INDEX, \
STR_VALUE : NUM_VALUE}
ARR_GRID.append(OBJ_ELEMENT)
def add_an_geo_element(self, ARR_GRID, NUM_INDEX=-999, NUM_J=0, NUM_I=0, \
NUM_NX = 0, NUM_NY = 0, NUM_NT=0, \
ARR_VALUE_STR=[], ARR_VALUE_NUM=[] ):
""" Adding an geological element to an empty array
The information for lat and lon of center, edge, and vertex will
be stored for further used.
"""
NUM_NVAR = len(ARR_VALUE_STR)
if NUM_NX == 0 or NUM_NY == 0:
NUM_NX = self.NUM_NX
NUM_NY = self.NUM_NY
if NUM_NT == 0:
NUM_NT = self.NUM_NT
NUM_CENTER_LON = self.ARR_LON[NUM_J][NUM_I]
NUM_CENTER_LAT = self.ARR_LAT[NUM_J][NUM_I]
if NUM_I == 0:
NUM_WE_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5
NUM_EW_LON = -1 * ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5
elif NUM_I == NUM_NX - 1:
NUM_WE_LON = -1 * ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5
NUM_EW_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5
else:
NUM_WE_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5
NUM_EW_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5
if NUM_J == 0:
NUM_SN_LAT = -1 * ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5
NUM_NS_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5
elif NUM_J == NUM_NY - 1:
NUM_SN_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5
NUM_NS_LAT = -1 * ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5
else:
NUM_SN_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5
NUM_NS_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5
ARR_NE = [ NUM_CENTER_LON + NUM_EW_LON , NUM_CENTER_LAT + NUM_NS_LAT ]
ARR_NW = [ NUM_CENTER_LON + NUM_WE_LON , NUM_CENTER_LAT + NUM_NS_LAT ]
ARR_SE = [ NUM_CENTER_LON + NUM_EW_LON , NUM_CENTER_LAT + NUM_SN_LAT ]
ARR_SW = [ NUM_CENTER_LON + NUM_WE_LON , NUM_CENTER_LAT + NUM_SN_LAT ]
if NUM_INDEX == -999:
NUM_INDEX = self.NUM_LAST_INDEX +1
self.NUM_LAST_INDEX += 1
OBJ_ELEMENT = {"INDEX" : NUM_INDEX,\
"INDEX_I" : NUM_I,\
"INDEX_J" : NUM_J,\
"CENTER" : {"LAT" : NUM_CENTER_LAT, "LON" : NUM_CENTER_LON},\
"VERTEX" : {"NE": ARR_NE, "SE": ARR_SE, "SW": ARR_SW, "NW": ARR_NW},\
"EDGE" : {"N": NUM_CENTER_LAT + NUM_NS_LAT,"S": NUM_CENTER_LAT + NUM_SN_LAT,\
"E": NUM_CENTER_LON + NUM_EW_LON,"W": NUM_CENTER_LON + NUM_WE_LON}}
if len(ARR_VALUE_STR) > 0:
for I, VAR in enumerate(ARR_VALUE_STR):
OBJ_ELEMENT[VAR] = [{ "VALUE" : 0.0} for t in range(NUM_NT) ]
if len(ARR_VALUE_NUM) == NUM_NVAR:
for T in range(NUM_NT):
OBJ_ELEMENT[VAR][T]["VALUE"] = ARR_VALUE_NUM[I][T]
ARR_GRID.append(OBJ_ELEMENT)
def add_an_geo_variable(self, ARR_GRID, NUM_INDEX=-999, NUM_J=0, NUM_I=0, NUM_NT=0,\
STR_VALUE=STR_VALUE_INIT, NUM_VALUE=NUM_VALUE_INIT ):
if NUM_INDEX == -999:
NUM_INDEX = self.INDEX_MAP[NUM_J][NUM_I]
if NUM_NT == 0:
NUM_NT = self.NUM_NT
ARR_GRID[NUM_INDEX][STR_VALUE] = {{"VALUE": NUM_VALUE } for t in range(NUM_NT)}
def create_resample_lat_lon(self, ARR_RANGE_LAT=[0,0],NUM_EDGE_LAT=0,\
ARR_RANGE_LON=[0,0],NUM_EDGE_LON=0 ):
self.NUM_GRIDS_LON = round((ARR_RANGE_LON[1] - ARR_RANGE_LON[0])/NUM_EDGE_LON)
self.NUM_GRIDS_LAT = round((ARR_RANGE_LAT[1] - ARR_RANGE_LAT[0])/NUM_EDGE_LAT)
self.ARR_LAT = [[ 0 for i in range(self.NUM_GRIDS_LON)] for j in range(self.NUM_GRIDS_LAT) ]
self.ARR_LON = [[ 0 for i in range(self.NUM_GRIDS_LON)] for j in range(self.NUM_GRIDS_LAT) ]
for j in range(self.NUM_GRIDS_LAT):
for i in range(self.NUM_GRIDS_LON):
NUM_LAT = ARR_RANGE_LAT[0] + NUM_EDGE_LAT * j
NUM_LON = ARR_RANGE_LON[0] + NUM_EDGE_LON * i
self.ARR_LON[j][i] = ARR_RANGE_LON[0] + NUM_EDGE_LON * i
self.ARR_LAT[j][i] = ARR_RANGE_LAT[0] + NUM_EDGE_LAT * j
def create_reference_map(self, MAP_TARGET, MAP_RESAMPLE, STR_TYPE="FIX", NUM_SHIFT=0.001, IF_PB=False):
"""Must input with OBJ_REFERENCE
WARNING: The edge of gridcells may not be included due to the unfinished algorithm
"""
self.ARR_REFERENCE_MAP = []
if STR_TYPE=="GRIDBYGEO":
NUM_OBJ_G_LEN = len(MAP_TARGET)
for OBJ_G in MAP_TARGET:
NUM_G_COOR = [OBJ_G["CENTER"]["LAT"], OBJ_G["CENTER"]["LON"]]
for OBJ_R in MAP_RESAMPLE:
NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] - OBJ_G["CENTER"]["LON"])
NUM_CHK_IN_SN = (OBJ_R["EDGE"]["N"] - OBJ_G["CENTER"]["LAT"]) *\
(OBJ_R["EDGE"]["S"] - OBJ_G["CENTER"]["LAT"])
if NUM_CHK_IN_EW == 0: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_SN == 0: NUM_CHK_IN_SN = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_EW < 0 and NUM_CHK_IN_SN < 0:
OBJ_ELEMENT = {"INDEX" : OBJ_G["INDEX"],\
"CENTER" : OBJ_G["CENTER"],\
"INDEX_REF" : OBJ_R["INDEX"],\
"INDEX_REF_I" : OBJ_R["INDEX_I"],\
"INDEX_REF_J" : OBJ_R["INDEX_J"],\
"CENTER_REF" : OBJ_R["CENTER"],\
}
self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT)
break
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([OBJ_G["INDEX"]], [NUM_OBJ_G_LEN]), STR_DES="CREATING REFERENCE MAP")
elif STR_TYPE=="FIX":
NUM_OBJ_G_LEN = len(MAP_TARGET)
for OBJ_G in MAP_TARGET:
NUM_G_COOR = [OBJ_G["CENTER"]["LAT"], OBJ_G["CENTER"]["LON"]]
if self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] == -999 or self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] == -999:
NUM_CHK_EW_IN = -1
else:
NUM_CHK_EW_IN = (NUM_G_COOR[1] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] ) * ( NUM_G_COOR[1] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] )
if self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] == -999 or self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] == -999:
NUM_CHK_SN_IN = -1
else:
NUM_CHK_SN_IN = (NUM_G_COOR[0] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] ) * ( NUM_G_COOR[0] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] )
if NUM_CHK_EW_IN < 0 and NUM_CHK_SN_IN < 0:
for OBJ_R in MAP_RESAMPLE:
NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] - OBJ_G["CENTER"]["LON"])
NUM_CHK_IN_SN = (OBJ_R["EDGE"]["N"] - OBJ_G["CENTER"]["LAT"]) *\
(OBJ_R["EDGE"]["S"] - OBJ_G["CENTER"]["LAT"])
if NUM_CHK_IN_EW == 0: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_SN == 0: NUM_CHK_IN_SN = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_EW < 0 and NUM_CHK_IN_SN < 0:
OBJ_ELEMENT = {"INDEX" : OBJ_G["INDEX"],\
"INDEX_I" : OBJ_G["INDEX_I"],\
"INDEX_J" : OBJ_G["INDEX_J"],\
"CENTER" : OBJ_G["CENTER"],\
"INDEX_REF" : OBJ_R["INDEX"],\
"INDEX_REF_I" : OBJ_R["INDEX_I"],\
"INDEX_REF_J" : OBJ_R["INDEX_J"],\
"CENTER_REF" : OBJ_R["CENTER"],\
}
self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT)
break
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([OBJ_G["INDEX"]], [NUM_OBJ_G_LEN]), STR_DES="CREATING REFERENCE MAP")
def export_grid_map(self, ARR_GRID_IN, STR_DIR, STR_FILENAME, ARR_VAR_STR=[],\
ARR_VAR_ITEM=["MEAN", "MEDIAN", "MIN", "MAX", "P95", "P75", "P25", "P05"],\
NUM_NX=0, NUM_NY=0, NUM_NT=0, STR_TYPE="netCDF4", IF_PB=False ):
TIME_NOW = time.gmtime()
STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday)
STR_TIME_NOW = "{0:04d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec)
if NUM_NX==0: NUM_NX = self.NUM_NX
if NUM_NY==0: NUM_NY = self.NUM_NY
if NUM_NT==0: NUM_NT = self.NUM_NT
if STR_TYPE == "netCDF4":
NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'w', format="NETCDF4")
# CREATE ATTRIBUTEs:
NCDF4_DATA.description = \
"The grid information in netCDF4"
NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(STR_DATE_NOW, STR_TIME_NOW)
# CREATE DIMENSIONs:
NCDF4_DATA.createDimension("Y" , NUM_NY )
NCDF4_DATA.createDimension("X" , NUM_NX )
NCDF4_DATA.createDimension("Time" , NUM_NT )
NCDF4_DATA.createDimension("Values", None )
# CREATE BASIC VARIABLES:
NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X"))
NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X"))
NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X"))
NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X"))
NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X"))
# CREATE GROUP for Variables:
for VAR in ARR_VAR_STR:
NCDF4_DATA.createGroup(VAR)
for ITEM in ARR_VAR_ITEM:
if ITEM == "VALUE" :
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X", "Values"))
else:
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X"))
# WRITE IN VARIABLE
for V in ["INDEX", "INDEX_J", "INDEX_I"]:
map_in = self.convert_grid2map(ARR_GRID_IN, V, NX=NUM_NX, NY=NUM_NY, NC_TYPE="INT")
for n in range(len(map_in)):
NCDF4_DATA.variables[V][n] = map_in[n]
for V1 in ["CENTER"]:
for V2 in ["LON", "LAT"]:
map_in = self.convert_grid2map(ARR_GRID_IN, V1, V2, NX=NUM_NX, NY=NUM_NY, NC_TYPE="FLOAT")
for n in range(len(map_in)):
NCDF4_DATA.variables["{0:s}_{1:s}".format(V1, V2)][n] = map_in[n]
for V1 in ARR_VAR_STR:
for V2 in ARR_VAR_ITEM:
map_in = self.convert_grid2map(ARR_GRID_IN, V1, V2, NX=NUM_NX, NY=NUM_NY, NT=NUM_NT)
for n in range(len(map_in)):
NCDF4_DATA.groups[V1].variables[V2][n] = map_in[n]
NCDF4_DATA.close()
def export_grid(self, ARR_GRID_IN, STR_DIR, STR_FILENAME, ARR_VAR_STR=[],\
ARR_VAR_ITEM=["VALUE", "MEAN", "MEDIAN", "MIN", "MAX", "P95", "P75", "P25", "P05"],\
NUM_NX=0, NUM_NY=0, NUM_NT=0, STR_TYPE="netCDF4", IF_PB=False ):
TIME_NOW = time.gmtime()
STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday)
STR_TIME_NOW = "{0:04d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec)
if NUM_NX==0: NUM_NX = self.NUM_NX
if NUM_NY==0: NUM_NY = self.NUM_NY
if NUM_NT==0: NUM_NT = self.NUM_NT
if STR_TYPE == "netCDF4":
NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'w', format="NETCDF4")
# CREATE ATTRIBUTEs:
NCDF4_DATA.description = \
"The grid information in netCDF4"
NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(STR_DATE_NOW, STR_TIME_NOW)
# CREATE DIMENSIONs:
NCDF4_DATA.createDimension("Y" , NUM_NY )
NCDF4_DATA.createDimension("X" , NUM_NX )
NCDF4_DATA.createDimension("Time" , NUM_NT )
NCDF4_DATA.createDimension("Values", None )
# CREATE BASIC VARIABLES:
INDEX = NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X"))
INDEX_J = NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X"))
INDEX_I = NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X"))
CENTER_LON = NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X"))
CENTER_LAT = NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X"))
# CREATE GROUP for Variables:
for VAR in ARR_VAR_STR:
NCDF4_DATA.createGroup(VAR)
for ITEM in ARR_VAR_ITEM:
if ITEM == "VALUE" :
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X", "Values"))
else:
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X"))
# WRITE IN VARIABLE
for IND, OBJ in enumerate(ARR_GRID_IN):
j = OBJ["INDEX_J"]
i = OBJ["INDEX_I"]
INDEX [j,i] = OBJ["INDEX"]
INDEX_J [j,i] = OBJ["INDEX_J"]
INDEX_I [j,i] = OBJ["INDEX_I"]
CENTER_LON [j,i] = OBJ["CENTER"]["LON"]
CENTER_LAT [j,i] = OBJ["CENTER"]["LAT"]
for VAR in ARR_VAR_STR:
for ITEM in ARR_VAR_ITEM:
for T in range(NUM_NT):
NCDF4_DATA.groups[VAR].variables[ITEM][T,j,i] = OBJ[VAR][T][ITEM]
if IF_PB: TOOLS.progress_bar((IND+1)/(NUM_NX*NUM_NY), STR_DES="WRITING PROGRESS")
NCDF4_DATA.close()
def export_reference_map(self, STR_DIR, STR_FILENAME, STR_TYPE="netCDF4", IF_PB=False, IF_PARALLEL=False ):
TIME_NOW = time.gmtime()
self.STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday)
self.STR_TIME_NOW = "{0:02d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec)
STR_INPUT_FILENAME = "{0:s}/{1:s}".format(STR_DIR, STR_FILENAME)
if STR_TYPE == "netCDF4":
IF_FILECHK = os.path.exists(STR_INPUT_FILENAME)
if IF_FILECHK:
NCDF4_DATA = NC.Dataset(STR_INPUT_FILENAME, 'a', format="NETCDF4", parallel=IF_PARALLEL)
INDEX = NCDF4_DATA.variables["INDEX" ]
INDEX_J = NCDF4_DATA.variables["INDEX_J" ]
INDEX_I = NCDF4_DATA.variables["INDEX_I" ]
CENTER_LON = NCDF4_DATA.variables["CENTER_LON" ]
CENTER_LAT = NCDF4_DATA.variables["CENTER_LAT" ]
INDEX_REF = NCDF4_DATA.variables["INDEX_REF" ]
INDEX_REF_J = NCDF4_DATA.variables["INDEX_REF_J" ]
INDEX_REF_I = NCDF4_DATA.variables["INDEX_REF_I" ]
CENTER_REF_LON = NCDF4_DATA.variables["CENTER_REF_LON" ]
CENTER_REF_LAT = NCDF4_DATA.variables["CENTER_REF_LAT" ]
else:
NCDF4_DATA = NC.Dataset(STR_INPUT_FILENAME, 'w', format="NETCDF4", parallel=IF_PARALLEL)
# CREATE ATTRIBUTEs:
NCDF4_DATA.description = \
"The netCDF4 version of reference map which contains grid information for resampling"
NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(self.STR_DATE_NOW, self.STR_TIME_NOW)
# CREATE DIMENSIONs:
NCDF4_DATA.createDimension("Y",self.NUM_NY)
NCDF4_DATA.createDimension("X",self.NUM_NX)
# CREATE_VARIABLES:
INDEX = NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X"))
INDEX_J = NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X"))
INDEX_I = NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X"))
CENTER_LON = NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X"))
CENTER_LAT = NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X"))
INDEX_REF = NCDF4_DATA.createVariable("INDEX_REF", "i4", ("Y", "X"))
INDEX_REF_J = NCDF4_DATA.createVariable("INDEX_REF_J", "i4", ("Y", "X"))
INDEX_REF_I = NCDF4_DATA.createVariable("INDEX_REF_I", "i4", ("Y", "X"))
CENTER_REF_LON = NCDF4_DATA.createVariable("CENTER_REF_LON", "f8", ("Y", "X"))
CENTER_REF_LAT = NCDF4_DATA.createVariable("CENTER_REF_LAT", "f8", ("Y", "X"))
NUM_TOTAL_OBJ = len(self.ARR_REFERENCE_MAP)
NUM_MAX_I = self.NUM_NX
for OBJ in self.ARR_REFERENCE_MAP:
j = OBJ["INDEX_J"]
i = OBJ["INDEX_I"]
INDEX[j,i] = OBJ["INDEX"]
INDEX_J[j,i] = OBJ["INDEX_J"]
INDEX_I[j,i] = OBJ["INDEX_I"]
INDEX_REF[j,i] = OBJ["INDEX_REF"]
INDEX_REF_J[j,i] = OBJ["INDEX_REF_J"]
INDEX_REF_I[j,i] = OBJ["INDEX_REF_I"]
CENTER_LON [j,i] = OBJ["CENTER"]["LON"]
CENTER_LAT [j,i] = OBJ["CENTER"]["LAT"]
CENTER_REF_LON [j,i] = OBJ["CENTER_REF"]["LON"]
CENTER_REF_LAT [j,i] = OBJ["CENTER_REF"]["LAT"]
if IF_PB: TOOLS.progress_bar((i+j*NUM_MAX_I)/float(NUM_TOTAL_OBJ), STR_DES="Exporting")
NCDF4_DATA.close()
def import_reference_map(self, STR_DIR, STR_FILENAME, ARR_X_RANGE=[], ARR_Y_RANGE=[], STR_TYPE="netCDF4", IF_PB=False):
self.ARR_REFERENCE_MAP = []
self.NUM_MAX_INDEX_RS = 0
self.NUM_MIN_INDEX_RS = 999
if len(ARR_X_RANGE) != 0:
self.I_MIN = ARR_X_RANGE[0]
self.I_MAX = ARR_X_RANGE[1]
else:
self.I_MIN = 0
self.I_MAX = self.REFERENCE_MAP_NX
if len(ARR_Y_RANGE) != 0:
self.J_MIN = ARR_Y_RANGE[0]
self.J_MAX = ARR_Y_RANGE[1]
else:
self.J_MIN = 0
self.J_MAX = self.REFERENCE_MAP_NY
if STR_TYPE == "netCDF4":
NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'r', format="NETCDF4")
# READ DIMENSIONs:
self.REFERENCE_MAP_NY = NCDF4_DATA.dimensions["Y"].size
self.REFERENCE_MAP_NX = NCDF4_DATA.dimensions["X"].size
# CREATE_VARIABLES:
INDEX = NCDF4_DATA.variables["INDEX" ]
INDEX_J = NCDF4_DATA.variables["INDEX_J" ]
INDEX_I = NCDF4_DATA.variables["INDEX_I" ]
CENTER_LON = NCDF4_DATA.variables["CENTER_LON" ]
CENTER_LAT = NCDF4_DATA.variables["CENTER_LAT" ]
INDEX_REF = NCDF4_DATA.variables["INDEX_REF" ]
INDEX_REF_J = NCDF4_DATA.variables["INDEX_REF_J" ]
INDEX_REF_I = NCDF4_DATA.variables["INDEX_REF_I" ]
CENTER_REF_LON = NCDF4_DATA.variables["CENTER_REF_LON" ]
CENTER_REF_LAT = NCDF4_DATA.variables["CENTER_REF_LAT" ]
for j in range(self.J_MIN, self.J_MAX):
for i in range(self.I_MIN, self.I_MAX):
OBJ_ELEMENT = {"INDEX" : 0 ,\
"INDEX_I" : 0 ,\
"INDEX_J" : 0 ,\
"CENTER" : {"LAT": 0.0, "LON": 0.0} ,\
"INDEX_REF" : 0 ,\
"INDEX_REF_I" : 0 ,\
"INDEX_REF_J" : 0 ,\
"CENTER_REF" : {"LAT": 0.0, "LON": 0.0} }
if INDEX [j][i] != None:
OBJ_ELEMENT["INDEX"] = INDEX [j][i]
OBJ_ELEMENT["INDEX_J"] = INDEX_J [j][i]
OBJ_ELEMENT["INDEX_I"] = INDEX_I [j][i]
OBJ_ELEMENT["INDEX_REF"] = INDEX_REF [j][i]
OBJ_ELEMENT["INDEX_REF_J"] = INDEX_REF_J [j][i]
OBJ_ELEMENT["INDEX_REF_I"] = INDEX_REF_I [j][i]
OBJ_ELEMENT["CENTER"]["LAT"] = CENTER_LAT [j][i]
OBJ_ELEMENT["CENTER"]["LON"] = CENTER_LON [j][i]
OBJ_ELEMENT["CENTER_REF"]["LAT"] = CENTER_REF_LAT[j][i]
OBJ_ELEMENT["CENTER_REF"]["LON"] = CENTER_REF_LON[j][i]
else:
OBJ_ELEMENT["INDEX"] = INDEX [j][i]
OBJ_ELEMENT["INDEX_I"] = INDEX_J [j][i]
OBJ_ELEMENT["INDEX_J"] = INDEX_I [j][i]
OBJ_ELEMENT["INDEX_REF"] = -999
OBJ_ELEMENT["INDEX_REF_J"] = -999
OBJ_ELEMENT["INDEX_REF_I"] = -999
OBJ_ELEMENT["CENTER"]["LAT"] = CENTER_LAT [j][i]
OBJ_ELEMENT["CENTER"]["LON"] = CENTER_LON [j][i]
OBJ_ELEMENT["CENTER_REF"]["LAT"] = -999
OBJ_ELEMENT["CENTER_REF"]["LON"] = -999
self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT)
self.NUM_MIN_INDEX_RS = min(self.NUM_MIN_INDEX_RS, INDEX_REF[j][i])
self.NUM_MAX_INDEX_RS = max(self.NUM_MAX_INDEX_RS, INDEX_REF[j][i])
if IF_PB: TOOLS.progress_bar((j - self.J_MIN + 1)/float(self.J_MAX - self.J_MIN), STR_DES="IMPORTING")
if self.NUM_MIN_INDEX_RS == 0:
self.NUM_MAX_RS = self.NUM_MAX_INDEX_RS + 1
NCDF4_DATA.close()
def create_resample_map(self, ARR_REFERENCE_MAP=[], ARR_VARIABLES=["Value"], ARR_GRID_IN=[],\
IF_PB=False, NUM_NT=0, NUM_NX=0, NUM_NY=0, NUM_NULL=-9999.999):
if NUM_NT == 0:
NUM_NT = self.NUM_NT
if NUM_NX == 0:
NUM_NX = self.NUM_NX
if NUM_NY == 0:
NUM_NY = self.NUM_NY
if len(ARR_REFERENCE_MAP) == 0:
self.ARR_RESAMPLE_OUT = []
self.ARR_RESAMPLE_OUT_PARA = {"EDGE": {"N": 0.0,"S": 0.0,"E": 0.0,"W": 0.0}}
NUM_END_J = self.NUM_GRIDS_LAT - 1
NUM_END_I = self.NUM_GRIDS_LON - 1
ARR_EMPTY = [float("NaN") for n in range(self.NUM_NT)]
for J in range(self.NUM_GRIDS_LAT):
for I in range(self.NUM_GRIDS_LON):
NUM_IND = I + J * self.NUM_GRIDS_LON
self.add_an_geo_element(self.ARR_RESAMPLE_OUT, NUM_INDEX=NUM_IND, NUM_J=J, NUM_I=I, \
NUM_NX= self.NUM_GRIDS_LON, NUM_NY= self.NUM_GRIDS_LAT,\
ARR_VALUE_STR=ARR_VARIABLES, NUM_NT=NUM_NT)
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] = max( self.ARR_LAT[NUM_END_J][0], self.ARR_LAT[NUM_END_J][NUM_END_I] )
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] = min( self.ARR_LAT[0][0], self.ARR_LAT[0][NUM_END_I] )
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] = min( self.ARR_LAT[0][0], self.ARR_LAT[NUM_END_J][0] )
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] = max( self.ARR_LAT[0][NUM_END_I], self.ARR_LAT[NUM_END_J][NUM_END_I] )
self.NUM_MAX_INDEX_RS = NUM_IND
else:
if ARR_GRID_IN == []: ARR_GRID_IN = self.ARR_GRID
self.ARR_RESAMPLE_OUT = [ {} for n in range(NUM_NX * NUM_NY)]
for IND in range(len(self.ARR_RESAMPLE_OUT)):
for VAR in ARR_VARIABLES:
self.ARR_RESAMPLE_OUT[IND][VAR] = [{"VALUE" : []} for T in range(NUM_NT) ]
#for IND in range(len(ARR_REFERENCE_MAP)):
for IND in range(len(ARR_GRID_IN)):
R_IND = ARR_REFERENCE_MAP[IND]["INDEX_REF"]
R_J = ARR_REFERENCE_MAP[IND]["INDEX_REF_J"]
R_I = ARR_REFERENCE_MAP[IND]["INDEX_REF_I"]
R_IND_FIX = TOOLS.fix_ind(R_IND, R_J, R_I, ARR_XRANGE=self.ARR_RESAMPLE_LIM_X, ARR_YRANGE=self.ARR_RESAMPLE_LIM_Y, NX=NUM_NX, NY=NUM_NY)
if R_IND != None:
for VAR in ARR_VARIABLES:
for T in range(NUM_NT):
#print("R_IND:{0:d}, T:{1:d}, IND:{2:d} ".format(R_IND, T, IND))
NUM_VAL_IN = ARR_GRID_IN[IND][VAR][T]["VALUE"]
self.ARR_RESAMPLE_OUT[R_IND][VAR][T]["VALUE"].append(NUM_VAL_IN)
self.ARR_RESAMPLE_OUT[R_IND]["INDEX"] = ARR_REFERENCE_MAP[IND]["INDEX_REF"]
self.ARR_RESAMPLE_OUT[R_IND]["INDEX_J"] = ARR_REFERENCE_MAP[IND]["INDEX_REF_J"]
self.ARR_RESAMPLE_OUT[R_IND]["INDEX_I"] = ARR_REFERENCE_MAP[IND]["INDEX_REF_I"]
self.ARR_RESAMPLE_OUT[R_IND]["CENTER"] = {"LAT": 0.0, "LON": 0.0 }
self.ARR_RESAMPLE_OUT[R_IND]["CENTER"]["LAT"] = ARR_REFERENCE_MAP[IND]["CENTER"]["LAT"]
self.ARR_RESAMPLE_OUT[R_IND]["CENTER"]["LON"] = ARR_REFERENCE_MAP[IND]["CENTER"]["LON"]
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([IND], [len(ARR_GRID_IN)]), STR_DES="RESAMPLING PROGRESS")
def cal_resample_map(self, ARR_VARIABLES, ARR_GRID_IN=[], NUM_NT=0, IF_PB=False, \
DIC_PERCENTILE={ "P05": 0.05, "P10": 0.1, "P25": 0.25, "P75": 0.75, "P90": 0.90, "P95": 0.95}, NUM_NULL=-9999.999):
if NUM_NT == 0:
NUM_NT = self.NUM_NT
NUM_RS_OUT_LEN = len(self.ARR_RESAMPLE_OUT)
for IND in range(NUM_RS_OUT_LEN):
for VAR in ARR_VARIABLES:
for T in range(NUM_NT):
ARR_IN = self.ARR_RESAMPLE_OUT[IND][VAR][T]["VALUE"]
if len(ARR_IN) > 0:
ARR_IN.sort()
NUM_ARR_LEN = len(ARR_IN)
NUM_ARR_MEAN = sum(ARR_IN) / float(NUM_ARR_LEN)
NUM_ARR_S2SUM = 0
if math.fmod(NUM_ARR_LEN,2) == 1:
NUM_MPOS = [int((NUM_ARR_LEN-1)/2.0), int((NUM_ARR_LEN-1)/2.0)]
else:
NUM_MPOS = [int(NUM_ARR_LEN/2.0) , int(NUM_ARR_LEN/2.0 -1) ]
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MIN"] = min(ARR_IN)
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MAX"] = max(ARR_IN)
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MEAN"] = NUM_ARR_MEAN
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MEDIAN"] = ARR_IN[NUM_MPOS[0]] *0.5 + ARR_IN[NUM_MPOS[1]] *0.5
for STVA in DIC_PERCENTILE:
self.ARR_RESAMPLE_OUT[IND][VAR][T][STVA] = ARR_IN[ round(NUM_ARR_LEN * DIC_PERCENTILE[STVA])-1]
for VAL in ARR_IN:
NUM_ARR_S2SUM += (VAL - NUM_ARR_MEAN)**2
self.ARR_RESAMPLE_OUT[IND][VAR][T]["STD"] = (NUM_ARR_S2SUM / max(1, NUM_ARR_LEN-1))**0.5
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([IND], [NUM_RS_OUT_LEN]), STR_DES="RESAMPLING CALCULATION")
def convert_grid2map(self, ARR_GRID_IN, STR_VAR, STR_VAR_TYPE="", NX=0, NY=0, NT=0, IF_PB=False, NC_TYPE=""):
if NC_TYPE == "INT":
if NT == 0:
ARR_OUT = NP.empty([NY, NX], dtype=NP.int8)
else:
ARR_OUT = NP.empty([NT, NY, NX], dtype=NP.int8)
elif NC_TYPE == "FLOAT":
if NT == 0:
ARR_OUT = NP.empty([NY, NX], dtype=NP.float64)
else:
ARR_OUT = NP.empty([NT, NY, NX], dtype=NP.float64)
else:
if NT == 0:
ARR_OUT = [[ self.NUM_NULL for i in range(NX)] for j in range(NY) ]
else:
ARR_OUT = [[[ self.NUM_NULL for i in range(NX)] for j in range(NY) ] for t in range(NT)]
if STR_VAR_TYPE == "":
for I, GRID in enumerate(ARR_GRID_IN):
if GRID["INDEX"] != -999:
if NT == 0:
#print(GRID["INDEX_J"], GRID["INDEX_I"], GRID[STR_VAR])
ARR_OUT[ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR]
else:
for T in range(NT):
ARR_OUT[T][ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][T]
if IF_PB==True: TOOLS.progress_bar(((I+1)/(len(ARR_GRID_IN))))
else:
for I, GRID in enumerate(ARR_GRID_IN):
if GRID["INDEX"] != -999:
if NT == 0:
ARR_OUT[ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][STR_VAR_TYPE]
else:
for T in range(NT):
ARR_OUT[T][ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][T][STR_VAR_TYPE]
if IF_PB==True: TOOLS.progress_bar(((I+1)/(len(ARR_GRID_IN))))
return ARR_OUT
def mask_grid(self, ARR_GRID_IN, STR_VAR, STR_VAR_TYPE, NUM_NT=0, STR_MASK="MASK",\
ARR_NUM_DTM=[0,1,2], ARR_NUM_DTM_RANGE=[0,1]):
if NUM_NT == 0:
NUM_NT= self.NUM_NT
for IND, GRID in enumerate(ARR_GRID_IN):
for T in range(NUM_NT):
NUM_DTM = GEO_TOOLS.mask_dtm(GRID[STR_VAR][T][STR_VAR_TYPE], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE)
ARR_GRID_IN[IND][STR_VAR][T][STR_MASK] = NUM_DTM
class MATH_TOOLS:
""" Some math tools that help us to calculate.
gau_kde: kernel density estimator by Gaussian Function
standard_dev: The Standard deviation
"""
def GaussJordanEli(arr_in):
num_ydim = len(arr_in)
num_xdim = len(arr_in[0])
arr_out = arr_in
if num_ydim -num_xdim == 0 or num_xdim - num_ydim == 1:
arr_i = NP.array([[0.0 for j in range(num_ydim)] for i in range(num_ydim)])
for ny in range(num_ydim):
arr_i[ny][ny] = 1.0
#print(arr_i)
for nx in range(num_xdim):
for ny in range(nx+1, num_ydim):
arr_i [ny] = arr_i [ny] - arr_i [nx] * arr_out[ny][nx] / float(arr_out[nx][nx])
arr_out[ny] = arr_out[ny] - arr_out[nx] * arr_out[ny][nx] / float(arr_out[nx][nx])
if num_xdim - num_ydim == 1:
for nx in range(num_xdim-1,-1,-1):
for ny in range(num_ydim-1,nx, -1):
print(nx,ny)
arr_i [nx] = arr_i [nx] - arr_i [ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
arr_out[nx] = arr_out[nx] - arr_out[ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
else:
for nx in range(num_xdim,-1,-1):
for ny in range(num_ydim-1, nx, -1):
print(nx,ny)
arr_i [nx] = arr_i [nx] - arr_i [ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
arr_out[nx] = arr_out[nx] - arr_out[ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
if num_xdim - num_ydim == 1:
arr_sol = [0.0 for n in range(num_ydim)]
for ny in range(num_ydim):
arr_sol[ny] = arr_out[ny][num_xdim-1]/arr_out[ny][ny]
return arr_out, arr_i, arr_sol
else:
return arr_out, arr_i
else:
print("Y dim: {0:d}, X dim: {1:d}: can not apply Gaussian-Jordan".format(num_ydim, num_xdim))
return [0]
def finding_XM_LSM(arr_in1, arr_in2, m=2):
# Finding the by least square method
arr_out=[[0.0 for i in range(m+2)] for j in range(m+1)]
arr_x_power_m = [0.0 for i in range(m+m+1)]
arr_xy_power_m = [0.0 for i in range(m+1)]
for n in range(len(arr_x_power_m)):
for x in range(len(arr_in1)):
arr_x_power_m[n] += arr_in1[x] ** n
for n in range(len(arr_xy_power_m)):
for x in range(len(arr_in1)):
arr_xy_power_m[n] += arr_in1[x] ** n * arr_in2[x]
for j in range(m+1):
for i in range(j,j+m+1):
arr_out[j][i-j] = arr_x_power_m[i]
arr_out[j][m+1] = arr_xy_power_m[j]
return arr_out
def cal_modelperform (arr_obs , arr_sim , num_empty=-999.999):
# Based on Vazquez et al. 2002 (Hydrol. Process.)
num_arr = len(arr_obs)
num_n_total = num_arr
num_sum = 0
num_obs_sum = 0
for n in range( num_arr ):
if math.isnan(arr_obs[n]) or arr_obs[n] == num_empty:
num_n_total += -1
else:
num_sum = num_sum + ( arr_sim[n] - arr_obs[n] ) ** 2
num_obs_sum = num_obs_sum + arr_obs[n]
if num_n_total == 0 or num_obs_sum == 0:
RRMSE = -999.999
RMSE = -999.999
obs_avg = -999.999
else:
RRMSE = ( num_sum / num_n_total ) ** 0.5 * ( num_n_total / num_obs_sum )
RMSE = ( num_sum / num_n_total ) ** 0.5
obs_avg = num_obs_sum / num_n_total
num_n_total = num_arr
oo_sum = 0
po_sum = 0
for nn in range( num_arr ):
if math.isnan(arr_obs[nn]) or arr_obs[nn] == num_empty:
num_n_total = num_n_total - 1
else:
oo_sum = oo_sum + ( arr_obs[nn] - obs_avg ) ** 2
po_sum = po_sum + ( arr_sim[nn] - arr_obs[nn] ) ** 2
if num_n_total == 0 or oo_sum * po_sum == 0:
EF = -999.999
CD = -999.999
else:
EF = ( oo_sum - po_sum ) / oo_sum
CD = oo_sum / po_sum
return RRMSE,EF,CD,RMSE, num_arr
def cal_kappa(ARR_IN, NUM_n=0, NUM_N=0, NUM_k=0):
""" Fleiss' kappa
Mustt input with ARR_IN in the following format:
ARR_IN = [ [ NUM for k in range(catalogue)] for N in range(Subjects)]
Additional parameters: NUM_n is the number of raters (e.g. sim and obs results)
Additional parameters: NUM_N is the number of subjects (e.g the outputs
Additional parameters: NUM_k is the number of catalogue (e.g. results )
"""
if NUM_N == 0:
NUM_N = len(ARR_IN)
if NUM_n == 0:
NUM_n = sum(ARR_IN[0])
if NUM_k == 0:
NUM_k = len(ARR_IN[0])
ARR_p_out = [ 0 for n in range(NUM_k)]
ARR_P_OUT = [ 0 for n in range(NUM_N)]
for N in range(NUM_N):
for k in range(NUM_k):
ARR_p_out[k] += ARR_IN[N][k]
ARR_P_OUT[N] += ARR_IN[N][k] ** 2
ARR_P_OUT[N] -= NUM_n
ARR_P_OUT[N] = ARR_P_OUT[N] * (1./(NUM_n *(NUM_n - 1)))
for k in range(NUM_k):
ARR_p_out[k] = ARR_p_out[k] / (NUM_N * NUM_n)
NUM_P_BAR = 0
for N in range(NUM_N):
NUM_P_BAR += ARR_P_OUT[N]
NUM_P_BAR = NUM_P_BAR / float(NUM_N)
NUM_p_bar = 0
for k in ARR_p_out:
NUM_p_bar += k **2
return (NUM_P_BAR - NUM_p_bar) / (1 - NUM_p_bar)
def gau_kde(ARR_IN_X, ARR_IN_I, NUM_BW=0.1 ):
NUM_SUM = 0.
NUM_LENG = len(ARR_IN_X)
ARR_OUT = [ 0. for n in range(NUM_LENG)]
for IND_J, J in enumerate(ARR_IN_X):
NUM_SUM = 0.0
for I in ARR_IN_I:
NUM_SUM += 1 / (2 * math.pi)**0.5 * math.e ** (-0.5 * ((J-I)/NUM_BW) ** 2 )
ARR_OUT[IND_J] = NUM_SUM / len(ARR_IN_I) / NUM_BW
return ARR_OUT
def standard_dev(ARR_IN):
NUM_SUM = sum(ARR_IN)
NUM_N = len(ARR_IN)
NUM_MEAN = 1.0*NUM_SUM/NUM_N
NUM_SUM2 = 0.0
for N in ARR_IN:
if not math.isnan(N):
NUM_SUM2 = (N-NUM_MEAN)**2
else:
NUM_N += -1
return (NUM_SUM2 / (NUM_N-1)) ** 0.5
def h_esti(ARR_IN):
#A rule-of-thumb bandwidth estimator
NUM_SIGMA = standard_dev(ARR_IN)
NUM_N = len(ARR_IN)
return ((4 * NUM_SIGMA ** 5) / (3*NUM_N) ) ** 0.2
def data2array(ARR_IN, STR_IN="MEAN"):
NUM_J = len(ARR_IN)
NUM_I = len(ARR_IN[0])
ARR_OUT = [[ 0.0 for i in range(NUM_I)] for j in range(NUM_J) ]
for j in range(NUM_J):
for i in range(NUM_I):
ARR_OUT[j][i] = ARR_IN[j][i][STR_IN]
return ARR_OUT
def reshape2d(ARR_IN):
ARR_OUT=[]
for A in ARR_IN:
for B in A:
ARR_OUT.append(B)
return ARR_OUT
def NormalVector( V1, V2):
return [(V1[1]*V2[2] - V1[2]*V2[1]), (V1[2]*V2[0] - V1[0]*V2[2]),(V1[0]*V2[1] - V1[1]*V2[0])]
def NVtoPlane( P0, P1, P2):
"""Input of P should be 3-dimensionals"""
V1 = [(P1[0]-P0[0]),(P1[1]-P0[1]),(P1[2]-P0[2])]
V2 = [(P2[0]-P0[0]),(P2[1]-P0[1]),(P2[2]-P0[2])]
ARR_NV = MATH_TOOLS.NormalVector(V1, V2)
D = ARR_NV[0] * P0[0] + ARR_NV[1] * P0[1] + ARR_NV[2] * P0[2]
return ARR_NV[0],ARR_NV[1],ARR_NV[2],D
def FindZatP3( P0, P1, P2, P3):
""" input of P: (X,Y,Z); but P3 is (X,Y) only """
A,B,C,D = MATH_TOOLS.NVtoPlane(P0, P1, P2)
return (D-A*P3[0] - B*P3[1])/float(C)
class TOOLS:
""" TOOLS is contains:
timestamp
fix_ind
progress_bar
cal_progrss
"""
ARR_HOY = [0, 744, 1416, 2160, 2880, 3624, 4344, 5088, 5832, 6552, 7296, 8016, 8760]
ARR_HOY_LEAP = [0, 744, 1440, 2184, 2904, 3648, 4368, 5112, 5856, 6576, 7320, 8040, 8784]
def NNARR(ARR_IN, IF_PAIRING=False):
"Clean the NaN value in the array"
if IF_PAIRING:
ARR_SIZE = len(ARR_IN)
ARR_OUT = [ [] for N in range(ARR_SIZE)]
for ind_n, N in enumerate(ARR_IN[0]):
IF_NAN = False
for ind_a in range(ARR_SIZE):
if math.isnan(ARR_IN[ind_a][ind_n]):
IF_NAN = True
break
if not IF_NAN:
for ind_a in range(ARR_SIZE):
ARR_OUT[ind_a].append(ARR_IN[ind_a][ind_n])
else:
ARR_OUT = [ ]
for N in ARR_IN:
if not math.isnan(N):
ARR_OUT.append(N)
return ARR_OUT
def DATETIME2HOY(ARR_TIME, ARR_HOY_IN=[]):
if math.fmod(ARR_TIME[0], 4) == 0 and len(ARR_HOY_IN) == 0:
ARR_HOY_IN = [0, 744, 1440, 2184, 2904, 3648, 4368, 5112, 5856, 6576, 7320, 8040, 8784]
elif math.fmod(ARR_TIME[0], 4) != 0 and len(ARR_HOY_IN) == 0:
ARR_HOY_IN = [0, 744, 1416, 2160, 2880, 3624, 4344, 5088, 5832, 6552, 7296, 8016, 8760]
else:
ARR_HOY_IN = ARR_HOY_IN
return ARR_HOY_IN[ARR_TIME[1]-1] + (ARR_TIME[2]-1)*24 + ARR_TIME[3]
def timestamp(STR_IN=""):
print("{0:04d}-{1:02d}-{2:02d}_{3:02d}:{4:02d}:{5:02d} {6:s}".format(time.gmtime().tm_year, time.gmtime().tm_mon, time.gmtime().tm_mday,\
time.gmtime().tm_hour, time.gmtime().tm_min, time.gmtime().tm_sec, STR_IN) )
def fix_ind(IND_IN, IND_J, IND_I, ARR_XRANGE=[], ARR_YRANGE=[], NX=0, NY=0):
NUM_DY = ARR_YRANGE[0]
NUM_NX_F = ARR_XRANGE[0]
NUM_NX_R = NX - (ARR_XRANGE[1]+1)
if IND_J == ARR_YRANGE[0]:
IND_OUT = IND_IN - NUM_DY * NX - NUM_NX_F
else:
IND_OUT = IND_IN - NUM_DY * NX - NUM_NX_F * (IND_J - NUM_DY +1) - NUM_NX_R * (IND_J - NUM_DY)
return IND_OUT
def progress_bar(NUM_PROGRESS, NUM_PROGRESS_BIN=0.05, STR_SYS_SYMBOL="=", STR_DES="Progress"):
NUM_SYM = int(NUM_PROGRESS / NUM_PROGRESS_BIN)
sys.stdout.write('\r')
sys.stdout.write('[{0:20s}] {1:4.2f}% {2:s}'.format(STR_SYS_SYMBOL*NUM_SYM, NUM_PROGRESS*100, STR_DES))
sys.stdout.flush()
def clean_arr(ARR_IN, CRITERIA=1):
ARR_OUT=[]
for i,n in enumerate(ARR_IN):
if len(n)> CRITERIA:
ARR_OUT.append(n)
return ARR_OUT
def cal_loop_progress(ARR_INDEX, ARR_INDEX_MAX, NUM_CUM_MAX=1, NUM_CUM_IND=1, NUM_TOTAL_MAX=1):
""" Please list from smallest to largest, i.e.: x->y->z """
if len(ARR_INDEX) == len(ARR_INDEX_MAX):
for i, i_index in enumerate(ARR_INDEX):
NUM_IND_PER = (i_index+1)/float(ARR_INDEX_MAX[i])
NUM_TOTAL_MAX = NUM_TOTAL_MAX * ARR_INDEX_MAX[i]
if i >0: NUM_CUM_MAX = NUM_CUM_MAX * ARR_INDEX_MAX[i-1]
NUM_CUM_IND = NUM_CUM_IND + NUM_CUM_MAX * i_index
return NUM_CUM_IND / float(NUM_TOTAL_MAX)
else:
print("Wrong dimenstion for in put ARR_INDEX ({0:d}) and ARR_INDEX_MAX ({1:d})".format(len(ARR_INDEX), len(ARR_INDEX_MAX)))
def calendar_cal(ARR_START_TIME, ARR_INTERVAL, ARR_END_TIME_IN=[0, 0, 0, 0, 0, 0.0], IF_LEAP=False):
ARR_END_TIME = [ 0,0,0,0,0,0.0]
ARR_DATETIME = ["SECOND", "MINUTE", "HOUR","DAY", "MON", "YEAR"]
NUM_ARR_DATETIME = len(ARR_DATETIME)
IF_FERTIG = False
ARR_FERTIG = [0,0,0,0,0,0]
DIC_TIME_LIM = \
{"YEAR" : {"START": 0 , "LIMIT": 9999 },\
"MON" : {"START": 1 , "LIMIT": 12 },\
"DAY" : {"START": 1 , "LIMIT": 31 },\
"HOUR" : {"START": 0 , "LIMIT": 23 },\
"MINUTE": {"START": 0 , "LIMIT": 59 },\
"SECOND": {"START": 0 , "LIMIT": 59 },\
}
for I, T in enumerate(ARR_START_TIME):
ARR_END_TIME[I] = T + ARR_INTERVAL[I]
while IF_FERTIG == False:
if math.fmod(ARR_END_TIME[0],4) == 0: IF_LEAP=True
if IF_LEAP:
ARR_DAY_LIM = [0,31,29,31,30,31,30,31,31,30,31,30,31]
else:
ARR_DAY_LIM = [0,31,28,31,30,31,30,31,31,30,31,30,31]
for I, ITEM in enumerate(ARR_DATETIME):
NUM_ARR_POS = NUM_ARR_DATETIME-I-1
if ITEM == "DAY":
if ARR_END_TIME[NUM_ARR_POS] > ARR_DAY_LIM[ARR_END_TIME[1]]:
ARR_END_TIME[NUM_ARR_POS] = ARR_END_TIME[NUM_ARR_POS] - ARR_DAY_LIM[ARR_END_TIME[1]]
ARR_END_TIME[NUM_ARR_POS - 1] += 1
else:
if ARR_END_TIME[NUM_ARR_POS] > DIC_TIME_LIM[ITEM]["LIMIT"]:
ARR_END_TIME[NUM_ARR_POS - 1] += 1
ARR_END_TIME[NUM_ARR_POS] = ARR_END_TIME[NUM_ARR_POS] - DIC_TIME_LIM[ITEM]["LIMIT"] - 1
for I, ITEM in enumerate(ARR_DATETIME):
NUM_ARR_POS = NUM_ARR_DATETIME-I-1
if ITEM == "DAY":
if ARR_END_TIME[NUM_ARR_POS] <= ARR_DAY_LIM[ARR_END_TIME[1]]: ARR_FERTIG[NUM_ARR_POS] = 1
else:
if ARR_END_TIME[NUM_ARR_POS] <= DIC_TIME_LIM[ITEM]["LIMIT"]: ARR_FERTIG[NUM_ARR_POS] = 1
if sum(ARR_FERTIG) == 6: IF_FERTIG = True
return ARR_END_TIME
class MPI_TOOLS:
def __init__(self, MPI_SIZE=1, MPI_RANK=0,\
NUM_NX_END=1, NUM_NY_END=1, NUM_NX_START=0, NUM_NY_START=0, NUM_NX_CORES=1 ,\
NUM_NX_TOTAL=1, NUM_NY_TOTAL=1 ):
""" END number follow the python philisophy: End number is not included in the list """
self.NUM_SIZE = MPI_SIZE
self.NUM_RANK = MPI_RANK
self.NUM_NX_START = NUM_NX_START
self.NUM_NY_START = NUM_NY_START
self.NUM_NX_SIZE = NUM_NX_END - NUM_NX_START
self.NUM_NY_SIZE = NUM_NY_END - NUM_NY_START
self.NUM_NX_CORES = NUM_NX_CORES
self.NUM_NY_CORES = max(1, int(self.NUM_SIZE / NUM_NX_CORES))
self.ARR_RANK_DESIGN = [ {} for n in range(self.NUM_SIZE)]
def CPU_GEOMETRY_2D(self):
NUM_NX_REMAIN = self.NUM_NX_SIZE % self.NUM_NX_CORES
NUM_NY_REMAIN = self.NUM_NY_SIZE % self.NUM_NY_CORES
NUM_NX_DIFF = int((self.NUM_NX_SIZE - NUM_NX_REMAIN) / self.NUM_NX_CORES )
NUM_NY_DIFF = int((self.NUM_NY_SIZE - NUM_NY_REMAIN) / self.NUM_NY_CORES )
NUM_NY_DIFF_P1 = NUM_NY_DIFF + 1
NUM_NX_DIFF_P1 = NUM_NX_DIFF + 1
IND_RANK = 0
ARR_RANK_DESIGN = [ 0 for n in range(self.NUM_SIZE)]
for ny in range(self.NUM_NY_CORES):
for nx in range(self.NUM_NX_CORES):
NUM_RANK = ny * self.NUM_NX_CORES + nx
DIC_IN = {"INDEX_IN": NUM_RANK, "NX_START": 0, "NY_START": 0, "NX_END": 0, "NY_END": 0 }
if ny < NUM_NY_REMAIN:
DIC_IN["NY_START"] = (ny + 0) * NUM_NY_DIFF_P1 + self.NUM_NY_START
DIC_IN["NY_END" ] = (ny + 1) * NUM_NY_DIFF_P1 + self.NUM_NY_START
else:
DIC_IN["NY_START"] = (ny - NUM_NY_REMAIN + 0) * NUM_NY_DIFF + NUM_NY_REMAIN * NUM_NY_DIFF_P1 + self.NUM_NY_START
DIC_IN["NY_END" ] = (ny - NUM_NY_REMAIN + 1) * NUM_NY_DIFF + NUM_NY_REMAIN * NUM_NY_DIFF_P1 + self.NUM_NY_START
if nx < NUM_NX_REMAIN:
DIC_IN["NX_START"] = (nx + 0) * NUM_NX_DIFF_P1 + self.NUM_NX_START
DIC_IN["NX_END" ] = (nx + 1) * NUM_NX_DIFF_P1 + self.NUM_NX_START
else:
DIC_IN["NX_START"] = (nx - NUM_NX_REMAIN + 0) * NUM_NX_DIFF + NUM_NX_REMAIN * NUM_NX_DIFF_P1 + self.NUM_NX_START
DIC_IN["NX_END" ] = (nx - NUM_NX_REMAIN + 1) * NUM_NX_DIFF + NUM_NX_REMAIN * NUM_NX_DIFF_P1 + self.NUM_NX_START
ARR_RANK_DESIGN[NUM_RANK] = DIC_IN
self.ARR_RANK_DESIGN = ARR_RANK_DESIGN
return ARR_RANK_DESIGN
def CPU_MAP(self ):
ARR_CPU_MAP = [ [ NP.nan for i in range(self.NUM_NX_TOTAL)] for j in range(self.NUM_NY_TOTAL) ]
for RANK in range(len(ARR_RANK_DESIGN)):
print("DEAL WITH {0:d} {1:d}".format(RANK, ARR_RANK_DESIGN[RANK]["INDEX_IN"] ))
for jj in range(ARR_RANK_DESIGN[RANK]["NY_START"], ARR_RANK_DESIGN[RANK]["NY_END"]):
for ii in range(ARR_RANK_DESIGN[RANK]["NX_START"], ARR_RANK_DESIGN[RANK]["NX_END"]):
ARR_CPU_MAP[jj][ii] = ARR_RANK_DESIGN[RANK]["INDEX_IN"]
return MAP_CPU
def GATHER_ARR_2D(self, ARR_IN, ARR_IN_GATHER, ARR_RANK_DESIGN=[]):
if ARR_RANK_DESIGN == []:
ARR_RANK_DESIGN = self.ARR_RANK_DESIGN
for N in range(1, self.NUM_SIZE):
I_STA = ARR_RANK_DESIGN[N]["NX_START"]
I_END = ARR_RANK_DESIGN[N]["NX_END" ]
J_STA = ARR_RANK_DESIGN[N]["NY_START"]
J_END = ARR_RANK_DESIGN[N]["NY_END" ]
for J in range(J_STA, J_END ):
for I in range(I_STA, I_END ):
ARR_IN[J][I] = ARR_IN_GATHER[N][J][I]
return ARR_IN
def MPI_MESSAGE(self, STR_TEXT=""):
TIME_NOW = time.gmtime()
print("MPI RANK: {0:5d} @ {1:02d}:{2:02d}:{3:02d} # {4:s}"\
.format(self.NUM_RANK, TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec, STR_TEXT ))
class GEO_TOOLS:
def __init__(self):
STR_NCDF4PY = NC.__version__
print("Using netCDF4 for Python, Version: {0:s}".format(STR_NCDF4PY))
def mask_dtm(self, NUM, ARR_DTM=[0,1,2], ARR_DTM_RANGE=[0,1], ARR_DTM_STR=["OUT","IN","OUT"]):
""" The determination algorithm is : x-1 < NUM <= x """
for i, n in enumerate(ARR_DTM):
if i == 0:
if NUM <= ARR_DTM_RANGE[i]: NUM_OUT = n
elif i == len(ARR_DTM_RANGE):
if NUM > ARR_DTM_RANGE[i-1]: NUM_OUT = n
else:
if NUM > ARR_DTM_RANGE[i-1] and NUM <= ARR_DTM_RANGE[i]: NUM_OUT = n
return NUM_OUT
def mask_array(self, ARR_IN, ARR_MASK_OUT=[], ARR_DTM=[0,1,2], ARR_DTM_RANGE=[0,1], ARR_DTM_STR=["OUT","IN","OUT"], IF_2D=False):
if IF_2D:
NUM_NX = len(ARR_IN[0])
NUM_NY = len(ARR_IN)
ARR_OUT = [ [ self.NUM_NULL for i in range(NUM_NX)] for j in range(NUM_NY) ]
for J in range(NUM_NY):
for I in range(NUM_NY):
ARR_OUT[J][I] = self.mask_dtm(ARR_IN[J][I], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE, ARR_STR_DTM=ARR_STR_DTM)
else:
NUM_NX = len(ARR_IN)
ARR_OUT = [0 for n in range(NUM_NX)]
for N in range(NUM_NX):
ARR_OUT[N] = self.mask_dtm(ARR_IN[N], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE, ARR_STR_DTM=ARR_STR_DTM)
return ARR_OUT
def MAKE_LAT_LON_ARR(self, FILE_NC_IN, STR_LAT="lat", STR_LON="lon", source="CFC"):
""" Reading LAT and LON from a NC file """
NC_DATA_IN = NC.Dataset(FILE_NC_IN, "r", format="NETCDF4")
if source == "CFC":
arr_lat_in = NC_DATA_IN.variables[STR_LAT]
arr_lon_in = NC_DATA_IN.variables[STR_LON]
num_nlat = len(arr_lat_in)
num_nlon = len(arr_lon_in)
arr_lon_out = [[0.0 for i in range(num_nlon)] for j in range(num_nlat)]
arr_lat_out = [[0.0 for i in range(num_nlon)] for j in range(num_nlat)]
for j in range(num_nlat):
for i in range(num_nlon):
arr_lon_out[j][i] = arr_lat_in[j]
arr_lat_out[j][i] = arr_lon_in[i]
return arr_lat_out, arr_lon_out
class NETCDF4_HELPER:
def __init__(self):
STR_NCDF4PY = NC.__version__
print("Using netCDF4 for Python, Version: {0:s}".format(STR_NCDF4PY))
def create_wrf_ensemble(self, STR_FILE_IN, STR_FILE_OUT, ARR_VAR=[], STR_DIR="./", NUM_ENSEMBLE_SIZE=1 ):
FILE_OUT = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILE_OUT), "w",format="NETCDF4")
FILE_IN = NC.Dataset("{1:s}/{1:s}".format(STR_DIR, STR_FILE_IN ), "r",format="NETCDF4")
# CREATE DIMENSIONS:
for DIM in FILE_IN.dimensions:
FILE_OUT.createDimension(DIM, FILE_IN.dimensions[DIM].size )
FILE_OUT.createDimension("Ensembles", NUM_ENSEMBLE_SIZE )
# CREATE ATTRIBUTES:
FILE_OUT.TITLE = FILE_IN.TITLE
FILE_OUT.START_DATE = FILE_IN.START_DATE
FILE_OUT.SIMULATION_START_DATE = FILE_IN.SIMULATION_START_DATE
FILE_OUT.DX = FILE_IN.DX
FILE_OUT.DY = FILE_IN.DY
FILE_OUT.SKEBS_ON = FILE_IN.SKEBS_ON
FILE_OUT.SPEC_BDY_FINAL_MU = FILE_IN.SPEC_BDY_FINAL_MU
FILE_OUT.USE_Q_DIABATIC = FILE_IN.USE_Q_DIABATIC
FILE_OUT.GRIDTYPE = FILE_IN.GRIDTYPE
FILE_OUT.DIFF_OPT = FILE_IN.DIFF_OPT
FILE_OUT.KM_OPT = FILE_IN.KM_OPT
if len(ARR_VAR) >0:
for V in ARR_VAR:
if V[1] == "2D":
FILE_OUT.createVariable(V[0], "f8", ("Ensembles", "Time", "south_north", "west_east" ))
elif V[1] == "3D":
FILE_OUT.createVariable(V[0], "f8", ("Ensembles", "Time", "bottom_top", "south_north", "west_east" ))
FILE_OUT.close()
FILE_IN.close()
def add_ensemble(self, FILE_IN, FILE_OUT, STR_VAR, STR_DIM="2D", STR_DIR="./", IND_ENSEMBLE=0):
FILE_OUT = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, FILE_OUT), "a",format="NETCDF4")
FILE_IN = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, FILE_IN ), "r",format="NETCDF4")
ARR_VAR_IN = FILE_IN.variables[STR_VAR]
NUM_NT = len(ARR_VAR_IN)
NUM_NK = FILE_IN.dimensions["bottom_top"].size
NUM_NJ = FILE_IN.dimensions["south_north"].size
NUM_NI = FILE_IN.dimensions["west_east"].size
for time in range(NUM_NT):
if STR_DIM == "2D":
FILE_OUT.variables[STR_VAR][IND_ENSEMBLE, time] = FILE_IN.variables[STR_VAR][time]
elif STR_DIM == "3D":
for k in range(NUM_NK):
FILE_OUT.variables[STR_VAR][IND_ENSEMBLE, time] = FILE_IN.variables[STR_VAR][time]
FILE_OUT.close()
FILE_IN.close()
class WRF_HELPER:
STR_DIR_ROOT = "./"
NUM_TIME_INIT = 0
NUM_SHIFT = 0.001
def __init__(self):
"""
Remember: most array should be follow the rule of [j,i] instead of [x,y].
"""
STR_NCDF4PY = NC.__version__
print("Using netCDF4 for Python, Version: {0:s}".format(STR_NCDF4PY))
def GEO_INFORMATER(self, STR_FILE="geo_em.d01.nc", STR_DIR=""):
print("INPUT GEO FILE: {0:s}".format(STR_FILE))
if STR_DIR == "":
STR_DIR == self.STR_DIR_ROOT
self.FILE_IN = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILE ), "r",format="NETCDF4")
self.MAP_LAT = self.FILE_IN.variables["CLAT"] [self.NUM_TIME_INIT]
self.MAP_LON = self.FILE_IN.variables["CLONG"][self.NUM_TIME_INIT]
ARR_TMP_IN = self.FILE_IN.variables["CLONG"][0]
# Since NetCDF4 for python does not support the hyphen in attributes, I
# am forced to calculate the NX and NY based on a map in the NC file.
self.NUM_NX = len(ARR_TMP_IN[0])
self.NUM_NY = len(ARR_TMP_IN)
self.NUM_DX = self.FILE_IN.DX
self.NUM_DY = self.FILE_IN.DX
def GEO_HELPER(self, ARR_LL_SW, ARR_LL_NE):
self.MAP_CROP_MASK = [[ 0 for i in range(self.NUM_NX)] for j in range(self.NUM_NY)]
self.DIC_CROP_INFO = {"NE": {"LAT":0, "LON":0, "I":0, "J":0},\
"SW": {"LAT":0, "LON":0, "I":0, "J":0}}
ARR_TMP_I = []
ARR_TMP_J = []
for j in range(self.NUM_NY):
for i in range(self.NUM_NX):
NUM_CHK_SW_J = self.MAP_LAT[j][i] - ARR_LL_SW[0]
if NUM_CHK_SW_J == 0:
NUM_CHK_SW_J = self.MAP_LAT[j][i] - ARR_LL_SW[0] + self.NUM_SHIFT
NUM_CHK_SW_I = self.MAP_LON[j][i] - ARR_LL_SW[1]
if NUM_CHK_SW_I == 0:
NUM_CHK_SW_I = self.MAP_LAT[j][i] - ARR_LL_SW[1] - self.NUM_SHIFT
NUM_CHK_NE_J = self.MAP_LAT[j][i] - ARR_LL_NE[0]
if NUM_CHK_NE_J == 0:
NUM_CHK_NE_J = self.MAP_LAT[j][i] - ARR_LL_NE[0] + self.NUM_SHIFT
NUM_CHK_NE_I = self.MAP_LON[j][i] - ARR_LL_NE[1]
if NUM_CHK_NE_I == 0:
NUM_CHK_NE_I = self.MAP_LON[j][i] - ARR_LL_NE[1] - self.NUM_SHIFT
NUM_CHK_NS_IN = NUM_CHK_SW_J * NUM_CHK_NE_J
NUM_CHK_WE_IN = NUM_CHK_SW_I * NUM_CHK_NE_I
if NUM_CHK_NS_IN < 0 and NUM_CHK_WE_IN < 0:
self.MAP_CROP_MASK[j][i] = 1
ARR_TMP_J.append(j)
ARR_TMP_I.append(i)
NUM_SW_J = min( ARR_TMP_J )
NUM_SW_I = min( ARR_TMP_I )
NUM_NE_J = max( ARR_TMP_J )
NUM_NE_I = max( ARR_TMP_I )
self.DIC_CROP_INFO["NE"]["J"] = NUM_NE_J
self.DIC_CROP_INFO["NE"]["I"] = NUM_NE_I
self.DIC_CROP_INFO["NE"]["LAT"] = self.MAP_LAT[NUM_NE_J][NUM_NE_I]
self.DIC_CROP_INFO["NE"]["LON"] = self.MAP_LON[NUM_NE_J][NUM_NE_I]
self.DIC_CROP_INFO["SW"]["J"] = NUM_SW_J
self.DIC_CROP_INFO["SW"]["I"] = NUM_SW_I
self.DIC_CROP_INFO["SW"]["LAT"] = self.MAP_LAT[NUM_SW_J][NUM_SW_I]
self.DIC_CROP_INFO["SW"]["LON"] = self.MAP_LON[NUM_SW_J][NUM_SW_I]
def PROFILE_HELPER(STR_FILE_IN, ARR_DATE_START, NUM_DOMS=3, NUM_TIMESTEPS=24, IF_PB=False):
"""
This functions reads the filename, array of starting date,
and simulation hours and numbers of domains
to profiling the time it takes for WRF.
"""
FILE_READ_IN = open("{0:s}".format(STR_FILE_IN))
ARR_READ_IN = FILE_READ_IN.readlines()
NUM_TIME = NUM_TIMESTEPS
NUM_DOMAIN = NUM_DOMS
NUM_DATE_START = ARR_DATE_START
NUM_LEN_IN = len(ARR_READ_IN)
ARR_TIME_PROFILE = [[0 for T in range(NUM_TIME)] for D in range(NUM_DOMS)]
for I, TEXT_IN in enumerate(ARR_READ_IN):
ARR_TEXT = re.split("\s",TEXT_IN.strip())
if ARR_TEXT[0] == "Timing":
if ARR_TEXT[2] == "main:" or ARR_TEXT[2] == "main":
for ind, T in enumerate(ARR_TEXT):
if T == "time" : ind_time_text = ind + 1
if T == "elapsed": ind_elapsed_text = ind - 1
if T == "domain" : ind_domain_text = ind + 3
arr_time_in = re.split("_", ARR_TEXT[ind_time_text])
arr_date = re.split("-", arr_time_in[0])
arr_time = re.split(":", arr_time_in[1])
num_domain = int(re.split(":", ARR_TEXT[ind_domain_text])[0])
num_elapsed = float(ARR_TEXT[ind_elapsed_text])
NUM_HOUR_FIX = (int(arr_date[2]) - NUM_DATE_START[2]) * 24
NUM_HOUR = NUM_HOUR_FIX + int(arr_time[0])
ARR_TIME_PROFILE[num_domain-1][NUM_HOUR] += num_elapsed
if IF_PB: TOOLS.progress_bar(I/float(NUM_LEN_IN))
#self.ARR_TIME_PROFILE = ARR_TIME_PROFILE
return ARR_TIME_PROFILE
class DATA_READER:
"""
The DATA_READER is based on my old work: gridtrans.py.
"""
def __init__(self, STR_NULL="noData", NUM_NULL=-999.999):
self.STR_NULL=STR_NULL
self.NUM_NULL=NUM_NULL
def stripblnk(arr,*num_typ):
new_arr=[]
for i in arr:
if i == "":
pass
else:
if num_typ[0] == 'int':
new_arr.append(int(i))
elif num_typ[0] == 'float':
new_arr.append(float(i))
elif num_typ[0] == '':
new_arr.append(i)
else:
print("WRONG num_typ!")
return new_arr
def tryopen(self, sourcefile, ag):
try:
opf=open(sourcefile,ag)
return opf
except :
print("No such file.")
return "error"
def READCSV(self, sourcefile):
opf = self.tryopen(sourcefile,'r')
opfchk = self.tryopen(sourcefile,'r')
print("reading source file {0:s}".format(sourcefile))
chk_lines = opfchk.readlines()
num_totallines = len(chk_lines)
ncols = 0
num_notnum = 0
for n in range(num_totallines):
line_in = chk_lines[n]
c_first = re.findall(".",line_in.strip())
if c_first[0] == "#":
num_notnum += 1
else:
ncols = len( re.split(",",line_in.strip()) )
break
if ncols == 0:
print("something wrong with the input file! (all comments?)")
else:
del opfchk
nrows=num_totallines - num_notnum
result_arr=[[self.NUM_NULL for j in range(ncols)] for i in range(nrows)]
result_arr_text=[]
num_pass = 0
for j in range(0,num_totallines):
# chk if comment
#print (j,i,chk_val)
line_in = opf.readline()
c_first = re.findall(".",line_in.strip())[0]
if c_first == "#":
result_arr_text.append(line_in)
num_pass += 1
else:
arr_in = re.split(",",line_in.strip())
for i in range(ncols):
chk_val = arr_in[i]
if chk_val == self.STR_NULL:
result_arr[j-num_pass][i] = self.NUM_NULL
else:
result_arr[j-num_pass][i] = float(chk_val)
return result_arr,result_arr_text
| metalpen1984/SciTool_Py | GRIDINFORMER.py | Python | lgpl-3.0 | 66,239 |
<?php
declare(strict_types=1);
namespace slapper\entities;
class SlapperVex extends SlapperEntity {
const TYPE_ID = 105;
const HEIGHT = 0.8;
}
| jojoe77777/Slapper | src/slapper/entities/SlapperVex.php | PHP | lgpl-3.0 | 156 |
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.core.widgets.reviews;
import org.sonar.api.web.AbstractRubyTemplate;
import org.sonar.api.web.RubyRailsWidget;
import org.sonar.api.web.WidgetCategory;
import org.sonar.api.web.WidgetProperties;
import org.sonar.api.web.WidgetProperty;
import org.sonar.api.web.WidgetPropertyType;
@WidgetCategory({ "Reviews" })
@WidgetProperties(
{
@WidgetProperty(key = "numberOfLines", type = WidgetPropertyType.INTEGER, defaultValue = "5",
description="Maximum number of reviews displayed at the same time.")
}
)
public class MyReviewsWidget extends AbstractRubyTemplate implements RubyRailsWidget {
public String getId() {
return "my_reviews";
}
public String getTitle() {
return "My open reviews";
}
@Override
protected String getTemplatePath() {
return "/org/sonar/plugins/core/widgets/reviews/my_reviews.html.erb";
}
} | leodmurillo/sonar | plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/reviews/MyReviewsWidget.java | Java | lgpl-3.0 | 1,757 |
<?php
/**
* Smarty Internal Plugin Compile Section
*
* Compiles the {section} {sectionelse} {/section} tags
*
* @package Brainy
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Section Class
*
* @package Brainy
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Section extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('name', 'loop');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('name', 'loop');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('start', 'step', 'max', 'show');
/**
* Compiles code for the {section} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler) {
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$this->openTag($compiler, 'section', array('section'));
$output = '';
$section_name = $_attr['name'];
$output .= "if (isset(\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name])) unset(\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name]);\n";
$section_props = "\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name]";
foreach ($_attr as $attr_name => $attr_value) {
switch ($attr_name) {
case 'loop':
$output .= "{$section_props}['loop'] = is_array(\$_loop=$attr_value) ? count(\$_loop) : max(0, (int) \$_loop); unset(\$_loop);\n";
break;
case 'show':
if (is_bool($attr_value))
$show_attr_value = $attr_value ? 'true' : 'false';
else
$show_attr_value = "(bool) $attr_value";
$output .= "{$section_props}['show'] = $show_attr_value;\n";
break;
case 'name':
$output .= "{$section_props}['$attr_name'] = $attr_value;\n";
break;
case 'max':
case 'start':
$output .= "{$section_props}['$attr_name'] = (int) $attr_value;\n";
break;
case 'step':
$output .= "{$section_props}['$attr_name'] = ((int) $attr_value) == 0 ? 1 : (int) $attr_value;\n";
break;
}
}
if (!isset($_attr['show']))
$output .= "{$section_props}['show'] = true;\n";
if (!isset($_attr['loop']))
$output .= "{$section_props}['loop'] = 1;\n";
if (!isset($_attr['max']))
$output .= "{$section_props}['max'] = {$section_props}['loop'];\n";
else
$output .= "if ({$section_props}['max'] < 0)\n" . " {$section_props}['max'] = {$section_props}['loop'];\n";
if (!isset($_attr['step']))
$output .= "{$section_props}['step'] = 1;\n";
if (!isset($_attr['start']))
$output .= "{$section_props}['start'] = {$section_props}['step'] > 0 ? 0 : {$section_props}['loop']-1;\n";
else {
$output .= "if ({$section_props}['start'] < 0)\n" . " {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" . "else\n" . " {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n";
}
$output .= "if ({$section_props}['show']) {\n";
if (!isset($_attr['start']) && !isset($_attr['step']) && !isset($_attr['max'])) {
$output .= " {$section_props}['total'] = {$section_props}['loop'];\n";
} else {
$output .= " {$section_props}['total'] = min(ceil(({$section_props}['step'] > 0 ? {$section_props}['loop'] - {$section_props}['start'] : {$section_props}['start']+1)/abs({$section_props}['step'])), {$section_props}['max']);\n";
}
$output .= " if ({$section_props}['total'] == 0)\n" . " {$section_props}['show'] = false;\n" . "} else\n" . " {$section_props}['total'] = 0;\n";
$output .= "if ({$section_props}['show']):\n";
$output .= "
for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1;
{$section_props}['iteration'] <= {$section_props}['total'];
{$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n";
$output .= "{$section_props}['rownum'] = {$section_props}['iteration'];\n";
$output .= "{$section_props}['index_prev'] = {$section_props}['index'] - {$section_props}['step'];\n";
$output .= "{$section_props}['index_next'] = {$section_props}['index'] + {$section_props}['step'];\n";
$output .= "{$section_props}['first'] = ({$section_props}['iteration'] == 1);\n";
$output .= "{$section_props}['last'] = ({$section_props}['iteration'] == {$section_props}['total']);\n";
return $output;
}
}
/**
* Smarty Internal Plugin Compile Sectionelse Class
*
* @package Brainy
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Sectionelse extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {sectionelse} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler) {
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
list($openTag) = $this->closeTag($compiler, array('section'));
$this->openTag($compiler, 'sectionelse', array('sectionelse'));
return "endfor;\nelse:\n";
}
}
/**
* Smarty Internal Plugin Compile Sectionclose Class
*
* @package Brainy
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Sectionclose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/section} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler) {
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
list($openTag) = $this->closeTag($compiler, array('section', 'sectionelse'));
if ($openTag == 'sectionelse') {
return "endif;\n";
} else {
return "endfor;\nendif;\n";
}
}
}
| chriseling/brainy | src/Brainy/sysplugins/smarty_internal_compile_section.php | PHP | lgpl-3.0 | 7,064 |
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* 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, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.javascript.checks;
import org.sonar.check.Rule;
import org.sonar.plugins.javascript.api.EslintBasedCheck;
import org.sonar.plugins.javascript.api.JavaScriptRule;
import org.sonar.plugins.javascript.api.TypeScriptRule;
@JavaScriptRule
@TypeScriptRule
@Rule(key = "S5542")
public class EncryptionSecureModeCheck implements EslintBasedCheck {
@Override
public String eslintKey() {
return "encryption-secure-mode";
}
}
| SonarSource/sonar-javascript | javascript-checks/src/main/java/org/sonar/javascript/checks/EncryptionSecureModeCheck.java | Java | lgpl-3.0 | 1,307 |
/*
* This file is part of Gaia Sky, which is released under the Mozilla Public License 2.0.
* See the file LICENSE.md in the project root for full license details.
*/
package gaiasky.desktop.util;
import gaiasky.util.Logger;
import gaiasky.util.Logger.Log;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Wee utility class to check the operating system and the desktop environment.
* It also offers retrieval of common system folders.
*
* @author Toni Sagrista
*/
public class SysUtils {
private static Log logger = Logger.getLogger(SysUtils.class);
/**
* Initialise directories
*/
public static void mkdirs() {
// Top level
try {
Files.createDirectories(getDataDir());
Files.createDirectories(getConfigDir());
// Bottom level
Files.createDirectories(getDefaultCameraDir());
Files.createDirectories(getDefaultMusicDir());
Files.createDirectories(getDefaultFramesDir());
Files.createDirectories(getDefaultScreenshotsDir());
Files.createDirectories(getDefaultTmpDir());
Files.createDirectories(getDefaultMappingsDir());
Files.createDirectories(getDefaultBookmarksDir());
} catch (IOException e) {
logger.error(e);
}
}
private static String OS;
private static boolean linux, mac, windows, unix, solaris;
static {
OS = System.getProperty("os.name").toLowerCase();
linux = OS.indexOf("linux") >= 0;
mac = OS.indexOf("macos") >= 0 || OS.indexOf("mac os") >= 0;
windows = OS.indexOf("win") >= 0;
unix = OS.indexOf("unix") >= 0;
solaris = OS.indexOf("sunos") >= 0;
}
public static String getXdgDesktop() {
return System.getenv("XDG_CURRENT_DESKTOP");
}
public static boolean checkLinuxDesktop(String desktop) {
try {
String value = getXdgDesktop();
return value != null && !value.isEmpty() && value.equalsIgnoreCase(desktop);
} catch (Exception e) {
e.printStackTrace(System.err);
}
return false;
}
public static boolean checkUnity() {
return isLinux() && checkLinuxDesktop("ubuntu");
}
public static boolean checkGnome() {
return isLinux() && checkLinuxDesktop("gnome");
}
public static boolean checkKDE() {
return isLinux() && checkLinuxDesktop("kde");
}
public static boolean checkXfce() {
return isLinux() && checkLinuxDesktop("xfce");
}
public static boolean checkBudgie() {
return isLinux() && checkLinuxDesktop("budgie:GNOME");
}
public static boolean checkI3() {
return isLinux() && checkLinuxDesktop("i3");
}
public static String getOSName() {
return OS;
}
public static String getOSFamily() {
if (isLinux())
return "linux";
if (isWindows())
return "win";
if (isMac())
return "macos";
if (isUnix())
return "unix";
if (isSolaris())
return "solaris";
return "unknown";
}
public static boolean isLinux() {
return linux;
}
public static boolean isWindows() {
return windows;
}
public static boolean isMac() {
return mac;
}
public static boolean isUnix() {
return unix;
}
public static boolean isSolaris() {
return solaris;
}
public static String getOSArchitecture() {
return System.getProperty("os.arch");
}
public static String getOSVersion() {
return System.getProperty("os.version");
}
private static final String GAIASKY_DIR_NAME = "gaiasky";
private static final String DOTGAIASKY_DIR_NAME = ".gaiasky";
private static final String CAMERA_DIR_NAME = "camera";
private static final String SCREENSHOTS_DIR_NAME = "screenshots";
private static final String FRAMES_DIR_NAME = "frames";
private static final String MUSIC_DIR_NAME = "music";
private static final String MAPPINGS_DIR_NAME = "mappings";
private static final String BOOKMARKS_DIR_NAME = "bookmarks";
private static final String MPCDI_DIR_NAME = "mpcdi";
private static final String DATA_DIR_NAME = "data";
private static final String TMP_DIR_NAME = "tmp";
private static final String CRASHREPORTS_DIR_NAME = "crashreports";
/**
* Gets a file pointer to the camera directory.
*
* @return A pointer to the Gaia Sky camera directory
*/
public static Path getDefaultCameraDir() {
return getDataDir().resolve(CAMERA_DIR_NAME);
}
/**
* Gets a file pointer to the default screenshots directory.
*
* @return A pointer to the Gaia Sky screenshots directory
*/
public static Path getDefaultScreenshotsDir() {
return getDataDir().resolve(SCREENSHOTS_DIR_NAME);
}
/**
* Gets a file pointer to the frames directory.
*
* @return A pointer to the Gaia Sky frames directory
*/
public static Path getDefaultFramesDir() {
return getDataDir().resolve(FRAMES_DIR_NAME);
}
/**
* Gets a file pointer to the music directory.
*
* @return A pointer to the Gaia Sky music directory
*/
public static Path getDefaultMusicDir() {
return getDataDir().resolve(MUSIC_DIR_NAME);
}
/**
* Gets a file pointer to the mappings directory.
*
* @return A pointer to the Gaia Sky mappings directory
*/
public static Path getDefaultMappingsDir() {
return getConfigDir().resolve(MAPPINGS_DIR_NAME);
}
public static String getMappingsDirName() {
return MAPPINGS_DIR_NAME;
}
/**
* Gets a file pointer to the bookmarks directory.
*
* @return A pointer to the Gaia Sky bookmarks directory
*/
public static Path getDefaultBookmarksDir() {
return getConfigDir().resolve(BOOKMARKS_DIR_NAME);
}
public static String getBookmarksDirName() {
return BOOKMARKS_DIR_NAME;
}
/**
* Gets a file pointer to the mpcdi directory.
*
* @return A pointer to the Gaia Sky mpcdi directory
*/
public static Path getDefaultMpcdiDir() {
return getDataDir().resolve(MPCDI_DIR_NAME);
}
/**
* Gets a file pointer to the local data directory where the data files are downloaded and stored.
*
* @return A pointer to the local data directory where the data files are
*/
public static Path getLocalDataDir() {
return getDataDir().resolve(DATA_DIR_NAME);
}
/**
* Gets a file pointer to the crash reports directory, where crash reports are stored.
*
* @return A pointer to the crash reports directory
*/
public static Path getCrashReportsDir() {
return getDataDir().resolve(CRASHREPORTS_DIR_NAME);
}
/**
* Gets a file pointer to the temporary directory within the cache directory. See {@link #getCacheDir()}.
*
* @return A pointer to the Gaia Sky temporary directory in the user's home.
*/
public static Path getDefaultTmpDir() {
return getCacheDir().resolve(TMP_DIR_NAME);
}
/**
* Returns the default data directory. That is ~/.gaiasky/ in Windows and macOS, and ~/.local/share/gaiasky
* in Linux.
*
* @return Default data directory
*/
public static Path getDataDir() {
if (isLinux()) {
return getXdgDataHome().resolve(GAIASKY_DIR_NAME);
} else {
return getUserHome().resolve(DOTGAIASKY_DIR_NAME);
}
}
/**
* Returns the default cache directory, for non-essential data. This is ~/.gaiasky/ in Windows and macOS, and ~/.cache/gaiasky
* in Linux.
*
* @return The default cache directory
*/
public static Path getCacheDir() {
if (isLinux()) {
return getXdgCacheHome().resolve(GAIASKY_DIR_NAME);
} else {
return getDataDir();
}
}
public static Path getConfigDir() {
if (isLinux()) {
return getXdgConfigHome().resolve(GAIASKY_DIR_NAME);
} else {
return getUserHome().resolve(DOTGAIASKY_DIR_NAME);
}
}
public static Path getHomeDir() {
return getUserHome();
}
public static Path getUserHome() {
return Paths.get(System.getProperty("user.home"));
}
private static Path getXdgDataHome() {
String dataHome = System.getenv("XDG_DATA_HOME");
if (dataHome == null || dataHome.isEmpty()) {
return Paths.get(System.getProperty("user.home"), ".local", "share");
} else {
return Paths.get(dataHome);
}
}
private static Path getXdgConfigHome() {
String configHome = System.getenv("XDG_CONFIG_HOME");
if (configHome == null || configHome.isEmpty()) {
return Paths.get(System.getProperty("user.home"), ".config");
} else {
return Paths.get(configHome);
}
}
private static Path getXdgCacheHome() {
String cacheHome = System.getenv("XDG_CACHE_HOME");
if (cacheHome == null || cacheHome.isEmpty()) {
return Paths.get(System.getProperty("user.home"), ".cache");
} else {
return Paths.get(cacheHome);
}
}
public static double getJavaVersion() {
String version = System.getProperty("java.version");
if (version.contains(("."))) {
int pos = version.indexOf('.');
pos = version.indexOf('.', pos + 1);
return Double.parseDouble(version.substring(0, pos));
} else {
return Double.parseDouble(version);
}
}
}
| ari-zah/gaiasandbox | core/src/gaiasky/desktop/util/SysUtils.java | Java | lgpl-3.0 | 9,893 |
package com.taiter.ce.Enchantments.Global;
import org.bukkit.Material;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Skeleton.SkeletonType;
import org.bukkit.entity.Zombie;
import org.bukkit.event.Event;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.scheduler.BukkitRunnable;
import com.taiter.ce.EffectManager;
import com.taiter.ce.Enchantments.CEnchantment;
public class Headless extends CEnchantment {
public Headless(Application app) {
super(app);
triggers.add(Trigger.DAMAGE_GIVEN);
resetMaxLevel();
}
@Override
public void effect(Event e, ItemStack item, int level) {
EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) e;
final Player player = (Player) event.getDamager();
final LivingEntity ent = (LivingEntity) event.getEntity();
new BukkitRunnable() {
@Override
public void run() {
if (ent.getHealth() <= 0) {
byte type = 3;
if (ent instanceof Skeleton) {
type = 0;
if (((Skeleton) ent).getSkeletonType().equals(SkeletonType.WITHER))
type = 1;
} else if (ent instanceof Zombie)
type = 2;
else if (ent instanceof Creeper)
type = 4;
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, type);
if (type == 3) {
SkullMeta sm = (SkullMeta) skull.getItemMeta();
sm.setOwner(ent.getName());
skull.setItemMeta(sm);
}
ent.getWorld().dropItem(ent.getLocation(), skull);
EffectManager.playSound(player.getLocation(), "BLOCK_ANVIL_LAND", 0.1f, 1.5f);
}
}
}.runTaskLater(getPlugin(), 5l);
}
@Override
public void initConfigEntries() {
}
}
| Taiterio/ce | src/com/taiter/ce/Enchantments/Global/Headless.java | Java | lgpl-3.0 | 2,233 |
package net.minecraft.src;
// MCPatcher Start
import com.prupe.mcpatcher.cc.ColorizeEntity;
// MCPatcher End
public class ItemArmor extends Item {
/** Holds the 'base' maxDamage that each armorType have. */
private static final int[] maxDamageArray = new int[] {11, 16, 15, 13};
private static final String[] field_94606_cu = new String[] {"leather_helmet_overlay", "leather_chestplate_overlay", "leather_leggings_overlay", "leather_boots_overlay"};
public static final String[] field_94603_a = new String[] {"empty_armor_slot_helmet", "empty_armor_slot_chestplate", "empty_armor_slot_leggings", "empty_armor_slot_boots"};
private static final IBehaviorDispenseItem field_96605_cw = new BehaviorDispenseArmor();
/**
* Stores the armor type: 0 is helmet, 1 is plate, 2 is legs and 3 is boots
*/
public final int armorType;
/** Holds the amount of damage that the armor reduces at full durability. */
public final int damageReduceAmount;
/**
* Used on RenderPlayer to select the correspondent armor to be rendered on the player: 0 is cloth, 1 is chain, 2 is
* iron, 3 is diamond and 4 is gold.
*/
public final int renderIndex;
/** The EnumArmorMaterial used for this ItemArmor */
private final EnumArmorMaterial material;
private Icon field_94605_cw;
private Icon field_94604_cx;
public ItemArmor(int par1, EnumArmorMaterial par2EnumArmorMaterial, int par3, int par4) {
super(par1);
this.material = par2EnumArmorMaterial;
this.armorType = par4;
this.renderIndex = par3;
this.damageReduceAmount = par2EnumArmorMaterial.getDamageReductionAmount(par4);
this.setMaxDamage(par2EnumArmorMaterial.getDurability(par4));
this.maxStackSize = 1;
this.setCreativeTab(CreativeTabs.tabCombat);
BlockDispenser.dispenseBehaviorRegistry.putObject(this, field_96605_cw);
}
public int getColorFromItemStack(ItemStack par1ItemStack, int par2) {
if (par2 > 0) {
return 16777215;
} else {
int var3 = this.getColor(par1ItemStack);
if (var3 < 0) {
var3 = 16777215;
}
return var3;
}
}
public boolean requiresMultipleRenderPasses() {
return this.material == EnumArmorMaterial.CLOTH;
}
/**
* Return the enchantability factor of the item, most of the time is based on material.
*/
public int getItemEnchantability() {
return this.material.getEnchantability();
}
/**
* Return the armor material for this armor item.
*/
public EnumArmorMaterial getArmorMaterial() {
return this.material;
}
/**
* Return whether the specified armor ItemStack has a color.
*/
public boolean hasColor(ItemStack par1ItemStack) {
return this.material != EnumArmorMaterial.CLOTH ? false : (!par1ItemStack.hasTagCompound() ? false : (!par1ItemStack.getTagCompound().hasKey("display") ? false : par1ItemStack.getTagCompound().getCompoundTag("display").hasKey("color")));
}
/**
* Return the color for the specified armor ItemStack.
*/
public int getColor(ItemStack par1ItemStack) {
if (this.material != EnumArmorMaterial.CLOTH) {
return -1;
} else {
NBTTagCompound var2 = par1ItemStack.getTagCompound();
if (var2 == null) {
// MCPatcher Start
return ColorizeEntity.undyedLeatherColor;
// MCPatcher End
} else {
NBTTagCompound var3 = var2.getCompoundTag("display");
// MCPatcher Start
return var3 == null ? ColorizeEntity.undyedLeatherColor : (var3.hasKey("color") ? var3.getInteger("color") : ColorizeEntity.undyedLeatherColor);
// MCPatcher End
}
}
}
/**
* Gets an icon index based on an item's damage value and the given render pass
*/
public Icon getIconFromDamageForRenderPass(int par1, int par2) {
return par2 == 1 ? this.field_94605_cw : super.getIconFromDamageForRenderPass(par1, par2);
}
/**
* Remove the color from the specified armor ItemStack.
*/
public void removeColor(ItemStack par1ItemStack) {
if (this.material == EnumArmorMaterial.CLOTH) {
NBTTagCompound var2 = par1ItemStack.getTagCompound();
if (var2 != null) {
NBTTagCompound var3 = var2.getCompoundTag("display");
if (var3.hasKey("color")) {
var3.removeTag("color");
}
}
}
}
public void func_82813_b(ItemStack par1ItemStack, int par2) {
if (this.material != EnumArmorMaterial.CLOTH) {
throw new UnsupportedOperationException("Can\'t dye non-leather!");
} else {
NBTTagCompound var3 = par1ItemStack.getTagCompound();
if (var3 == null) {
var3 = new NBTTagCompound();
par1ItemStack.setTagCompound(var3);
}
NBTTagCompound var4 = var3.getCompoundTag("display");
if (!var3.hasKey("display")) {
var3.setCompoundTag("display", var4);
}
var4.setInteger("color", par2);
}
}
/**
* Return whether this item is repairable in an anvil.
*/
public boolean getIsRepairable(ItemStack par1ItemStack, ItemStack par2ItemStack) {
return this.material.getArmorCraftingMaterial() == par2ItemStack.itemID ? true : super.getIsRepairable(par1ItemStack, par2ItemStack);
}
public void registerIcons(IconRegister par1IconRegister) {
super.registerIcons(par1IconRegister);
if (this.material == EnumArmorMaterial.CLOTH) {
this.field_94605_cw = par1IconRegister.registerIcon(field_94606_cu[this.armorType]);
}
this.field_94604_cx = par1IconRegister.registerIcon(field_94603_a[this.armorType]);
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*/
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) {
int var4 = EntityLiving.getArmorPosition(par1ItemStack) - 1;
ItemStack var5 = par3EntityPlayer.getCurrentArmor(var4);
if (var5 == null) {
par3EntityPlayer.setCurrentItemOrArmor(var4, par1ItemStack.copy());
par1ItemStack.stackSize = 0;
}
return par1ItemStack;
}
public static Icon func_94602_b(int par0) {
switch (par0) {
case 0:
return Item.helmetDiamond.field_94604_cx;
case 1:
return Item.plateDiamond.field_94604_cx;
case 2:
return Item.legsDiamond.field_94604_cx;
case 3:
return Item.bootsDiamond.field_94604_cx;
default:
return null;
}
}
/**
* Returns the 'max damage' factor array for the armor, each piece of armor have a durability factor (that gets
* multiplied by armor material factor)
*/
static int[] getMaxDamageArray() {
return maxDamageArray;
}
}
| Spoutcraft/Spoutcraft | src/main/java/net/minecraft/src/ItemArmor.java | Java | lgpl-3.0 | 6,355 |
<?php
namespace Cron;
class CronClass
{
/** @var array Обработанный список задач крона */
protected $cron = array();
/** @var string Путь к файлу с задачами крона */
protected $cronFile;
/** @var string Адрес, на который будут высылаться уведомления с крона */
protected $cronEmail;
/** @var \DateTime Время последнего успешного запуска крона */
protected $modifyTime;
/** @var string Путь к файлу с настройками Ideal CMS */
protected $dataFile;
/** @var string Корень сайта */
protected $siteRoot;
/** @var string Сообщение после тестового запуска скрипта */
protected $message = '';
/**
* CronClass constructor.
*
* @param string $siteRoot Корень сайта, относительно которого указываются скрипты в кроне
* @param string $cronFile Путь к файлу crontab сайта
* @param string $dataFile Путь к файлу настроек Ideal CMS (для получения координат отправки сообщений с крона)
*/
public function __construct($siteRoot = '', $cronFile = '', $dataFile = '')
{
$this->cronFile = empty($cronFile) ? __DIR__ . '/../../../crontab' : $cronFile;
$this->dataFile = empty($dataFile) ? __DIR__ . '/../../../site_data.php' : $dataFile;
$this->siteRoot = empty($siteRoot) ? dirname(dirname(dirname(dirname(__DIR__)))) : $siteRoot;
}
/**
* Делает проверку на доступность файла настроек, правильность заданий в системе и возможность
* модификации скрипта обработчика крона
*/
public function testAction()
{
$success = true;
// Проверяем доступность файла настроек для чтения
if (is_readable($this->dataFile)) {
$this->message .= "Файл с настройками сайта существует и доступен для чтения\n";
} else {
$this->message .= "Файл с настройками сайта {$this->dataFile} не существует или он недоступен для чтения\n";
$success = false;
}
// Проверяем доступность запускаемого файла для изменения его даты
if (is_writable($this->cronFile)) {
$this->message .= "Файл \"" . $this->cronFile . "\" позволяет вносить изменения в дату модификации\n";
} else {
$this->message .= "Не получается изменить дату модификации файла \"" . $this->cronFile . "\"\n";
$success = false;
}
// Загружаем данные из cron-файла в переменные класса
try {
$this->loadCrontab($this->cronFile);
} catch (\Exception $e) {
$this->message .= $e->getMessage() . "\n";
$success = false;
}
// Проверяем правильность задач в файле
if (!$this->testTasks($this->cron)) {
$success = false;
}
return $success;
}
/**
* Проверяет правильность введённых задач
*
* @param array $cron Список задач крона
* @return bool Правильно или нет записаны задачи крона
*/
public function testTasks($cron)
{
$success = true;
$taskIsset = false;
$tasks = $currentTasks = '';
foreach ($cron as $cronTask) {
list($taskExpression, $fileTask) = $this->parseCronTask($cronTask);
// Проверяем правильность написания выражения для крона и существование файла для выполнения
if (\Cron\CronExpression::isValidExpression($taskExpression) !== true) {
$this->message .= "Неверное выражение \"{$taskExpression}\"\n";
$success = false;
}
if ($fileTask && !is_readable($fileTask)) {
$this->message .= "Файл \"{$fileTask}\" не существует или он недоступен для чтения\n";
$success = false;
} elseif (!$fileTask) {
$this->message .= "Не задан исполняемый файл для выражения \"{$taskExpression}\"\n";
$success = false;
}
// Получаем дату следующего запуска задачи
$cronModel = \Cron\CronExpression::factory($taskExpression);
$nextRunDate = $cronModel->getNextRunDate($this->modifyTime);
$tasks .= $cronTask . "\nСледующий запуск файла \"{$fileTask}\" назначен на "
. $nextRunDate->format('d.m.Y H:i:s') . "\n";
$taskIsset = true;
// Если дата следующего запуска меньше, либо равна текущей дате, то добавляем задачу на запуск
$now = new \DateTime();
if ($nextRunDate <= $now) {
$currentTasks .= $cronTask . "\n" . $fileTask . "\n"
. 'modify: ' . $this->modifyTime->format('d.m.Y H:i:s') . "\n"
. 'nextRun: ' . $nextRunDate->format('d.m.Y H:i:s') . "\n"
. 'now: ' . $now->format('d.m.Y H:i:s') . "\n";
}
}
// Если в задачах из настройках Ideal CMS не обнаружено ошибок, уведомляем об этом
if ($success && $taskIsset) {
$this->message .= "В задачах из файла crontab ошибок не обнаружено\n";
} elseif (!$taskIsset) {
$this->message .= implode("\n", $cron) . "Пока нет ни одного задания для выполнения\n";
}
// Отображение информации о задачах, требующих запуска в данный момент
if ($currentTasks && $success) {
$this->message .= "\nЗадачи для запуска в данный момент:\n";
$this->message .= $currentTasks;
} elseif ($taskIsset && $success) {
$this->message .= "\nВ данный момент запуск задач не требуется\n";
}
// Отображение информации о запланированных задачах и времени их запуска
$tasks = $tasks && $success ? "\nЗапланированные задачи:\n" . $tasks : '';
$this->message .= $tasks . "\n";
return $success;
}
/**
* Обработка задач крона и запуск нужных задач
* @throws \Exception
*/
public function runAction()
{
// Загружаем данные из cron-файла
$this->loadCrontab($this->cronFile);
// Вычисляем путь до файла "site_data.php" в корне админки
$dataFileName = stream_resolve_include_path($this->dataFile);
// Получаем данные настроек системы
$siteData = require $dataFileName;
$data = array(
'domain' => $siteData['domain'],
'robotEmail' => $siteData['robotEmail'],
'adminEmail' => $this->cronEmail ? $this->cronEmail : $siteData['cms']['adminEmail'],
);
// Переопределяем стандартный обработчик ошибок для отправки уведомлений на почту
set_error_handler(function ($errno, $errstr, $errfile, $errline) use ($data) {
// Формируем текст ошибки
$_err = 'Ошибка [' . $errno . '] ' . $errstr . ', в строке ' . $errline . ' файла ' . $errfile;
// Выводим текст ошибки
echo $_err . "\n";
// Формируем заголовки письма и отправляем уведомление об ошибке на почту ответственного лица
$header = "From: \"{$data['domain']}\" <{$data['robotEmail']}>\r\n";
$header .= "Content-type: text/plain; charset=\"utf-8\"";
mail($data['adminEmail'], 'Ошибка при выполнении крона', $_err, $header);
});
// Обрабатываем задачи для крона из настроек Ideal CMS
$nowCron = new \DateTime();
foreach ($this->cron as $cronTask) {
list($taskExpression, $fileTask) = $this->parseCronTask($cronTask);
if (!$taskExpression || !$fileTask) {
continue;
}
// Получаем дату следующего запуска задачи
$cron = \Cron\CronExpression::factory($taskExpression);
$nextRunDate = $cron->getNextRunDate($this->modifyTime);
$nowCron = new \DateTime();
// Если дата следующего запуска меньше, либо равна текущей дате, то запускаем скрипт
if ($nextRunDate <= $nowCron) {
// Что бы не случилось со скриптом, изменяем дату модификации файла содержащего задачи для крона
touch($this->cronFile, $nowCron->getTimestamp());
// todo завести отдельный временный файл, куда записывать дату последнего прохода по крону, чтобы
// избежать ситуации, когда два задания должны выполниться в одну минуту, а выполняется только одно
// Запускаем скрипт
require_once $fileTask;
break; // Прекращаем цикл выполнения задач, чтобы не произошло наложения задач друг на друга
}
}
// Изменяем дату модификации файла содержащего задачи для крона
touch($this->cronFile, $nowCron->getTimestamp());
}
/**
* Возвращает сообщения после тестирования cron'а
*
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Разбирает задачу для крона из настроек Ideal CMS
* @param string $cronTask Строка в формате "* * * * * /path/to/file.php"
* @return array Массив, где первым элементом является строка соответствующая интервалу запуска задачи по крону,
* а вторым элементом является путь до запускаемого файла
*/
protected function parseCronTask($cronTask)
{
// Получаем cron-формат запуска файла в первых пяти элементах массива и путь до файла в последнем элементе
$taskParts = explode(' ', $cronTask, 6);
$fileTask = '';
if (count($taskParts) >= 6) {
$fileTask = array_pop($taskParts);
}
// Если запускаемый скрипт указан относительно корня сайта, то абсолютизируем его
if ($fileTask && strpos($fileTask, '/') !== 0) {
$fileTask = $this->siteRoot . '/' . $fileTask;
}
$fileTask = trim($fileTask);
$taskExpression = implode(' ', $taskParts);
return array($taskExpression, $fileTask);
}
/**
* Загружаем данные из крона в переменные cron, cronEmail, modifyTime
*
* @throws \Exception
*/
private function loadCrontab($fileName)
{
$fileName = stream_resolve_include_path($fileName);
if ($fileName) {
$this->cron = $this->parseCrontab(file_get_contents($fileName));
} else {
$this->cron = array();
$fileName = stream_resolve_include_path(dirname($fileName)) . 'crontab';
file_put_contents($fileName, '');
}
$this->cronFile = $fileName;
// Получаем дату модификации скрипта (она же считается датой последнего запуска)
$this->modifyTime = new \DateTime();
$this->modifyTime->setTimestamp(filemtime($fileName));
}
/**
* Извлечение почтового адреса для отправки уведомлений с крона. Формат MAILTO="email@email.com"
*
* @param string $cronString Необработанный crontab
* @return array Обработанный crontab
*/
public function parseCrontab($cronString)
{
$cron = explode(PHP_EOL, $cronString);
foreach ($cron as $k => $item) {
$item = trim($item);
if (empty($item)) {
// Пропускаем пустые строки
continue;
}
if ($item[0] === '#') {
// Если это комментарий, то удаляем его из задач
unset($cron[$k]);
continue;
}
if (stripos($item, 'mailto') !== false) {
// Если это адрес, извлекаем его
$arr = explode('=', $item);
if (empty($arr[1])) {
$this->message = 'Некорректно указан почтовый ящик для отправки сообщений';
}
$email = trim($arr[1]);
$this->cronEmail = trim($email, '"\'');
// Убираем строку с адресом из списка задач
unset($cron[$k]);
}
}
return $cron;
}
}
| ideals/Ideal-CMS | Library/Cron/CronClass.php | PHP | lgpl-3.0 | 14,959 |
/*
* Created on May 19, 2008
*
* Copyright (c) 2008, The JUNG Authors
*
* All rights reserved.
*
* This software is open-source under the BSD license; see either
* "license.txt" or
* https://github.com/jrtom/jung/blob/master/LICENSE for a description.
*/
package edu.uci.ics.jung.algorithms.filters;
import java.util.Collection;
import com.google.common.base.Predicate;
import edu.uci.ics.jung.graph.Graph;
/**
* Transforms the input graph into one which contains only those vertices
* that pass the specified <code>Predicate</code>. The filtered graph
* is a copy of the original graph (same type, uses the same vertex and
* edge objects). Only those edges whose entire incident vertex collection
* passes the predicate are copied into the new graph.
*
* @author Joshua O'Madadhain
*/
public class VertexPredicateFilter<V,E> implements Filter<V,E>
{
protected Predicate<V> vertex_pred;
/**
* Creates an instance based on the specified vertex <code>Predicate</code>.
* @param vertex_pred the predicate that specifies which vertices to add to the filtered graph
*/
public VertexPredicateFilter(Predicate<V> vertex_pred)
{
this.vertex_pred = vertex_pred;
}
@SuppressWarnings("unchecked")
public Graph<V,E> apply(Graph<V,E> g)
{
Graph<V, E> filtered;
try
{
filtered = g.getClass().newInstance();
}
catch (InstantiationException e)
{
throw new RuntimeException("Unable to create copy of existing graph: ", e);
}
catch (IllegalAccessException e)
{
throw new RuntimeException("Unable to create copy of existing graph: ", e);
}
for (V v : g.getVertices())
if (vertex_pred.apply(v))
filtered.addVertex(v);
Collection<V> filtered_vertices = filtered.getVertices();
for (E e : g.getEdges())
{
Collection<V> incident = g.getIncidentVertices(e);
if (filtered_vertices.containsAll(incident))
filtered.addEdge(e, incident);
}
return filtered;
}
}
| drzhonghao/grapa | jung-algorithms/src/main/java/edu/uci/ics/jung/algorithms/filters/VertexPredicateFilter.java | Java | lgpl-3.0 | 2,185 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* 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, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.ce;
import org.sonar.ce.queue.CeQueueImpl;
import org.sonar.ce.task.log.CeTaskLogging;
import org.sonar.core.platform.Module;
import org.sonar.server.ce.http.CeHttpClientImpl;
public class CeModule extends Module {
@Override
protected void configureModule() {
add(CeTaskLogging.class,
CeHttpClientImpl.class,
// Queue
CeQueueImpl.class);
}
}
| SonarSource/sonarqube | server/sonar-webserver-core/src/main/java/org/sonar/server/ce/CeModule.java | Java | lgpl-3.0 | 1,241 |
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* 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, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import * as React from 'react';
import { shallow } from 'enzyme';
import SearchFilterContainer from '../SearchFilterContainer';
it('searches', () => {
const onQueryChange = jest.fn();
const wrapper = shallow(<SearchFilterContainer onQueryChange={onQueryChange} query={{}} />);
expect(wrapper).toMatchSnapshot();
wrapper.find('SearchBox').prop<Function>('onChange')('foo');
expect(onQueryChange).toBeCalledWith({ search: 'foo' });
});
| Godin/sonar | server/sonar-web/src/main/js/apps/projects/filters/__tests__/SearchFilterContainer-test.tsx | TypeScript | lgpl-3.0 | 1,288 |
<?php
/**
* This file is part of MetaModels/core.
*
* (c) 2012-2019 The MetaModels team.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This project is provided in good faith and hope to be usable by anyone.
*
* @package MetaModels/core
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @author David Maack <david.maack@arcor.de>
* @author Sven Baumann <baumann.sv@gmail.com>
* @copyright 2012-2019 The MetaModels team.
* @license https://github.com/MetaModels/core/blob/master/LICENSE LGPL-3.0-or-later
* @filesource
*/
namespace MetaModels\Helper;
/**
* Gateway to the Contao "Controller" class for usage of the core without
* importing any class.
*
* This is achieved using the magic functions which will relay the call
* to the parent class Controller. See there for a list of function that can
* be called (everything in Controller.php that is declared as protected).
*
* @deprecated Deprecated in favor of contao-events-bindings
*/
class ContaoController extends \Controller
{
/**
* The instance.
*
* @var ContaoController
*/
protected static $objInstance = null;
/**
* Get the static instance.
*
* @static
* @return ContaoController
*/
public static function getInstance()
{
if (self::$objInstance == null) {
self::$objInstance = new self();
}
return self::$objInstance;
}
/**
* Protected constructor for singleton instance.
*/
protected function __construct()
{
parent::__construct();
$this->import('Database');
}
/**
* Makes all protected methods from class Controller callable publically.
*
* @param string $strMethod The method to call.
*
* @param array $arrArgs The arguments.
*
* @return mixed
*
* @throws \RuntimeException When the method is unknown.
*/
public function __call($strMethod, $arrArgs)
{
if (method_exists($this, $strMethod)) {
return call_user_func_array(array($this, $strMethod), $arrArgs);
}
throw new \RuntimeException('undefined method: Controller::' . $strMethod);
}
/**
* Makes all protected methods from class Controller callable publically from static context (requires PHP 5.3).
*
* @param string $strMethod The method to call.
*
* @param array $arrArgs The arguments.
*
* @return mixed
*
* @throws \RuntimeException When the method is unknown.
*/
public static function __callStatic($strMethod, $arrArgs)
{
if (method_exists(__CLASS__, $strMethod)) {
return call_user_func_array(array(self::getInstance(), $strMethod), $arrArgs);
}
throw new \RuntimeException('undefined method: Controller::' . $strMethod);
}
}
| MetaModels/core | src/Helper/ContaoController.php | PHP | lgpl-3.0 | 2,956 |
/*
* This file is part of AlmightyNotch.
*
* Copyright (c) 2014 <http://dev.bukkit.org/server-mods/almightynotch//>
*
* AlmightyNotch 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.
*
* AlmightyNotch 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 AlmightyNotch. If not, see <http://www.gnu.org/licenses/>.
*/
package ninja.amp.almightynotch.event.player;
public class QuicksandEvent {
// Moods: Bored, Displeased
// Mood Modifier: 5
}
| ampayne2/AlmightyNotch | src/main/java/ninja/amp/almightynotch/event/player/QuicksandEvent.java | Java | lgpl-3.0 | 931 |
/*
* Intake, a command processing library
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) Intake team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.intake.example.i18n;
import com.sk89q.intake.example.i18n.util.Messages;
import com.sk89q.intake.util.i18n.ResourceProvider;
public class ExampleResourceProvider implements ResourceProvider {
private final Messages msg = new Messages(I18nExample.RESOURCE_NAME);
@Override
public String getString(String key) {
return msg.getString(key);
}
}
| TheE/Intake | intake-example/src/main/java/com/sk89q/intake/example/i18n/ExampleResourceProvider.java | Java | lgpl-3.0 | 1,183 |
/*
* Copyright (c) 2013 University of Nice Sophia-Antipolis
*
* This file is part of btrplace.
* 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 btrplace.btrpsl.constraint;
import btrplace.model.constraint.SatConstraint;
import org.reflections.Reflections;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;
/**
* Unit tests for {@link DefaultConstraintsCatalog}.
*
* @author Fabien Hermenier
*/
public class DefaultConstraintsCatalogTest {
/**
* Check if there is a builder for each SatConstraint
* bundled with btrplace-api.
*/
@Test
public void testCovering() throws Exception {
DefaultConstraintsCatalog c = DefaultConstraintsCatalog.newBundle();
Reflections reflections = new Reflections("btrplace.model");
Set<Class<? extends SatConstraint>> impls = new HashSet<>();
for (Class cstr : reflections.getSubTypesOf(SatConstraint.class)) {
if (!Modifier.isAbstract(cstr.getModifiers())) {
impls.add(cstr);
}
}
Assert.assertEquals(c.getAvailableConstraints().size(), impls.size());
}
}
| fhermeni/btrplace-btrpsl | src/test/java/btrplace/btrpsl/constraint/DefaultConstraintsCatalogTest.java | Java | lgpl-3.0 | 1,816 |
/*
Copyright 2012-2014 Infinitycoding all rights reserved
This file is part of the HugeUniversalGameEngine.
HUGE 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.
HUGE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the Universe Kernel. If not, see <http://www.gnu.org/licenses/>.
*/
/*
@author Michael Sippel <micha@infinitycoding.de>
*/
#include <huge/math/vector.h>
#include <huge/sdl.h>
namespace huge
{
namespace sdl
{
int init(void)
{
return SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
}
Window::Window()
: title(NULL), size(Vector2i(800, 600))
{
}
Window::Window(char *title_)
: title(title_), size(Vector2i(800, 600))
{
}
Window::Window(Vector2i size_)
: title(NULL), size(size_)
{
}
Window::Window(char *title_, Vector2i size_)
: title(title_), size(size_)
{
}
Window::~Window()
{
}
GLContext::GLContext()
{
GLContext(new GLWindow());
}
GLContext::GLContext(Window *window_)
: window(window_)
{
this->sdl_context = (SDL_GLContext*) SDL_GL_CreateContext(this->window->sdl_window);
if(this->sdl_context == NULL)
{
printf("OpenGL context creation failed!\n");
}
}
GLContext::~GLContext()
{
SDL_GL_DeleteContext(this->sdl_context);
}
void GLContext::activate_(void)
{
SDL_GL_MakeCurrent(this->window->sdl_window, this->sdl_context);
}
GLWindow::GLWindow()
{
this->create();
}
GLWindow::GLWindow(char *title_)
{
this->title = title_;
this->create();
}
GLWindow::GLWindow(Vector2i size_)
{
this->size = size_;
this->create();
}
GLWindow::GLWindow(char *title_, Vector2i size_)
{
this->title = title_;
this->size = size_;
this->create();
}
GLWindow::~GLWindow()
{
SDL_DestroyWindow(this->sdl_window);
}
void GLWindow::swap(void)
{
SDL_GL_SwapWindow(this->sdl_window);
}
void GLWindow::create(void)
{
this->sdl_window = SDL_CreateWindow(this->title, 0, 0, this->size.x(), this->size.y(), SDL_WINDOW_OPENGL);
if(this->sdl_window == NULL)
{
printf("SDL window creation failed!\n");
}
}
}; // namespace sdl
}; // namespace huge
| infinitycoding/huge | src/sdl/sdl.cpp | C++ | lgpl-3.0 | 2,586 |
<?php
require_once(__DIR__."/../model/JuradoProfesional.php");
require_once(__DIR__."/../model/JuradoProfesionalMapper.php");
require_once(__DIR__."/../model/User.php");
require_once(__DIR__."/../model/UserMapper.php");
require_once(__DIR__."/../model/Concurso.php");
require_once(__DIR__."/../model/ConcursoMapper.php");
require_once(__DIR__."/../core/ViewManager.php");
require_once(__DIR__."/../controller/BaseController.php");
require_once(__DIR__."/../controller/UsersController.php");
class JuradoProfesionalController extends BaseController {
private $juradoProfesionalMapper;
private $userMapper;
private $concursoMapper;
public function __construct() {
parent::__construct();
$this->juradoProfesionalMapper = new JuradoProfesionalMapper();
$this->concursoMapper = new ConcursoMapper();
$this->userMapper = new UserMapper();
}
/*redirecciona a la página principal del sitio web*/
public function index() {
$juradoProfesional = $this->juradoProfesionalMapper->findAll();
$concursos = $this->concursoMapper->findConcurso("pinchosOurense");
$this->view->setVariable("juradoProfesional", $juradoProfesional);
$this->view->setVariable("concursos", $concursos);
$this->view->render("concursos", "index");
}
/*redirecciona a la vista del perfil del jurado profesional*/
public function perfil(){
$currentuser = $this->view->getVariable("currentusername");
$juradoProfesional = $this->juradoProfesionalMapper->findById($currentuser);
$this->view->setVariable("juradoPro", $juradoProfesional);
$this->view->render("juradoProfesional", "perfil");
}
/*redirecciona al formulario de modificacion de los datos de un jurado profesional*/
public function modificar(){
$currentuser = $this->view->getVariable("currentusername");
$juradoProfesional = $this->juradoProfesionalMapper->findById($currentuser);
$this->view->setVariable("juradoPro", $juradoProfesional);
$this->view->render("juradoProfesional", "modificar");
}
/*Recupera los datos del formulario de modificacion de un jurado profesional,
comprueba que son correctos y llama a update() de JuradoProfesionalMapper.php
donde se realiza la actualizacion de los datos.*/
public function update(){
$jproid = $_REQUEST["usuario"];
$jpro = $this->juradoProfesionalMapper->findById($jproid);
$errors = array();
if($this->userMapper->isValidUser($_POST["usuario"],$_POST["passActual"])){
if (isset($_POST["submit"])) {
$jpro->setNombre($_POST["nombre"]);
$jpro->setEmail($_POST["correo"]);
$jpro->setProfesion($_POST["profesion"]);
if(!(strlen(trim($_POST["passNew"])) == 0)){
if ($_POST["passNew"]==$_POST["passNueva"]) {
$jpro->setPassword($_POST["passNueva"]);
}
else{
$errors["pass"] = "Las contraseñas tienen que ser iguales";
$this->view->setVariable("errors", $errors);
$this->view->setVariable("juradoPro", $jpro);
$this->view->render("juradoProfesional", "modificar");
return false;
}
}
try{
$this->juradoProfesionalMapper->update($jpro);
$this->view->setFlash(sprintf("Usuario \"%s\" modificado correctamente.",$jpro ->getNombre()));
$this->view->redirect("juradoProfesional", "index");
}catch(ValidationException $ex) {
$errors = $ex->getErrors();
$this->view->setVariable("errors", $errors);
}
}
}
else{
$errors["passActual"] = "<span>La contraseña es obligatoria</span>";
$this->view->setVariable("errors", $errors);
$this->view->setVariable("juradoPro", $jpro);
$this->view->render("juradoProfesional", "modificar");
}
}
/*Llama a delete() de JuradoProfesionalMapper.php que elimina un jurado profesional y las votaciones
que este realizó.*/
public function eliminar(){
$jproid = $_REQUEST["usuario"];
$juradoProfesional = $this->juradoProfesionalMapper->findById($jproid);
// Does the post exist?
if ($juradoProfesional == NULL) {
throw new Exception("No existe el usuario ".$jproid);
}
// Delete the Jurado Popular object from the database
$this->juradoProfesionalMapper->delete($juradoProfesional);
$this->view->setFlash(sprintf("Usuario \"%s\" eliminado.",$juradoProfesional ->getId()));
$this->view->redirect("organizador", "index");
}
/*lista los jurado profesionales para eliminarlos*/
public function listarEliminar(){
$juradoProfesional = $this->juradoProfesionalMapper->findAll();
$this->view->setVariable("juradoProfesional", $juradoProfesional);
$this->view->render("juradoProfesional", "listaEliminar");
}
/*lista los jurados profesionales*/
public function listar(){
$juradoProfesional = $this->juradoProfesionalMapper->findAll();
$this->view->setVariable("juradoProfesional", $juradoProfesional);
$this->view->render("juradoProfesional", "listar");
}
/*redirecciona a la vista de votar de un jurado profesional*/
public function votar(){
$currentuser = $this->view->getVariable("currentusername");
$juradoProfesional = $this->juradoProfesionalMapper->findById($currentuser);
//devuelve los pinchos con sus votos de un jurado profesional
$votos = $this->juradoProfesionalMapper->votos($currentuser);
//devuelve la ronda en la que esta el jurado profesional
$ronda = $this->juradoProfesionalMapper->getRonda($currentuser);
$this->view->setVariable("juradoPro", $juradoProfesional);
$this->view->setVariable("votos", $votos);
$this->view->setVariable("ronda", $ronda);
$this->view->render("juradoProfesional", "votar");
}
/*modifica el pincho y su voto correspondiente de un jurado profesional*/
public function votarPincho(){
$currentuser = $this->view->getVariable("currentusername");
$juradoProfesional = $this->juradoProfesionalMapper->findById($currentuser);
$votos = $this->juradoProfesionalMapper->votar($_POST['currentusername'], $_POST['idPincho'], $_POST['voto']);
$this->view->redirect("juradoProfesional", "votar");
}
}
| xrlopez/ABP | controller/JuradoProfesionalController.php | PHP | lgpl-3.0 | 6,331 |
let idCounter = 0;
function nextId() {
return ++idCounter;
}
// if the platform throws an exception, the worker will kill & restart it, however if a callback comes in there could
// be a race condition which tries to still access session functions which have already been terminated by the worker.
// this function wrapper only calls the session functions if they still exist.
function referenceProtection(session) {
if (typeof session === 'undefined') { throw new Error('session object not provided'); }
function checkScope(funcName) {
return (msg) => {
if (typeof session[funcName] === 'function') {
session[funcName](msg);
}
}
}
return {
actor: session.actor,
debug: checkScope('debug'),
sendToClient: checkScope('sendToClient')
}
}
class IncomingHandlers {
constructor(session) {
this.session = referenceProtection(session);
}
buddy(from, state, statusText) {
if (from !== this.session.actor['@id']) {
this.session.debug('received buddy presence update: ' + from + ' - ' + state);
this.session.sendToClient({
'@type': 'update',
actor: { '@id': from },
target: this.session.actor,
object: {
'@type': 'presence',
status: statusText,
presence: state
}
});
}
}
buddyCapabilities(id, capabilities) {
this.session.debug('received buddyCapabilities: ' + id);
}
chat(from, message) {
this.session.debug("received chat message from " + from);
this.session.sendToClient({
'@type': 'send',
actor: {
'@type': 'person',
'@id': from
},
target: this.session.actor,
object: {
'@type': 'message',
content: message,
'@id': nextId()
}
});
}
chatstate(from, name) {
this.session.debug('received chatstate event: ' + from, name);
}
close() {
this.session.debug('received close event with no handler specified');
this.session.sendToClient({
'@type': 'close',
actor: this.session.actor,
target: this.session.actor
});
this.session.debug('**** xmpp this.session.for ' + this.session.actor['@id'] + ' closed');
this.session.connection.disconnect();
}
error(error) {
try {
this.session.debug("*** XMPP ERROR (rl): " + error);
this.session.sendToClient({
'@type': 'error',
object: {
'@type': 'error',
content: error
}
});
} catch (e) {
this.session.debug('*** XMPP ERROR (rl catch): ', e);
}
}
groupBuddy(id, groupBuddy, state, statusText) {
this.session.debug('received groupbuddy event: ' + id);
this.session.sendToClient({
'@type': 'update',
actor: {
'@id': `${id}/${groupBuddy}`,
'@type': 'person',
displayName: groupBuddy
},
target: {
'@id': id,
'@type': 'room'
},
object: {
'@type': 'presence',
status: statusText,
presence: state
}
});
}
groupChat(room, from, message, stamp) {
this.session.debug('received groupchat event: ' + room, from, message, stamp);
this.session.sendToClient({
'@type': 'send',
actor: {
'@type': 'person',
'@id': from
},
target: {
'@type': 'room',
'@id': room
},
object: {
'@type': 'message',
content: message,
'@id': nextId()
}
});
}
online() {
this.session.debug('online');
this.session.debug('reconnectioned ' + this.session.actor['@id']);
}
subscribe(from) {
this.session.debug('received subscribe request from ' + from);
this.session.sendToClient({
'@type': "request-friend",
actor: { '@id': from },
target: this.session.actor
});
}
unsubscribe(from) {
this.session.debug('received unsubscribe request from ' + from);
this.session.sendToClient({
'@type': "remove-friend",
actor: { '@id': from },
target: this.session.actor
});
}
/**
* Handles all unknown conditions that we don't have an explicit handler for
**/
__stanza(stanza) {
// simple-xmpp currently doesn't seem to handle error state presence so we'll do it here for now.
// TODO: consider moving this.session.to simple-xmpp once it's ironed out and proven to work well.
if ((stanza.attrs.type === 'error')) {
const error = stanza.getChild('error');
let message = stanza.toString();
let type = 'message';
if (stanza.is('presence')) {
type = 'update';
}
if (error) {
message = error.toString();
if (error.getChild('remote-server-not-found')) {
// when we get this.session.type of return message, we know it was a response from a join
type = 'join';
message = 'remote server not found ' + stanza.attrs.from;
}
}
this.session.sendToClient({
'@type': type,
actor: {
'@id': stanza.attrs.from,
'@type': 'room'
},
object: {
'@type': 'error', // type error
content: message
},
target: {
'@id': stanza.attrs.to,
'@type': 'person'
}
});
} else if (stanza.is('iq')) {
if (stanza.attrs.id === 'muc_id' && stanza.attrs.type === 'result') {
this.session.debug('got room attendance list');
this.roomAttendance(stanza);
return;
}
const query = stanza.getChild('query');
if (query) {
const entries = query.getChildren('item');
for (let e in entries) {
if (! entries.hasOwnProperty(e)) {
continue;
}
this.session.debug('STANZA ATTRS: ', entries[e].attrs);
if (entries[e].attrs.subscription === 'both') {
this.session.sendToClient({
'@type': 'update',
actor: { '@id': entries[e].attrs.jid, displayName: entries[e].attrs.name },
target: this.session.actor,
object: {
'@type': 'presence',
status: '',
presence: state
}
});
} else if ((entries[e].attrs.subscription === 'from') &&
(entries[e].attrs.ask) && (entries[e].attrs.ask === 'subscribe')) {
this.session.sendToClient({
'@type': 'update',
actor: { '@id': entries[e].attrs.jid, displayName: entries[e].attrs.name },
target: this.session.actor,
object: {
'@type': 'presence',
statusText: '',
presence: 'notauthorized'
}
});
} else {
/**
* cant figure out how to know if one of these query stanzas are from
* added contacts or pending requests
*/
this.session.sendToClient({
'@type': 'request-friend',
actor: { '@id': entries[e].attrs.jid, displayName: entries[e].attrs.name },
target: this.session.actor
});
}
}
}
// } else {
// this.session.debug("got XMPP unknown stanza... " + stanza);
}
}
roomAttendance(stanza) {
const query = stanza.getChild('query');
if (query) {
let members = [];
const entries = query.getChildren('item');
for (let e in entries) {
if (!entries.hasOwnProperty(e)) {
continue;
}
members.push(entries[e].attrs.name);
}
this.session.sendToClient({
'@type': 'observe',
actor: {
'@id': stanza.attrs.from,
'@type': 'room'
},
target: {
'@id': stanza.attrs.to,
'@type': 'person'
},
object: {
'@type': 'attendance',
members: members
}
});
}
}
}
module.exports = IncomingHandlers;
| sockethub/sockethub-platform-xmpp | lib/incoming-handlers.js | JavaScript | lgpl-3.0 | 7,988 |
# -*- coding: utf-8 -*-
module Vnet
module Event
#
# Shared events:
#
ACTIVATE_INTERFACE = "activate_interface"
DEACTIVATE_INTERFACE = "deactivate_interface"
# *_INITIALIZED
#
# First event queued after the non-yielding and non-blocking
# initialization of an item query from the database.
#
# *_UNLOAD_ITEM
#
# When the node wants to unload it's own loaded items the
# 'unload_item' event should be used instead of 'deleted_item'.
#
# *_CREATED_ITEM
#
# The item was added to the database and basic information of
# the item sent to relevant nodes. The manager should decide if it
# should initialize the item or not.
#
# *_DELETED_ITEM
#
# The item was deleted from the database and should be unloaded
# from all nodes.
#
# Active Interface events:
#
ACTIVE_INTERFACE_INITIALIZED = "active_interface_initialized"
ACTIVE_INTERFACE_UNLOAD_ITEM = "active_interface_unload_item"
ACTIVE_INTERFACE_CREATED_ITEM = "active_interface_created_item"
ACTIVE_INTERFACE_DELETED_ITEM = "active_interface_deleted_item"
ACTIVE_INTERFACE_UPDATED = "active_interface_updated"
#
# Active Network events:
#
ACTIVE_NETWORK_INITIALIZED = "active_network_initialized"
ACTIVE_NETWORK_UNLOAD_ITEM = "active_network_unload_item"
ACTIVE_NETWORK_CREATED_ITEM = "active_network_created_item"
ACTIVE_NETWORK_DELETED_ITEM = "active_network_deleted_item"
ACTIVE_NETWORK_ACTIVATE = "active_network_activate"
ACTIVE_NETWORK_DEACTIVATE = "active_network_deactivate"
#
# Active Route Link events:
#
ACTIVE_ROUTE_LINK_INITIALIZED = "active_route_link_initialized"
ACTIVE_ROUTE_LINK_UNLOAD_ITEM = "active_route_link_unload_item"
ACTIVE_ROUTE_LINK_CREATED_ITEM = "active_route_link_created_item"
ACTIVE_ROUTE_LINK_DELETED_ITEM = "active_route_link_deleted_item"
ACTIVE_ROUTE_LINK_ACTIVATE = "active_route_link_activate"
ACTIVE_ROUTE_LINK_DEACTIVATE = "active_route_link_deactivate"
#
# Active Segment events:
#
ACTIVE_SEGMENT_INITIALIZED = "active_segment_initialized"
ACTIVE_SEGMENT_UNLOAD_ITEM = "active_segment_unload_item"
ACTIVE_SEGMENT_CREATED_ITEM = "active_segment_created_item"
ACTIVE_SEGMENT_DELETED_ITEM = "active_segment_deleted_item"
ACTIVE_SEGMENT_ACTIVATE = "active_segment_activate"
ACTIVE_SEGMENT_DEACTIVATE = "active_segment_deactivate"
#
# Active Port events:
#
ACTIVE_PORT_INITIALIZED = "active_port_initialized"
ACTIVE_PORT_UNLOAD_ITEM = "active_port_unload_item"
ACTIVE_PORT_CREATED_ITEM = "active_port_created_item"
ACTIVE_PORT_DELETED_ITEM = "active_port_deleted_item"
ACTIVE_PORT_ACTIVATE = "active_port_activate"
ACTIVE_PORT_DEACTIVATE = "active_port_deactivate"
#
# Datapath events:
#
DATAPATH_INITIALIZED = 'datapath_initialized'
DATAPATH_UNLOAD_ITEM = 'datapath_unload_item'
DATAPATH_CREATED_ITEM = 'datapath_created_item'
DATAPATH_DELETED_ITEM = 'datapath_deleted_item'
DATAPATH_UPDATED_ITEM = 'datapath_updated_item'
HOST_DATAPATH_INITIALIZED = 'host_datapath_initialized'
HOST_DATAPATH_UNLOAD_ITEM = 'host_datapath_unload_item'
ACTIVATE_NETWORK_ON_HOST = 'activate_network_on_host'
DEACTIVATE_NETWORK_ON_HOST = 'deactivate_network_on_host'
ADDED_DATAPATH_NETWORK = 'added_datapath_network'
REMOVED_DATAPATH_NETWORK = 'removed_datapath_network'
ACTIVATE_DATAPATH_NETWORK = 'activate_datapath_network'
DEACTIVATE_DATAPATH_NETWORK = 'deactivate_datapath_network'
ACTIVATE_SEGMENT_ON_HOST = 'activate_segment_on_host'
DEACTIVATE_SEGMENT_ON_HOST = 'deactivate_segment_on_host'
ADDED_DATAPATH_SEGMENT = 'added_datapath_segment'
REMOVED_DATAPATH_SEGMENT = 'removed_datapath_segment'
ACTIVATE_DATAPATH_SEGMENT = 'activate_datapath_segment'
DEACTIVATE_DATAPATH_SEGMENT = 'deactivate_datapath_segment'
ACTIVATE_ROUTE_LINK_ON_HOST = 'activate_route_link_on_host'
DEACTIVATE_ROUTE_LINK_ON_HOST = 'deactivate_route_link_on_host'
ADDED_DATAPATH_ROUTE_LINK = 'added_datapath_route_link'
REMOVED_DATAPATH_ROUTE_LINK = 'removed_datapath_route_link'
ACTIVATE_DATAPATH_ROUTE_LINK = 'activate_datapath_route_link'
DEACTIVATE_DATAPATH_ROUTE_LINK = 'deactivate_datapath_route_link'
#
# Interface events:
#
INTERFACE_INITIALIZED = "interface_initialized"
INTERFACE_UNLOAD_ITEM = "interface_unload_item"
INTERFACE_CREATED_ITEM = "interface_created_item"
INTERFACE_DELETED_ITEM = "interface_deleted_item"
INTERFACE_UPDATED = "interface_updated"
INTERFACE_ENABLED_FILTERING = "interface_enabled_filtering"
INTERFACE_DISABLED_FILTERING = "interface_disabled_filtering"
INTERFACE_ENABLED_FILTERING2 = "interface_enabled_filtering2"
INTERFACE_DISABLED_FILTERING2 = "interface_disabled_filtering2"
# MAC and IPv4 addresses:
INTERFACE_LEASED_MAC_ADDRESS = "interface_leased_mac_address"
INTERFACE_RELEASED_MAC_ADDRESS = "interface_released_mac_address"
INTERFACE_LEASED_IPV4_ADDRESS = "interface_leased_ipv4_address"
INTERFACE_RELEASED_IPV4_ADDRESS = "interface_released_ipv4_address"
#
# Interface Network events:
#
INTERFACE_NETWORK_INITIALIZED = "interface_network_initialized"
INTERFACE_NETWORK_UNLOAD_ITEM = "interface_network_unload_item"
INTERFACE_NETWORK_CREATED_ITEM = "interface_network_created_item"
INTERFACE_NETWORK_DELETED_ITEM = "interface_network_deleted_item"
INTERFACE_NETWORK_UPDATED_ITEM = "interface_network_updated_item"
#
# Interface Route Link events:
#
INTERFACE_ROUTE_LINK_INITIALIZED = "interface_route_link_initialized"
INTERFACE_ROUTE_LINK_UNLOAD_ITEM = "interface_route_link_unload_item"
INTERFACE_ROUTE_LINK_CREATED_ITEM = "interface_route_link_created_item"
INTERFACE_ROUTE_LINK_DELETED_ITEM = "interface_route_link_deleted_item"
INTERFACE_ROUTE_LINK_UPDATED_ITEM = "interface_route_link_updated_item"
#
# Interface Segment events:
#
INTERFACE_SEGMENT_INITIALIZED = "interface_segment_initialized"
INTERFACE_SEGMENT_UNLOAD_ITEM = "interface_segment_unload_item"
INTERFACE_SEGMENT_CREATED_ITEM = "interface_segment_created_item"
INTERFACE_SEGMENT_DELETED_ITEM = "interface_segment_deleted_item"
INTERFACE_SEGMENT_UPDATED_ITEM = "interface_segment_updated_item"
#
# Interface Port events:
#
INTERFACE_PORT_INITIALIZED = "interface_port_initialized"
INTERFACE_PORT_UNLOAD_ITEM = "interface_port_unload_item"
INTERFACE_PORT_CREATED_ITEM = "interface_port_created_item"
INTERFACE_PORT_DELETED_ITEM = "interface_port_deleted_item"
INTERFACE_PORT_UPDATED = "interface_port_updated"
INTERFACE_PORT_ACTIVATE = "interface_port_activate"
INTERFACE_PORT_DEACTIVATE = "interface_port_deactivate"
#
# Filter events:
#
FILTER_INITIALIZED = "filter_initialized"
FILTER_UNLOAD_ITEM = "filter_unload_item"
FILTER_CREATED_ITEM = "filter_created_item"
FILTER_DELETED_ITEM = "filter_deleted_item"
FILTER_UPDATED = "filter_updated"
FILTER_ADDED_STATIC = "filter_added_static"
FILTER_REMOVED_STATIC = "filter_removed_static"
#
# Filter events:
#
MAC_RANGE_GROUP_CREATED_ITEM = "mac_range_group_created_item"
MAC_RANGE_GROUP_DELETED_ITEM = "mac_range_group_deleted_item"
#
# Network event:
#
NETWORK_INITIALIZED = "network_initialized"
NETWORK_UNLOAD_ITEM = "network_unload_item"
NETWORK_DELETED_ITEM = "network_deleted_item"
NETWORK_UPDATE_ITEM_STATES = "network_update_item_states"
#
# lease policy event
#
LEASE_POLICY_INITIALIZED = "lease_policy_initialized"
LEASE_POLICY_CREATED_ITEM = "lease_policy_created_item"
LEASE_POLICY_DELETED_ITEM = "lease_policy_deleted_item"
#
# Port events:
#
PORT_INITIALIZED = "port_initialized"
PORT_FINALIZED = "port_finalized"
PORT_ATTACH_INTERFACE = "port_attach_interface"
PORT_DETACH_INTERFACE = "port_detach_interface"
#
# Route events:
#
ROUTE_INITIALIZED = "route_initialized"
ROUTE_UNLOAD_ITEM = "route_unload_item"
ROUTE_CREATED_ITEM = "route_created_item"
ROUTE_DELETED_ITEM = "route_deleted_item"
ROUTE_ACTIVATE_NETWORK = "route_activate_network"
ROUTE_DEACTIVATE_NETWORK = "route_deactivate_network"
ROUTE_ACTIVATE_ROUTE_LINK = "route_activate_route_link"
ROUTE_DEACTIVATE_ROUTE_LINK = "route_deactivate_route_link"
#
# Router event:
#
ROUTER_INITIALIZED = "router_initialized"
ROUTER_UNLOAD_ITEM = "router_unload_item"
ROUTER_CREATED_ITEM = "router_created_item"
ROUTER_DELETED_ITEM = "router_deleted_item"
#
# Segment events:
#
SEGMENT_INITIALIZED = "segment_initialized"
SEGMENT_UNLOAD_ITEM = "segment_unload_item"
SEGMENT_CREATED_ITEM = "segment_created_item"
SEGMENT_DELETED_ITEM = "segment_deleted_item"
SEGMENT_UPDATE_ITEM_STATES = "segment_update_item_states"
#
# Service events:
#
SERVICE_INITIALIZED = "service_initialized"
SERVICE_UNLOAD_ITEM = "service_unload_item"
SERVICE_CREATED_ITEM = "service_created_item"
SERVICE_DELETED_ITEM = "service_deleted_item"
SERVICE_ACTIVATE_INTERFACE = "service_activate_interface"
SERVICE_DEACTIVATE_INTERFACE = "service_deactivate_interface"
#
# Translation events:
#
TRANSLATION_INITIALIZED = "translation_initialized"
TRANSLATION_UNLOAD_ITEM = "translation_unload_item"
TRANSLATION_CREATED_ITEM = "translation_created_item"
TRANSLATION_DELETED_ITEM = "translation_deleted_item"
TRANSLATION_ADDED_STATIC_ADDRESS = "translation_added_static_address"
TRANSLATION_REMOVED_STATIC_ADDRESS = "translation_removed_static_address"
#
# Topology events:
#
TOPOLOGY_INITIALIZED = 'topology_initialized'
TOPOLOGY_UNLOAD_ITEM = 'topology_unload_item'
TOPOLOGY_CREATED_ITEM = 'topology_created_item'
TOPOLOGY_DELETED_ITEM = 'topology_deleted_item'
TOPOLOGY_ADDED_DATAPATH = 'topology_added_datapath'
TOPOLOGY_REMOVED_DATAPATH = 'topology_removed_datapath'
TOPOLOGY_ADDED_LAYER = 'topology_added_layer'
TOPOLOGY_REMOVED_LAYER = 'topology_removed_layer'
TOPOLOGY_ADDED_MAC_RANGE_GROUP = 'topology_added_mac_range_group'
TOPOLOGY_REMOVED_MAC_RANGE_GROUP = 'topology_removed_mac_range_group'
TOPOLOGY_ADDED_NETWORK = 'topology_added_network'
TOPOLOGY_REMOVED_NETWORK = 'topology_removed_network'
TOPOLOGY_ADDED_SEGMENT = 'topology_added_segment'
TOPOLOGY_REMOVED_SEGMENT = 'topology_removed_segment'
TOPOLOGY_ADDED_ROUTE_LINK = 'topology_added_route_link'
TOPOLOGY_REMOVED_ROUTE_LINK = 'topology_removed_route_link'
TOPOLOGY_NETWORK_ACTIVATED = 'topology_network_activated'
TOPOLOGY_NETWORK_DEACTIVATED = 'topology_network_deactivated'
TOPOLOGY_SEGMENT_ACTIVATED = 'topology_segment_activated'
TOPOLOGY_SEGMENT_DEACTIVATED = 'topology_segment_deactivated'
TOPOLOGY_ROUTE_LINK_ACTIVATED = 'topology_route_link_activated'
TOPOLOGY_ROUTE_LINK_DEACTIVATED = 'topology_route_link_deactivated'
#
# tunnel event
#
ADDED_TUNNEL = "added_tunnel"
REMOVED_TUNNEL = "removed_tunnel"
INITIALIZED_TUNNEL = "initialized_tunnel"
TUNNEL_UPDATE_PROPERTY_STATES = "tunnel_update_property_states"
ADDED_HOST_DATAPATH_NETWORK = "added_host_datapath_network"
ADDED_REMOTE_DATAPATH_NETWORK = "added_remote_datapath_network"
ADDED_HOST_DATAPATH_SEGMENT = "added_host_datapath_segment"
ADDED_REMOTE_DATAPATH_SEGMENT = "added_remote_datapath_segment"
ADDED_HOST_DATAPATH_ROUTE_LINK = "added_host_datapath_route_link"
ADDED_REMOTE_DATAPATH_ROUTE_LINK = "added_remote_datapath_route_link"
REMOVED_HOST_DATAPATH_NETWORK = "removed_host_datapath_network"
REMOVED_REMOTE_DATAPATH_NETWORK = "removed_remote_datapath_network"
REMOVED_HOST_DATAPATH_SEGMENT = "removed_host_datapath_segment"
REMOVED_REMOTE_DATAPATH_SEGMENT = "removed_remote_datapath_segment"
REMOVED_HOST_DATAPATH_ROUTE_LINK = "removed_host_datapath_route_link"
REMOVED_REMOTE_DATAPATH_ROUTE_LINK = "removed_remote_datapath_route_link"
#
# dns service
#
SERVICE_ADDED_DNS = "added_dns_service"
SERVICE_REMOVED_DNS = "removed_dns_service"
SERVICE_UPDATED_DNS = "updated_dns_service"
#
# dns record
#
ADDED_DNS_RECORD = "added_dns_record"
REMOVED_DNS_RECORD = "removed_dns_record"
#
# Ip Retention Container Events:
#
IP_RETENTION_CONTAINER_INITIALIZED = 'ip_retention_container_initialized'
IP_RETENTION_CONTAINER_UNLOAD_ITEM = 'ip_retention_container_unload_item'
IP_RETENTION_CONTAINER_CREATED_ITEM = 'ip_retention_container_created_item'
IP_RETENTION_CONTAINER_DELETED_ITEM = 'ip_retention_container_deleted_item'
IP_RETENTION_CONTAINER_ADDED_IP_RETENTION = 'ip_retention_container_added_ip_retention'
IP_RETENTION_CONTAINER_REMOVED_IP_RETENTION = 'ip_retention_container_removed_ip_retention'
IP_RETENTION_CONTAINER_LEASE_TIME_EXPIRED = 'ip_retention_container_lease_time_expired'
IP_RETENTION_CONTAINER_GRACE_TIME_EXPIRED = 'ip_retention_container_grace_time_expired'
end
end
| axsh/openvnet | vnet/lib/vnet/event.rb | Ruby | lgpl-3.0 | 13,317 |
/*
* ARMarkerSquare.cpp
* ARToolKitUWP
*
* This work is a modified version of the original "ARMarkerSquare.cpp" of
* ARToolKit. The copyright and license information of ARToolKit is included
* in this document as required by its GNU Lesser General Public License
* version 3.
*
* This file is a part of ARToolKitUWP.
*
* ARToolKitUWP 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.
*
* ARToolKitUWP 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 ARToolKitUWP. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2017 Long Qian
*
* Author: Long Qian
* Contact: lqian8@jhu.edu
*
*/
/* The original copyright information: *//*
* ARMarkerSquare.cpp
* ARToolKit5
*
* This file is part of ARToolKit.
*
* ARToolKit 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.
*
* ARToolKit 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 ARToolKit. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules, and to
* copy and distribute the resulting executable under terms of your choice,
* provided that you also meet, for each linked independent module, the terms and
* conditions of the license of that module. An independent module is a module
* which is neither derived from nor based on this library. If you modify this
* library, you may extend this exception to your version of the library, but you
* are not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version.
*
* Copyright 2015 Daqri, LLC.
* Copyright 2010-2015 ARToolworks, Inc.
*
* Author(s): Philip Lamb.
*
*/
#include "pch.h"
#include <ARMarkerSquare.h>
#include <ARController.h>
#ifndef MAX
# define MAX(x,y) (x > y ? x : y)
#endif
ARMarkerSquare::ARMarkerSquare() : ARMarker(SINGLE),
m_loaded(false),
m_arPattHandle(NULL),
m_cf(0.0f),
m_cfMin(AR_CONFIDENCE_CUTOFF_DEFAULT),
patt_id(-1),
patt_type(-1),
useContPoseEstimation(true)
{
}
ARMarkerSquare::~ARMarkerSquare()
{
if (m_loaded) unload();
}
bool ARMarkerSquare::unload()
{
if (m_loaded) {
freePatterns();
if (patt_type == AR_PATTERN_TYPE_TEMPLATE && patt_id != -1) {
if (m_arPattHandle) {
arPattFree(m_arPattHandle, patt_id);
m_arPattHandle = NULL;
}
}
patt_id = patt_type = -1;
m_cf = 0.0f;
m_width = 0.0f;
m_loaded = false;
}
return (true);
}
bool ARMarkerSquare::initWithPatternFile(const char* path, ARdouble width, ARPattHandle *arPattHandle)
{
// Ensure the pattern string is valid
if (!path || !arPattHandle) return false;
if (m_loaded) unload();
ARController::logv(AR_LOG_LEVEL_INFO, "Loading single AR marker from file '%s', width %f.", path, width);
m_arPattHandle = arPattHandle;
patt_id = arPattLoad(m_arPattHandle, path);
if (patt_id < 0) {
ARController::logv(AR_LOG_LEVEL_ERROR, "Error: unable to load single AR marker from file '%s'.", path);
arPattHandle = NULL;
return false;
}
patt_type = AR_PATTERN_TYPE_TEMPLATE;
m_width = width;
visible = visiblePrev = false;
// An ARPattern to hold an image of the pattern for display to the user.
allocatePatterns(1);
patterns[0]->loadTemplate(patt_id, m_arPattHandle, (float)m_width);
m_loaded = true;
return true;
}
bool ARMarkerSquare::initWithPatternFromBuffer(const char* buffer, ARdouble width, ARPattHandle *arPattHandle)
{
// Ensure the pattern string is valid
if (!buffer || !arPattHandle) return false;
if (m_loaded) unload();
ARController::logv(AR_LOG_LEVEL_INFO, "Loading single AR marker from buffer, width %f.", width);
m_arPattHandle = arPattHandle;
patt_id = arPattLoadFromBuffer(m_arPattHandle, buffer);
if (patt_id < 0) {
ARController::logv(AR_LOG_LEVEL_ERROR, "Error: unable to load single AR marker from buffer.");
return false;
}
patt_type = AR_PATTERN_TYPE_TEMPLATE;
m_width = width;
visible = visiblePrev = false;
// An ARPattern to hold an image of the pattern for display to the user.
allocatePatterns(1);
patterns[0]->loadTemplate(patt_id, arPattHandle, (float)m_width);
m_loaded = true;
return true;
}
bool ARMarkerSquare::initWithBarcode(int barcodeID, ARdouble width)
{
if (barcodeID < 0) return false;
if (m_loaded) unload();
ARController::logv(AR_LOG_LEVEL_INFO, "Adding single AR marker with barcode %d, width %f.", barcodeID, width);
patt_id = barcodeID;
patt_type = AR_PATTERN_TYPE_MATRIX;
m_width = width;
visible = visiblePrev = false;
// An ARPattern to hold an image of the pattern for display to the user.
allocatePatterns(1);
patterns[0]->loadMatrix(patt_id, AR_MATRIX_CODE_3x3, (float)m_width); // FIXME: need to determine actual matrix code type.
m_loaded = true;
return true;
}
ARdouble ARMarkerSquare::getConfidence()
{
return (m_cf);
}
ARdouble ARMarkerSquare::getConfidenceCutoff()
{
return (m_cfMin);
}
void ARMarkerSquare::setConfidenceCutoff(ARdouble value)
{
if (value >= AR_CONFIDENCE_CUTOFF_DEFAULT && value <= 1.0f) {
m_cfMin = value;
}
}
bool ARMarkerSquare::updateWithDetectedMarkers(ARMarkerInfo* markerInfo, int markerNum, AR3DHandle *ar3DHandle) {
ARController::logv(AR_LOG_LEVEL_DEBUG, "ARMarkerSquare::update(), id: %d\n", patt_id);
if (patt_id < 0) return false; // Can't update if no pattern loaded
visiblePrev = visible;
if (markerInfo) {
int k = -1;
if (patt_type == AR_PATTERN_TYPE_TEMPLATE) {
// Iterate over all detected markers.
for (int j = 0; j < markerNum; j++) {
if (patt_id == markerInfo[j].idPatt) {
// The pattern of detected trapezoid matches marker[k].
if (k == -1) {
if (markerInfo[j].cfPatt > m_cfMin) k = j; // Count as a match if match confidence exceeds cfMin.
}
else if (markerInfo[j].cfPatt > markerInfo[k].cfPatt) k = j; // Or if it exceeds match confidence of a different already matched trapezoid (i.e. assume only one instance of each marker).
}
}
if (k != -1) {
markerInfo[k].id = markerInfo[k].idPatt;
markerInfo[k].cf = markerInfo[k].cfPatt;
markerInfo[k].dir = markerInfo[k].dirPatt;
}
}
else {
for (int j = 0; j < markerNum; j++) {
if (patt_id == markerInfo[j].idMatrix) {
if (k == -1) {
if (markerInfo[j].cfMatrix >= m_cfMin) k = j; // Count as a match if match confidence exceeds cfMin.
}
else if (markerInfo[j].cfMatrix > markerInfo[k].cfMatrix) k = j; // Or if it exceeds match confidence of a different already matched trapezoid (i.e. assume only one instance of each marker).
}
}
if (k != -1) {
markerInfo[k].id = markerInfo[k].idMatrix;
markerInfo[k].cf = markerInfo[k].cfMatrix;
markerInfo[k].dir = markerInfo[k].dirMatrix;
}
}
// Consider marker visible if a match was found.
if (k != -1) {
visible = true;
m_cf = markerInfo[k].cf;
// If the model is visible, update its transformation matrix
if (visiblePrev && useContPoseEstimation) {
// If the marker was visible last time, use "cont" version of arGetTransMatSquare
arGetTransMatSquareCont(ar3DHandle, &(markerInfo[k]), trans, m_width, trans);
}
else {
// If the marker wasn't visible last time, use normal version of arGetTransMatSquare
arGetTransMatSquare(ar3DHandle, &(markerInfo[k]), m_width, trans);
}
}
else {
visible = false;
m_cf = 0.0f;
}
}
else {
visible = false;
m_cf = 0.0f;
}
return (ARMarker::update()); // Parent class will finish update.
}
| qian256/HoloLensARToolKit | ARToolKitUWP/ARToolKitUWP/src/ARMarkerSquare.cpp | C++ | lgpl-3.0 | 8,515 |
/*
This source file is part of KBEngine
For the latest info, see http://www.kbengine.org/
Copyright (c) 2008-2012 KBEngine.
KBEngine 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.
KBEngine 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 KBEngine. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(DEFINE_IN_INTERFACE)
#undef __CELLAPPMGR_INTERFACE_H__
#endif
#ifndef __CELLAPPMGR_INTERFACE_H__
#define __CELLAPPMGR_INTERFACE_H__
// common include
#if defined(CELLAPPMGR)
#include "cellappmgr.hpp"
#endif
#include "cellappmgr_interface_macros.hpp"
#include "network/interface_defs.hpp"
//#define NDEBUG
// windows include
#if KBE_PLATFORM == PLATFORM_WIN32
#else
// linux include
#endif
namespace KBEngine{
/**
BASEAPPMGRËùÓÐÏûÏ¢½Ó¿ÚÔڴ˶¨Òå
*/
NETWORK_INTERFACE_DECLARE_BEGIN(CellappmgrInterface)
// ijapp×¢²á×Ô¼ºµÄ½Ó¿ÚµØÖ·µ½±¾app
CELLAPPMGR_MESSAGE_DECLARE_ARGS10(onRegisterNewApp, MERCURY_VARIABLE_MESSAGE,
int32, uid,
std::string, username,
int8, componentType,
uint64, componentID,
int8, globalorderID,
int8, grouporderID,
uint32, intaddr,
uint16, intport,
uint32, extaddr,
uint16, extport)
// ijappÖ÷¶¯ÇëÇólook¡£
CELLAPPMGR_MESSAGE_DECLARE_ARGS0(lookApp, MERCURY_FIXED_MESSAGE)
// ij¸öappÇëÇó²é¿´¸Ãapp¸ºÔØ×´Ì¬¡£
CELLAPPMGR_MESSAGE_DECLARE_ARGS0(queryLoad, MERCURY_FIXED_MESSAGE)
// ij¸öappÏò±¾app¸æÖª´¦Óڻ״̬¡£
CELLAPPMGR_MESSAGE_DECLARE_ARGS2(onAppActiveTick, MERCURY_FIXED_MESSAGE,
COMPONENT_TYPE, componentType,
COMPONENT_ID, componentID)
// baseEntityÇëÇó´´½¨ÔÚÒ»¸öеÄspaceÖС£
CELLAPPMGR_MESSAGE_DECLARE_STREAM(reqCreateInNewSpace, MERCURY_VARIABLE_MESSAGE)
// baseEntityÇëÇó»Ö¸´ÔÚÒ»¸öеÄspaceÖС£
CELLAPPMGR_MESSAGE_DECLARE_STREAM(reqRestoreSpaceInCell, MERCURY_VARIABLE_MESSAGE)
// ÏûϢת·¢£¬ ÓÉij¸öappÏëͨ¹ý±¾app½«ÏûϢת·¢¸øÄ³¸öapp¡£
CELLAPPMGR_MESSAGE_DECLARE_STREAM(forwardMessage, MERCURY_VARIABLE_MESSAGE)
// ÇëÇ󹨱շþÎñÆ÷
CELLAPPMGR_MESSAGE_DECLARE_STREAM(reqCloseServer, MERCURY_VARIABLE_MESSAGE)
// ÇëÇó²éѯwatcherÊý¾Ý
CELLAPPMGR_MESSAGE_DECLARE_STREAM(queryWatcher, MERCURY_VARIABLE_MESSAGE)
// ¸üÐÂcellappÐÅÏ¢¡£
CELLAPPMGR_MESSAGE_DECLARE_ARGS2(updateCellapp, MERCURY_FIXED_MESSAGE,
COMPONENT_ID, componentID,
float, load)
NETWORK_INTERFACE_DECLARE_END()
#ifdef DEFINE_IN_INTERFACE
#undef DEFINE_IN_INTERFACE
#endif
}
#endif
| cnsoft/kbengine-cocos2dx | kbe/src/server/cellappmgr/cellappmgr_interface.hpp | C++ | lgpl-3.0 | 3,080 |
package jmathlibtests.toolbox.string;
import jmathlib.tools.junit.framework.JMathLibTestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
public class testStrncmp extends JMathLibTestCase {
public testStrncmp(String name) {
super(name);
}
public static void main (String[] args) {
junit.textui.TestRunner.run (suite());
}
public static Test suite() {
return new TestSuite(testStrncmp.class);
}
public void testStrcmpi01() {
assertEvalScalarEquals("a=strncmp('abcdxxx','abcddd', 3);", "a", 1);
}
public void testStrcmpi02() {
assertEvalScalarEquals("a=strncmp('abcDDD','abcDD', 3);", "a", 1);
}
public void testStrcmpi03() {
assertEvalScalarEquals("a=strncmp('abxxxd','abcd', 3);", "a", 0);
}
public void testStrcmpi04() {
assertEvalScalarEquals("a=strncmp('abc','abcdd', 3);", "a", 1);
}
public void testStrcmpi05() {
assertEvalScalarEquals("a=strncmp('ab','abcd', 3);", "a", 0);
}
public void testStrcmpi06() {
assertEvalScalarEquals("a=strncmpi('abcd','ab', 3);", "a", 0);
}
public void testStrcmpi07() {
assertEvalScalarEquals("a=strncmp('abcd','abcXx', 3);", "a", 1);
}
}
| nightscape/JMathLib | src/jmathlibtests/toolbox/string/testStrncmp.java | Java | lgpl-3.0 | 1,263 |
/*
* Model Tools.
* Copyright (C) 2013 Pal Hargitai (pal@lunarray.org)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.lunarray.model.descriptor.test.domain;
import java.math.BigInteger;
import java.util.Calendar;
import org.lunarray.model.descriptor.presentation.RenderType;
import org.lunarray.model.descriptor.presentation.annotations.PresentationHint;
public class SampleEntity18
implements ModelMarker {
private SampleEntity17 test01;
private boolean test02;
private BigInteger test03;
private String test04;
@PresentationHint(format = "ddmmyyyy")
private Calendar test05;
private SampleEnum01 test06;
private SampleEntity01 test07;
@PresentationHint(render = RenderType.RADIO)
private SampleEnum01 test08;
public SampleEntity17 getTest01() {
return this.test01;
}
public BigInteger getTest03() {
return this.test03;
}
public String getTest04() {
return this.test04;
}
public Calendar getTest05() {
return this.test05;
}
public SampleEnum01 getTest06() {
return this.test06;
}
public SampleEntity01 getTest07() {
return this.test07;
}
public SampleEnum01 getTest08() {
return this.test08;
}
public boolean isTest02() {
return this.test02;
}
public void setTest01(final SampleEntity17 test01) {
this.test01 = test01;
}
public void setTest02(final boolean test02) {
this.test02 = test02;
}
public void setTest03(final BigInteger test03) {
this.test03 = test03;
}
public void setTest04(final String test04) {
this.test04 = test04;
}
public void setTest05(final Calendar test05) {
this.test05 = test05;
}
public void setTest06(final SampleEnum01 test06) {
this.test06 = test06;
}
public void setTest07(final SampleEntity01 test07) {
this.test07 = test07;
}
public void setTest08(final SampleEnum01 test08) {
this.test08 = test08;
}
}
| lunarray-org/model-descriptor | src/test/java/org/lunarray/model/descriptor/test/domain/SampleEntity18.java | Java | lgpl-3.0 | 2,482 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lxml import html
import requests
import csv, codecs, cStringIO
import sys
class Person:
def __init__(self, party, name, email):
self.party = party
self.name = name
self.email = email
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
# For some very weird reason, party can contain utf-8 characters. But last_name can. Weird
party_pages = {
'Socialdemokraterna': 'http://www.riksdagen.se/sv/ledamoter-partier/Socialdemokraterna/Ledamoter/',
'Moderaterna': 'http://www.riksdagen.se/sv/ledamoter-partier/Moderata-samlingspartiet/Ledamoter/',
'Sverigedemokraterna': 'http://www.riksdagen.se/sv/ledamoter-partier/Sverigedemokraterna/Ledamoter/',
'Miljopartiet': 'http://www.riksdagen.se/sv/ledamoter-partier/Miljopartiet-de-grona/Ledamoter/',
'Centerpartiet': 'http://www.riksdagen.se/sv/ledamoter-partier/Centerpartiet/Ledamoter/',
'Vansterpartiet': 'http://www.riksdagen.se/sv/ledamoter-partier/Vansterpartiet/Ledamoter/',
'Liberalerna': 'http://www.riksdagen.se/sv/ledamoter-partier/Folkpartiet/Ledamoter/',
'Kristdemokraterna': 'http://www.riksdagen.se/sv/ledamoter-partier/Kristdemokraterna/Ledamoter/',
}
if __name__ == "__main__":
all_people = []
for party, party_page in party_pages.iteritems():
page = requests.get(party_page)
tree = html.fromstring(page.text)
# Only include "ledamöter", not "partisekreterare" and such since they don't have emails
names = tree.xpath("//*[contains(@class, 'large-12 columns alphabetical component-fellows-list')]//a[contains(@class, 'fellow-item-container')]/@href")
root = "http://www.riksdagen.se"
unique_name_list = []
for name in names:
full_url = root + name
if full_url not in unique_name_list:
unique_name_list.append(full_url)
print unique_name_list
print "unique:"
for name_url in unique_name_list:
print name_url
personal_page = requests.get(name_url)
personal_tree = html.fromstring(personal_page.text)
email_list = personal_tree.xpath("//*[contains(@class, 'scrambled-email')]/text()")
email_scrambled = email_list[0]
email = email_scrambled.replace(u'[på]', '@')
print email
name_list = personal_tree.xpath("//header/h1[contains(@class, 'biggest fellow-name')]/text()")
name = name_list[0]
name = name.replace("\n", "")
name = name.replace("\r", "")
name = name[:name.find("(")-1]
name = name.strip()
print name
print "-----"
person = Person(party, name, email)
all_people.append(person)
for person in all_people:
print person.party + ", " + person.name + ", " + person.email
with open('names.csv', 'wb') as csvfile:
fieldnames = ['name', 'email', 'party']
writer = UnicodeWriter(csvfile)
writer.writerow(fieldnames)
for person in all_people:
print person.party + ", " + person.name + ", " + person.email
writer.writerow([person.name, person.email, person.party])
| samuelskanberg/riksdagen-crawler | scraper.py | Python | unlicense | 4,168 |
<?php
class regis_kec extends kecamatan_controller{
var $controller;
function regis_kec(){
parent::__construct();
$this->controller = get_class($this);
$this->load->model('regis_kec_model','dm');
$this->load->model("coremodel","cm");
//$this->load->helper("serviceurl");
}
function index(){
$data_array=array();
$content = $this->load->view($this->controller."_view",$data_array,true);
$this->set_subtitle("Registrasi Pertanahan");
$this->set_title("Kecamatan");
$this->set_content($content);
$this->cetak();
}
function get_data() {
// show_array($userdata);
$draw = $_REQUEST['draw']; // get the requested page
$start = $_REQUEST['start'];
$limit = $_REQUEST['length']; // get how many rows we want to have into the grid
$sidx = isset($_REQUEST['order'][0]['column'])?$_REQUEST['order'][0]['column']:0; // get index row - i.e. user click to sort
$sord = isset($_REQUEST['order'][0]['dir'])?$_REQUEST['order'][0]['dir']:"asc"; // get the direction if(!$sidx) $sidx =1;
$nama_pemilik = $_REQUEST['columns'][1]['search']['value'];
$userdata = $this->session->userdata('kec_login');
$desa = $userdata['kecamatan'];
// $this->db->where('desa_tanah', $desa);
// order[0][column]
$req_param = array (
"sort_by" => $sidx,
"sort_direction" => $sord,
"limit" => null,
"nama_pemilik" => $nama_pemilik,
"desa" => $desa
);
$row = $this->dm->data($req_param)->result_array();
$count = count($row);
$req_param['limit'] = array(
'start' => $start,
'end' => $limit
);
$result = $this->dm->data($req_param)->result_array();
$arr_data = array();
foreach($result as $row) :
$id = $row['id'];
if ($row['status'] == 1) {
$action = "<div class='btn-group'>
<button type='button' class='btn btn-danger'>Pending</button>
<button type='button' class='btn btn-danger dropdown-toggle' data-toggle='dropdown'>
<span class='caret'></span>
<span class='sr-only'>Toggle Dropdown</span>
</button>
<ul class='dropdown-menu' role='menu'>
<li><a href='#' onclick=\"approved('$id')\" ><i class='fa fa-trash'></i> Menyetujui</a></li>
<li><a href='regis_kec/detail?id=$id'><i class='fa fa-edit'></i> Detail</a></li>
</ul>
</div>";
}else {
$action = '<div class="btn-group">
<button type="button" class="btn btn-success">Selsai</button>
<button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
</ul>
</div>';
}
$row['tgl_register_desa'] = flipdate($row['tgl_register_desa']);
$arr_data[] = array(
$row['tgl_register_desa'],
$row['no_register_desa'],
$row['nama_pemilik'],
$action,
);
endforeach;
$responce = array('draw' => $draw, // ($start==0)?1:$start,
'recordsTotal' => $count,
'recordsFiltered' => $count,
'data'=>$arr_data
);
echo json_encode($responce);
}
function detail(){
$get = $this->input->get();
$id = $get['id'];
$this->db->where('id',$id);
$biro_jasa = $this->db->get('tanah');
$data = $biro_jasa->row_array();
$this->db->where('id', $id);
$rs = $this->db->get('tanah');
$data = $rs->row_array();
extract($data);
$this->db->where('id', $desa_tanah);
$qr = $this->db->get('tiger_desa');
$rs = $qr->row_array();
$data['desa_tanah'] = $rs['desa'];
$this->db->where('id', $kec_tanah);
$qr = $this->db->get('tiger_kecamatan');
$rs = $qr->row_array();
$data['kec_tanah'] = $rs['kecamatan'];
$this->db->where('id', $kab_tanah);
$qr = $this->db->get('tiger_kota');
$rs = $qr->row_array();
$data['kab_tanah'] = $rs['kota'];
$data['tgl_lhr_pemilik'] = flipdate($data['tgl_lhr_pemilik']);
$data['tgl_pernyataan'] = flipdate($data['tgl_pernyataan']);
$data['tgl_register_desa'] = flipdate($data['tgl_register_desa']);
$userdata = $this->session->userdata('kec_login');
$this->db->where('kec_tanah', $userdata['kecamatan']);
$this->db->where('status', 2);
$rs = $this->db->get('tanah');
$data['no_data_kec'] = $rs->num_rows()+1;
$data['arr_kecamatan'] = $this->cm->arr_dropdown3("tiger_kecamatan", "id", "kecamatan", "kecamatan", "id_kota", "19_5");
$data['action'] = 'update';
$content = $this->load->view("regis_kec_view_form_detail",$data,true);
$this->set_subtitle("");
$this->set_title("Detail Registrasi Pertanahan");
$this->set_content($content);
$this->cetak();
}
function cek_no_reg($no_register_kec){
$this->db->where("no_register_kec",$no_register_kec);
if(empty($no_register_kec)){
$this->form_validation->set_message('cek_no_reg', ' No Registrasi Harus Di Isi');
return false;
}
if($this->db->get("tanah")->num_rows() > 0)
{
$this->form_validation->set_message('cek_no_reg', ' Sudah Ada Data Dengan No Registrasi Ini');
return false;
}
}
function update(){
$post = $this->input->post();
$this->load->library('form_validation');
$this->form_validation->set_rules('tgl_register_kec','Tanggal Registrasi','required');
$userdata = $this->session->userdata('kec_login');
$post['no_register_kec'] = $post['no_data_kec'].''.$userdata['format_reg'];
$post['no_ket_kec'] = $post['no_data_kec'].''.$userdata['format_ket'];
$this->form_validation->set_message('required', ' %s Harus diisi ');
$this->form_validation->set_error_delimiters('', '<br>');
//show_array($data);
if($this->form_validation->run() == TRUE ) {
$userdata = $this->session->userdata('kec_login');
$post['camat'] = $userdata['nama_camat'];
$post['jabatan_camat'] = $userdata['jabatan_camat'];
$post['nip_camat'] = $userdata['nip_camat'];
$post['tgl_register_kec'] = flipdate($post['tgl_register_kec']);
$post['status'] = 2;
$this->db->where("id",$post['id']);
$res = $this->db->update('tanah', $post);
if($res){
$arr = array("error"=>false,'message'=>"Register Kecamatan Berhasil");
}
else {
$arr = array("error"=>true,'message'=>"Register Kecamatan Gagal");
}
}
else {
$arr = array("error"=>true,'message'=>validation_errors());
}
echo json_encode($arr);
}
function approved(){
$get = $this->input->post();
$id = $get['id'];
$userdata = $this->session->userdata();
$this->db->where("id",$post['id']);
$res = $this->db->update('tanah', $post);
if($res){
$arr = array("error"=>false,"message"=>$this->db->last_query()." DATA BERASIL DI SETUJUI");
}
else {
$arr = array("error"=>true,"message"=>"DATA GAGAL DISETUJUI ".mysql_error());
}
//redirect('sa_birojasa_user');
echo json_encode($arr);
}
}
?> | NizarHafizulllah/pertanahan | application/modules/regis_kec/controllers/regis_kec.php | PHP | unlicense | 8,314 |
module Collectable
extend ActiveSupport::Concern
included do
attr_readonly :collectors_count
has_many :collections, as: :target
has_many :collectors, through: :collections, class_name: 'User', source: :user
end
def collected_by?(current_user)
return false if current_user.nil?
!!collections.where(user_id: current_user.id).first
end
end | Edisonangela/manager | app/models/concerns/collectable.rb | Ruby | unlicense | 379 |
package org.hyperic.hq.api.model;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.hyperic.hq.api.model.common.MapPropertiesAdapter;
import org.hyperic.hq.api.model.common.PropertyListMapAdapter;
@XmlRootElement(namespace=RestApiConstants.SCHEMA_NAMESPACE)
@XmlType(name="ResourceConfigType", namespace=RestApiConstants.SCHEMA_NAMESPACE)
public class ResourceConfig implements Serializable{
private static final long serialVersionUID = 8233944180632888593L;
private String resourceID;
private Map<String,String> mapProps ;
private Map<String,PropertyList> mapListProps;
public ResourceConfig() {}//EOM
public ResourceConfig(final String resourceID, final Map<String,String> mapProps, final Map<String,PropertyList> mapListProps) {
this.resourceID = resourceID ;
this.mapProps = mapProps ;
this.mapListProps = mapListProps ;
}//EOM
public final void setResourceID(final String resourceID) {
this.resourceID = resourceID ;
}//EOM
public final String getResourceID() {
return this.resourceID ;
}//EOM
public final void setMapProps(final Map<String,String> configValues) {
this.mapProps= configValues ;
}//EOM
@XmlJavaTypeAdapter(MapPropertiesAdapter.class)
public final Map<String,String> getMapProps() {
return this.mapProps ;
}//EOM
@XmlJavaTypeAdapter(PropertyListMapAdapter.class)
public Map<String,PropertyList> getMapListProps() {
return mapListProps;
}
public void setMapListProps(Map<String,PropertyList> mapListProps) {
this.mapListProps = mapListProps;
}
/**
* Adds properties to the given key if it already exists,
* otherwise adds the key with the given properties list
* @param key
* @param properties Values to add to the Property list
*/
public void putMapListProps(String key, Collection<ConfigurationValue> properties) {
if (null == this.mapListProps) {
this.mapListProps = new HashMap<String, PropertyList>();
}
if (mapListProps.containsKey(key)) {
mapListProps.get(key).addAll(properties);
} else {
mapListProps.put(key, new PropertyList(properties));
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((resourceID == null) ? 0 : resourceID.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ResourceConfig other = (ResourceConfig) obj;
if (resourceID == null) {
if (other.resourceID != null)
return false;
} else if (!resourceID.equals(other.resourceID))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder() ;
return this.toString(builder, "").toString() ;
}//EOM
public final StringBuilder toString(final StringBuilder builder, final String indentation) {
return builder.append(indentation).append("ResourceConfig [resourceID=").append(resourceID).append("\n").append(indentation).append(", mapProps=").
append(mapProps.toString().replaceAll(",", "\n"+indentation + " ")).append("]") ;
}//EOM
}//EOC
| cc14514/hq6 | hq-api/src/main/java/org/hyperic/hq/api/model/ResourceConfig.java | Java | unlicense | 3,524 |
import matplotlib.pyplot as plt
import numpy as np
n = 50
x = np.random.randn(n)
y = x * np.random.randn(n)
fig, ax = plt.subplots(2, figsize=(6, 6))
ax[0].scatter(x, y, s=50)
sizes = (np.random.randn(n) * 8) ** 2
ax[1].scatter(x, y, s=sizes)
fig.show()
"""(

)"""
| pythonpatterns/patterns | p0171.py | Python | unlicense | 323 |
from django.apps import AppConfig
class GroupInvitationsConfig(AppConfig):
name = 'GroupInvitations'
verbose_name = 'Group Invitations' | Yury191/brownstonetutors | GroupInvitations/apps.py | Python | unlicense | 144 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PLCv4.Models
{
public class ApplicationRoleListViewModel
{
public string Id { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public int NumberOfUsers { get; set; }
}
}
| AdrianPT/Eureka-PLC | src/PLCv4/Models/ApplicationRoleListViewModel.cs | C# | unlicense | 369 |
/**
* Gulp Task HTML
* @author kuakman <3dimentionar@gmail.com>
**/
let fs = require('fs-extra');
let _ = require('underscore');
let spawnSync = require('child_process').spawnSync;
module.exports = function(package, args) {
return () => {
return spawnSync('./node_modules/.bin/pug', [
'--path', './src/html',
'--out', './dist',
'--obj', `\'${JSON.stringify(_.pick(package, 'name', 'version', 'profile'))}\'`, '--pretty', './src/html'
], {
cwd: process.cwd(),
stdio: 'inherit',
shell: true
});
};
};
| kuakman/app-start-pipeline | scripts/html.js | JavaScript | unlicense | 526 |
package io.github.picodotdev.blogbitix.entitiesid.domain.product;
import io.github.picodotdev.blogbitix.entitiesid.DefaultPostgresContainer;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
@ContextConfiguration(initializers = { DefaultPostgresContainer.Initializer.class })
public class ProductRepositoryTest {
@Autowired
private ProductRepository productRepository;
@Test
void testRepositoryGenerateId() {
// given
ProductId id = productRepository.generateId();
Product product = new Product(id, "Raspberry Pi", LocalDate.now(), new BigDecimal("80.0"), 10);
// and
productRepository.save(product);
// then
assertEquals(product, productRepository.findById(id).get());
}
} | picodotdev/blog-ejemplos | EntitiesId/src/test/java/io/github/picodotdev/blogbitix/entitiesid/domain/product/ProductRepositoryTest.java | Java | unlicense | 1,085 |
function nSplit(msg, n) {
let expr = new RegExp(".{1," + n + "}", "g");
let presplit = msg.match(expr);
let twoSplit = presplit.map((x) => {
if (x.length != n) {
let i = 0;
let ret = "";
while (i < n - x.length) {
ret += " ";
i++
};
return x + ret;
} else
return x;
});
return twoSplit;
}
function backSwap(msg) {
let newBw = "";
let newFw = "";
let newArr = [];
for (let fw = 0; fw < msg.length; fw++) {
let bw = msg.length - (fw + 1);
let myFw = msg[fw];
let myBw = msg[bw];
newFw = myBw[0] + myFw.slice(1);
newBw = myFw[0] + myBw.slice(1);
newArr[fw] = newFw;
newArr[bw] = newBw;
// console.log(fw, newFw, bw, newBw);
if (bw <= fw)
break;
}
return newArr;
}
function encode(msg, n) {
let comp_msg = msg.split(' ').join('');
let split_msg = nSplit(comp_msg, n);
return backSwap(split_msg);
}
// var myLoveMsg = "Dear Jade, I love you so much! Lets go on adventures & make memories.";
var myLoveMsg = "Ja de Il ov ey ou so mu ch .Y ou ar ew on de rf ul an da ma zi ng in so ma ny wa ys .Y ou ar et ru ly sp ec ia lt om eb ee b an dl ho pe we ca ns up po rt ea ch ot he ra nd be tw ee nu sd oa ma zi ng th in gs ❤";
// var rvLoveMsg = "se ir oa ee eI ao &e eo us nm vc a! oe gs to Ln hd ue ot ur ys vm lk ,m dm Jr ae D.";
var rvLoveMsg = ".a ge il tv ny zu mo ou sh nY eu tr bw nn re hf ol cn ea ra pi ug nn co wa py ha ds aY bu er et ou ly ip ec sa lt rm eb ae o, .n yl wo ne me sa is np zo mt da ah ut re da od ee aw oe .u cd ma sa oi eg oh In ds J❤";
var nwsMsg = myLoveMsg.split(' ').join('');
var nwsrvMsg = rvLoveMsg.split(' ').join('');
var myCode = nSplit(myLoveMsg, 2);
var nwsCode = nSplit(nwsMsg, 2);
var nwsrvCode = nSplit(nwsrvMsg, 2);
var bsmyCode = backSwap(myCode);
var bsmynwsCode = backSwap(nwsCode);
var bsmynwsrvCode = backSwap(nwsrvCode);
console.log(myLoveMsg);
// console.log(myCode.join(' '));
// console.log(bsmyCode.join(' '));
console.log(nwsCode.join(' '));
console.log(bsmynwsCode.join(' '));
console.log(nwsrvCode.join(' '));
console.log(bsmynwsrvCode.join(' '));
// let myText = encode("Hello Dawg, HEllo DAWGDJLKSAD", 2);
// console.log(myText.join(' ')); | ConflictingTheories/scripts | javascript/lib/nSplit.js | JavaScript | unlicense | 2,366 |
import enum
class H264Trellis(enum.Enum):
DISABLED = 'DISABLED'
ENABLED_FINAL_MB = 'ENABLED_FINAL_MB'
ENABLED_ALL = 'ENABLED_ALL'
| bitmovin/bitmovin-python | bitmovin/resources/enums/h264_trellis.py | Python | unlicense | 144 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Visio = Microsoft.Office.Interop.Visio;
using VisCellIndicies = Microsoft.Office.Interop.Visio.VisCellIndices;
using VisSectionIndices = Microsoft.Office.Interop.Visio.VisSectionIndices;
using VisRowIndicies = Microsoft.Office.Interop.Visio.VisRowIndices;
using VisSLO = Microsoft.Office.Interop.Visio.VisSpatialRelationCodes;
using PomExplorer.PomAccess;
using System.IO;
namespace PomExplorer.VisioDrawing
{
class PomPainter
{
private Dictionary<String, Visio.Shape> _artifactsAlreadyDrawn = new Dictionary<string, Visio.Shape>();
private Visio.Page _page;
private double _rectWidth = 2.5;
private double _rectHeight = 0.5;
private double _spacing = 0.5;
private double _centerHor;
private double _centerVert;
private double _pageTop;
private String _fontSize = "9pt";
private MavenProject _project;
private PomPainterStyle _style;
public PomPainter(Visio.Page page, MavenProject project)
{
_page = page;
_centerHor = _page.PageSheet.CellsU["PageWidth"].ResultIU / 2;
_pageTop = _page.PageSheet.CellsU["PageHeight"].ResultIU;
_centerVert = _pageTop / 2;
_project = project;
}
public void Paint(PomPainterStyle style)
{
_style = style;
if (_project.Shape == null)
{
_project.Shape = CreateRect(_project, 0, _rectHeight * 2);
}
DrawProject(_project);
}
public void DrawProject(MavenProject project)
{
if (_style == PomPainterStyle.PomDependencies || _style == PomPainterStyle.PomHierarchy) DrawDependencies(project);
if (_style == PomPainterStyle.PomHierarchy) DrawModules(project);
}
private void DrawModules(MavenProject project)
{
foreach (var module in project.Modules)
{
if (module.Project.Shape == null)
{
module.Project.Shape = CreateRect(module.Project, _centerHor, _centerVert);
}
Connect(project.Shape, module.Project.Shape);
DrawProject(module.Project);
}
}
private void DrawDependencies(MavenProject project)
{
foreach (var dependency in project.Dependencies)
{
var rectDependency = CreateRect(dependency, _centerHor, _centerVert);
Connect(project.Shape, rectDependency);
}
}
private double getBottom(Visio.Shape shape)
{
return shape.CellsU["PinY"].ResultIU+shape.CellsU["Height"].ResultIU;
}
private Visio.Shape CreateRect(Artifact artifact, double offsetX, double offsetY)
{
if (!_artifactsAlreadyDrawn.ContainsKey(artifact.ArtifactKey))
{
_artifactsAlreadyDrawn.Add(artifact.ArtifactKey, CreateRect(artifact.ArtifactSummary, offsetX, offsetY, _rectWidth, _rectHeight));
}
return _artifactsAlreadyDrawn[artifact.ArtifactKey];
}
private Visio.Shape CreateRect(String name, double offsetX, double offsetY, double width, double height)
{
Visio.Page page = Globals.ThisAddIn.Application.ActivePage;
var rect = page.DrawRectangle(_centerHor + offsetX - width / 2, _pageTop - offsetY, _centerHor + offsetX + width / 2, _pageTop - offsetY - height);
var textFont = rect.CellsSRC[(short)VisSectionIndices.visSectionCharacter, 0, (short)VisCellIndicies.visCharacterSize];
var textAlign = rect.CellsSRC[(short)VisSectionIndices.visSectionCharacter, 0, (short)VisCellIndicies.visHorzAlign];
textFont.FormulaU = _fontSize;
rect.Text = name;
textAlign.FormulaU = "0";
return rect;
}
private void Connect(Visio.Shape shape1, Visio.Shape shape2)
{
var cn = _page.Application.ConnectorToolDataObject;
var connector = _page.Drop(cn, 3, 3) as Visio.Shape;
// https://msdn.microsoft.com/en-us/library/office/ff767991.aspx
var anchorShape1 = shape1.CellsSRC[1, 1, 0];
var beginConnector = connector.CellsU["BeginX"];
var anchorShape2 = shape2.CellsSRC[1, 1, 0];
var endConnector = connector.CellsU["EndX"];
beginConnector.GlueTo(anchorShape1);
endConnector.GlueTo(anchorShape2);
connector.CellsSRC[(short)VisSectionIndices.visSectionObject, (short)VisRowIndicies.visRowLine, (short)VisCellIndicies.visLineEndArrow].FormulaU = "13";
connector.CellsSRC[(short)VisSectionIndices.visSectionObject, (short)VisRowIndicies.visRowShapeLayout, (short)VisCellIndicies.visLineEndArrow].FormulaU = "1";
connector.CellsSRC[(short)VisSectionIndices.visSectionObject, (short)VisRowIndicies.visRowShapeLayout, (short)VisCellIndicies.visSLOLineRouteExt].FormulaU = "16";
}
}
}
| mamu7211/VisioPomAnalyzer | PomExplorer/PomExplorer/VisioDrawing/PomPainter.cs | C# | unlicense | 5,331 |
#!/usr/local/bin/elev8
var EXPAND_BOTH = { x : 1.0, y : 1.0 };
var FILL_BOTH = { x : -1.0, y : -1.0 };
var logo_icon = elm.Icon ({
image : elm.datadir + "data/images/logo_small.png",
});
var logo_icon_unscaled = elm.Icon ({
image : elm.datadir + "data/images/logo_small.png",
resizable_up : false,
resizable_down : false,
});
var desc = elm.Window({
title : "Radios demo",
elements : {
the_background : elm.Background ({
weight : EXPAND_BOTH,
resize : true,
}),
radio_box : elm.Box ({
weight : EXPAND_BOTH,
resize : true,
elements : {
sized_radio_icon : elm.Radio ({
icon : logo_icon,
label : "Icon sized to radio",
weight : EXPAND_BOTH,
align : { x : 1.0, y : 0.5 },
value : 0,
group : "rdg",
}),
unscaled_radio_icon : elm.Radio ({
icon : logo_icon_unscaled,
label : "Icon no scale",
weight : EXPAND_BOTH,
align : { x : 1.0, y : 0.5 },
value : 1,
group : "rdg",
}),
label_only_radio : elm.Radio ({
label : "Label Only",
value : 2,
group : "rdg",
}),
disabled_radio : elm.Radio ({
label : "Disabled",
enabled : false,
value : 3,
group : "rdg",
}),
icon_radio : elm.Radio ({
icon : logo_icon_unscaled,
value : 4,
group : "rdg",
}),
disabled_icon_radio : elm.Radio ({
enabled : false,
icon : logo_icon_unscaled,
value : 5,
group : "rdg",
}),
},
}),
},
});
var win = elm.realise(desc);
| maikodaraine/EnlightenmentUbuntu | bindings/elev8/data/javascript/radio.js | JavaScript | unlicense | 2,132 |
#include <iostream>
int main(int argc, char const *argv[])
{
int x = 1;
int y = 9;
printf("0. x:%i y:%i\n",x,y);
//newbie
int s;
s = x;
x = y;
y = s;
printf("1. x:%i y:%i\n",x,y);
//hacker
x=x+y;
y=x-y;
x=x-y;
printf("2. x:%i y:%i\n",x,y);
//pro hacker
x^=y;
y^=x;
x^=y;
printf("3. x:%i y:%i\n",x,y);
return 0;
} | varpeti/Suli | Angol/Előad/p009.cpp | C++ | unlicense | 399 |
package crazypants.enderio.conduits.conduit.redstone;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.enderio.core.api.client.gui.ITabPanel;
import com.enderio.core.common.util.DyeColor;
import com.enderio.core.common.util.NNList;
import com.enderio.core.common.util.NullHelper;
import com.enderio.core.common.vecmath.Vector4f;
import com.google.common.collect.Lists;
import crazypants.enderio.base.EnderIO;
import crazypants.enderio.base.conduit.ConduitUtil;
import crazypants.enderio.base.conduit.ConnectionMode;
import crazypants.enderio.base.conduit.IClientConduit;
import crazypants.enderio.base.conduit.IConduit;
import crazypants.enderio.base.conduit.IConduitNetwork;
import crazypants.enderio.base.conduit.IConduitTexture;
import crazypants.enderio.base.conduit.IGuiExternalConnection;
import crazypants.enderio.base.conduit.RaytraceResult;
import crazypants.enderio.base.conduit.geom.CollidableComponent;
import crazypants.enderio.base.conduit.redstone.ConnectivityTool;
import crazypants.enderio.base.conduit.redstone.signals.BundledSignal;
import crazypants.enderio.base.conduit.redstone.signals.CombinedSignal;
import crazypants.enderio.base.conduit.redstone.signals.Signal;
import crazypants.enderio.base.conduit.registry.ConduitRegistry;
import crazypants.enderio.base.diagnostics.Prof;
import crazypants.enderio.base.filter.FilterRegistry;
import crazypants.enderio.base.filter.capability.CapabilityFilterHolder;
import crazypants.enderio.base.filter.capability.IFilterHolder;
import crazypants.enderio.base.filter.gui.FilterGuiUtil;
import crazypants.enderio.base.filter.redstone.DefaultInputSignalFilter;
import crazypants.enderio.base.filter.redstone.DefaultOutputSignalFilter;
import crazypants.enderio.base.filter.redstone.IInputSignalFilter;
import crazypants.enderio.base.filter.redstone.IOutputSignalFilter;
import crazypants.enderio.base.filter.redstone.IRedstoneSignalFilter;
import crazypants.enderio.base.filter.redstone.items.IItemInputSignalFilterUpgrade;
import crazypants.enderio.base.filter.redstone.items.IItemOutputSignalFilterUpgrade;
import crazypants.enderio.base.render.registry.TextureRegistry;
import crazypants.enderio.base.tool.ToolUtil;
import crazypants.enderio.conduits.conduit.AbstractConduit;
import crazypants.enderio.conduits.config.ConduitConfig;
import crazypants.enderio.conduits.gui.RedstoneSettings;
import crazypants.enderio.conduits.render.BlockStateWrapperConduitBundle;
import crazypants.enderio.conduits.render.ConduitTexture;
import crazypants.enderio.powertools.lang.Lang;
import crazypants.enderio.util.EnumReader;
import crazypants.enderio.util.Prep;
import net.minecraft.block.Block;
import net.minecraft.block.BlockRedstoneWire;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static crazypants.enderio.conduits.init.ConduitObject.item_redstone_conduit;
public class InsulatedRedstoneConduit extends AbstractConduit implements IRedstoneConduit, IFilterHolder<IRedstoneSignalFilter> {
static final Map<String, IConduitTexture> ICONS = new HashMap<>();
static {
ICONS.put(KEY_INS_CORE_OFF_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit_core_1"), ConduitTexture.core(3)));
ICONS.put(KEY_INS_CORE_ON_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit_core_0"), ConduitTexture.core(3)));
ICONS.put(KEY_INS_CONDUIT_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit"), ConduitTexture.arm(1)));
ICONS.put(KEY_CONDUIT_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit"), ConduitTexture.arm(3)));
ICONS.put(KEY_TRANSMISSION_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit"), ConduitTexture.arm(2)));
}
// --------------------------------- Class Start
// -------------------------------------------
private final EnumMap<EnumFacing, IRedstoneSignalFilter> outputFilters = new EnumMap<EnumFacing, IRedstoneSignalFilter>(EnumFacing.class);
private final EnumMap<EnumFacing, IRedstoneSignalFilter> inputFilters = new EnumMap<EnumFacing, IRedstoneSignalFilter>(EnumFacing.class);
private final EnumMap<EnumFacing, ItemStack> outputFilterUpgrades = new EnumMap<EnumFacing, ItemStack>(EnumFacing.class);
private final EnumMap<EnumFacing, ItemStack> inputFilterUpgrades = new EnumMap<EnumFacing, ItemStack>(EnumFacing.class);
private Map<EnumFacing, ConnectionMode> forcedConnections = new EnumMap<EnumFacing, ConnectionMode>(EnumFacing.class);
private Map<EnumFacing, DyeColor> inputSignalColors = new EnumMap<EnumFacing, DyeColor>(EnumFacing.class);
private Map<EnumFacing, DyeColor> outputSignalColors = new EnumMap<EnumFacing, DyeColor>(EnumFacing.class);
private Map<EnumFacing, Boolean> signalStrengths = new EnumMap<EnumFacing, Boolean>(EnumFacing.class);
private RedstoneConduitNetwork network;
private int activeUpdateCooldown = 0;
private boolean activeDirty = false;
private boolean connectionsDirty = false; // TODO: can this be merged with super.connectionsDirty?
private int signalIdBase = 0;
@SuppressWarnings("unused")
public InsulatedRedstoneConduit() {
}
@Override
public @Nullable RedstoneConduitNetwork getNetwork() {
return network;
}
@Override
public boolean setNetwork(@Nonnull IConduitNetwork<?, ?> network) {
this.network = (RedstoneConduitNetwork) network;
return super.setNetwork(network);
}
@Override
public void clearNetwork() {
this.network = null;
}
@Override
@Nonnull
public Class<? extends IConduit> getBaseConduitType() {
return IRedstoneConduit.class;
}
@Override
public void updateNetwork() {
World world = getBundle().getEntity().getWorld();
if (NullHelper.untrust(world) != null) {
updateNetwork(world);
}
}
@Override
public void updateEntity(@Nonnull World world) {
super.updateEntity(world);
if (!world.isRemote) {
if (activeUpdateCooldown > 0) {
--activeUpdateCooldown;
Prof.start(world, "updateActiveState");
updateActiveState();
Prof.stop(world);
}
if (connectionsDirty) {
if (hasExternalConnections()) {
network.updateInputsFromConduit(this, false);
}
connectionsDirty = false;
}
}
}
@Override
public void setActive(boolean active) {
if (active != this.active) {
activeDirty = true;
}
this.active = active;
updateActiveState();
}
private void updateActiveState() {
if (ConduitConfig.showState.get() && activeDirty && activeUpdateCooldown == 0) {
setClientStateDirty();
activeDirty = false;
activeUpdateCooldown = 4;
}
}
@Override
public void onChunkUnload() {
RedstoneConduitNetwork networkR = getNetwork();
if (networkR != null) {
BundledSignal oldSignals = networkR.getBundledSignal();
List<IRedstoneConduit> conduits = Lists.newArrayList(networkR.getConduits());
super.onChunkUnload();
networkR.afterChunkUnload(conduits, oldSignals);
}
}
@Override
public boolean onBlockActivated(@Nonnull EntityPlayer player, @Nonnull EnumHand hand, @Nonnull RaytraceResult res, @Nonnull List<RaytraceResult> all) {
World world = getBundle().getEntity().getWorld();
DyeColor col = DyeColor.getColorFromDye(player.getHeldItem(hand));
final CollidableComponent component = res.component;
if (col != null && component != null && component.isDirectional()) {
if (!world.isRemote) {
if (getConnectionMode(component.getDirection()).acceptsInput()) {
// Note: There's no way to set the input color in IN_OUT mode...
setOutputSignalColor(component.getDirection(), col);
} else {
setInputSignalColor(component.getDirection(), col);
}
}
return true;
} else if (ToolUtil.isToolEquipped(player, hand)) {
if (world.isRemote) {
return true;
}
if (component != null) {
EnumFacing faceHit = res.movingObjectPosition.sideHit;
if (component.isCore()) {
BlockPos pos = getBundle().getLocation().offset(faceHit);
Block id = world.getBlockState(pos).getBlock();
if (id == ConduitRegistry.getConduitModObjectNN().getBlock()) {
IRedstoneConduit neighbour = ConduitUtil.getConduit(world, pos.getX(), pos.getY(), pos.getZ(), IRedstoneConduit.class);
if (neighbour != null && neighbour.getConnectionMode(faceHit.getOpposite()) == ConnectionMode.DISABLED) {
neighbour.setConnectionMode(faceHit.getOpposite(), ConnectionMode.NOT_SET);
}
setConnectionMode(faceHit, ConnectionMode.NOT_SET);
return ConduitUtil.connectConduits(this, faceHit);
}
forceConnectionMode(faceHit, ConnectionMode.IN_OUT);
return true;
} else {
EnumFacing connDir = component.getDirection();
if (externalConnections.contains(connDir)) {
if (network != null) {
network.destroyNetwork();
}
externalConnectionRemoved(connDir);
forceConnectionMode(connDir, ConnectionMode.getNext(getConnectionMode(connDir)));
return true;
} else if (containsConduitConnection(connDir)) {
BlockPos pos = getBundle().getLocation().offset(connDir);
IRedstoneConduit neighbour = ConduitUtil.getConduit(getBundle().getEntity().getWorld(), pos.getX(), pos.getY(), pos.getZ(), IRedstoneConduit.class);
if (neighbour != null) {
if (network != null) {
network.destroyNetwork();
}
final RedstoneConduitNetwork neighbourNetwork = neighbour.getNetwork();
if (neighbourNetwork != null) {
neighbourNetwork.destroyNetwork();
}
neighbour.conduitConnectionRemoved(connDir.getOpposite());
conduitConnectionRemoved(connDir);
neighbour.connectionsChanged();
connectionsChanged();
updateNetwork();
neighbour.updateNetwork();
return true;
}
}
}
}
}
return false;
}
@Override
public void forceConnectionMode(@Nonnull EnumFacing dir, @Nonnull ConnectionMode mode) {
setConnectionMode(dir, mode);
forcedConnections.put(dir, mode);
onAddedToBundle();
if (network != null) {
network.updateInputsFromConduit(this, false);
}
}
@Override
@Nonnull
public ItemStack createItem() {
return new ItemStack(item_redstone_conduit.getItemNN(), 1, 0);
}
@Override
public void onInputsChanged(@Nonnull EnumFacing side, int[] inputValues) {
}
@Override
public void onInputChanged(@Nonnull EnumFacing side, int inputValue) {
}
@Override
@Nonnull
public DyeColor getInputSignalColor(@Nonnull EnumFacing dir) {
DyeColor res = inputSignalColors.get(dir);
if (res == null) {
return DyeColor.RED;
}
return res;
}
@Override
public void setInputSignalColor(@Nonnull EnumFacing dir, @Nonnull DyeColor col) {
inputSignalColors.put(dir, col);
if (network != null) {
network.updateInputsFromConduit(this, false);
}
setClientStateDirty();
collidablesDirty = true;
}
@Override
@Nonnull
public DyeColor getOutputSignalColor(@Nonnull EnumFacing dir) {
DyeColor res = outputSignalColors.get(dir);
if (res == null) {
return DyeColor.GREEN;
}
return res;
}
@Override
public void setOutputSignalColor(@Nonnull EnumFacing dir, @Nonnull DyeColor col) {
outputSignalColors.put(dir, col);
if (network != null) {
network.updateInputsFromConduit(this, false);
}
setClientStateDirty();
collidablesDirty = true;
}
@Override
public boolean isOutputStrong(@Nonnull EnumFacing dir) {
if (signalStrengths.containsKey(dir)) {
return signalStrengths.get(dir);
}
return false;
}
@Override
public void setOutputStrength(@Nonnull EnumFacing dir, boolean isStrong) {
if (isOutputStrong(dir) != isStrong) {
if (isStrong) {
signalStrengths.put(dir, isStrong);
} else {
signalStrengths.remove(dir);
}
if (network != null) {
network.notifyNeigborsOfSignalUpdate();
}
}
}
@Override
public boolean canConnectToExternal(@Nonnull EnumFacing direction, boolean ignoreConnectionState) {
if (ignoreConnectionState) { // you can always force an external connection
return true;
}
ConnectionMode forcedConnection = forcedConnections.get(direction);
if (forcedConnection == ConnectionMode.DISABLED) {
return false;
} else if (forcedConnection == ConnectionMode.IN_OUT || forcedConnection == ConnectionMode.OUTPUT || forcedConnection == ConnectionMode.INPUT) {
return true;
}
// Not set so figure it out
World world = getBundle().getBundleworld();
BlockPos pos = getBundle().getLocation().offset(direction);
IBlockState bs = world.getBlockState(pos);
if (bs.getBlock() == ConduitRegistry.getConduitModObjectNN().getBlock()) {
return false;
}
return ConnectivityTool.shouldAutoConnectRedstone(world, bs, pos, direction.getOpposite());
}
@Override
public int isProvidingWeakPower(@Nonnull EnumFacing toDirection) {
toDirection = toDirection.getOpposite();
if (!getConnectionMode(toDirection).acceptsInput()) {
return 0;
}
if (network == null || !network.isNetworkEnabled()) {
return 0;
}
int result = 0;
CombinedSignal signal = getNetworkOutput(toDirection);
result = Math.max(result, signal.getStrength());
return result;
}
@Override
public int isProvidingStrongPower(@Nonnull EnumFacing toDirection) {
if (isOutputStrong(toDirection.getOpposite())) {
return isProvidingWeakPower(toDirection);
} else {
return 0;
}
}
@Override
@Nonnull
public CombinedSignal getNetworkOutput(@Nonnull EnumFacing side) {
ConnectionMode mode = getConnectionMode(side);
if (network == null || !mode.acceptsInput()) {
return CombinedSignal.NONE;
}
DyeColor col = getOutputSignalColor(side);
BundledSignal bundledSignal = network.getBundledSignal();
return bundledSignal.getFilteredSignal(col, (IOutputSignalFilter) getSignalFilter(side, true));
}
@Override
@Nonnull
public Signal getNetworkInput(@Nonnull EnumFacing side) {
if (network != null) {
network.setNetworkEnabled(false);
}
CombinedSignal result = CombinedSignal.NONE;
if (acceptSignalsForDir(side)) {
int input = getExternalPowerLevel(side);
result = new CombinedSignal(input);
IInputSignalFilter filter = (IInputSignalFilter) getSignalFilter(side, false);
result = filter.apply(result, getBundle().getBundleworld(), getBundle().getLocation().offset(side));
}
if (network != null) {
network.setNetworkEnabled(true);
}
return new Signal(result, signalIdBase + side.ordinal());
}
protected int getExternalPowerLevelProtected(@Nonnull EnumFacing side) {
if (network != null) {
network.setNetworkEnabled(false);
}
int input = getExternalPowerLevel(side);
if (network != null) {
network.setNetworkEnabled(true);
}
return input;
}
protected int getExternalPowerLevel(@Nonnull EnumFacing dir) {
World world = getBundle().getBundleworld();
BlockPos loc = getBundle().getLocation().offset(dir);
int res = 0;
if (world.isBlockLoaded(loc)) {
int strong = world.getStrongPower(loc, dir);
if (strong > 0) {
return strong;
}
res = world.getRedstonePower(loc, dir);
IBlockState bs = world.getBlockState(loc);
Block block = bs.getBlock();
if (res <= 15 && block == Blocks.REDSTONE_WIRE) {
int wireIn = bs.getValue(BlockRedstoneWire.POWER);
res = Math.max(res, wireIn);
}
}
return res;
}
// @Optional.Method(modid = "computercraft")
// @Override
// @Nonnull
// public Map<DyeColor, Signal> getComputerCraftSignals(@Nonnull EnumFacing side) {
// Map<DyeColor, Signal> ccSignals = new EnumMap<DyeColor, Signal>(DyeColor.class);
//
// int bundledInput = getComputerCraftBundledPowerLevel(side);
// if (bundledInput >= 0) {
// for (int i = 0; i < 16; i++) {
// int color = bundledInput >>> i & 1;
// Signal signal = new Signal(color == 1 ? 16 : 0, signalIdBase + side.ordinal());
// ccSignals.put(DyeColor.fromIndex(Math.max(0, 15 - i)), signal);
// }
// }
//
// return ccSignals;
// }
// @Optional.Method(modid = "computercraft")
// private int getComputerCraftBundledPowerLevel(EnumFacing dir) {
// World world = getBundle().getBundleworld();
// BlockPos pos = getBundle().getLocation().offset(dir);
//
// if (world.isBlockLoaded(pos)) {
// return ComputerCraftAPI.getBundledRedstoneOutput(world, pos, dir.getOpposite());
// } else {
// return -1;
// }
// }
@Override
@Nonnull
public ConnectionMode getConnectionMode(@Nonnull EnumFacing dir) {
ConnectionMode res = forcedConnections.get(dir);
if (res == null) {
return getDefaultConnectionMode();
}
return res;
}
@Override
@Nonnull
public ConnectionMode getDefaultConnectionMode() {
return ConnectionMode.OUTPUT;
}
@Override
@Nonnull
public NNList<ItemStack> getDrops() {
NNList<ItemStack> res = super.getDrops();
for (ItemStack stack : inputFilterUpgrades.values()) {
if (stack != null && Prep.isValid(stack)) {
res.add(stack);
}
}
for (ItemStack stack : outputFilterUpgrades.values()) {
if (stack != null && Prep.isValid(stack)) {
res.add(stack);
}
}
return res;
}
@Override
public boolean onNeighborBlockChange(@Nonnull Block blockId) {
World world = getBundle().getBundleworld();
if (world.isRemote) {
return false;
}
boolean res = super.onNeighborBlockChange(blockId);
if (network == null || network.updatingNetwork) {
return false;
}
if (blockId != ConduitRegistry.getConduitModObjectNN().getBlock()) {
connectionsDirty = true;
}
return res;
}
private boolean acceptSignalsForDir(@Nonnull EnumFacing dir) {
if (!getConnectionMode(dir).acceptsOutput()) {
return false;
}
BlockPos loc = getBundle().getLocation().offset(dir);
return ConduitUtil.getConduit(getBundle().getEntity().getWorld(), loc.getX(), loc.getY(), loc.getZ(), IRedstoneConduit.class) == null;
}
// ---------------------
// TEXTURES
// ---------------------
@Override
public int getRedstoneSignalForColor(@Nonnull DyeColor col) {
if (network != null) {
return network.getSignalStrengthForColor(col);
}
return 0;
}
@SuppressWarnings("null")
@Override
@Nonnull
public IConduitTexture getTextureForState(@Nonnull CollidableComponent component) {
if (component.isCore()) {
return ConduitConfig.showState.get() && isActive() ? ICONS.get(KEY_INS_CORE_ON_ICON) : ICONS.get(KEY_INS_CORE_OFF_ICON);
}
return ICONS.get(KEY_INS_CONDUIT_ICON);
}
@SuppressWarnings("null")
@Override
@Nonnull
public IConduitTexture getTransmitionTextureForState(@Nonnull CollidableComponent component) {
return ConduitConfig.showState.get() && isActive() ? ICONS.get(KEY_TRANSMISSION_ICON) : ICONS.get(KEY_CONDUIT_ICON);
}
@Override
@SideOnly(Side.CLIENT)
public @Nullable Vector4f getTransmitionTextureColorForState(@Nonnull CollidableComponent component) {
return null;
}
@Override
protected void readTypeSettings(@Nonnull EnumFacing dir, @Nonnull NBTTagCompound dataRoot) {
forceConnectionMode(dir, EnumReader.get(ConnectionMode.class, dataRoot.getShort("connectionMode")));
setInputSignalColor(dir, EnumReader.get(DyeColor.class, dataRoot.getShort("inputSignalColor")));
setOutputSignalColor(dir, EnumReader.get(DyeColor.class, dataRoot.getShort("outputSignalColor")));
setOutputStrength(dir, dataRoot.getBoolean("signalStrong"));
}
@Override
protected void writeTypeSettingsToNbt(@Nonnull EnumFacing dir, @Nonnull NBTTagCompound dataRoot) {
dataRoot.setShort("connectionMode", (short) forcedConnections.get(dir).ordinal());
dataRoot.setShort("inputSignalColor", (short) getInputSignalColor(dir).ordinal());
dataRoot.setShort("outputSignalColor", (short) getOutputSignalColor(dir).ordinal());
dataRoot.setBoolean("signalStrong", isOutputStrong(dir));
}
@Override
public void writeToNBT(@Nonnull NBTTagCompound nbtRoot) {
super.writeToNBT(nbtRoot);
if (!forcedConnections.isEmpty()) {
byte[] modes = new byte[6];
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
ConnectionMode mode = forcedConnections.get(dir);
if (mode != null) {
modes[i] = (byte) mode.ordinal();
} else {
modes[i] = -1;
}
i++;
}
nbtRoot.setByteArray("forcedConnections", modes);
}
if (!inputSignalColors.isEmpty()) {
byte[] modes = new byte[6];
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
DyeColor col = inputSignalColors.get(dir);
if (col != null) {
modes[i] = (byte) col.ordinal();
} else {
modes[i] = -1;
}
i++;
}
nbtRoot.setByteArray("signalColors", modes);
}
if (!outputSignalColors.isEmpty()) {
byte[] modes = new byte[6];
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
DyeColor col = outputSignalColors.get(dir);
if (col != null) {
modes[i] = (byte) col.ordinal();
} else {
modes[i] = -1;
}
i++;
}
nbtRoot.setByteArray("outputSignalColors", modes);
}
if (!signalStrengths.isEmpty()) {
byte[] modes = new byte[6];
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
boolean isStrong = dir != null && isOutputStrong(dir);
if (isStrong) {
modes[i] = 1;
} else {
modes[i] = 0;
}
i++;
}
nbtRoot.setByteArray("signalStrengths", modes);
}
for (Entry<EnumFacing, IRedstoneSignalFilter> entry : inputFilters.entrySet()) {
if (entry.getValue() != null) {
IRedstoneSignalFilter f = entry.getValue();
NBTTagCompound itemRoot = new NBTTagCompound();
FilterRegistry.writeFilterToNbt(f, itemRoot);
nbtRoot.setTag("inSignalFilts." + entry.getKey().name(), itemRoot);
}
}
for (Entry<EnumFacing, IRedstoneSignalFilter> entry : outputFilters.entrySet()) {
if (entry.getValue() != null) {
IRedstoneSignalFilter f = entry.getValue();
NBTTagCompound itemRoot = new NBTTagCompound();
FilterRegistry.writeFilterToNbt(f, itemRoot);
nbtRoot.setTag("outSignalFilts." + entry.getKey().name(), itemRoot);
}
}
for (Entry<EnumFacing, ItemStack> entry : inputFilterUpgrades.entrySet()) {
ItemStack up = entry.getValue();
if (up != null && Prep.isValid(up)) {
IRedstoneSignalFilter filter = getSignalFilter(entry.getKey(), true);
FilterRegistry.writeFilterToStack(filter, up);
NBTTagCompound itemRoot = new NBTTagCompound();
up.writeToNBT(itemRoot);
nbtRoot.setTag("inputSignalFilterUpgrades." + entry.getKey().name(), itemRoot);
}
}
for (Entry<EnumFacing, ItemStack> entry : outputFilterUpgrades.entrySet()) {
ItemStack up = entry.getValue();
if (up != null && Prep.isValid(up)) {
IRedstoneSignalFilter filter = getSignalFilter(entry.getKey(), false);
FilterRegistry.writeFilterToStack(filter, up);
NBTTagCompound itemRoot = new NBTTagCompound();
up.writeToNBT(itemRoot);
nbtRoot.setTag("outputSignalFilterUpgrades." + entry.getKey().name(), itemRoot);
}
}
}
@Override
public void readFromNBT(@Nonnull NBTTagCompound nbtRoot) {
super.readFromNBT(nbtRoot);
forcedConnections.clear();
byte[] modes = nbtRoot.getByteArray("forcedConnections");
if (modes.length == 6) {
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
if (modes[i] >= 0) {
forcedConnections.put(dir, ConnectionMode.values()[modes[i]]);
}
i++;
}
}
inputSignalColors.clear();
byte[] cols = nbtRoot.getByteArray("signalColors");
if (cols.length == 6) {
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
if (cols[i] >= 0) {
inputSignalColors.put(dir, DyeColor.values()[cols[i]]);
}
i++;
}
}
outputSignalColors.clear();
byte[] outCols = nbtRoot.getByteArray("outputSignalColors");
if (outCols.length == 6) {
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
if (outCols[i] >= 0) {
outputSignalColors.put(dir, DyeColor.values()[outCols[i]]);
}
i++;
}
}
signalStrengths.clear();
byte[] strengths = nbtRoot.getByteArray("signalStrengths");
if (strengths.length == 6) {
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
if (strengths[i] > 0) {
signalStrengths.put(dir, true);
}
i++;
}
}
inputFilters.clear();
outputFilters.clear();
inputFilterUpgrades.clear();
outputFilterUpgrades.clear();
for (EnumFacing dir : EnumFacing.VALUES) {
String key = "inSignalFilts." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound filterTag = (NBTTagCompound) nbtRoot.getTag(key);
IRedstoneSignalFilter filter = (IRedstoneSignalFilter) FilterRegistry.loadFilterFromNbt(filterTag);
inputFilters.put(dir, filter);
}
key = "inputSignalFilterUpgrades." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound upTag = (NBTTagCompound) nbtRoot.getTag(key);
ItemStack ups = new ItemStack(upTag);
inputFilterUpgrades.put(dir, ups);
}
key = "outputSignalFilterUpgrades." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound upTag = (NBTTagCompound) nbtRoot.getTag(key);
ItemStack ups = new ItemStack(upTag);
outputFilterUpgrades.put(dir, ups);
}
key = "outSignalFilts." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound filterTag = (NBTTagCompound) nbtRoot.getTag(key);
IRedstoneSignalFilter filter = (IRedstoneSignalFilter) FilterRegistry.loadFilterFromNbt(filterTag);
outputFilters.put(dir, filter);
}
}
}
@Override
public String toString() {
return "RedstoneConduit [network=" + network + " connections=" + conduitConnections + " active=" + active + "]";
}
@SideOnly(Side.CLIENT)
@Override
public void hashCodeForModelCaching(BlockStateWrapperConduitBundle.ConduitCacheKey hashCodes) {
super.hashCodeForModelCaching(hashCodes);
hashCodes.addEnum(inputSignalColors);
hashCodes.addEnum(outputSignalColors);
if (ConduitConfig.showState.get() && isActive()) {
hashCodes.add(1);
}
}
@Override
public @Nonnull RedstoneConduitNetwork createNetworkForType() {
return new RedstoneConduitNetwork();
}
@SideOnly(Side.CLIENT)
@Nonnull
@Override
public ITabPanel createGuiPanel(@Nonnull IGuiExternalConnection gui, @Nonnull IClientConduit con) {
return new RedstoneSettings(gui, con);
}
@Override
@SideOnly(Side.CLIENT)
public boolean updateGuiPanel(@Nonnull ITabPanel panel) {
if (panel instanceof RedstoneSettings) {
return ((RedstoneSettings) panel).updateConduit(this);
}
return false;
}
@SideOnly(Side.CLIENT)
@Override
public int getGuiPanelTabOrder() {
return 2;
}
// ----------------- CAPABILITIES ------------
@Override
public boolean hasInternalCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
if (capability == CapabilityFilterHolder.FILTER_HOLDER_CAPABILITY) {
return true;
}
return super.hasInternalCapability(capability, facing);
}
@Override
@Nullable
public <T> T getInternalCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
if (capability == CapabilityFilterHolder.FILTER_HOLDER_CAPABILITY) {
return CapabilityFilterHolder.FILTER_HOLDER_CAPABILITY.cast(this);
}
return super.getInternalCapability(capability, facing);
}
// -------------------------------------------
// FILTERS
// -------------------------------------------
@Override
public void setSignalIdBase(int id) {
signalIdBase = id;
}
@Override
@Nonnull
public IRedstoneSignalFilter getSignalFilter(@Nonnull EnumFacing dir, boolean isOutput) {
if (!isOutput) {
return NullHelper.first(inputFilters.get(dir), DefaultInputSignalFilter.instance);
} else {
return NullHelper.first(outputFilters.get(dir), DefaultOutputSignalFilter.instance);
}
}
public void setSignalFilter(@Nonnull EnumFacing dir, boolean isInput, @Nonnull IRedstoneSignalFilter filter) {
if (!isInput) {
inputFilters.put(dir, filter);
} else {
outputFilters.put(dir, filter);
}
setClientStateDirty();
connectionsDirty = true;
}
@Override
public @Nonnull IRedstoneSignalFilter getFilter(int filterIndex, int param1) {
return getSignalFilter(EnumFacing.getFront(param1), filterIndex == getInputFilterIndex() ? true : !(filterIndex == getOutputFilterIndex()));
}
@Override
public void setFilter(int filterIndex, int param1, @Nonnull IRedstoneSignalFilter filter) {
setSignalFilter(EnumFacing.getFront(param1), filterIndex == getInputFilterIndex() ? true : !(filterIndex == getOutputFilterIndex()), filter);
}
@Override
@Nonnull
public ItemStack getFilterStack(int filterIndex, int param1) {
if (filterIndex == getInputFilterIndex()) {
return NullHelper.first(inputFilterUpgrades.get(EnumFacing.getFront(param1)), Prep.getEmpty());
} else if (filterIndex == getOutputFilterIndex()) {
return NullHelper.first(outputFilterUpgrades.get(EnumFacing.getFront(param1)), Prep.getEmpty());
}
return Prep.getEmpty();
}
@Override
public void setFilterStack(int filterIndex, int param1, @Nonnull ItemStack stack) {
if (filterIndex == getInputFilterIndex()) {
if (Prep.isValid(stack)) {
inputFilterUpgrades.put(EnumFacing.getFront(param1), stack);
} else {
inputFilterUpgrades.remove(EnumFacing.getFront(param1));
}
} else if (filterIndex == getOutputFilterIndex()) {
if (Prep.isValid(stack)) {
outputFilterUpgrades.put(EnumFacing.getFront(param1), stack);
} else {
outputFilterUpgrades.remove(EnumFacing.getFront(param1));
}
}
final IRedstoneSignalFilter filterForUpgrade = FilterRegistry.<IRedstoneSignalFilter> getFilterForUpgrade(stack);
if (filterForUpgrade != null) {
setFilter(filterIndex, param1, filterForUpgrade);
}
}
@Override
public int getInputFilterIndex() {
return FilterGuiUtil.INDEX_INPUT_REDSTONE;
}
@Override
public int getOutputFilterIndex() {
return FilterGuiUtil.INDEX_OUTPUT_REDSTONE;
}
@Override
public boolean isFilterUpgradeAccepted(@Nonnull ItemStack stack, boolean isInput) {
if (!isInput) {
return stack.getItem() instanceof IItemInputSignalFilterUpgrade;
} else {
return stack.getItem() instanceof IItemOutputSignalFilterUpgrade;
}
}
@Override
@Nonnull
public NNList<ITextComponent> getConduitProbeInformation(@Nonnull EntityPlayer player) {
final NNList<ITextComponent> result = super.getConduitProbeInformation(player);
if (getExternalConnections().isEmpty()) {
ITextComponent elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_HEADING_NO_CONNECTIONS.toChatServer();
elem.getStyle().setColor(TextFormatting.GOLD);
result.add(elem);
} else {
for (EnumFacing dir : getExternalConnections()) {
if (dir == null) {
continue;
}
ITextComponent elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_HEADING.toChatServer(new TextComponentTranslation(EnderIO.lang.addPrefix("facing." + dir)));
elem.getStyle().setColor(TextFormatting.GREEN);
result.add(elem);
ConnectionMode mode = getConnectionMode(dir);
if (mode.acceptsInput()) {
elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_STRONG.toChatServer(isProvidingStrongPower(dir));
elem.getStyle().setColor(TextFormatting.BLUE);
result.add(elem);
elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_WEAK.toChatServer(isProvidingWeakPower(dir));
elem.getStyle().setColor(TextFormatting.BLUE);
result.add(elem);
}
if (mode.acceptsOutput()) {
elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_EXTERNAL.toChatServer(getExternalPowerLevelProtected(dir));
elem.getStyle().setColor(TextFormatting.BLUE);
result.add(elem);
}
}
}
return result;
}
}
| HenryLoenwind/EnderIO | enderio-conduits/src/main/java/crazypants/enderio/conduits/conduit/redstone/InsulatedRedstoneConduit.java | Java | unlicense | 33,880 |
$.extend(window.lang_fa, {
"helpStop": "متوقف کردن آموزش",
}); | trollderius/wouldyourather_phonegap | www/~commons/modules/tutorial/lang/fa.js | JavaScript | unlicense | 76 |
package crazypants.enderio.machine.capbank.network;
import javax.annotation.Nonnull;
import com.enderio.core.common.util.BlockCoord;
import crazypants.enderio.conduit.IConduitBundle;
import crazypants.enderio.conduit.power.IPowerConduit;
import crazypants.enderio.machine.IoMode;
import crazypants.enderio.machine.capbank.TileCapBank;
import crazypants.enderio.power.IPowerInterface;
import net.minecraft.util.EnumFacing;
public class EnergyReceptor {
private final @Nonnull IPowerInterface receptor;
private final @Nonnull EnumFacing fromDir;
private final @Nonnull IoMode mode;
private final BlockCoord location;
private final IPowerConduit conduit;
public EnergyReceptor(@Nonnull TileCapBank cb, @Nonnull IPowerInterface receptor, @Nonnull EnumFacing dir) {
this.receptor = receptor;
fromDir = dir;
mode = cb.getIoMode(dir);
if(receptor.getProvider() instanceof IConduitBundle) {
conduit = ((IConduitBundle) receptor.getProvider()).getConduit(IPowerConduit.class);
} else {
conduit = null;
}
location = cb.getLocation();
}
public IPowerConduit getConduit() {
return conduit;
}
public @Nonnull IPowerInterface getReceptor() {
return receptor;
}
public @Nonnull EnumFacing getDir() {
return fromDir;
}
public @Nonnull IoMode getMode() {
return mode;
}
//NB: Special impl of equals and hash code based solely on the location and dir
//This is done to ensure the receptors in the Networks Set are added / removed correctly
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + fromDir.hashCode();
result = prime * result + ((location == null) ? 0 : location.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
EnergyReceptor other = (EnergyReceptor) obj;
if(fromDir != other.fromDir) {
return false;
}
if(location == null) {
if(other.location != null) {
return false;
}
} else if(!location.equals(other.location)) {
return false;
}
return true;
}
@Override
public String toString() {
return "EnergyReceptor [receptor=" + receptor + ", fromDir=" + fromDir + ", mode=" + mode + ", conduit=" + conduit + "]";
}
}
| D-Inc/EnderIO | src/main/java/crazypants/enderio/machine/capbank/network/EnergyReceptor.java | Java | unlicense | 2,445 |
/*****************************************************************************
*
* HOPERUN PROPRIETARY INFORMATION
*
* The information contained herein is proprietary to HopeRun
* and shall not be reproduced or disclosed in whole or in part
* or used for any design or manufacture
* without direct written authorization from HopeRun.
*
* Copyright (c) 2012 by HopeRun. All rights reserved.
*
*****************************************************************************/
package com.hoperun.telematics.mobile.activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.hoperun.telematics.mobile.R;
import com.hoperun.telematics.mobile.framework.net.ENetworkServiceType;
import com.hoperun.telematics.mobile.framework.net.callback.INetCallback;
import com.hoperun.telematics.mobile.framework.net.callback.INetCallbackArgs;
import com.hoperun.telematics.mobile.framework.service.NetworkService;
import com.hoperun.telematics.mobile.helper.AnimationHelper;
import com.hoperun.telematics.mobile.helper.CacheManager;
import com.hoperun.telematics.mobile.helper.DialogHelper;
import com.hoperun.telematics.mobile.helper.NetworkCallbackHelper;
import com.hoperun.telematics.mobile.helper.TestDataManager;
import com.hoperun.telematics.mobile.model.fuel.FuelRequest;
import com.hoperun.telematics.mobile.model.fuel.FuelResponse;
/**
*
* @author fan_leilei
*
*/
public class FuelStateActivity extends DefaultActivity {
private ImageView pointerImage;
private TextView consumeText;
private TextView remainText;
private static final String TAG = "FuelStateActivity";
private FuelResponse fuelResponse;
/*
* (non-Javadoc)
*
* @see
* com.hoperun.telematics.mobile.framework.BaseActivity#onCreate(android
* .os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ui_fuel_layout);
initViews();
setTitleBar(this, getString(R.string.fuel_title));
}
/**
*
*/
private void initViews() {
pointerImage = (ImageView) findViewById(R.id.pointerImage);
consumeText = (TextView) findViewById(R.id.consumeText);
remainText = (TextView) findViewById(R.id.remainText);
}
@Override
protected void onBindServiceFinish(ComponentName className) {
super.onBindServiceFinish(className);
if (className.getClassName().equals(NetworkService.class.getName())) {
startProgressDialog(ENetworkServiceType.Fuel);
getFuelInfo();
}
}
/**
*
*/
private void getFuelInfo() {
// leilei,test code if
// if (TestDataManager.IS_TEST_MODE) {
// mCallBack2.callback(null);
// } else {
String vin = CacheManager.getInstance().getVin();
if (vin == null) {
vin = getString(R.string.testVin);
}
String license = CacheManager.getInstance().getLicense();
if (license == null) {
license = getString(R.string.testLicense1);
}
FuelRequest request = new FuelRequest(vin, license);
String postJson = request.toJsonStr();
sendAsyncMessage(ENetworkServiceType.Fuel, postJson, mCallBack);
// }
}
// NetworkCallbackHelper.IErrorEventListener displayer = new
// NetworkCallbackHelper.IErrorEventListener() {
// @Override
// public void onResponseReturned(BaseResponse response) {
// fuelResponse = (FuelResponse) response;
// updateViews(fuelResponse);
// }
//
// @Override
// public void onRetryButtonClicked() {
// // refresh(null);
// }
// };
// NetworkCallbackHelper.showInfoFromResponse(FuelStateActivity.this, args,
// FuelResponse.class, displayer);
private INetCallback mCallBack = new INetCallback() {
@Override
public void callback(final INetCallbackArgs args) {
stopProgressDialog();
Context context = FuelStateActivity.this;
OnClickListener retryBtnListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startProgressDialog(ENetworkServiceType.Fuel);
}
};
// 检查是否有非业务级的错误
if (!NetworkCallbackHelper.haveSystemError(context, args.getStatus())) {
stopProgressDialog();
String payload = args.getPayload();
if (NetworkCallbackHelper.isPayloadNullOrEmpty(payload)) {
DialogHelper.alertDialog(context, R.string.error_empty_payload, R.string.ok);
} else {
Gson gson = new Gson();
fuelResponse = gson.fromJson(payload, FuelResponse.class);
if (NetworkCallbackHelper.isErrorResponse(context, fuelResponse)) {
// 当返回的信息为异常提示信息的时候,判断异常类型并弹出提示对话框
NetworkCallbackHelper.alertBusinessError(context, fuelResponse.getErrorCode());
} else {
updateViews(fuelResponse);
}
}
} else {
// 根据各接口情况选择重试或直接提示
String errMsg = args.getErrorMessage();
Log.e(TAG, errMsg);
errMsg = getString(R.string.error_async_return_fault);
startReload(errMsg, retryBtnListener);
}
}
};
// leilei,test code
// private INetCallback mCallBack2 = new INetCallback() {
//
// @Override
// public void callback(INetCallbackArgs args) {
// new Thread() {
// @Override
// public void run() {
// try {
// Thread.sleep(1500);
// stopProgressDialog();
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// updateViews(TestDataManager.getInstance().getFuelInfo());
// }
// });
// } catch (InterruptedException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
// }.start();
//
// }
// };
private static final long ANIMATION_DURATION = 1000;
private static final float ANIMATION_START_DEGREE = 0;
private static final float ANIMATION_END_DEGREE = 108;
private static final float ANIMATION_DEGREE_RANGE = ANIMATION_END_DEGREE - ANIMATION_START_DEGREE;
private void updateViews(FuelResponse response) {
consumeText.setText(getString(R.string.fuel_consume, response.getConsumption()));
remainText.setText(getString(R.string.fuel_remaining, response.getRemainingMileage()));
float maxFuel = response.getMaxFuel();
float remainFuel = response.getRemainingFuel();
float endDegree = ANIMATION_DEGREE_RANGE * remainFuel / maxFuel;
AnimationHelper.startOnceRotateAnimation(pointerImage, ANIMATION_START_DEGREE, endDegree, ANIMATION_DURATION);
}
} | yangjun2/android | telematics_android/src/com/hoperun/telematics/mobile/activity/FuelStateActivity.java | Java | unlicense | 6,629 |
/*
* cuReVM.cpp
*
* (Un)License: Public Domain
* You can use and modify this file without any restriction.
* Do what you want.
* No warranties and disclaimer of any damages.
* More info: http://unlicense.org
* The latest sources: https://github.com/republib
*/
#include "base/rebase.hpp"
#include "expr/reexpr.hpp"
class TestReVM: public ReTest {
private:
ReSource m_source;
ReASTree m_tree;
ReStringReader m_reader;
const char* m_currentSource;
public:
TestReVM() :
ReTest("ReVM"),
m_source(),
m_tree(),
m_reader(m_source) {
m_source.addReader(&m_reader);
doIt();
}
protected:
void setSource(const char* content) {
ReASItem::reset();
m_currentSource = content;
m_tree.clear();
m_source.clear();
m_reader.clear();
m_reader.addSource("<test>", content);
m_source.addReader(&m_reader);
m_source.addSourceUnit(m_reader.currentSourceUnit());
}
private:
void checkAST(const char* fileExpected, int lineNo) {
QByteArray fnExpected = "test";
fnExpected += QDir::separator().toLatin1();
fnExpected += "ReVM";
fnExpected += (char) QDir::separator().toLatin1();
fnExpected += fileExpected;
QByteArray fnCurrent = getTempFile(fileExpected, "ReVM");
ReMFParser parser(m_source, m_tree);
parser.parse();
ReVirtualMachine vm(m_tree, m_source);
vm.setFlag(ReVirtualMachine::VF_TRACE_STATEMENTS);
ReFileWriter writer(fnCurrent);
vm.setTraceWriter(&writer);
writer.write(m_currentSource);
vm.executeModule("<test>");
assertEqualFiles(fnExpected.constData(), fnCurrent.constData(),
__FILE__, lineNo);
}
public:
void baseTest() {
setSource("Int a=2+3*4;\nfunc Void main():\na;\nendf");
checkAST("baseTest.txt", __LINE__);
}
virtual void run(void) {
baseTest();
}
};
void testReVM() {
TestReVM test;
}
| republib/reqt | cunit/cuReVM.cpp | C++ | unlicense | 1,955 |
'use strict';
function ProfileSearch(injector) {
var service = this;
service.list = function(params) {
var connection = injector.connection;
var ProfileModel = injector.ProfileModel;
var profileSearch = new ProfileModel();
var page = params.page || 1;
var where = params.where || [];
var order = params.order || [];
var limit = params.limit || 10;
var fields = params.fields || profileSearch.fields;
profileSearch.page = page;
profileSearch.order = order;
profileSearch.where = where;
profileSearch.limit = limit;
profileSearch.fields = fields;
connection.search(profileSearch);
};
}
module.exports = ProfileSearch;
| luiz-simples/kauris | server/src/profile/profile.search.js | JavaScript | unlicense | 703 |
import {GameConfig} from '../../../config/game.config';
import {GuiUtils} from '../../../utils/gui.utils';
import {isString} from 'util';
export class CrossButton {
private state: Phaser.State = null;
private game: Phaser.Game = null;
private url: string = '';
private container: Phaser.Group = null;
private btns: Phaser.Button[] = [];
private sprites: Phaser.Sprite[] = [];
constructor(state: Phaser.State, crossUrl: string = '') {
this.state = state;
this.game = GameConfig.GAME;
this.url = crossUrl;
this.container = this.game.add.group();
}
link(url: string): CrossButton {
this.url = url;
return this;
}
sprite(): CrossButton {
return this;
}
animatedSprite(): CrossButton {
return this;
}
button(x: number, y: number, scale: number, asset: string, frames?: any|any[],
overHandler: Function = GuiUtils.addOverHandler,
outHandler: Function = GuiUtils.addOutHandler): CrossButton {
if (frames == null) {
frames = [0, 0, 0];
}
else if (isString(frames)) {
frames = [frames, frames, frames];
}
this.btns.push(GuiUtils.makeButton(
this.state, this.container,
x, y, scale,
'', asset, frames,
true, true, true, GuiUtils.goCross(this.url), overHandler, outHandler));
return this;
}
buttonAndReturn(x: number, y: number, scale: number, asset: string, frames?: any|any[],
overHandler: Function = GuiUtils.addOverHandler,
outHandler: Function = GuiUtils.addOutHandler): Phaser.Button {
if (frames == null) {
frames = [0, 0, 0];
}
else if (isString(frames)) {
frames = [frames, frames, frames];
}
const btn = GuiUtils.makeButton(
this.state, this.container,
x, y, scale,
'', asset, frames,
true, true, true, GuiUtils.goCross(this.url), overHandler, outHandler);
this.btns.push(btn);
return btn;
}
getBody(): Phaser.Group {
return this.container;
}
dispose() {
for (let btn of this.btns) {
btn.destroy(true);
}
for (let spr of this.sprites) {
spr.destroy(true);
}
this.container.destroy(true);
}
} | B1zDelNick/phaser-npm-webpack-typescript-starter-project-master | src/states/template/final/cross.button.ts | TypeScript | unlicense | 2,417 |
package BreadthAndDepthFirstSearch;
// https://leetcode.com/problems/increasing-order-search-tree/
import java.util.ArrayList;
import java.util.Arrays;
public class IncreasingOrderBinarySearchTree {
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int value) {
val = value;
}
static TreeNode buildBinaryTree(ArrayList<Integer> array) {
return buildBinaryTree(array, 0, array.size() - 1);
}
private static TreeNode buildBinaryTree(ArrayList<Integer> array, int start, int end) {
if (start > end || array.get(start) == null) {
return null;
}
TreeNode node = new TreeNode(array.get(start));
int leftChildIndex = 2 * start + 1;
int rightChildIndex = 2 * start + 2;
if (leftChildIndex <= end) {
node.left = buildBinaryTree(array, leftChildIndex, end);
}
if (rightChildIndex <= end) {
node.right = buildBinaryTree(array, rightChildIndex, end);
}
return node;
}
}
private static TreeNode current = null;
private static TreeNode increasingBST(TreeNode root) {
TreeNode result = new TreeNode(0);
current = result;
inOrder(root);
return result.right;
}
private static void inOrder(TreeNode node) {
if (node == null) {
return;
}
inOrder(node.left);
node.left = null;
current.right = node;
current = node;
inOrder(node.right);
}
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<>(Arrays.asList(5, 3, 6, 2, 4, null, 8, 1, null, null, null, 7, 9));
TreeNode root = TreeNode.buildBinaryTree(array);
TreeNode result = increasingBST(root);
System.out.println(result);
}
}
| gagarwal/codingproblemsandsolutions | src/BreadthAndDepthFirstSearch/IncreasingOrderBinarySearchTree.java | Java | unlicense | 1,654 |
var net = require('net')
var chatServer = net.createServer(),
clientList = []
chatServer.on('connection', function(client) {
client.name = client.remoteAddress + ':' + client.remotePort
client.write('Hi ' + client.name + '!\n');
console.log(client.name + ' joined')
clientList.push(client)
client.on('data', function(data) {
broadcast(data, client)
})
client.on('end', function(data) {
console.log(client.name + ' quit')
clientList.splice(clientList.indexOf(client), 1)
})
client.on('error', function(e) {
console.log(e)
})
})
function broadcast(message, client) {
for(var i=0;i<clientList.length;i+=1) {
if(client !== clientList[i]) {
if(clientList[i].writable) {
clientList[i].write(client.name + " says " + message)
} else {
cleanup.push(clientList[i])
clientList[i].destroy()
}
}
}
}
chatServer.listen(9000)
| mattcoffey/node.js | chatServer.js | JavaScript | unlicense | 1,002 |
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['sap/ui/model/FormatException', 'sap/ui/model/odata/type/ODataType',
'sap/ui/model/ParseException', 'sap/ui/model/ValidateException'],
function(FormatException, ODataType, ParseException, ValidateException) {
"use strict";
var rGuid = /^[A-F0-9]{8}-([A-F0-9]{4}-){3}[A-F0-9]{12}$/i;
/**
* Returns the locale-dependent error message.
*
* @returns {string}
* the locale-dependent error message.
* @private
*/
function getErrorMessage() {
return sap.ui.getCore().getLibraryResourceBundle().getText("EnterGuid");
}
/**
* Sets the constraints.
*
* @param {sap.ui.model.odata.type.Guid} oType
* the type instance
* @param {object} [oConstraints]
* constraints, see {@link #constructor}
*/
function setConstraints(oType, oConstraints) {
var vNullable = oConstraints && oConstraints.nullable;
oType.oConstraints = undefined;
if (vNullable === false || vNullable === "false") {
oType.oConstraints = {nullable: false};
} else if (vNullable !== undefined && vNullable !== true && vNullable !== "true") {
jQuery.sap.log.warning("Illegal nullable: " + vNullable, null, oType.getName());
}
}
/**
* Constructor for an OData primitive type <code>Edm.Guid</code>.
*
* @class This class represents the OData primitive type <a
* href="http://www.odata.org/documentation/odata-version-2-0/overview#AbstractTypeSystem">
* <code>Edm.Guid</code></a>.
*
* In {@link sap.ui.model.odata.v2.ODataModel ODataModel} this type is represented as a
* <code>string</code>.
*
* @extends sap.ui.model.odata.type.ODataType
*
* @author SAP SE
* @version 1.28.10
*
* @alias sap.ui.model.odata.type.Guid
* @param {object} [oFormatOptions]
* format options as defined in the interface of {@link sap.ui.model.SimpleType}; this
* type ignores them since it does not support any format options
* @param {object} [oConstraints]
* constraints; {@link #validateValue validateValue} throws an error if any constraint is
* violated
* @param {boolean|string} [oConstraints.nullable=true]
* if <code>true</code>, the value <code>null</code> is accepted
* @public
* @since 1.27.0
*/
var EdmGuid = ODataType.extend("sap.ui.model.odata.type.Guid",
/** @lends sap.ui.model.odata.type.Guid.prototype */
{
constructor : function (oFormatOptions, oConstraints) {
ODataType.apply(this, arguments);
setConstraints(this, oConstraints);
}
}
);
/**
* Formats the given value to the given target type.
*
* @param {string} sValue
* the value to be formatted
* @param {string} sTargetType
* the target type; may be "any" or "string".
* See {@link sap.ui.model.odata.type} for more information.
* @returns {string}
* the formatted output value in the target type; <code>undefined</code> or <code>null</code>
* are formatted to <code>null</code>
* @throws {sap.ui.model.FormatException}
* if <code>sTargetType</code> is unsupported
* @public
*/
EdmGuid.prototype.formatValue = function(sValue, sTargetType) {
if (sValue === undefined || sValue === null) {
return null;
}
if (sTargetType === "string" || sTargetType === "any") {
return sValue;
}
throw new FormatException("Don't know how to format " + this.getName() + " to "
+ sTargetType);
};
/**
* Returns the type's name.
*
* @returns {string}
* the type's name
* @public
*/
EdmGuid.prototype.getName = function () {
return "sap.ui.model.odata.type.Guid";
};
/**
* Parses the given value to a GUID.
*
* @param {string} sValue
* the value to be parsed, maps <code>""</code> to <code>null</code>
* @param {string} sSourceType
* the source type (the expected type of <code>sValue</code>); must be "string".
* See {@link sap.ui.model.odata.type} for more information.
* @returns {string}
* the parsed value
* @throws {sap.ui.model.ParseException}
* if <code>sSourceType</code> is unsupported
* @public
*/
EdmGuid.prototype.parseValue = function (sValue, sSourceType) {
var sResult;
if (sValue === "" || sValue === null) {
return null;
}
if (sSourceType !== "string") {
throw new ParseException("Don't know how to parse " + this.getName() + " from "
+ sSourceType);
}
// remove all whitespaces and separators
sResult = sValue.replace(/[-\s]/g, '');
if (sResult.length != 32) {
// don't try to add separators to invalid value
return sValue;
}
sResult = sResult.slice(0, 8) + '-' + sResult.slice(8, 12) + '-' + sResult.slice(12, 16)
+ '-' + sResult.slice(16, 20) + '-' + sResult.slice(20);
return sResult.toUpperCase();
};
/**
* Validates whether the given value in model representation is valid and meets the
* given constraints.
*
* @param {string} sValue
* the value to be validated
* @returns {void}
* @throws {sap.ui.model.ValidateException}
* if the value is not valid
* @public
*/
EdmGuid.prototype.validateValue = function (sValue) {
if (sValue === null) {
if (this.oConstraints && this.oConstraints.nullable === false) {
throw new ValidateException(getErrorMessage());
}
return;
}
if (typeof sValue !== "string") {
// This is a "technical" error by calling validate w/o parse
throw new ValidateException("Illegal " + this.getName() + " value: " + sValue);
}
if (!rGuid.test(sValue)) {
throw new ValidateException(getErrorMessage());
}
};
return EdmGuid;
});
| ghostxwheel/utorrent-webui | resources/sap/ui/model/odata/type/Guid-dbg.js | JavaScript | unlicense | 5,646 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Contains test cases for the utils.py module."""
from __future__ import unicode_literals
import sys
import os.path
import unittest
PATH = os.path.realpath(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(PATH)))
try:
from youtube_dl_gui import utils
except ImportError as error:
print error
sys.exit(1)
class TestToBytes(unittest.TestCase):
"""Test case for the to_bytes method."""
def test_to_bytes_bytes(self):
self.assertEqual(utils.to_bytes("596.00B"), 596.00)
self.assertEqual(utils.to_bytes("133.55B"), 133.55)
def test_to_bytes_kilobytes(self):
self.assertEqual(utils.to_bytes("1.00KiB"), 1024.00)
self.assertEqual(utils.to_bytes("5.55KiB"), 5683.20)
def test_to_bytes_megabytes(self):
self.assertEqual(utils.to_bytes("13.64MiB"), 14302576.64)
self.assertEqual(utils.to_bytes("1.00MiB"), 1048576.00)
def test_to_bytes_gigabytes(self):
self.assertEqual(utils.to_bytes("1.00GiB"), 1073741824.00)
self.assertEqual(utils.to_bytes("1.55GiB"), 1664299827.20)
def test_to_bytes_terabytes(self):
self.assertEqual(utils.to_bytes("1.00TiB"), 1099511627776.00)
class TestFormatBytes(unittest.TestCase):
"""Test case for the format_bytes method."""
def test_format_bytes_bytes(self):
self.assertEqual(utils.format_bytes(518.00), "518.00B")
def test_format_bytes_kilobytes(self):
self.assertEqual(utils.format_bytes(1024.00), "1.00KiB")
def test_format_bytes_megabytes(self):
self.assertEqual(utils.format_bytes(1048576.00), "1.00MiB")
def test_format_bytes_gigabytes(self):
self.assertEqual(utils.format_bytes(1073741824.00), "1.00GiB")
def test_format_bytes_terabytes(self):
self.assertEqual(utils.format_bytes(1099511627776.00), "1.00TiB")
def main():
unittest.main()
if __name__ == "__main__":
main()
| Sofronio/youtube-dl-gui | tests/test_utils.py | Python | unlicense | 1,981 |
#include "escapeTimeFractal.h"
escapeTimeFractal::escapeTimeFractal() : fractal()
{
zoomed_fr_x_max = FR_X_MAX;
zoomed_fr_x_min = FR_X_MIN;
zoomed_fr_y_max = FR_Y_MAX;
zoomed_fr_y_min = FR_Y_MIN;
}
void escapeTimeFractal::render(QImage *image, int begin, int end)
{
for (int i = begin; i < end; ++i)
{
for (int j = 0; j < screenWidth; ++j)
{
int iteration = escape((double)j, (double)i);
image->setPixel(j, i, getColor(iteration, maxIterations).rgb());
}
}
}
QColor escapeTimeFractal::getColor(int value, int maxValue) const
{
QColor color;
if (value >= maxValue)
{
// zwróć czarny kolor
color.setRgb(0, 0, 0);
return color;
}
double t = value / (double) maxValue;
int r = (int)(9 * (1 - t) * t * t * t * 255);
int g = (int)(15 * (1 - t) * (1 - t) * t * t * 255);
int b = (int)(8.5 * (1 - t) * (1 - t) * (1 - t) * t * 255);
color.setRgb(r, g, b);
return color;
}
| kamilwu/fracx | src/escapeTimeFractal.cpp | C++ | unlicense | 904 |
var assert = require('assert')
var path = require('path')
var fs = require('fs-extra')
var sinon = require('sinon')
var broccoli = require('broccoli')
var Q = require('q')
var Filter = require('..')
describe('Filter', function() {
var ORIG_DIR = path.join(__dirname, 'files')
var DIR = path.join(__dirname, 'files-copy')
var ONE_FILE_DIR = path.join(__dirname, 'one-file')
var builder
var createCustomFilter = function() {
var CustomFilter = function(inputTrees, options) {
if (!(this instanceof CustomFilter)) return new CustomFilter(inputTrees, options)
Filter.apply(this, arguments)
}
CustomFilter.prototype = Object.create(Filter.prototype)
return CustomFilter
}
beforeEach(function() {
fs.copySync(ORIG_DIR, DIR)
})
afterEach(function() {
if (builder) builder.cleanup()
fs.removeSync(DIR)
})
it('throws when "processFileContent" is not implemented', function(done) {
var CustomFilter = createCustomFilter()
var tree = new CustomFilter(DIR)
builder = new broccoli.Builder(tree)
builder.build()
.then(function() { done(new Error('Have not thrown')) })
.catch(function() { done() })
})
it('calls "processFileContent"', function() {
var CustomFilter = createCustomFilter()
var spy = CustomFilter.prototype.processFileContent = sinon.spy()
var tree = new CustomFilter(ONE_FILE_DIR)
builder = new broccoli.Builder(tree)
return builder.build().then(function() {
var args = spy.firstCall.args
assert.equal(args[0], 'file.js\n')
assert.equal(args[1], 'file.js')
assert.equal(args[2], ONE_FILE_DIR)
})
})
var FILTERED = 'filtered'
it('filters files', function() {
var CustomFilter = createCustomFilter()
CustomFilter.prototype.processFileContent = function() { return FILTERED }
var tree = new CustomFilter(ONE_FILE_DIR)
builder = new broccoli.Builder(tree)
return builder.build().then(function(result) {
var dir = result.directory
var content = fs.readFileSync(path.join(dir, 'file.js'), 'utf-8')
assert.equal(content, FILTERED)
})
})
it('uses "targetExtension"', function() {
var CustomFilter = createCustomFilter()
CustomFilter.prototype.processFileContent = function() { return FILTERED }
var tree = new CustomFilter(ONE_FILE_DIR, {targetExtension: 'ext'})
builder = new broccoli.Builder(tree)
return builder.build().then(function(result) {
var dir = result.directory
var content = fs.readFileSync(path.join(dir, 'file.ext'), 'utf-8')
assert.equal(content, FILTERED)
})
})
it('uses "changeFileName"', function() {
var CustomFilter = createCustomFilter()
CustomFilter.prototype.processFileContent = function() { return FILTERED }
var tree = new CustomFilter(ONE_FILE_DIR, {
targetExtension: 'ext',
changeFileName: function(name) { return name + '.changed' }
})
builder = new broccoli.Builder(tree)
return builder.build().then(function(result) {
var dir = result.directory
var content = fs.readFileSync(path.join(dir, 'file.js.changed'), 'utf-8')
assert.equal(content, FILTERED)
})
})
it('can return many files', function() {
var RESULT = [
{path: 'file1.js', content: 'FILE1'},
{path: 'file2.js', content: 'FILE2'}
]
var CustomFilter = createCustomFilter()
CustomFilter.prototype.processFileContent = function() { return RESULT }
var tree = new CustomFilter(ONE_FILE_DIR)
builder = new broccoli.Builder(tree)
return builder.build().then(function(result) {
var dir = result.directory
RESULT.forEach(function(file) {
var content = fs.readFileSync(path.join(dir, file.path), 'utf-8')
assert.equal(content, file.content)
})
})
})
it('can process files asynchronously', function() {
var CustomFilter = createCustomFilter()
CustomFilter.prototype.processFileContent = function() {
var deferred = Q.defer()
setTimeout(function() { deferred.resolve(FILTERED) })
return deferred.promise
}
var tree = new CustomFilter(ONE_FILE_DIR)
builder = new broccoli.Builder(tree)
return builder.build().then(function(result) {
var dir = result.directory
var content = fs.readFileSync(path.join(dir, 'file.js'), 'utf-8')
assert.equal(content, FILTERED)
})
})
it('copy not changed files from cache', function() {
var CustomFilter = createCustomFilter()
var spy = CustomFilter.prototype.processFileContent = sinon.spy()
var tree = new CustomFilter(DIR)
builder = new broccoli.Builder(tree)
return builder.build()
.then(function() { assert.equal(spy.callCount, 3) })
.then(function() {
fs.writeFileSync(path.join(DIR, 'file.js'), 'CHANGED')
return builder.build()
})
.then(function() { assert.equal(spy.callCount, 4) })
})
it('finds files using globs', function() {
var CustomFilter = createCustomFilter()
var spy = CustomFilter.prototype.processFileContent = sinon.spy()
var tree = new CustomFilter(DIR, {files: ['**/*.js']})
builder = new broccoli.Builder(tree)
return builder.build()
.then(function() { assert.equal(spy.callCount, 1) })
})
})
| sunflowerdeath/broccoli-glob-filter | tests/test.js | JavaScript | unlicense | 5,011 |
/**
*
* This is the "container" for global variables. I made it so we won't have to worry
* about "conflicts" with local variable names.
*
*/
var NFL_PICKS_GLOBAL = {
/**
* Here to store data from the server so we can hopefully load it once and then
* get to it whenever it's needed as we're dealing with other stuff.
*/
data: {
teams: [],
players: [],
years: []
},
/**
* The possible types for what they can view. Like standings, picks, and stats.
* Holds label and value pairs of all the possible types.
*/
types: [],
/**
* Holds label value pairs of all the players we show. Not all of them will be "real"... like if we
* want to show "Everybody" or something like that. It'll be in here too.
*/
players: [],
/**
* All of the real players in label value pairs. This is so we can send only real players to the server
* and pick them apart from the non-real players.
*/
realPlayers: [],
/**
* All the years we want to show. It'll have year ranges too (like "jurassic period" and "modern era"). It's
* label and value pairs like the other arrays.
*/
years: [],
/**
* All the label and value pairs for the real and individual years.
*/
realYears: [],
/**
* All the weeks we want to show in label value pairs. It'll have ranges too (like "regular season" and "playoffs).
*/
weeks: [],
/**
* All the individual and real weeks that we want to send to the server.
*/
realWeeks: [],
/**
* All of the label/value pairs of the different stats we can show.
*/
statNames: [],
/**
* The current selections for everything they can pick.
*/
selections: {},
/**
* Whether they're selecting more than one player at a time
* or not.
*/
multiselectPlayer: false,
/**
* Whether they're selecting more than one week at a time or not.
*/
multiselectWeek: false,
/**
* Whether they're selecting more than one year at a time or not.
*/
multiselectYear: false,
/**
* The previous type they picked. This is so we can decide how much of the view we need
* to "refresh" when we update it.
*/
previousType: null,
/**
* Switches that say whether these pick grids have been shown. If they haven't, we want
* to make sure we don't show the picks for all years and weeks (unless they specifically asked
* for that).
* We don't want to do that because that's a lot of info to show. So, these are here basically
* so we can "smartly" default the year and week selections for the picks and pick splits grids.
*/
havePicksBeenShown: false,
havePickSplitsBeenShown: false,
/**
* Whether we should push the previous parameters onto the backward navigation stack.
*/
pushPreviousParameters: true,
/**
* The previous parameters that were used to show the view. This is so they can go back
* and forth pretty easily.
*/
previousParameters: null,
/**
* The stacks for navigating forward and backward. They hold the parameters that were shown for the "view".
* When they change the view, we put the previous parameters on the backward stack and when they navigate backward,
* we pop those parameters off to change the view and put the previous ones on the forward stack.
*/
navigationForwardStack: [],
navigationBackwardStack: [],
/**
* So we can get the current year and week number which come in handy.
*/
currentYear: null,
currentWeekKey: null,
/**
* So we can show the games for the current week.
*/
gamesForCurrentWeek: null,
/**
* For holding the initial selections for when the page first shows up. We set some of these
* variables with values from the server (like the year) and others (like the type) to constants.
*/
initialType: null,
initialYear: null,
initialWeek: null,
initialPlayer: null,
initialTeam: null,
initialStatName: null
};
/**
* When the document's been loaded on the browser, we want to:
*
* 1. Go to the server and get the selection criteria (teams, players, initial values).
* 2. Initialize the UI based on those values.
*/
$(document).ready(
function(){
getSelectionCriteriaAndInitialize();
});
/**
*
* This function will initialize the view. It assumes all the stuff from the server
* that's needed to initialize is setup.
*
* @returns
*/
function initializeView(){
//Steps to do:
// 1. Set the initial selections for the type, year, week, ...
// 2. Update the view based on those selections.
initializeSelections();
updateView();
}
/**
*
* Sets the initial selections for the type, year, week...
* They're all set like this:
*
* 1. The initial value comes from NFL_PICKS_GLOBAL.
* 2. If there's a url parameter for the selection, it's used instead.
*
* This way, we...
*
* 1. Set the initial values when loading the data from the server (for stuff like
* week and year).
* 2. Allow the overriding of the values by url parameters.
*
* Number 2 makes it so people can send direct urls and get the view they want the first
* time the page shows up.
*
* @returns
*/
function initializeSelections(){
//Steps to do:
// 1. Get the parameters that were sent in the url.
// 2. Initialize each selection with its global initial value.
// 3. If there's a value for it in the url, use that instead so the url
// overrides what we assume initially.
var parameters = getUrlParameters();
var type = NFL_PICKS_GLOBAL.initialType;
if (isDefined(parameters) && isDefined(parameters.type)){
type = parameters.type;
}
setSelectedType(type);
var year = NFL_PICKS_GLOBAL.initialYear;
if (isDefined(parameters) && isDefined(parameters.year)){
year = parameters.year;
}
setSelectedYears(year);
var week = NFL_PICKS_GLOBAL.initialWeek;
if (isDefined(parameters) && isDefined(parameters.week)){
week = parameters.week;
}
setSelectedWeeks(week);
var player = NFL_PICKS_GLOBAL.initialPlayer;
if (isDefined(parameters) && isDefined(parameters.player)){
player = parameters.player;
}
setSelectedPlayers(player);
var statName = NFL_PICKS_GLOBAL.initialStatName;
if (isDefined(parameters) && isDefined(parameters.statName)){
statName = parameters.statName;
}
setSelectedStatName(statName);
var team = NFL_PICKS_GLOBAL.initialTeam;
if (isDefined(parameters) && isDefined(parameters.team)){
team = parameters.team;
}
setSelectedTeams(team);
resetPlayerSelections();
resetYearSelections();
resetWeekSelections();
resetTeamSelections();
updateTypeLink();
updatePlayersLink();
updateWeeksLink();
updateYearsLink();
updateTeamsLink();
updateStatNameLink();
}
/**
*
* This function will set all the selections from the given parameters. It's here
* so that we can do the "navigate forward and backward" thing. We keep those parameters
* in maps and then, to go forward and backward, we just have to feed the map we want to
* this function.
*
* This function <i>WON'T</i> update the view. You'll have to do that yourself after calling it.
*
* @param parameters
* @returns
*/
function setSelectionsFromParameters(parameters){
//Steps to do:
// 1. If the parameters don't have anything, there's nothing to do.
// 2. Otherwise, just go through and set each individual value.
if (!isDefined(parameters)){
return;
}
if (isDefined(parameters.type)){
setSelectedType(parameters.type);
}
if (isDefined(parameters.player)){
setSelectedPlayers(parameters.player);
}
if (isDefined(parameters.year)){
setSelectedYears(parameters.year);
}
if (isDefined(parameters.week)){
setSelectedWeeks(parameters.week);
}
if (isDefined(parameters.team)){
setSelectedTeams(parameters.team);
}
if (isDefined(parameters.statName)){
setSelectedStatName(parameters.statName);
}
if (isDefined(parameters.multiselectPlayer)){
setMultiselectPlayer(parameters.multiselectPlayer);
setMultiselectPlayerValue(parameters.multiselectPlayer);
}
if (isDefined(parameters.multiselectYear)){
setMultiselectYear(parameters.multiselectYear);
setMultiselectYearValue(parameters.multiselectYear);
}
if (isDefined(parameters.multiselectWeek)){
setMultiselectWeek(parameters.multiselectWeek);
setMultiselectWeekValue(parameters.multiselectWeek);
}
if (isDefined(parameters.multiselectTeam)){
setMultiselectTeam(parameters.multiselectTeam);
setMultiselectTeamValue(parameters.multiselectTeam);
}
}
/**
*
* This function will get the parameters in a map from the url in the browser. If there
* aren't any parameters, it'll return null. Otherwise, it'll return a map with the parameter
* names as the keys and the values as the url.
*
* @returns
*/
function getUrlParameters() {
//Steps to do:
// 1. If there aren't any parameters, there's nothing to do.
// 2. Otherwise, each parameter should be separated by an ampersand, so break them apart on that.
// 3. Go through each parameter and get the key and value and that's a parameter.
// 4. That's it.
if (isBlank(location.search)){
return null;
}
var parameterNamesAndValues = location.search.substring(1, location.search.length).split('&');
var urlParameters = {};
for (var index = 0; index < parameterNamesAndValues.length; index++) {
var parameterNameAndValue = parameterNamesAndValues[index].split('=');
//Make sure to decode both the name and value in case there are weird values in them.
var name = decodeURIComponent(parameterNameAndValue[0]);
var value = decodeURIComponent(parameterNameAndValue[1]);
urlParameters[name] = value;
}
return urlParameters;
}
/**
*
* Gets all the values for each kind of parameter (type, year, week, ...)
* and returns them in a map with the key being the parameter.
*
* Here so we can easily get what's selected (for the navigate forward and backward
* stuff).
*
* @returns
*/
function getSelectedParameters(){
var parameters = {};
parameters.type = getSelectedType();
parameters.player = getSelectedPlayerValues();
parameters.year = getSelectedYearValues();
parameters.week = getSelectedWeekValues();
parameters.statName = getSelectedStatName();
parameters.team = getSelectedTeamValues();
parameters.multiselectPlayer = getMultiselectPlayer();
parameters.multiselectYear = getMultiselectYear();
parameters.multiselectWeek = getMultiselectWeek();
parameters.multiselectTeam = getMultiselectTeam();
return parameters;
}
/**
*
* This function will get the initial selection criteria (teams, players, ...)
* from the server and create the selection criteria for those options.
*
* It will also initialize the NFL_PICKS_GLOBAL values (some are pulled from the server,
* so that's why we do it in this function) and call the function that initializes the view
* once it's ready.
*
* Those initial values will be:
*
* 1. type - standings
* 2. year - current
* 3. week - all
* 4. player - all
* 5. team - all
* 6. statName - champions
*
* @returns
*/
function getSelectionCriteriaAndInitialize(){
//Steps to do:
// 1. Send the request to the server to get the selection criteria.
// 2. When it comes back, pull out the years, players, and teams
// and set the options for them in each select.
// 3. Set the initial values in the NFL_PICKS_GLOBAL variable.
// 4. Now that we have all the criteria and initial values, we can initialize the view.
$.ajax({url: 'nflpicks?target=selectionCriteria',
contentType: 'application/json; charset=UTF-8'}
)
.done(function(data) {
var selectionCriteriaContainer = $.parseJSON(data);
NFL_PICKS_GLOBAL.data.teams = selectionCriteriaContainer.teams;
NFL_PICKS_GLOBAL.data.players = selectionCriteriaContainer.players;
NFL_PICKS_GLOBAL.data.years = selectionCriteriaContainer.years;
var types = [{label: 'Standings', value: 'standings'},
{label: 'Picks', value: 'picks'},
{label: 'Stats', value: 'stats'}];
NFL_PICKS_GLOBAL.types = types;
var typeSelectorHtml = createTypeSelectorHtml(types);
$('#typesContainer').empty();
$('#selectorContainer').append(typeSelectorHtml);
var years = selectionCriteriaContainer.years;
//We want the "all" year option to be first.
var yearOptions = [{label: 'All', value: 'all'},
{label: 'Jurassic Period (2010-2015)', value: 'jurassic-period'},
{label: 'First year (2016)', value: 'first-year'},
{label: 'Modern Era (2017 - now)', value: 'modern-era'}];
var realYears = [];
for (var index = 0; index < years.length; index++){
var year = years[index];
yearOptions.push({label: year, value: year});
realYears.push({label: year, value: year});
}
NFL_PICKS_GLOBAL.years = yearOptions;
NFL_PICKS_GLOBAL.realYears = realYears;
var yearSelectorHtml = createYearSelectorHtml(yearOptions);
$('#yearsContainer').empty();
$('#selectorContainer').append(yearSelectorHtml);
var weekOptions = [{label: 'All', value: 'all'},
{label: 'Regular season', value: 'regular_season'},
{label: 'Playoffs', value: 'playoffs'},
{label: 'Week 1', value: '1'}, {label: 'Week 2', value: '2'},
{label: 'Week 3', value: '3'}, {label: 'Week 4', value: '4'},
{label: 'Week 5', value: '5'}, {label: 'Week 6', value: '6'},
{label: 'Week 7', value: '7'}, {label: 'Week 8', value: '8'},
{label: 'Week 9', value: '9'}, {label: 'Week 10', value: '10'},
{label: 'Week 11', value: '11'}, {label: 'Week 12', value: '12'},
{label: 'Week 13', value: '13'}, {label: 'Week 14', value: '14'},
{label: 'Week 15', value: '15'}, {label: 'Week 16', value: '16'},
{label: 'Week 17', value: '17'}, {label: 'Week 18', value: '18'},
{label: 'Wild Card', value: 'wildcard'},
{label: 'Divisional', value: 'divisional'},
{label: 'Conference Championship', value: 'conference_championship'},
{label: 'Superbowl', value: 'superbowl'}
];
//could these be 1, 2, 3, 4, ... again and just change the playoffs?
//yeah i think so
//week=1,2,3,4,wildcard,divisional,superbowl
//yeah that's better than
//week=1,2,3,wildcard,divisional
//need to change .... importer ... the model util function ... this
//and that should be it.
var realWeeks = [{label: 'Week 1', value: '1'}, {label: 'Week 2', value: '2'},
{label: 'Week 3', value: '3'}, {label: 'Week 4', value: '4'},
{label: 'Week 5', value: '5'}, {label: 'Week 6', value: '6'},
{label: 'Week 7', value: '7'}, {label: 'Week 8', value: '8'},
{label: 'Week 9', value: '9'}, {label: 'Week 10', value: '10'},
{label: 'Week 11', value: '11'}, {label: 'Week 12', value: '12'},
{label: 'Week 13', value: '13'}, {label: 'Week 14', value: '14'},
{label: 'Week 15', value: '15'}, {label: 'Week 16', value: '16'},
{label: 'Week 17', value: '17'}, {label: 'Week 18', value: '18'},
{label: 'Wild Card', value: 'wildcard'},
{label: 'Divisional', value: 'divisional'},
{label: 'Conference Championship', value: 'conference_championship'},
{label: 'Superbowl', value: 'superbowl'}
];
//need to refactor the NFL_PICKS_GLOBAL so that it has all the options
//and all the data
//NFL_PICKS_GLOBAL.criteria.weeks - the weeks as selection criteria
//NFL_PICKS_GLOBAL.data.weeks - all the actual weeks
//global_setWeeks
//global_setRealWeeks
//global_getWeeks
//selector_blah
//html_blah
//yeah this needs to be done
//nflpicks global needs to be defined in a separate javascript file
NFL_PICKS_GLOBAL.weeks = weekOptions;
NFL_PICKS_GLOBAL.realWeeks = realWeeks;
var weekSelectorHtml = createWeekSelectorHtml(weekOptions);
$('#selectorContainer').append(weekSelectorHtml);
var players = selectionCriteriaContainer.players;
//We want the "all" player option to be the first one.
var playerOptions = [{label: 'Everybody', value: 'all'}];
var realPlayers = [];
for (var index = 0; index < players.length; index++){
var player = players[index];
var playerObject = {label: player, value: player};
playerOptions.push(playerObject);
realPlayers.push(playerObject);
}
setOptionsInSelect('player', playerOptions);
NFL_PICKS_GLOBAL.players = playerOptions;
NFL_PICKS_GLOBAL.realPlayers = realPlayers;
var playerSelectorHtml = createPlayerSelectorHtml(playerOptions);
$('#selectorContainer').append(playerSelectorHtml);
//Need to filter the teams so that we only show teams that had a game in a given year.
//Probably just do a ui filter because we probably don't want to make a trip to the server
//
var teams = selectionCriteriaContainer.teams;
//Sort the teams in alphabetical order to make sure we show them in a consistent order.
teams.sort(function (teamA, teamB){
if (teamA.abbreviation < teamB.abbreviation){
return -1;
}
else if (teamA.abbreviation > teamB.abbreviation){
return 1;
}
return 0;
});
//We also want the "all" option to be first.
var teamOptions = [{label: 'All', value: 'all'}];
for (var index = 0; index < teams.length; index++){
var team = teams[index];
teamOptions.push({label: team.abbreviation, value: team.abbreviation});
}
var teamSelectorHtml = createTeamSelectorHtml(teamOptions);
$('#selectorContainer').append(teamSelectorHtml);
NFL_PICKS_GLOBAL.teams = teamOptions;
var statNameOptions = [{label: 'Champions', value: 'champions'},
{label: 'Championship Standings', value: 'championshipStandings'},
{label: 'Season Standings', value: 'seasonStandings'},
{label: 'Week Standings', value: 'weekStandings'},
{label: 'Weeks Won Standings', value: 'weeksWonStandings'},
{label: 'Weeks Won By Week', value: 'weeksWonByWeek'},
{label: 'Week Records By Player', value: 'weekRecordsByPlayer'},
{label: 'Pick Accuracy', value: 'pickAccuracy'},
{label: 'Pick Splits', value: 'pickSplits'},
{label: 'Week Comparison', value: 'weekComparison'},
{label: 'Season Progression', value: 'seasonProgression'}];
var statNameSelectorHtml = createStatNameSelectorHtml(statNameOptions);
$('#selectorContainer').append(statNameSelectorHtml);
NFL_PICKS_GLOBAL.statNames = statNameOptions;
//The current year and week come from the server.
NFL_PICKS_GLOBAL.currentYear = selectionCriteriaContainer.currentYear;
NFL_PICKS_GLOBAL.currentWeekKey = selectionCriteriaContainer.currentWeekKey;
//Initially, we want to see the standings for the current year for everybody, so set those
//as the initial types.
NFL_PICKS_GLOBAL.initialType = 'standings';
NFL_PICKS_GLOBAL.initialYear = NFL_PICKS_GLOBAL.currentYear + '';
NFL_PICKS_GLOBAL.initialWeek = 'all';
NFL_PICKS_GLOBAL.initialPlayer = 'all';
NFL_PICKS_GLOBAL.initialTeam = 'all';
NFL_PICKS_GLOBAL.initialStatName = 'champions';
initializeView();
})
.fail(function() {
})
.always(function() {
});
}
/**
*
* This function will cause the view to "navigate forward". We can only do that if
* we've gone back. So, this function will check the stack that holds the "forward parameters",
* pop the top of it off (if there's something in it), and then cause the view to have those
* parameters.
*
* Before navigating, it will take the current parameters and put them on the previous stack
* so they can go back if they hit "back".
*
* @returns
*/
function navigateForward(){
//Steps to do:
// 1. If there aren't any forward parameters, there's no way to go forward.
// 2. The current parameters should go on the previous stack.
// 3. Get the forward parameters off the forward stack.
// 4. Set them as the selections.
// 5. Update the view and make sure it doesn't push any parameters on any
// stack
// 6. Flip the switch back so any other navigation will push parameters
// on the previous stack.
if (NFL_PICKS_GLOBAL.navigationForwardStack.length == 0){
return;
}
var currentParameters = getSelectedParameters();
NFL_PICKS_GLOBAL.navigationBackwardStack.push(currentParameters);
var parameters = NFL_PICKS_GLOBAL.navigationForwardStack.pop();
setSelectionsFromParameters(parameters);
//Before updating the view, flip the switch that the updateView function uses to
//decide whether to push the parameters for the current view on the stack or not.
//Since we're navigating forward, we take care of that in this function instead.
//A little bootleg, so it probably means I designed it wrong...
NFL_PICKS_GLOBAL.pushPreviousParameters = false;
updateView();
NFL_PICKS_GLOBAL.pushPreviousParameters = true;
}
/**
*
* This function will cause the view to show the previous view. It's the same thing
* as going backward except will pull from the navigate backward stack. The previous parameters
* for the view are stored on a stack, so to go backward, we just have to pop those parameters
* off, set them as the selections, and the update the view.
*
* It'll also take the current parameters (before going backward) and push them on the forward stack
* so navigating forward, after going backward, brings them back to where they were.
*
* @returns
*/
function navigateBackward(){
//Steps to do:
// 1. If there isn't anything to backward to, there's nothing to do.
// 2. The current parameters should go on the forward stack since they're
// what we want to show if people navigate forward
// 3. The parameters we want to use come off the backward stack.
// 4. Flip the switch that says to not push any parameters on in the view function.
// 5. Update based on the parameters we got.
// 6. Flip the switch back so that any other navigation causes the parameters
// to go on the previous stack.
if (NFL_PICKS_GLOBAL.navigationBackwardStack.length == 0){
return;
}
var currentParameters = getSelectedParameters();
NFL_PICKS_GLOBAL.navigationForwardStack.push(currentParameters);
var parameters = NFL_PICKS_GLOBAL.navigationBackwardStack.pop();
//stuff is updated here...
setSelectionsFromParameters(parameters);
//Just like when navigating forward, we don't want the updateView function to fiddle
//with the navigation stacks since we're doing it here. After the view has been updated, though,
//flip the switch back so that any other navigation cause the updateView function save the
//current view before changing.
NFL_PICKS_GLOBAL.pushPreviousParameters = false;
updateView();
NFL_PICKS_GLOBAL.pushPreviousParameters = true;
}
/**
*
* This function will make it so we only show the forward and backward
* links if they can actually navigate forward and backward. It just checks
* the length of the stacks and uses that to decide whether to show
* or hide each link.
*
* @returns
*/
function updateNavigationLinksVisibility(){
//Steps to do:
// 1. If the stack doesn't have anything in it, we shouldn't show
// the link.
// 2. Otherwise, we should.
if (NFL_PICKS_GLOBAL.navigationForwardStack.length == 0){
$('#navigationFowardContainer').hide();
}
else {
$('#navigationFowardContainer').show();
}
if (NFL_PICKS_GLOBAL.navigationBackwardStack.length == 0){
$('#navigationBackwardContainer').hide();
}
else {
$('#navigationBackwardContainer').show();
}
}
/**
*
* The "main" function for the UI. Makes it so we show what they picked on the screen.
* It bases its decision on the "type" variable and then just calls the right function
* based on what that is.
*
* If the NFL_PICKS_GLOBAL.pushPreviousParameters switch is flipped, it'll also update
* the navigation stacks. That switch is there so that:
*
* 1. When they do any non-forward or backward navigation action, we update the stacks.
* 2. When they push forward or backward, we can handle the stacks other places.
*
* @returns
*/
function updateView(){
//Steps to do:
// 1. Before doing anything, if the switch is flipped, we should save the parameters
// from the last navigation on the backward stack so they can go backward to what
// we're currently on, if they want.
// 2. Get the type of view they want.
// 3. Update the selector view based on the type.
// 4. Decide which function to call based on that.
// 5. After the view is updated, keep the current selected parameters around so we can push
// them on the "back" stack the next time they make a change.
// 6. Make sure we're showing the right "navigation" links.
//If there are previous parameters, and we should push them, then push them on the backward
//navigation stack so they can go back to that view with the back button.
//If we shouldn't push them, that means the caller is handling the stack stuff themselves.
//And, if we should push them, that means they did some "action" that takes them on a
//different "branch", so we should clear out the forward stack since they can't go
//forward anymore.
if (NFL_PICKS_GLOBAL.previousParameters != null && NFL_PICKS_GLOBAL.pushPreviousParameters){
NFL_PICKS_GLOBAL.navigationBackwardStack.push(NFL_PICKS_GLOBAL.previousParameters);
NFL_PICKS_GLOBAL.navigationForwardStack = [];
}
var type = getSelectedType();
//Update the selectors that get shown. We want to show different things depending
//on the type.
updateSelectors(type);
//And update the options for the criteria in each selector.
updateAvailableCriteriaOptions();
if ('picks' == type){
updatePicks();
}
else if ('standings' == type) {
updateStandings();
}
else if ('stats' == type){
updateStats();
}
//At this point, the selected parameters are the current parameters. We want to
//keep them around in case we need to push them on the stack the next time through.
NFL_PICKS_GLOBAL.previousParameters = getSelectedParameters();
updateTypeLink();
updatePlayersLink();
updateYearsLink();
updateWeeksLink();
updateTeamsLink();
updateStatNameLink();
//And we need to make sure we're showing the right "forward" and "back" links.
updateNavigationLinksVisibility();
}
/**
*
* This function will update the available options for the criteria based on what's selected.
* It's here mainly for the situation where you select an option in a "selector" and that option
* should cause options in other selectors to be either shown or hidden.
*
* I made it for the situation where somebody picks a year and we should only show the teams
* that actually existed that year. Like, if somebody picks "2020" as the year, we shouldn't
* show "OAK", but we should show "LV".
*
* ... And now it's here to handle the change in week for the 2021 season where a 17th game was added.
*
* It will farm the work out to other functions that handle the specific scenarios for each
* kind of "selector".
*
* @returns
*/
function updateAvailableCriteriaOptions(){
updateAvailableTeamOptions();
updateAvailableWeekOptions();
//updateAvailableWeekOptions.................
//
//main_updateAvailableTeamOptions
}
/**
*
* This function will update the available teams that can be selected. It will just go through
* and check whether each team was "active" during the selected years. If they were, then it'll
* show them and if they weren't, it'll hide them.
*
* @returns
*/
function updateAvailableTeamOptions(){
//Steps to do:
// 1. Get the year values as integers.
// 2. Go through every team and get when it started and ended.
// 3. If the year it started is after any of the selected years and it doesn't have an
// end or its end is before one of the selected years, that means it played games during
// the selected years so it should be shown.
// 4. Otherwise, it didn't and so it should be hidden.
var currentSelectedYearValues = getYearValuesForSelectedYears();
var integerYearValues = getValuesAsIntegers(currentSelectedYearValues);
var teamsToShow = [];
var teamsToHide = [];
//All the teams are stored in the global variable. Just have to go through them.
var teams = NFL_PICKS_GLOBAL.data.teams;
for (var index = 0; index < teams.length; index++){
var team = teams[index];
//Flipping this switch off and I'll flip it on if the team's start and end years show
//it played games in the selected years.
var showTeam = false;
//Make sure to turn their years into numbers.
var teamStartYearInteger = parseInt(team.startYear);
var teamEndYearInteger = -1;
if (isDefined(team.endYear)){
teamEndYearInteger = parseInt(team.endYear);
}
//Go through each selected year.
for (var yearIndex = 0; yearIndex < integerYearValues.length; yearIndex++){
var currentYearValue = integerYearValues[yearIndex];
//If the team started before the current year and either is still active (end year = -1) or was active after the
//current year, that means it played games in the selected year, so it should be shown.
if (teamStartYearInteger <= currentYearValue && (teamEndYearInteger == -1 || teamEndYearInteger >= currentYearValue)){
showTeam = true;
}
}
//Just put it in the list based on whether it should be shown or not.
if (showTeam){
teamsToShow.push(team.abbreviation);
}
else {
teamsToHide.push(team.abbreviation);
}
}
//Show the teams that should be shown in the selector dropdown.
showTeamItems(teamsToShow);
//Hide the teams that should be hidden in the selector.
hideTeamItems(teamsToHide);
//And, we have to go through and unselect the ones we should hide in case they
//were selected. If we just hide them and they're still selected, they'll still
//show up on the ui, just not in the selection dropdown.
for (var index = 0; index < teamsToHide.length; index++){
var teamToHide = teamsToHide[index];
unselectTeamFull(teamToHide);
}
}
//updateSelectors
function getAvailableWeeksForYears(yearValues){
var integerYearValues = getValuesAsIntegers(currentSelectedYearValues);
var availableWeeksBefore2021 = ['1', '2', '3', '4', '5', '6', '7',
'8', '9', '10', '11', '12', '13', '14',
'15', '16', '17', 'wildcard', 'divisional', 'conference_championship',
'superbowl'];
var availableWeeksAfter2021 = ['1', '2', '3', '4', '5', '6', '7',
'8', '9', '10', '11', '12', '13', '14',
'15', '16', '17', '18', 'wildcard', 'divisional', 'conference_championship',
'superbowl'];
for (var index = 0; index < integerYearValues.length; index++){
var integerYearValue = integerYearValues[index];
if (integerYearValue >= 2021){
return availableWeeksAfter2021;
}
}
return availableWeeksBefore2021;
}
function updateAvailableWeekOptions(){
var currentSelectedYearValues = getYearValuesForSelectedYears();
var weeksToShow = ['1', '2', '3', '4', '5', '6', '7',
'8', '9', '10', '11', '12', '13', '14',
'15', '16', '17', 'wildcard', 'divisional', 'conference_championship',
'superbowl'];
var weeksToHide = ['18'];
for (var index = 0; index < currentSelectedYearValues.length; index++){
var yearValue = currentSelectedYearValues[index];
if (yearValue >= 2021){
weeksToShow = ['1', '2', '3', '4', '5', '6', '7',
'8', '9', '10', '11', '12', '13', '14',
'15', '16', '17', '18', 'wildcard', 'divisional', 'conference_championship',
'superbowl'];
weeksToHide = [];
}
}
showWeekItems(weeksToShow);
hideWeekItems(weeksToHide);
//And, we have to go through and unselect the ones we should hide in case they
//were selected. If we just hide them and they're still selected, they'll still
//show up on the ui, just not in the selection dropdown.
for (var index = 0; index < weeksToHide.length; index++){
var weekToHide = weeksToHide[index];
unselectWeekFull(weekToHide);
}
}
/**
*
* This function will update the selectors for the given type. It just calls
* the specific type's update function.
*
* It will also update the multi-selects so that the selected values are updated
* if they're selecting multiple "items" (multiple players, weeks, or years).
*
* @param type
* @returns
*/
function updateSelectors(type){
//Steps to do:
// 1. Call the function based on the type.
// 2. Update the multi selects.
if ('picks' == type){
updatePicksSelectors(type);
}
else if ('standings' == type){
updateStandingsSelectors(type);
}
else if ('stats' == type){
updateStatsSelectors(type);
}
}
/**
*
* Updates the selectors so that they're good to go for when the type is picks.
*
* Shows:
* year, player, team, week
* Hides:
* stat name
*
* Only shows or hides something if the given type isn't the previous selected type.
*
* @param type
* @returns
*/
function updatePicksSelectors(type){
//Steps to do:
// 1. If the previous type is the same as the given one, we don't need
// to do anything to the selectors.
// 2. Show and hide what we need to.
// 3. Store the type we were given for next time.
var previousSelectedType = getPreviousType();
if (previousSelectedType == type){
return;
}
showPlayersLink();
showWeeksLink();
showYearsLink();
showTeamsLink();
hideStatNameLink();
setPreviousType(type);
}
/**
*
* Updates the selectors so that they're right for browsing the "standings".
*
* Shows:
* player, year, week, team
* Hides:
* stat name
*
* Only shows or hides something if the given type isn't the previous selected type.
*
* @param type
* @returns
*/
function updateStandingsSelectors(type){
//Steps to do:
// 1. If the previous type is the same as the given one, we don't need
// to do anything to the selectors.
// 2. Show and hide what we need to.
// 3. Store the type we were given for next time.
var previousSelectedType = getPreviousType();
if (previousSelectedType == type){
return;
}
showPlayersLink();
showWeeksLink();
showYearsLink();
showTeamsLink();
hideStatNameLink();
setPreviousType(type);
}
/**
*
* Updates the selectors so that they're good to go for browsing the
* "stats"
*
* Shows:
* stat name, others depending on the stat name
* Hides:
* depends on the stat name
*
* Stat name:
* champions
* shows: Nothing
* hides: player, year, week, team
* championship standings
* shows: Nothing
* hides: player, year, week, team
* week standings
* shows: player, year, week
* hides: team
* weeks won standings
* shows: year
* hides: player, team, week
* weeks won by week
* shows: year, week
* hides: team
* week records by player
* shows: year, week, player
* hides: team
* pick accuracy
* shows: year, player, team
* hides: week
* pick splits:
* shows: year, week, team
* hides: player
*
* @param type
* @returns
*/
function updateStatsSelectors(type){
//Steps to do:
// 1. We always want to show the stat name container.
// 2. Get the name of the stat we want to show.
// 3. Show and hide what we need to based on the kind of stat we want to show.
// 4. Store the type we were given for next time.
showStatNameLink();
var statName = getSelectedStatName();
if ('champions' == statName){
showPlayersLink();
showYearsLink();
hideWeeksLink();
hideTeamsLink();
}
else if ('championshipStandings' == statName){
showPlayersLink();
showYearsLink();
hideWeeksLink();
hideTeamsLink();
}
else if ('seasonStandings' == statName){
showPlayersLink();
showYearsLink();
showWeeksLink();
hideTeamsLink();
}
else if ('weekStandings' == statName){
showPlayersLink();
showYearsLink();
showWeeksLink();
hideTeamsLink();
}
else if ('weeksWonStandings' == statName){
showPlayersLink();
showYearsLink();
showWeeksLink();
hideTeamsLink();
}
else if ('weeksWonByWeek' == statName){
showPlayersLink();
showYearsLink();
showWeeksLink();
hideTeamsLink();
}
else if ('weekRecordsByPlayer' == statName){
showPlayersLink();
showYearsLink();
showWeeksLink();
hideTeamsLink();
}
else if ('pickAccuracy' == statName){
showPlayersLink();
showYearsLink();
showWeeksLink();
showTeamsLink();
}
else if ('pickSplits' == statName){
showPlayersLink();
showYearsLink();
showWeeksLink();
showTeamsLink();
}
else if ('weekComparison' == statName){
showPlayersLink();
showYearsLink();
showWeeksLink();
hideTeamsLink();
}
else if ('seasonProgression' == statName){
showPlayersLink();
showYearsLink();
showWeeksLink();
hideTeamsLink();
}
setPreviousType(type);
}
/**
*
* Gets the selected value for the type.
*
* @returns
*/
function getSelectedType(){
return $('input[name=type]:checked').val();
}
/**
*
* Sets the selected value for the type to the given type. Only does it
* if the type select input has the given type as an option.
*
* @param type
* @returns
*/
function setSelectedType(type){
$('input[name=type]').val([type]);
NFL_PICKS_GLOBAL.selections.type = type;
}
/**
*
* Gets the previous type that was selected. This is so we can decide
* whether to update stuff or not when the type changes.
*
* @returns
*/
function getPreviousType(){
return NFL_PICKS_GLOBAL.previousType;
}
/**
*
* Sets the previous type in the NFL_PICKS_GLOBAL variable. This is so we can decide
* whether to update stuff or not when the type changes.
*
* @param newPreviousType
* @returns
*/
function setPreviousType(newPreviousType){
NFL_PICKS_GLOBAL.previousType = newPreviousType;
}
/**
*
* This function will set the given players as being selected in the NFL_PICKS_GLOBAL
* variable (NFL_PICKS_GLOBAL.selections.players) and it'll call the "selectPlayer"
* function in the selectors file for each player so they get "selected" on the UI too.
*
* It expects the given players variable to either be...
* 1. An array of player names.
* 2. A comma separated string of player names.
* 3. A single player name.
*
* It will put the actual player objects into the NFL_PICKS_GLOBAL variable for
* each player name that's given.
*
* @param players
* @returns
*/
function setSelectedPlayers(players){
//Steps to do:
// 1. Check whether the players variable is an array.
// 2. If it is, just keep it.
// 3. Otherwise, it's a string so check to see if it has multiple values.
// 4. If it does, then turn it into an array.
// 5. Otherwise, just put it in there as a single value.
// 6. Go through each player in the array, get the actual object for the player name
// and put it in the global variable. And, "select" them in the ui.
var playerValuesArray = [];
var isArray = Array.isArray(players);
if (isArray){
playerValuesArray = players;
}
else {
var hasMultipleValues = doesValueHaveMultipleValues(players);
if (hasMultipleValues){
playerValuesArray = delimitedValueToArray(players);
}
else {
playerValuesArray.push(players);
}
}
var playersArray = [];
for (var index = 0; index < playerValuesArray.length; index++){
var value = playerValuesArray[index];
selectPlayer(value);
var player = getPlayer(value);
playersArray.push(player);
}
NFL_PICKS_GLOBAL.selections.players = playersArray;
}
/**
*
* This function will set the given years as being selected in the UI and in the
* NFL_PICKS_GLOBAL variable (NFL_PICKS_GLOBAL.selections.years).
*
* It expects the given years variable to either be...
* 1. An array of year values.
* 2. A comma separated string of year values.
* 3. A single year value.
*
* It will put the actual year objects into the NFL_PICKS_GLOBAL variable for
* each year value that's given.
*
* @param years
* @returns
*/
function setSelectedYears(years){
//Steps to do:
// 1. Check whether the years variable is an array.
// 2. If it is, just keep it.
// 3. Otherwise, it's a string so check to see if it has multiple values.
// 4. If it does, then turn it into an array.
// 5. Otherwise, just put it in there as a single value.
// 6. Go through each year in the array, get the actual object for the year
// and put it in the global variable. And, "select" it in the ui.
var yearValuesArray = [];
var isArray = Array.isArray(years);
if (isArray){
yearValuesArray = years;
}
else {
var hasMultipleValues = doesValueHaveMultipleValues(years);
if (hasMultipleValues){
yearValuesArray = delimitedValueToArray(years);
}
else {
yearValuesArray.push(years);
}
}
var yearsArray = [];
for (var index = 0; index < yearValuesArray.length; index++){
var value = yearValuesArray[index];
selectYear(value);
var year = getYear(value);
yearsArray.push(year);
}
NFL_PICKS_GLOBAL.selections.years = yearsArray;
}
/**
*
* This function will set the given weeks as being selected in the UI and in the
* NFL_PICKS_GLOBAL variable (NFL_PICKS_GLOBAL.selections.weeks).
*
* It expects the given weeks variable to either be...
* 1. An array of week numbers.
* 2. A comma separated string of week numbers.
* 3. A single week number.
*
* It will put the actual week objects into the NFL_PICKS_GLOBAL variable for
* each week number that's given.
*
* @param weeks
* @returns
*/
function setSelectedWeeks(weeks){
//Steps to do:
// 1. Check whether the weeks variable is an array.
// 2. If it is, just keep it.
// 3. Otherwise, it's a string so check to see if it has multiple values.
// 4. If it does, then turn it into an array.
// 5. Otherwise, just put it in there as a single value.
// 6. Go through each week in the array, get the actual object for the week
// and put it in the global variable. And, "select" it in the ui.
var weekValuesArray = [];
var isArray = Array.isArray(weeks);
if (isArray){
weekValuesArray = weeks;
}
else {
var hasMultipleValues = doesValueHaveMultipleValues(weeks);
if (hasMultipleValues){
weekValuesArray = delimitedValueToArray(weeks);
}
else {
weekValuesArray.push(weeks);
}
}
var weeksArray = [];
for (var index = 0; index < weekValuesArray.length; index++){
var value = weekValuesArray[index];
selectWeek(value);
var week = getWeek(value);
weeksArray.push(week);
}
//THIS was the key ... update the current week selections... geez this is too complicated
setCurrentWeekSelections(weekValuesArray);
NFL_PICKS_GLOBAL.selections.weeks = weeksArray;
}
/**
*
* This function will set the given teams as being selected in the UI and in the
* NFL_PICKS_GLOBAL variable (NFL_PICKS_GLOBAL.selections.teams).
*
* It expects the given teams variable to either be...
* 1. An array of team abbreviations.
* 2. A comma separated string of team abbreviations.
* 3. A single team abbreviation.
*
* It will put the actual team objects into the NFL_PICKS_GLOBAL variable for
* each team abbreviation that's given.
*
* @param teams
* @returns
*/
function setSelectedTeams(teams){
//Steps to do:
// 1. Check whether the teams variable is an array.
// 2. If it is, just keep it.
// 3. Otherwise, it's a string so check to see if it has multiple values.
// 4. If it does, then turn it into an array.
// 5. Otherwise, just put it in there as a single value.
// 6. Go through each team in the array, get the actual object for the team
// and put it in the global variable. And, "select" it in the ui.
var teamValuesArray = [];
var isArray = Array.isArray(teams);
if (isArray){
teamValuesArray = teams;
}
else {
var hasMultipleValues = doesValueHaveMultipleValues(teams);
if (hasMultipleValues){
teamValuesArray = delimitedValueToArray(teams);
}
else {
teamValuesArray.push(teams);
}
}
var teamsArray = [];
for (var index = 0; index < teamValuesArray.length; index++){
var value = teamValuesArray[index];
selectTeam(value);
var team = getTeam(value);
teamsArray.push(team);
}
//THIS was the key ... update the current team selections... geez this is too complicated
setCurrentTeamSelections(teamValuesArray);
NFL_PICKS_GLOBAL.selections.teams = teamsArray;
}
/**
*
* Gets the selected stat name.
*
* @returns
*/
function getSelectedStatName(){
return $('input[name=statName]:checked').val();
}
/**
*
* Sets the selected stat name if it's one of the options
* on the stat name input.
*
* @param statName
* @returns
*/
function setSelectedStatName(statName){
$('input[name=statName]').val([statName]);
NFL_PICKS_GLOBAL.selections.statName = statName;
}
/**
*
* This function will set the given html as the content we show. It'll clear out what's
* in there now.
*
* @param contentHtml
* @returns
*/
function setContent(contentHtml){
$('#contentContainer').empty();
$('#contentContainer').append(contentHtml);
}
/**
*
* This function will go get the standings from the server and show them on the UI.
*
* What standings it gets depends on the player, year, and week that are selected.
*
* @returns
*/
function updateStandings(){
//Steps to do:
// 1. Get the parameters to send (player, year, and week).
// 2. Send them to the server.
// 3. Update the UI with the results.
var playerValuesForRequest = getPlayerValuesForRequest();
var yearValuesForRequest = getYearValuesForRequest();
var weekValuesForRequest = getWeekValuesForRequest();
var teamValuesForRequest = getTeamValuesForRequest();
setContent('<div style="text-align: center;">Loading...</div>');
$.ajax({url: 'nflpicks?target=standings&player=' + playerValuesForRequest + '&year=' + yearValuesForRequest + '&week=' + weekValuesForRequest + '&team=' + teamValuesForRequest,
contentType: 'application/json; charset=UTF-8'}
)
.done(function(data) {
var standingsContainer = $.parseJSON(data);
//We want to show the records that came back, but we're going to have to sort them
//to make sure they're in the order we want.
var records = standingsContainer.records;
//We want the record with the most wins coming first. If they have the same number
//of wins, we want the one with fewer losses coming first.
//And if they're tied, we want them ordered by name.
records.sort(function (record1, record2){
if (record1.wins > record2.wins){
return -1;
}
else if (record1.wins < record2.wins){
return 1;
}
else {
if (record1.losses < record2.losses){
return -1;
}
else if (record1.losses > record2.losses){
return 1;
}
}
if (record1.player.name < record2.player.name){
return -1;
}
else if (record1.player.name > record2.player.name){
return 1;
}
return 0;
});
//Now that we have them sorted, we can create the html for the standings.
var standingsHtml = createStandingsHtml(standingsContainer.records);
//And set it as the content.
setContent(standingsHtml);
})
.fail(function() {
setContent('<div style="text-align: center;">Error</div>');
})
.always(function() {
});
}
/**
*
* This function will update the picks grid with the current selectors they ... picked.
* It'll get the parameters, go to the server to get the picks, and then update the UI
* with the grid.
*
* @returns
*/
function updatePicks(){
//Steps to do:
// 1. Get the parameters they picked.
// 2. Default the year and week to the current year and week if we should.
// 3. Go to the server and get the picks.
// 4. Update the UI with the picks grid.
var selectedYearValues = getSelectedYearValues();
var selectedWeekValues = getSelectedWeekValues();
//We need to make sure we only use "all" for the year if they explicitly set it.
//
//That should only happen if:
// 1. It's "all" in the url.
// 2. Or, they have seen the picks and have set it to "all" themselves.
//
//I'm doing it like this because using "all" for the year might bring back a lot
//of picks, so we should only do it if that's what they want to do.
var parameters = getUrlParameters();
var hasYearInUrl = false;
if (isDefined(parameters) && isDefined(parameters.year)){
hasYearInUrl = true;
}
//We want to default it to the current year if:
//
// 1. It's "all"
// 2. We haven't shown the picks before
// 3. The "all" isn't from the url.
//
//In that situation, they didn't "explicitly" set it to "all", so we want to show
//only picks for the current year to start off with.
if (selectedYearValues.includes('all') && !NFL_PICKS_GLOBAL.havePicksBeenShown && !hasYearInUrl){
var currentYear = NFL_PICKS_GLOBAL.currentYear + '';
setSelectedYears(currentYear);
updateYearsLink();
}
//Do the same thing with the week. We only want to show picks for all the weeks if
//they went out of their way to say that's what they wanted to do.
var hasWeekInUrl = false;
if (isDefined(parameters) && isDefined(parameters.week)){
hasWeekInUrl = true;
}
//If it's "all" and the picks haven't been shown and the "all" didn't come from the url,
//it's their first time seeing the picks, so we should show the ones for the current week.
if (selectedWeekValues.includes('all') && !NFL_PICKS_GLOBAL.havePicksBeenShown && !hasWeekInUrl){
var currentWeek = NFL_PICKS_GLOBAL.currentWeekKey + '';
setSelectedWeeks(currentWeek);
updateWeeksLink();
}
//At this point, we're going to show them the picks, so we should flip that switch.
NFL_PICKS_GLOBAL.havePicksBeenShown = true;
var playerValuesForRequest = getPlayerValuesForRequest();
var yearValuesForRequest = getYearValuesForRequest();
var weekValuesForRequest = getWeekValuesForRequest();
var teamValuesForRequest = getTeamValuesForRequest();
setContent('<div style="text-align: center;">Loading...</div>');
//Go to the server and get the grid.
$.ajax({url: 'nflpicks?target=compactPicksGrid&player=' + playerValuesForRequest + '&year=' + yearValuesForRequest + '&week=' + weekValuesForRequest + '&team=' + teamValuesForRequest,
contentType: 'application/json; charset=UTF-8'}
)
.done(function(data) {
//Update the UI with what the server sent back.
var picksGrid = $.parseJSON(data);
var picksGridHtml = createPicksGridHtml(picksGrid);
setContent(picksGridHtml);
})
.fail(function() {
setContent('<div style="text-align: center;">Error</div>');
})
.always(function() {
});
}
/**
*
* This function will get the stats from the server and update them on the ui. The stat that
* it shows depends on the statName they picked.
*
* @returns
*/
function updateStats(){
//Steps to do:
// 1. Get the selected parameters.
// 2. Make sure they're ok based on the stat name.
// 3. Go to the server and get the stats.
// 4. Update the UI with what came back.
var statName = getSelectedStatName();
var selectedPlayerValues = getPlayerValuesForRequest();
var selectedYearValues = getYearValuesForRequest();
var selectedWeekValues = getWeekValuesForRequest();
var selectedTeamValues = getTeamValuesForRequest();
//If the stat name is the "pick splits", we want to do the same thing we do with the picks grid.
//Only show "all" for the year or the week if they actually set it to "all".
//If it's the first time we're showing the pick splits, we only want to show all of them if that
//was in the url.
if (statName == 'pickSplits'){
//Since we're showing how players are split up, we want to show all players.
var selectedYearValues = getSelectedYearValues();
var selectedWeekValues = getSelectedWeekValues();
var urlParameters = getUrlParameters();
//Same deal as with the picks grid...
var hasYearInUrl = false;
if (isDefined(urlParameters) && isDefined(urlParameters.year)){
hasYearInUrl = true;
}
//If the year is "all", we haven't shown the picks, and "all" didn't come from the url, then we
//want the year we show the pick splits for to be the current year.
if (selectedYearValues.includes('all') && !NFL_PICKS_GLOBAL.havePickSplitsBeenShown && !hasYearInUrl){
var currentYear = NFL_PICKS_GLOBAL.currentYear + '';
setSelectedYears(currentYear);
updateYearsLink();
}
//Same deal as with the year and with the picks grid...
var hasWeekInUrl = false;
if (isDefined(urlParameters) && isDefined(urlParameters.week)){
hasWeekInUrl = true;
}
//If the week is "all", we haven't shown the picks, and "all" didn't come from the url, then we
//want the week we show the pick splits for to be the current week.
if (selectedWeekValues.includes('all') && !NFL_PICKS_GLOBAL.havePickSplitsBeenShown && !hasWeekInUrl){
var currentWeek = NFL_PICKS_GLOBAL.currentWeekKey + '';
setSelectedWeeks(currentWeek);
updateWeeksLink();
}
//And, since we're here, that means we've shown the pick splits to the user, so the next time, we won't
//do the funny business with the week and year.
NFL_PICKS_GLOBAL.havePickSplitsBeenShown = true;
}
var playerValuesForRequest = getPlayerValuesForRequest();
var yearValuesForRequest = getYearValuesForRequest();
var weekValuesForRequest = getWeekValuesForRequest();
var teamValuesForRequest = getTeamValuesForRequest();
setContent('<div style="text-align: center;">Loading...</div>');
//Send the request to the server.
$.ajax({url: 'nflpicks?target=stats&statName=' + statName + '&player=' + playerValuesForRequest + '&year=' + yearValuesForRequest +
'&week=' + weekValuesForRequest + '&team=' + teamValuesForRequest,
contentType: 'application/json; charset=UTF-8'}
)
.done(function(data) {
var statsHtml = '';
//Make the html for the kind of stat they wanted to see.
if ('champions' == statName){
var championships = $.parseJSON(data);
statsHtml = createChampionsHtml(championships);
}
else if ('championshipStandings' == statName){
var championships = $.parseJSON(data);
statsHtml = createChampionshipStandingsHtml(championships);
}
else if ('seasonStandings' == statName){
var seasonRecords = $.parseJSON(data);
statsHtml = createSeasonStandingsHtml(seasonRecords);
}
else if ('weeksWonStandings' == statName){
var weekRecords = $.parseJSON(data);
//We want to sort the records before we show them so we can show the rank.
sortWeekRecords(weekRecords);
statsHtml = createWeeksWonHtml(weekRecords);
}
else if ('weeksWonByWeek' == statName){
var weeksWonByWeek = $.parseJSON(data);
statsHtml = createWeeksWonByWeek(weeksWonByWeek);
}
else if ('weekRecordsByPlayer' == statName){
var weekRecords = $.parseJSON(data);
//Like with the other records, we want to sort them before we show them.
sortWeekRecordsBySeasonWeekAndRecord(weekRecords);
statsHtml = createWeekRecordsByPlayerHtml(weekRecords);
}
else if ('weekStandings' == statName){
var playerWeekRecords = $.parseJSON(data);
statsHtml = createWeekStandingsHtml(playerWeekRecords);
}
else if ('pickAccuracy' == statName){
var start = Date.now();
var pickAccuracySummaries = $.parseJSON(data);
var jsonElapsed = Date.now() - start;
var htmlStart = Date.now();
statsHtml = createPickAccuracySummariesHtml(pickAccuracySummaries);
var htmlElapsed = Date.now() - htmlStart;
}
else if ('pickSplits' == statName){
var pickSplits = $.parseJSON(data);
statsHtml = createPickSplitsGridHtml(pickSplits);
}
else if ('weekComparison' == statName){
var weekRecords = $.parseJSON(data);
//Like with the other records, we want to sort them before we show them.
sortWeekRecordsBySeasonWeekAndRecord(weekRecords);
statsHtml = createWeekComparisonHtml(weekRecords);
}
else if ('seasonProgression' == statName){
var weekRecords = $.parseJSON(data);
//Like with the other records, we want to sort them before we show them.
sortWeekRecordsBySeasonWeekAndRecord(weekRecords);
statsHtml = createSeasonProgressionHtml(weekRecords);
}
setContent(statsHtml);
})
.fail(function() {
setContent('<div style="text-align: center;">Error</div>');
})
.always(function() {
});
}
/**
*
* A "convenience" function that says whether any record in the given
* array has any ties.
*
* @param records
* @returns
*/
function hasTies(records){
//Steps to do:
// 1. Go through all the records and return true if one has a tie.
if (!isDefined(records)){
return false;
}
for (var index = 0; index < records.length; index++){
var record = records[index];
if (record.ties > 0){
return true;
}
}
return false;
}
/**
*
* This function will compare the given records and return -1 if the first record
* has more wins than the second, 1 if it has more, and 0 if it's the same.
*
* If the records have the same number of wins, then it bases the comparison on the
* losses. If record1 has the same wins but fewer losses, it should go first, so it
* returns -1.
*
* It'll return 0 if they have the exact same number of wins and losses.
*
* We do this in a few different places, so I decided to make a function.
*
* @param record1
* @param record2
* @returns
*/
function recordWinComparisonFunction(record1, record2){
//Steps to do:
// 1. Compare based on the wins first.
// 2. If they're the same, compare on the losses.
//More wins should go first.
if (record1.wins > record2.wins){
return -1;
}
//Fewer wins should go last.
else if (record1.wins < record2.wins){
return 1;
}
else {
//With the same number of wins, fewer losses should go first.
if (record1.losses < record2.losses){
return -1;
}
//And more losses should go second.
else if (record1.losses > record2.losses){
return 1;
}
}
//Same wins and losses = same record.
return 0;
}
/**
*
* When somebody clicks the "body" of the page, we want it to hide everything, so
* that's what this function will do. It just goes through and calls the function
* that hides the selectors. It also resets them too.
*
* @returns
*/
function onClickBody(){
hideTypeSelector();
resetAndHidePlayerSelections();
resetAndHideYearSelections();
resetAndHideWeekSelections();
hideStatNameSelector();
}
/**
*
* A convenience function for hiding all the selector containers. Not much
* to it.
*
* @returns
*/
function hideSelectorContainers(){
hideTypeSelector();
hidePlayerSelector();
hideYearSelector();
hideWeekSelector();
hideStatNameSelector();
hideTeamSelector();
}
/**
*
* This function switches the element with the given id from visibile to
* hidden or back (with the jquery "hide" and "show" functions).
*
* It decides whether something is visible by using the ":visible" property
* in jquery. If it's visible, it hides it. Otherwise, it shows it.
*
* @param id
* @returns
*/
function toggleVisibilty(id){
//Steps to do:
// 1. Get whether the element is visible.
// 2. Hide it if it is and show it if it's not.
var isElementVisible = isVisible(id);
if (isVisible){
$('#' + id).hide();
}
else {
$('#' + id).show();
}
}
/**
*
* A really dumb function for checking whether an element with the given
* id is visible or not. Just calls jquery to do the work.
*
* @param id
* @returns
*/
function isVisible(id){
var isElementVisible = $('#' + id).is(':visible');
return isElementVisible;
}
/**
*
* This function will toggle the visibility the weeks for the given week records
* at the given index. If they're shown, it'll hide them. If they're hidden,
* it'll show them. It's specific to the "weeks won" stat thing for now.
*
* @param index
* @returns
*/
function toggleShowWeeks(index){
//Steps to do:
// 1. Get whether the week records are shown now.
// 2. If they are, then hide them and change the link text.
// 3. Otherwise, show them and change the link text.
var isVisible = $('#week-records-' + index).is(':visible');
if (isVisible){
$('#week-records-' + index).hide();
$('#show-weeks-link-' + index).text('show weeks');
}
else {
$('#week-records-' + index).show();
$('#show-weeks-link-' + index).text('hide weeks');
}
}
/**
*
* This function will get the number rank of the given object in the given list.
* It will use the given comparison function to compare the object with other objects
* in the given list to decide where it fits, and it'll use the given "sameObjectFunction"
* to make sure an object doesn't "tie with itself".
*
* I made it because I wanted to do it in a few places (the original standings, weeks won standings,
* and a few other places).
*
* The given list <i>doesn't</i> need to be sorted in order for it to find the object's
* rank.
*
* It'll return an object that's like: {rank: 12, tie: true}, so people can get the
* numeric rank and whether it ties any other object in the list.
*
* Doing it this way, you'll have to call it for every object in the list ... This function
* is O(n), so that makes ranking every object in a list O(n^2). That kind of sucks,
* but it should be ok because we shouldn't be sorting hundreds or thousands of objects.
* I felt like it was ok to give up some speed to have it so each of the "standings"
* functions not have to duplicate the ranking code.
*
* @param object
* @param list
* @param comparisonFunction
* @param sameObjectFunction
* @returns
*/
function rank(object, list, comparisonFunction, sameObjectFunction){
//Steps to do:
// 1. Create the initial "rank" for the object and assume it has the highest rank.
// 2. Go through each object in the list and run the comparison object on it.
// 3. If it returns a positive number, that means the object is after the current
// one we're comparing it to, so we need to up the rank.
// 4. If it says they're the same, and the object hasn't already tied another object,
// then use the "sameObjectFunction" to see whether they're the exact same object or not.
// 5. If they aren't, then it's a real tie. If they aren't, then it's not.
var objectRank = {rank: 1, tie: false};
var numberOfRecordsBetter = 0;
var tie = false;
for (var index = 0; index < list.length; index++){
var currentObject = list[index];
var comparisonResult = comparisonFunction(object, currentObject);
if (comparisonResult > 0){
objectRank.rank++;
}
else if (comparisonResult == 0){
if (objectRank.tie == false){
var isSameObject = sameObjectFunction(object, currentObject);
if (!isSameObject){
objectRank.tie = true;
}
}
}
}
return objectRank;
}
/**
*
* A convenience function that'll sort the given weekRecords array
* by each weekRecord's length. A "weekRecord" will have a list
* of records for each week inside it. This will sort it so that
* the one with the most weeks comes first.
*
* This is for when we're ranking how many weeks a person has won and
* we want the person who's won the most weeks (has the most records)
* first.
*
* @param weekRecords
* @returns
*/
function sortWeekRecords(weekRecords){
//Steps to do:
// 1. Just run the sorting function on the records we were given.
weekRecords.sort(function (weekRecord1, weekRecord2){
if (weekRecord1.weekRecords.length > weekRecord2.weekRecords.length){
return -1;
}
else if (weekRecord1.weekRecords.length < weekRecord2.weekRecords.length){
return 1;
}
//Sort it alphabetically by name if they have the same record.
if (weekRecord1.player.name < weekRecord2.player.name){
return -1;
}
else if (weekRecord1.player.name > weekRecord2.player.name){
return 1;
}
return 0;
});
}
/**
*
* This function will sort the given week records by season and week
* so that the "oldest" records appear first. It's here for when we're showing
* how many weeks a person one and we want to show the weeks in chronological
* order. This function will make sure they're in chronological order.
*
* @param weekRecords
* @returns
*/
function sortWeekRecordsBySeasonAndWeek(weekRecords){
//Steps to do:
// 1. Just run the sorting function on the array
// we were given.
weekRecords.sort(function (weekRecord1, weekRecord2){
var year1 = parseInt(weekRecord1.season.year);
var year2 = parseInt(weekRecord2.season.year);
//If the year from one is before the other, we want the earlier one first.
if (year1 < year2){
return -1;
}
//And later one second.
else if (year1 > year2){
return 1;
}
else {
//Otherwise, compare on the weeks.
var week1 = weekRecord1.week.weekSequenceNumber;
var week2 = weekRecord2.week.weekSequenceNumber;
//With the earlier week first.
if (week1 < week2){
return -1;
}
else if (week1 > week2){
return 1;
}
}
return 0;
});
}
/**
*
* This function will sort the given array of "week records" so that it
* goes in ascending order by the week's year and week (so it's in increasing
* order by season and by week within each season).
*
* @param weekRecords
* @returns
*/
function sortWeekRecordsBySeasonWeekAndRecord(weekRecords){
//Steps to do:
// 1. Just run the sorting function on the array
// we were given.
weekRecords.sort(function (weekRecord1, weekRecord2){
var year1 = parseInt(weekRecord1.season.year);
var year2 = parseInt(weekRecord2.season.year);
//If the year from one is before the other, we want the earlier one first.
if (year1 < year2){
return -1;
}
//And later one second.
else if (year1 > year2){
return 1;
}
//If it's the same year...
else {
//Compare on the weeks.
var week1 = weekRecord1.week.weekSequenceNumber;
var week2 = weekRecord2.week.weekSequenceNumber;
//With the earlier week first.
if (week1 < week2){
return -1;
}
else if (week1 > week2){
return 1;
}
//same week, so sort by the record.
else {
if (weekRecord1.record.wins > weekRecord2.record.wins){
return -1;
}
else if (weekRecord1.record.wins < weekRecord2.record.wins){
return 1;
}
else {
if (weekRecord1.record.losses < weekRecord2.record.losses){
return -1;
}
else if (weekRecord1.record.losses > weekRecord2.record.losses){
return 1;
}
//Same year, week, wins, and losses, sort by the name
else {
if (weekRecord1.player.name < weekRecord2.player.name){
return -1;
}
else if (weekRecord1.player.name > weekRecord2.player.name){
return 1;
}
}
}
}
}
return 0;
});
}
/**
*
* This function will say whether a "specific" year was selected
* (basically if the year isn't "all" or one of the special ones).
*
* This should go in the selectors javascript file i think.
*
* @returns
*/
function isSpecificYearSelected(){
var selectedYears = getSelectedYears();
if (selectedYears.length > 1){
return false;
}
var selectedYear = selectedYears[0].value;
if ('all' == selectedYear || 'jurassic-period' == selectedYear || 'first-year' == selectedYear || 'modern-era' == selectedYear){
return false;
}
return true;
}
/**
*
* This function will say whether a "specific" team was selected
* (basically if the team isn't "all").
*
* @returns
*/
function isSpecificTeamSelected(){
var selectedTeams = getSelectedTeams();
if (selectedTeams.length > 1){
return false;
}
var selectedTeam = selectedTeams[0].value;
if ('all' == selectedTeam){
return false;
}
return true;
}
/**
*
* A convenience function for checking whether a single week is selected or not.
*
* It'll return false if:
* 1. There are no selected weeks.
* 2. There's more than one selected week.
* 3. There's one selected week, but it's the regular season, playoffs, or all.
*
* If all of those 3 things are false, it'll return true because that means there's a single
* week selected and it's not one of the ones that represents multiple weeks.
*
* @returns
*/
function isASingleWeekSelected(){
var selectedWeeks = getSelectedWeekValues();
if (isEmpty(selectedWeeks)){
return false;
}
if (selectedWeeks.length > 1){
return false;
}
var selectedWeek = selectedWeeks[0];
if ('all' == selectedWeek || 'regular_season' == selectedWeek || 'playoffs' == selectedWeek){
return false;
}
return true;
}
/**
*
* This function will say whether a "specific" week was selected.
* If the week is all, "regular-season", or "playoffs", then it takes
* that to mean a specific one isn't and a "range" is instead.
*
* @returns
*/
function isSpecificWeekSelected(){
var selectedWeeks = getSelectedWeeks();
if (isEmpty(selectedWeeks)){
return false;
}
var selectedWeek = selectedWeeks[0].value;
if ('all' == selectedWeek || 'regular_season' == selectedWeek || 'playoffs' == selectedWeek){
return false;
}
return true;
}
/**
*
* A convenience function for checking whether a single player is selected or not.
* It'll return false if the current selected player is "all" or if it has multiple
* values. Otherwise, it'll return true.
*
* @returns
*/
function isASinglePlayerSelected(){
var selectedPlayer = getSelectedPlayer();
if ('all' == selectedPlayer || doesValueHaveMultipleValues(selectedPlayer)){
return false;
}
return true;
}
/**
*
* This function will say whether a specific player is selected. If the
* current selected player is "all", it'll say there isn't. Otherwise, it'll
* say there is.
*
* @returns
*/
function isSpecificPlayerSelected(){
var selectedPlayers = getSelectedPlayers();
if (selectedPlayers.length > 1){
return false;
}
var selectedPlayer = selectedPlayers[0].value;
if ('all' == selectedPlayer){
return false;
}
return true;
}
/**
*
* This function will get the winning percentage. Here because we almost always want
* it formatted the same way, so I figured it was better to do it in a function.
*
* @param wins
* @param losses
* @returns
*/
function getWinningPercentage(wins, losses){
//Steps to do:
// 1. Get the actual percentage.
// 2. Make it 3 decimal places if it's a real number and blank if it's not.
var percentage = wins / (wins + losses);
var percentageString = '';
if (!isNaN(percentage)){
percentageString = percentage.toPrecision(3);
}
return percentageString;
}
/**
*
* A convenience function for sorting players by their name. Here in case
* we do it in multiple places.
*
* @param players
* @returns
*/
function sortPlayersByName(players){
//Steps to do:
// 1. Just compare each player by its name.
players.sort(function (player1, player2){
if (player1.name < player2.name){
return -1;
}
else if (player1.name > player2.name){
return 1;
}
return 0;
});
}
/**
*
* Here for when we're sorting something alphabetically and we don't
* care what kind of string it is.
*
* @param values
* @returns
*/
function sortAlphabetically(values){
values.sort(function (value1, value2){
if (value1 < value2){
return -1;
}
else if (value1 > value2){
return 1;
}
return 0;
});
}
/**
*
* Here so we can make sure the pick accuracies are in the right order (with the most
* accurate team coming first).
*
* @param pickAccuracySummaries
* @returns
*/
function sortPickAccuracySummariesByTimesRight(pickAccuracySummaries){
//Steps to do:
// 1. Just sort them by how many times the person was right picking a team.
pickAccuracySummaries.sort(function (pickAccuracySummaryA, pickAccuracySummaryB){
//More times right = front of the list.
if (pickAccuracySummaryA.timesRight > pickAccuracySummaryB.timesRight){
return -1;
}
//Fewer times right = back of the list.
else if (pickAccuracySummaryA.timesRight < pickAccuracySummaryB.timesRight){
return 1;
}
//If they have the same times right, sort on times wrong.
if (pickAccuracySummaryA.timesWrong < pickAccuracySummaryB.timesWrong){
return -1;
}
//Fewer times right = back of the list.
else if (pickAccuracySummaryA.timesWrong > pickAccuracySummaryB.timesWrong){
return 1;
}
//If they have the same times right and wrong, sort by player name.
if (pickAccuracySummaryA.player.name < pickAccuracySummaryB.player.name){
return -1;
}
else if (pickAccuracySummaryA.player.name > pickAccuracySummaryB.player.name){
return 1;
}
//If they have the same player name, sort by team abbreviation.
if (pickAccuracySummaryA.team.abbreviation < pickAccuracySummaryB.team.abbreviation){
return -1;
}
else if (pickAccuracySummaryA.team.abbreviation > pickAccuracySummaryB.team.abbreviation){
return 1;
}
return 0;
});
}
/**
*
* Shows or hides the details for pick accuracy. If it's currently shown, it'll hide
* it and if it's currently hidden, it'll show it.
*
* @param index
* @returns
*/
function toggleShowPickAccuracyDetails(index){
//Steps to do:
// 1. Get whether the container at the index is shown.
// 2. Hide it if it is, show it if it's not.
var isVisible = $('#pick-accuracy-details-' + index).is(':visible');
if (isVisible){
$('#pick-accuracy-details-' + index).hide();
$('#pick-accuracy-details-link-' + index).text('Details');
}
else {
$('#pick-accuracy-details-' + index).show();
$('#pick-accuracy-details-link-' + index).text('Hide');
}
}
/**
*
* This function will create a link that'll take them to the picks for the given
* year, week, team, and player (all optional) and show the given text. Here because
* we wanted to do this in a few places, so I figured it was best to do it as a function.
*
* @param linkText
* @param year
* @param week
* @param team
* @param player
* @returns
*/
function createPicksLink(linkText, year, week, team, player){
//Steps to do:
// 1. Just make a link that'll call the javascript function
// that actually updates the view.
// 2. All the arguments are optional, so only add them in if
// they're given.
var picksLink = '<a href="javascript:" onClick="showPickView(';
if (isDefined(year)){
var yearValue = year;
if (Array.isArray(year)){
yearValue = arrayToDelimitedValue(year, ',');
}
picksLink = picksLink + '\'' + yearValue + '\', ';
}
else {
picksLink = picksLink + 'null, ';
}
if (isDefined(week)){
var weekValue = week;
if (Array.isArray(week)){
weekValue = arrayToDelimitedValue(week, ',');
}
picksLink = picksLink + '\'' + weekValue + '\', ';
}
else {
picksLink = picksLink + 'null, ';
}
if (isDefined(team)){
var teamValue = team;
if (Array.isArray(team)){
teamValue = arrayToDelimitedValue(team, ',');
}
picksLink = picksLink + '\'' + teamValue + '\', ';
}
else {
picksLink = picksLink + 'null, ';
}
if (isDefined(player)){
var playerValue = player;
if (Array.isArray(player)){
playerValue = arrayToDelimitedValue(player, ',');
}
picksLink = picksLink + '\'' + playerValue + '\'';
}
else {
picksLink = picksLink + 'null';
}
picksLink = picksLink + ');">' + linkText + '</a>';
return picksLink;
}
/**
*
* This function will show the picks grid for the given year, week, team, and player.
* All the arguments are optional. It will just set each one as the selected
* year, week, team, and player (if it's given) and then cause the picks to be shown.
*
* It'll flip the global "havePicksBeenShown" switch to true so that the view shows
* all the picks for the given parameters and doesn't try to overrule it and only show
* a week's worth of picks.
*
* @param year
* @param week
* @param team
* @param player
* @returns
*/
function showPickView(year, week, team, player){
//Steps to do:
// 1. If we're coming from this function, then we don't want
// the updatePicks function saying "no, you can't see all the picks",
// so we need to flip the switch that disables that feature.
// 2. Set all the parameters that were given.
// 3. Call the function that'll show them on the screen.
//If this switch is true, we'll show the picks for the parameters no matter
//whether it's a week's worth or not. If it's not, it'll show only a week's
//worth as a way to prevent accidentally showing all the picks (which takes a while to do).
NFL_PICKS_GLOBAL.havePicksBeenShown = true;
setSelectedType('picks');
if (isDefined(year)){
setSelectedYears(year);
}
if (isDefined(week)){
setSelectedWeeks(week);
}
if (isDefined(player)){
setSelectedPlayers(player);
}
if (isDefined(team)){
selectSingleTeamFull(team);
}
updateView();
}
/**
*
* This function will shorten the given label so it's easier
* to show on phones and stuff with small widths. Up yours, twitter
* and bootstrap.
*
* @param label
* @returns
*/
function shortenWeekLabel(label){
if ('Playoffs - Wild Card' == label){
return 'Wild card';
}
else if ('Playoffs - Divisional' == label){
return 'Divisional';
}
else if ('Playoffs - Conference Championship' == label || 'Conference Championship' == label){
return 'Conf champ';
}
else if ('Playoffs - Super Bowl' == label){
return 'Super bowl';
}
return label;
}
/**
*
* This function will check whether the given value has multiple values
* in it or not. Basically, it'll return true if the given value is defined
* and it has a comma in it. It assumes the given value is a string and multiple
* values are separated by commas in that string.
*
* @param value
* @returns
*/
function doesValueHaveMultipleValues(value){
if (isDefined(value) && value.indexOf(',') != -1){
return true;
}
return false;
}
function showYearContainer(){
$('#yearContainer').show();
}
function hideYearContainer(){
$('#yearContainer').hide();
}
function showPlayerContainer(){
$('#playerContainer').show();
}
function hidePlayerContainer(){
$('#playerContainer').hide();
}
function showWeekContainer(){
$('#weekContainer').show();
}
function hideWeekContainer(){
$('#weekContainer').hide();
}
function showTeamContainer(){
$('#teamContainer').show();
}
function hideTeamContainer(){
$('#teamContainer').hide();
}
function showStatNameContainer(){
$('#statNameContainer').show();
}
function hideStatNameContainer(){
$('#statNameContainer').hide();
}
| hhhayssh/nflpicks | src/main/webapp/javascript/nflpicks.js | JavaScript | unlicense | 78,271 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PaperMarioBattleSystem.Extensions;
namespace PaperMarioBattleSystem
{
/// <summary>
/// The Timing Tutor Badge - teaches the timing of Stylish Moves by showing a "!" above the character's head when they should press A.
/// </summary>
public sealed class TimingTutorBadge : Badge
{
public TimingTutorBadge()
{
Name = "Timing Tutor";
Description = "Learn the timing for Stylish commands.";
BPCost = 1;
PriceValue = 120;
BadgeType = BadgeGlobals.BadgeTypes.TimingTutor;
AffectedType = BadgeGlobals.AffectedTypes.Both;
}
protected override void OnEquip()
{
//Flag that this BattleEntity should have Stylish Move timings shown
EntityEquipped.AddIntAdditionalProperty(Enumerations.AdditionalProperty.ShowStylishTimings, 1);
}
protected override void OnUnequip()
{
//Remove the flag that Stylish Move timings should be shown
EntityEquipped.SubtractIntAdditionalProperty(Enumerations.AdditionalProperty.ShowStylishTimings, 1);
}
}
}
| tdeeb/PaperMarioBattleSystem | PaperMarioBattleSystem/PaperMarioBattleSystem/Classes/Collectibles/Badges/TimingTutorBadge.cs | C# | unlicense | 1,310 |
require 'test/unit'
require 'bitcodin'
require 'json'
require 'coveralls'
Coveralls.wear!
module Bitcodin
class BitcodinApiCreateTest < Test::Unit::TestCase
def setup
# read access information (e.g. api key, etc.) from file
file = File.read('test/resources/settings.json')
data = JSON.parse(file)
@apiKey = data['apikey']
# create job config
manifestTypes = []
manifestTypes.push(ManifestType::MPEG_DASH_MPD)
manifestTypes.push(ManifestType::HLS_M3U8)
@job = Job.new(20541, 7353, manifestTypes)
end
def test_createJob
# create new bitcodinAPI instance
bitcodinAPI = BitcodinAPI.new(@apiKey)
# parse response to get job ID
response = bitcodinAPI.createJob(@job)
responseData = JSON.parse(response)
@jobId = responseData['jobId']
# check response code
assert_equal(response.code, ResponseCodes::POST)
end
def teardown
end
end
class BitcodinApiCreateWidevineDrmTest < Test::Unit::TestCase
def setup
# read access information (e.g. api key, etc.) from file
file = File.read('test/resources/settings.json')
data = JSON.parse(file)
@apiKey = data['apikey']
@drmConfig = WidevineDrmConfiguration.new('widevine_test', '1ae8ccd0e7985cc0b6203a55855a1034afc252980e970ca90e5202689f947ab9', 'd58ce954203b7c9a9a9d467f59839249', 'http://license.uat.widevine.com/cenc/getcontentkey', '746573745f69645f4639465043304e4f', 'mpeg_cenc')
# create job config
manifestTypes = []
manifestTypes.push(ManifestType::MPEG_DASH_MPD)
manifestTypes.push(ManifestType::HLS_M3U8)
@job = Job.new(20541, 7353, manifestTypes, 'standard', @drmConfig.values)
end
def test_createJob
# create new bitcodinAPI instance
bitcodinAPI = BitcodinAPI.new(@apiKey)
# parse response to get job ID
response = bitcodinAPI.createJob(@job)
responseData = JSON.parse(response)
@jobId = responseData['jobId']
# check response code
assert_equal(response.code, ResponseCodes::POST)
end
def teardown
end
end
class BitcodinApiCreatePlayreadyDrmTest < Test::Unit::TestCase
def setup
# read access information (e.g. api key, etc.) from file
file = File.read('test/resources/settings.json')
data = JSON.parse(file)
@apiKey = data['apikey']
@drmConfig = PlayreadyDrmConfiguration.new('XVBovsmzhP9gRIZxWfFta3VVRPzVEWmJsazEJ46I', 'http://playready.directtaps.net/pr/svc/rightsmanager.asmx', 'mpeg_cenc', '746573745f69645f4639465043304e4f')
# create job config
manifestTypes = []
manifestTypes.push(ManifestType::MPEG_DASH_MPD)
manifestTypes.push(ManifestType::HLS_M3U8)
@job = Job.new(20541, 7353, manifestTypes, 'standard', @drmConfig.values)
end
def test_createJob
# create new bitcodinAPI instance
bitcodinAPI = BitcodinAPI.new(@apiKey)
# parse response to get job ID
response = bitcodinAPI.createJob(@job)
responseData = JSON.parse(response)
@jobId = responseData['jobId']
# check response code
assert_equal(response.code, ResponseCodes::POST)
end
def teardown
end
end
class BitcodinApiCreateWidevinePlayreadyCombinedDrmTest < Test::Unit::TestCase
def setup
# read access information (e.g. api key, etc.) from file
file = File.read('test/resources/settings.json')
data = JSON.parse(file)
@apiKey = data['apikey']
@drmConfig = WidevinePlayreadyCombinedDrmConfiguration.new('eb676abbcb345e96bbcf616630f1a3da', '100b6c20940f779a4589152b57d2dacb', 'http://playready.directtaps.net/pr/svc/rightsmanager.asmx?PlayRight=1&ContentKey=EAtsIJQPd5pFiRUrV9Layw==', 'mpeg_cenc', 'CAESEOtnarvLNF6Wu89hZjDxo9oaDXdpZGV2aW5lX3Rlc3QiEGZrajNsamFTZGZhbGtyM2oqAkhEMgA=')
# create job config
manifestTypes = []
manifestTypes.push(ManifestType::MPEG_DASH_MPD)
manifestTypes.push(ManifestType::HLS_M3U8)
@job = Job.new(20541, 7353, manifestTypes, 'standard', @drmConfig.values)
end
def test_createJob
# create new bitcodinAPI instance
bitcodinAPI = BitcodinAPI.new(@apiKey)
# parse response to get job ID
response = bitcodinAPI.createJob(@job)
responseData = JSON.parse(response)
@jobId = responseData['jobId']
# check response code
assert_equal(response.code, ResponseCodes::POST)
end
def teardown
end
end
class BitcodinApiCreateHlsEncryptionTest < Test::Unit::TestCase
def setup
# read access information (e.g. api key, etc.) from file
file = File.read('test/resources/settings.json')
data = JSON.parse(file)
@apiKey = data['apikey']
@hlsEncryption = HLSEncryptionConfiguration.new('SAMPLE-AES', 'cab5b529ae28d5cc5e3e7bc3fd4a544d', '08eecef4b026deec395234d94218273d')
# create job config
manifestTypes = []
manifestTypes.push(ManifestType::MPEG_DASH_MPD)
manifestTypes.push(ManifestType::HLS_M3U8)
@job = Job.new(20541, 7353, manifestTypes, 'standard', nil, @hlsEncryption.values)
end
def test_createJob
# create new bitcodinAPI instance
bitcodinAPI = BitcodinAPI.new(@apiKey)
# parse response to get job ID
response = bitcodinAPI.createJob(@job)
responseData = JSON.parse(response)
@jobId = responseData['jobId']
# check response code
assert_equal(response.code, ResponseCodes::POST)
end
def teardown
end
end
class BitcodinApiCreateMultipleAudioStreamsTest < Test::Unit::TestCase
def setup
# read access information (e.g. api key, etc.) from file
file = File.read('test/resources/settings.json')
data = JSON.parse(file)
@apiKey = data['apikey']
bitcodinAPI = BitcodinAPI.new(@apiKey)
# create encoding profile
videoStreamConfig1 = VideoStreamConfig.new(0, 1024000, Profile::MAIN, Preset::PREMIUM, 480, 204)
videoStreamConfigs = [videoStreamConfig1]
audioStreamConfig1 = AudioStreamConfig.new(0, 256000)
audioStreamConfig2 = AudioStreamConfig.new(1, 256000)
audioStreamConfigs = [audioStreamConfig1, audioStreamConfig2]
encodingProfile = EncodingProfile.new('testProfileRuby', videoStreamConfigs, audioStreamConfigs)
# parse response to get encoding profile ID
response = bitcodinAPI.createEncodingProfile(encodingProfile)
responseData = JSON.parse(response)
encodingProfileId = responseData['encodingProfileId']
bitcodinAPI = BitcodinAPI.new(@apiKey)
# create input
httpConfig = HTTPInputConfig.new('http://bitbucketireland.s3.amazonaws.com/Sintel-two-audio-streams-short.mkv')
# parse response to get input ID
response = bitcodinAPI.createInput(httpConfig)
responseData = JSON.parse(response)
inputId = responseData['inputId']
# create job config
manifestTypes = []
manifestTypes.push(ManifestType::MPEG_DASH_MPD)
manifestTypes.push(ManifestType::HLS_M3U8)
# create audio metadata
audioMetaDataConfiguration0 = AudioMetaDataConfiguration.new(0, 'de', 'Just Sound')
audioMetaDataConfiguration1 = AudioMetaDataConfiguration.new(1, 'en', 'Sound and Voice')
@job = Job.new(inputId, encodingProfileId, manifestTypes, 'standard', nil, nil, [audioMetaDataConfiguration0, audioMetaDataConfiguration1])
end
def test_createJob
bitcodinAPI = BitcodinAPI.new(@apiKey)
# parse response to get job ID
response = bitcodinAPI.createJob(@job)
responseData = JSON.parse(response)
@jobId = responseData['jobId']
# check response code
assert_equal(response.code, ResponseCodes::POST)
end
def teardown
end
end
class BitcodinApiCreateLocationJobTest < Test::Unit::TestCase
def setup
file = File.read('test/resources/settings.json')
data = JSON.parse(file)
@apiKey = data['apikey']
bitcodinAPI = BitcodinAPI.new(@apiKey)
# create encoding profile
videoStreamConfig1 = VideoStreamConfig.new(0, 1024000, Profile::MAIN, Preset::PREMIUM, 480, 204)
videoStreamConfigs = [videoStreamConfig1]
audioStreamConfig1 = AudioStreamConfig.new(0, 256000)
audioStreamConfigs = [audioStreamConfig1]
encodingProfile = EncodingProfile.new('testProfileRuby', videoStreamConfigs, audioStreamConfigs)
# parse response to get encoding profile ID
response = bitcodinAPI.createEncodingProfile(encodingProfile)
responseData = JSON.parse(response)
encodingProfileId = responseData['encodingProfileId']
bitcodinAPI = BitcodinAPI.new(@apiKey)
# create input
httpConfig = HTTPInputConfig.new('http://bitbucketireland.s3.amazonaws.com/Sintel-two-audio-streams-short.mkv')
# parse response to get input ID
response = bitcodinAPI.createInput(httpConfig)
responseData = JSON.parse(response)
inputId = responseData['inputId']
# create job config
manifestTypes = []
manifestTypes.push(ManifestType::MPEG_DASH_MPD)
manifestTypes.push(ManifestType::HLS_M3U8)
@job = Job.new(inputId, encodingProfileId, manifestTypes, 'standard', nil, nil, nil, Location::DEFAULT)
end
def test_createJob
bitcodinAPI = BitcodinAPI.new(@apiKey)
# parse response to get job ID
response = bitcodinAPI.createJob(@job)
responseData = JSON.parse(response)
@jobId = responseData['jobId']
# check response code
assert_equal(response.code, ResponseCodes::POST)
end
def teardown
end
end
end
| bitmovin/bitcodin-ruby | test/jobs/bitcodin_api_create_test.rb | Ruby | unlicense | 9,797 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Brand'
db.create_table(u'automotive_brand', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=64)),
('slug', self.gf('autoslug.fields.AutoSlugField')(unique_with=(), max_length=50, populate_from='name')),
))
db.send_create_signal(u'automotive', ['Brand'])
# Adding model 'Model'
db.create_table(u'automotive_model', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('brand', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['automotive.Brand'])),
('name', self.gf('django.db.models.fields.CharField')(max_length=64)),
('full_name', self.gf('django.db.models.fields.CharField')(max_length=256, blank=True)),
('year', self.gf('django.db.models.fields.PositiveSmallIntegerField')(null=True, blank=True)),
))
db.send_create_signal(u'automotive', ['Model'])
def backwards(self, orm):
# Deleting model 'Brand'
db.delete_table(u'automotive_brand')
# Deleting model 'Model'
db.delete_table(u'automotive_model')
models = {
u'automotive.brand': {
'Meta': {'object_name': 'Brand'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "'name'"})
},
u'automotive.model': {
'Meta': {'object_name': 'Model'},
'brand': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['automotive.Brand']"}),
'full_name': ('django.db.models.fields.CharField', [], {'max_length': '256', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'year': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['automotive'] | mscam/django-automotive | automotive/south_migrations/0001_initial.py | Python | unlicense | 2,513 |
<?php
namespace MattyG\Http;
class Response
{
/**
* @var int
*/
protected $responseCode;
/**
* @var array
*/
protected $headers;
/**
* @var array
*/
protected $rawHeaders;
/**
* @var bool
*/
protected $headersSent;
/**
* @var string
*/
protected $body;
public function __construct()
{
$this->responseCode = 200;
$this->headers = array();
$this->rawHeaders = array();
$this->headersSent = false;
$this->body = "";
}
/**
* @param int $code
* @return Response
*/
public function setResponseCode($code)
{
$this->responseCode = $code;
return $this;
}
/**
* @return int
*/
public function getResponseCode()
{
return $this->responseCode;
}
/**
* @return void
*/
public function sendResponseCode()
{
http_response_code($this->responseCode);
}
/**
* @param array $rawHeaders
* @return Response
*/
public function setRawHeaders(array $rawHeaders = array())
{
$this->rawHeaders = $rawHeaders;
return $this;
}
/**
* @param string $rawHeader
* @return Response
*/
public function addRawHeader($rawHeader)
{
$this->rawHeaders[] = $rawHeader;
return $this;
}
/**
* @return array
*/
public function getRawHeaders()
{
return $this->rawHeaders;
}
/**
* @param array $headers
* @return Response
*/
public function setHeaders(array $headers = array())
{
$this->headers = $headers;
return $this;
}
/**
* @param string $header
* @param string $value
* @return Response
*/
public function addHeader($header, $value)
{
$this->headers[] = $header;
return $this;
}
/**
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* @param string $header
* @return Response|bool
*/
public function unsetHeader($header)
{
if (isset($this->headers[$header])) {
unset($this->headers[$header]);
return $this;
} else {
return false;
}
}
/**
* @return void
*/
public function sendHeaders()
{
if ($this->headersSent === true) {
return;
}
foreach ($this->rawHeaders as $rawHeader) {
header($rawHeader);
}
foreach ($this->headers as $header => $value) {
header($header . ": " . $value);
}
$this->headersSent = true;
}
/**
* @param string $body
* @return Response
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* @return string
*/
public function getBody()
{
return $this->body;
}
/**
* @return void
*/
public function sendBody()
{
$body = $this->getBody();
echo $body;
}
/**
* @return void
*/
public function sendResponse()
{
$this->sendHeaders();
$this->sendResponseCode();
$this->sendBody();
}
}
| djmattyg007/MattyG.Http | src/Response.php | PHP | unlicense | 3,333 |
<?php
//Database.php
//require_once('config.php'); //Might add config file to pull this in from later
class Database
{
protected static $connection;
private function dbConnect()
{
$databaseName = 'lockeythings';
$serverName = 'localhost';
$databaseUser = 'lockey';
$databasePassword = 'bobisyouruncle';
$databasePort = '3306';
// Not actual details! Placeholders! Leave my DB alone! :)
self::$connection = mysqli_connect ($serverName, $databaseUser, $databasePassword, 'lockeythings');
// mysqli_set_charset('utf-8',self::$connection);
if (self::$connection)
{
if (!mysqli_select_db (self::$connection, $databaseName))
{
echo("DB Not Found");
throw new Exception('DB Not found');
}
}
else
{
echo("No DB connection");
throw new Exception('No DB Connection');
}
return self::$connection;
}
public function query($query) {
// Connect to the database
$connection = $this -> dbConnect();
// Query the database
$result = mysqli_query($connection, $query);
return $result;
}
public function select($query) {
$rows = array();
$result = $this -> query($query);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
// echo("should have worked");
return $rows;
}
}
?>
| drenzul/lockeythings | public_html/helperclasses/database.php | PHP | unlicense | 1,755 |
<?php
function getAssets($statName,$userID) {
include 'connect.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql:');
mysql_select_db($dbname);
createIfNotExists($statName,$userID);
$query = sprintf("SELECT value FROM h_user_assets WHERE assets_id = (SELECT id FROM h_assets WHERE name = '%s' OR short_name = '%s') AND user_id = '%s'",
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID));
$result = mysql_query($query);
list($value) = mysql_fetch_row($result);
return $value;
}
function setAssets($statName,$userID,$quantity) {
include 'connect.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql');
mysql_select_db($dbname);
createIfNotExists($statName,$userID);
$query = sprintf("UPDATE h_user_assets SET quantity = '%s' WHERE assets_id = (SELECT id FROM h_assets WHERE name = '%s' OR short_name = '%s') AND user_id = '%s'",
mysql_real_escape_string($quantity),
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID));
$result = mysql_query($query);
}
function createIfNotExists($statName,$userID) {
include 'connect.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql:');
mysql_select_db($dbname);
$query = sprintf("SELECT count(quantity) FROM h_user_assets WHERE stat_id = (SELECT id FROM h_assets WHERE name = '%s' OR short_name = '%s') AND user_id = '%s'",
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID));
$result = mysql_query($query);
list($count) = mysql_fetch_row($result);
if($count == 0) {
// the stat doesn't exist; insert it into the database
$query = sprintf("INSERT INTO h_user_stats(assets_id,user_id,quantity) VALUES ((SELECT id FROM h_assets WHERE name = '%s' OR short_name = '%s'),'%s','%s')",
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID),
'0');
mysql_query($query);
}
}
?> | dvelle/The-hustle-game-on-facebook-c.2010 | hustle/hustle/test/estate.php | PHP | unlicense | 2,104 |
import React from 'react';
import Moment from 'moment';
import { Embed, Grid } from 'semantic-ui-react';
const VideoDetail = ({video}) => {
if (!video){
return <div>Loading...</div>;
}
const videoId = video.id.videoId;
const url = `https://www.youtube.com/embed/${videoId}`;
const pubTime = Moment(video.snippet.publishedAt).format('DD-MM-YYYY, h:mm:ss a')
return (
<Grid.Row stretched>
<Grid.Column >
<Embed active
autoplay={false}
brandedUI={false}
id={videoId}
placeholder='http://semantic-ui.com/images/image-16by9.png'
src={url}
source='youtube'/>
<div className="details">
<h5 className="meta-big-title">{video.snippet.title}</h5>
<div className="meta-description">{video.snippet.description}</div>
<div className="meta-time">Published: {pubTime}</div>
</div>
</Grid.Column>
</Grid.Row>
);
};
export default VideoDetail; | suemcnab/react-youtube-pxn-open | src/components/video_detail.js | JavaScript | unlicense | 891 |
class MyClass:
'''This is the docstring for this class'''
def __init__(self):
# setup per-instance variables
self.x = 1
self.y = 2
self.z = 3
class MySecondClass:
'''This is the docstring for this second class'''
def __init__(self):
# setup per-instance variables
self.p = 1
self.d = 2
self.q = 3
| dagostinelli/python-package-boilerplate | packagename/somemodule.py | Python | unlicense | 382 |
#%matplotlib inline
# All the imports
from __future__ import print_function, division
from math import *
import random
import sys
import matplotlib.pyplot as plt
# TODO 1: Enter your unity ID here
__author__ = "magoff2"
class O:
"""
Basic Class which
- Helps dynamic updates
- Pretty Prints
"""
def __init__(self, **kwargs):
self.has().update(**kwargs)
def has(self):
return self.__dict__
def update(self, **kwargs):
self.has().update(kwargs)
return self
def __repr__(self):
show = [':%s %s' % (k, self.has()[k])
for k in sorted(self.has().keys())
if k[0] is not "_"]
txt = ' '.join(show)
if len(txt) > 60:
show = map(lambda x: '\t' + x + '\n', show)
return '{' + ' '.join(show) + '}'
print("Unity ID: ", __author__)
####################################################################
#SECTION 2
####################################################################
# Few Utility functions
def say(*lst):
"""
Print whithout going to new line
"""
print(*lst, end="")
sys.stdout.flush()
def random_value(low, high, decimals=2):
"""
Generate a random number between low and high.
decimals incidicate number of decimal places
"""
return round(random.uniform(low, high),decimals)
def gt(a, b): return a > b
def lt(a, b): return a < b
def shuffle(lst):
"""
Shuffle a list
"""
random.shuffle(lst)
return lst
class Decision(O):
"""
Class indicating Decision of a problem
"""
def __init__(self, name, low, high):
"""
@param name: Name of the decision
@param low: minimum value
@param high: maximum value
"""
O.__init__(self, name=name, low=low, high=high)
class Objective(O):
"""
Class indicating Objective of a problem
"""
def __init__(self, name, do_minimize=True):
"""
@param name: Name of the objective
@param do_minimize: Flag indicating if objective has to be minimized or maximized
"""
O.__init__(self, name=name, do_minimize=do_minimize)
class Point(O):
"""
Represents a member of the population
"""
def __init__(self, decisions):
O.__init__(self)
self.decisions = decisions
self.objectives = None
def __hash__(self):
return hash(tuple(self.decisions))
def __eq__(self, other):
return self.decisions == other.decisions
def clone(self):
new = Point(self.decisions)
new.objectives = self.objectives
return new
class Problem(O):
"""
Class representing the cone problem.
"""
def __init__(self):
O.__init__(self)
# TODO 2: Code up decisions and objectives below for the problem
# using the auxilary classes provided above.
self.decisions = [Decision('r', 0, 10), Decision('h', 0, 20)]
self.objectives = [Objective('S'), Objective('T')]
@staticmethod
def evaluate(point):
[r, h] = point.decisions
l = (r**2 + h**2)**0.5
S = pi * r * l
T = S + pi * r**2
point.objectives = [S, T]
# TODO 3: Evaluate the objectives S and T for the point.
return point.objectives
@staticmethod
def is_valid(point):
[r, h] = point.decisions
# TODO 4: Check if the point has valid decisions
V = pi / 3 * (r**2) * h
return V > 200
def generate_one(self):
# TODO 5: Generate a valid instance of Point.
while(True):
point = Point([random_value(d.low, d.high) for d in self.decisions])
if Problem.is_valid(point):
return point
cone = Problem()
point = cone.generate_one()
cone.evaluate(point)
print (point)
def populate(problem, size):
population = []
# TODO 6: Create a list of points of length 'size'
for _ in xrange(size):
population.append(problem.generate_one())
return population
#or
#return(problem.generate_one() for _ in xrange(size)
pop = populate(cone,5)
print(pop)
def crossover(mom, dad):
# TODO 7: Create a new point which contains decisions from
# the first half of mom and second half of dad
n = len(mom.decisions)
return Point(mom.decisions[:n//2] + dad.decisions[n//2:])
mom = cone.generate_one()
dad = cone.generate_one()
print(mom)
print(dad)
print(crossover(mom,dad))
print(crossover(pop[0],pop[1]))
def mutate(problem, point, mutation_rate=0.01):
# TODO 8: Iterate through all the decisions in the point
# and if the probability is less than mutation rate
# change the decision(randomly set it between its max and min).
for i, d in enumerate(problem.decisions):
if(random.random() < mutation_rate) :
point.decisions[i] = random_value(d.low, d.high)
return point
def bdom(problem, one, two):
"""
Return if one dominates two
"""
objs_one = problem.evaluate(one)
objs_two = problem.evaluate(two)
if(one == two):
return False;
dominates = False
# TODO 9: Return True/False based on the definition
# of bdom above.
first = True
second = False
for i,_ in enumerate(problem.objectives):
if ((first is True) & gt(one.objectives[i], two.objectives[i])):
first = False
elif (not second & (one.objectives[i] is not two.objectives[i])):
second = True
dominates = first & second
return dominates
print(bdom(cone,pop[0],pop[1]))
def fitness(problem, population, point):
dominates = 0
# TODO 10: Evaluate fitness of a point.
# For this workshop define fitness of a point
# as the number of points dominated by it.
# For example point dominates 5 members of population,
# then fitness of point is 5.
for another in population:
if bdom(problem, point, another):
dominates += 1
return dominates
''' should be 1 because it will run across the same point.'''
print(fitness(cone, pop, pop[0]))
print('HELLO WORLD\n')
def elitism(problem, population, retain_size):
# TODO 11: Sort the population with respect to the fitness
# of the points and return the top 'retain_size' points of the population
fit_pop = [fitness(cone,population,pop) for pop in population]
population = [pop for _,pop in sorted(zip(fit_pop,population), reverse = True)]
return population[:retain_size]
print(elitism(cone, pop, 3))
def ga(pop_size=100, gens=250):
problem = Problem()
population = populate(problem, pop_size)
[problem.evaluate(point) for point in population]
initial_population = [point.clone() for point in population]
gen = 0
while gen < gens:
say(".")
children = []
for _ in range(pop_size):
mom = random.choice(population)
dad = random.choice(population)
while (mom == dad):
dad = random.choice(population)
child = mutate(problem, crossover(mom, dad))
if problem.is_valid(child) and child not in population + children:
children.append(child)
population += children
population = elitism(problem, population, pop_size)
gen += 1
print("")
return initial_population, population
def plot_pareto(initial, final):
initial_objs = [point.objectives for point in initial]
final_objs = [point.objectives for point in final]
initial_x = [i[0] for i in initial_objs]
initial_y = [i[1] for i in initial_objs]
final_x = [i[0] for i in final_objs]
final_y = [i[1] for i in final_objs]
plt.scatter(initial_x, initial_y, color='b', marker='+', label='initial')
plt.scatter(final_x, final_y, color='r', marker='o', label='final')
plt.title("Scatter Plot between initial and final population of GA")
plt.ylabel("Total Surface Area(T)")
plt.xlabel("Curved Surface Area(S)")
plt.legend(loc=9, bbox_to_anchor=(0.5, -0.175), ncol=2)
plt.show()
initial, final = ga()
plot_pareto(initial, final)
| gbtimmon/ase16GBT | code/4/ga/magoff2.py | Python | unlicense | 8,088 |
"""
You get an array of numbers, return the sum of all of the positives ones.
Example [1,-4,7,12] => 1 + 7 + 12 = 20
Note: array may be empty, in this case return 0.
"""
def positive_sum(arr):
# Your code here
sum = 0
for number in arr:
if number > 0:
sum += number
return sum
| aadithpm/code-a-day | py/Sum Of Positive.py | Python | unlicense | 316 |
/**
* [★★★★]200. Number of Islands
* finish: 2016-12-06
* https://leetcode.com/problems/number-of-islands/
*/
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function (grid) {
var count = 0, i, j;
for (i = 0; i < grid.length; i++) {
for (j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
count += 1;
grid[i] = modify(grid[i], j, 2);
visitAround(grid, i, j);
} else {
grid[i] = modify(grid[i], j, 2);
}
}
}
return count;
};
function modify(str, index, val) {
var arr = str.split('');
arr[index] = val;
return arr.join('');
}
function visitAround(grid, i, j) {
// top, right, down, left
visit(grid, i - 1, j);
visit(grid, i, j + 1);
visit(grid, i + 1, j);
visit(grid, i, j - 1);
}
function visit(grid, row, col) {
if (typeof grid[row] !== 'undefined' && typeof grid[row][col] !== 'undefined') {
if (grid[row][col] == 1) {
grid[row] = modify(grid[row], col, 2);
visitAround(grid, row, col);
} else {
grid[row] = modify(grid[row], col, 2);
}
}
}
write('algorithms: 200. Number of Islands', 'title');
write(numIslands(["10101", "11010", "10101", "01010"]));
write(numIslands(["11110", "11010", "11000", "00000"])); | wyf2learn/leetcode | problems/algorithms/200.number-of-islands.js | JavaScript | unlicense | 1,394 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Exam: IDateAndCopy
{
public String Name { get; set; }
public int Mark { get; set; }
public DateTime Date { get; set; }
public Exam(String N, int M, DateTime D)
{
Name = N;
Mark = M;
Date = D;
}
public Exam()
{
Name = "";
Mark = 0;
Date = new DateTime(1990,1,1);
}
public override string ToString()
{
return Name + " " + Mark.ToString() + " " + Date.ToShortDateString();
}
public virtual object DeepCopy()
{
Exam e = new Exam(Name, Mark, Date);
return (object)e;
}
}
}
| PolyakovSergey95/OOP | Polyakov_17/prakt_1/Exam.cs | C# | unlicense | 867 |
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* All rights reserved.
*/
package com.rushucloud.eip.models;
import org.springframework.ldap.odm.annotations.Entry;
/**
* Simple person object for OdmPerson posting to LDAP server.
*
* @author yangboz
*/
@Entry(objectClasses = {"person", "top"}, base = "")
public class SimplePerson
{
private String mobile;
public String getMobile()
{
return mobile;
}
public void setMobile(String mobile)
{
this.mobile = mobile;
}
private String email;
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
private String password;
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
private String username;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
private String wxToken;
public String getWxToken()
{
return wxToken;
}
public void setWxToken(String wxToken)
{
this.wxToken = wxToken;
}
private String code;
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
}
| yangboz/north-american-adventure | RushuMicroService/eip-rushucloud/src/main/java/com/rushucloud/eip/models/SimplePerson.java | Java | unlicense | 1,993 |
package othello.backend.classhelpers;
import othello.backend.State;
import othello.backend.classhelpers.BoardHelper;
import game.impl.Board;
import game.impl.BoardLocation;
import game.impl.GamePiece;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class BoardHelperTest {
@Test
public void testGetLocationById() throws Exception {
State state = mock(State.class);
Board board = mock(Board.class);
when(board.getLocations()).thenReturn(new ArrayList<BoardLocation>(){{
add(new BoardLocation("TEST1"));
add(new BoardLocation("TEST2"));
add(new BoardLocation("TEST3"));
add(new BoardLocation("TEST4"));
add(new BoardLocation("TEST5"));
add(new BoardLocation("TEST6"));
add(new BoardLocation("TEST7"));
}});
when(state.getBoard()).thenReturn(board);
BoardHelper boardHelper = new BoardHelper(state);
assertEquals("TEST4", boardHelper.getLocationById("TEST4").getId());
assertEquals("TEST7", boardHelper.getLocationById("TEST7").getId());
assertEquals("TEST1", boardHelper.getLocationById("TEST1").getId());
assertEquals(null, boardHelper.getLocationById("NON EXISTING"));
}
@Test
public void testIsLocationEmpty() throws Exception {
State state = mock(State.class);
BoardHelper boardHelper = new BoardHelper(state);
BoardLocation location = new BoardLocation("Test location");
assertTrue(boardHelper.isLocationEmpty(location));
location.setPiece(new GamePiece("Test Piece"));
assertFalse(boardHelper.isLocationEmpty(location));
location.setPiece(null);
assertTrue(boardHelper.isLocationEmpty(location));
}
@Test
public void testEmptyLocation() throws Exception {
State state = mock(State.class);
BoardHelper boardHelper = new BoardHelper(state);
BoardLocation location = new BoardLocation("Test location");
location.setPiece(new GamePiece("Test Piece"));
boardHelper.emptyLocation(location);
assertTrue(boardHelper.isLocationEmpty(location));
}
@Test
public void testDoesLocationExistOnBoard() throws Exception{
State state = mock(State.class);
Board board = mock(Board.class);
final BoardLocation theLocation = mock(BoardLocation.class);
ArrayList<BoardLocation> existingList = new ArrayList<BoardLocation>(){
{
add(theLocation);
}
};
ArrayList<BoardLocation> nonExistingList = new ArrayList<BoardLocation>();
when(state.getBoard()).thenReturn(board).thenReturn(board);
when(board.getLocations()).thenReturn(existingList).thenReturn(nonExistingList);
BoardHelper boardHelper = new BoardHelper(state);
assertTrue(boardHelper.doesLocationExistOnBoard(theLocation));
assertFalse(boardHelper.doesLocationExistOnBoard(theLocation));
}
}
| Grupp2/GameBoard-API-Games | testsrc/othello/backend/classhelpers/BoardHelperTest.java | Java | unlicense | 3,094 |
from __future__ import unicode_literals
from django.apps import AppConfig
class RewardsConfig(AppConfig):
name = 'rewards'
| bfrick22/monetary-rewards | mysite/rewards/apps.py | Python | unlicense | 130 |
import React from 'react'
import {
List,
ListItem,
LiAction,
LiSecondary,
LiPrimary,
LiAvatar,
Checkbox,
Radio,
Switch,
Icon,
} from 'styled-mdl'
const demo = () => (
<List>
<ListItem>
<LiPrimary>
<LiAvatar>
<Icon name="person" />
</LiAvatar>
Bryan Cranston
</LiPrimary>
<LiSecondary>
<LiAction>
<Checkbox defaultChecked />
</LiAction>
</LiSecondary>
</ListItem>
<ListItem>
<LiPrimary>
<LiAvatar>
<Icon name="person" />
</LiAvatar>
Aaron Paul
</LiPrimary>
<LiSecondary>
<LiAction>
<Radio />
</LiAction>
</LiSecondary>
</ListItem>
<ListItem>
<LiPrimary>
<LiAvatar>
<Icon name="person" />
</LiAvatar>
Bob Odenkirk
</LiPrimary>
<LiSecondary>
<LiAction>
<Switch defaultChecked />
</LiAction>
</LiSecondary>
</ListItem>
</List>
)
const caption = 'Avatars and controls'
const code = `<List>
<ListItem>
<LiPrimary>
<LiAvatar><Icon name="person" /></LiAvatar>
Bryan Cranston
</LiPrimary>
<LiSecondary>
<LiAction>
<Checkbox defaultChecked />
</LiAction>
</LiSecondary>
</ListItem>
<ListItem>
<LiPrimary>
<LiAvatar><Icon name="person" /></LiAvatar>
Aaron Paul
</LiPrimary>
<LiSecondary>
<LiAction>
<Radio />
</LiAction>
</LiSecondary>
</ListItem>
<ListItem>
<LiPrimary>
<LiAvatar><Icon name="person" /></LiAvatar>
Bob Odenkirk
</LiPrimary>
<LiSecondary>
<LiAction>
<Switch defaultChecked />
</LiAction>
</LiSecondary>
</ListItem>
</List>`
export default { demo, caption, code }
| isogon/styled-mdl-website | demos/lists/demos/avatarsAndControls.js | JavaScript | unlicense | 1,826 |
"""
Python bindings for GLFW.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = 'Florian Rhiem (florian.rhiem@gmail.com)'
__copyright__ = 'Copyright (c) 2013-2016 Florian Rhiem'
__license__ = 'MIT'
__version__ = '1.3.1'
# By default (ERROR_REPORTING = True), GLFW errors will be reported as Python
# exceptions. Set ERROR_REPORTING to False or set a curstom error callback to
# disable this behavior.
ERROR_REPORTING = True
import ctypes
import os
import functools
import glob
import sys
import subprocess
import textwrap
# Python 3 compatibility:
try:
_getcwd = os.getcwdu
except AttributeError:
_getcwd = os.getcwd
if sys.version_info.major > 2:
_to_char_p = lambda s: s.encode('utf-8')
def _reraise(exception, traceback):
raise exception.with_traceback(traceback)
else:
_to_char_p = lambda s: s
def _reraise(exception, traceback):
raise (exception, None, traceback)
class GLFWError(Exception):
"""
Exception class used for reporting GLFW errors.
"""
def __init__(self, message):
super(GLFWError, self).__init__(message)
def _find_library_candidates(library_names,
library_file_extensions,
library_search_paths):
"""
Finds and returns filenames which might be the library you are looking for.
"""
candidates = set()
for library_name in library_names:
for search_path in library_search_paths:
glob_query = os.path.join(search_path, '*'+library_name+'*')
for filename in glob.iglob(glob_query):
filename = os.path.realpath(filename)
if filename in candidates:
continue
basename = os.path.basename(filename)
if basename.startswith('lib'+library_name):
basename_end = basename[len('lib'+library_name):]
elif basename.startswith(library_name):
basename_end = basename[len(library_name):]
else:
continue
for file_extension in library_file_extensions:
if basename_end.startswith(file_extension):
if basename_end[len(file_extension):][:1] in ('', '.'):
candidates.add(filename)
if basename_end.endswith(file_extension):
basename_middle = basename_end[:-len(file_extension)]
if all(c in '0123456789.' for c in basename_middle):
candidates.add(filename)
return candidates
def _load_library(library_names, library_file_extensions,
library_search_paths, version_check_callback):
"""
Finds, loads and returns the most recent version of the library.
"""
candidates = _find_library_candidates(library_names,
library_file_extensions,
library_search_paths)
library_versions = []
for filename in candidates:
version = version_check_callback(filename)
if version is not None and version >= (3, 0, 0):
library_versions.append((version, filename))
if not library_versions:
return None
library_versions.sort()
return ctypes.CDLL(library_versions[-1][1])
def _glfw_get_version(filename):
"""
Queries and returns the library version tuple or None by using a
subprocess.
"""
version_checker_source = '''
import sys
import ctypes
def get_version(library_handle):
"""
Queries and returns the library version tuple or None.
"""
major_value = ctypes.c_int(0)
major = ctypes.pointer(major_value)
minor_value = ctypes.c_int(0)
minor = ctypes.pointer(minor_value)
rev_value = ctypes.c_int(0)
rev = ctypes.pointer(rev_value)
if hasattr(library_handle, 'glfwGetVersion'):
library_handle.glfwGetVersion(major, minor, rev)
version = (major_value.value,
minor_value.value,
rev_value.value)
return version
else:
return None
try:
input_func = raw_input
except NameError:
input_func = input
filename = input_func().strip()
try:
library_handle = ctypes.CDLL(filename)
except OSError:
pass
else:
version = get_version(library_handle)
print(version)
'''
args = [sys.executable, '-c', textwrap.dedent(version_checker_source)]
process = subprocess.Popen(args, universal_newlines=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out = process.communicate(filename)[0]
out = out.strip()
if out:
return eval(out)
else:
return None
if sys.platform == 'win32':
# only try glfw3.dll on windows
try:
_glfw = ctypes.CDLL('glfw3.dll')
except OSError:
_glfw = None
else:
_glfw = _load_library(['glfw', 'glfw3'], ['.so', '.dylib'],
['',
'/usr/lib64', '/usr/local/lib64',
'/usr/lib', '/usr/local/lib',
'/usr/lib/x86_64-linux-gnu/'], _glfw_get_version)
if _glfw is None:
raise ImportError("Failed to load GLFW3 shared library.")
_callback_repositories = []
class _GLFWwindow(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWwindow GLFWwindow;
"""
_fields_ = [("dummy", ctypes.c_int)]
class _GLFWmonitor(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWmonitor GLFWmonitor;
"""
_fields_ = [("dummy", ctypes.c_int)]
class _GLFWvidmode(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWvidmode GLFWvidmode;
"""
_fields_ = [("width", ctypes.c_int),
("height", ctypes.c_int),
("red_bits", ctypes.c_int),
("green_bits", ctypes.c_int),
("blue_bits", ctypes.c_int),
("refresh_rate", ctypes.c_uint)]
def __init__(self):
ctypes.Structure.__init__(self)
self.width = 0
self.height = 0
self.red_bits = 0
self.green_bits = 0
self.blue_bits = 0
self.refresh_rate = 0
def wrap(self, video_mode):
"""
Wraps a nested python sequence.
"""
size, bits, self.refresh_rate = video_mode
self.width, self.height = size
self.red_bits, self.green_bits, self.blue_bits = bits
def unwrap(self):
"""
Returns a nested python sequence.
"""
size = self.width, self.height
bits = self.red_bits, self.green_bits, self.blue_bits
return size, bits, self.refresh_rate
class _GLFWgammaramp(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWgammaramp GLFWgammaramp;
"""
_fields_ = [("red", ctypes.POINTER(ctypes.c_ushort)),
("green", ctypes.POINTER(ctypes.c_ushort)),
("blue", ctypes.POINTER(ctypes.c_ushort)),
("size", ctypes.c_uint)]
def __init__(self):
ctypes.Structure.__init__(self)
self.red = None
self.red_array = None
self.green = None
self.green_array = None
self.blue = None
self.blue_array = None
self.size = 0
def wrap(self, gammaramp):
"""
Wraps a nested python sequence.
"""
red, green, blue = gammaramp
size = min(len(red), len(green), len(blue))
array_type = ctypes.c_ushort*size
self.size = ctypes.c_uint(size)
self.red_array = array_type()
self.green_array = array_type()
self.blue_array = array_type()
for i in range(self.size):
self.red_array[i] = int(red[i]*65535)
self.green_array[i] = int(green[i]*65535)
self.blue_array[i] = int(blue[i]*65535)
pointer_type = ctypes.POINTER(ctypes.c_ushort)
self.red = ctypes.cast(self.red_array, pointer_type)
self.green = ctypes.cast(self.green_array, pointer_type)
self.blue = ctypes.cast(self.blue_array, pointer_type)
def unwrap(self):
"""
Returns a nested python sequence.
"""
red = [self.red[i]/65535.0 for i in range(self.size)]
green = [self.green[i]/65535.0 for i in range(self.size)]
blue = [self.blue[i]/65535.0 for i in range(self.size)]
return red, green, blue
class _GLFWcursor(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWcursor GLFWcursor;
"""
_fields_ = [("dummy", ctypes.c_int)]
class _GLFWimage(ctypes.Structure):
"""
Wrapper for:
typedef struct GLFWimage GLFWimage;
"""
_fields_ = [("width", ctypes.c_int),
("height", ctypes.c_int),
("pixels", ctypes.POINTER(ctypes.c_ubyte))]
def __init__(self):
ctypes.Structure.__init__(self)
self.width = 0
self.height = 0
self.pixels = None
self.pixels_array = None
def wrap(self, image):
"""
Wraps a nested python sequence.
"""
self.width, self.height, pixels = image
array_type = ctypes.c_ubyte * 4 * self.width * self.height
self.pixels_array = array_type()
for i in range(self.height):
for j in range(self.width):
for k in range(4):
self.pixels_array[i][j][k] = pixels[i][j][k]
pointer_type = ctypes.POINTER(ctypes.c_ubyte)
self.pixels = ctypes.cast(self.pixels_array, pointer_type)
def unwrap(self):
"""
Returns a nested python sequence.
"""
pixels = [[[int(c) for c in p] for p in l] for l in self.pixels_array]
return self.width, self.height, pixels
VERSION_MAJOR = 3
VERSION_MINOR = 2
VERSION_REVISION = 1
RELEASE = 0
PRESS = 1
REPEAT = 2
KEY_UNKNOWN = -1
KEY_SPACE = 32
KEY_APOSTROPHE = 39
KEY_COMMA = 44
KEY_MINUS = 45
KEY_PERIOD = 46
KEY_SLASH = 47
KEY_0 = 48
KEY_1 = 49
KEY_2 = 50
KEY_3 = 51
KEY_4 = 52
KEY_5 = 53
KEY_6 = 54
KEY_7 = 55
KEY_8 = 56
KEY_9 = 57
KEY_SEMICOLON = 59
KEY_EQUAL = 61
KEY_A = 65
KEY_B = 66
KEY_C = 67
KEY_D = 68
KEY_E = 69
KEY_F = 70
KEY_G = 71
KEY_H = 72
KEY_I = 73
KEY_J = 74
KEY_K = 75
KEY_L = 76
KEY_M = 77
KEY_N = 78
KEY_O = 79
KEY_P = 80
KEY_Q = 81
KEY_R = 82
KEY_S = 83
KEY_T = 84
KEY_U = 85
KEY_V = 86
KEY_W = 87
KEY_X = 88
KEY_Y = 89
KEY_Z = 90
KEY_LEFT_BRACKET = 91
KEY_BACKSLASH = 92
KEY_RIGHT_BRACKET = 93
KEY_GRAVE_ACCENT = 96
KEY_WORLD_1 = 161
KEY_WORLD_2 = 162
KEY_ESCAPE = 256
KEY_ENTER = 257
KEY_TAB = 258
KEY_BACKSPACE = 259
KEY_INSERT = 260
KEY_DELETE = 261
KEY_RIGHT = 262
KEY_LEFT = 263
KEY_DOWN = 264
KEY_UP = 265
KEY_PAGE_UP = 266
KEY_PAGE_DOWN = 267
KEY_HOME = 268
KEY_END = 269
KEY_CAPS_LOCK = 280
KEY_SCROLL_LOCK = 281
KEY_NUM_LOCK = 282
KEY_PRINT_SCREEN = 283
KEY_PAUSE = 284
KEY_F1 = 290
KEY_F2 = 291
KEY_F3 = 292
KEY_F4 = 293
KEY_F5 = 294
KEY_F6 = 295
KEY_F7 = 296
KEY_F8 = 297
KEY_F9 = 298
KEY_F10 = 299
KEY_F11 = 300
KEY_F12 = 301
KEY_F13 = 302
KEY_F14 = 303
KEY_F15 = 304
KEY_F16 = 305
KEY_F17 = 306
KEY_F18 = 307
KEY_F19 = 308
KEY_F20 = 309
KEY_F21 = 310
KEY_F22 = 311
KEY_F23 = 312
KEY_F24 = 313
KEY_F25 = 314
KEY_KP_0 = 320
KEY_KP_1 = 321
KEY_KP_2 = 322
KEY_KP_3 = 323
KEY_KP_4 = 324
KEY_KP_5 = 325
KEY_KP_6 = 326
KEY_KP_7 = 327
KEY_KP_8 = 328
KEY_KP_9 = 329
KEY_KP_DECIMAL = 330
KEY_KP_DIVIDE = 331
KEY_KP_MULTIPLY = 332
KEY_KP_SUBTRACT = 333
KEY_KP_ADD = 334
KEY_KP_ENTER = 335
KEY_KP_EQUAL = 336
KEY_LEFT_SHIFT = 340
KEY_LEFT_CONTROL = 341
KEY_LEFT_ALT = 342
KEY_LEFT_SUPER = 343
KEY_RIGHT_SHIFT = 344
KEY_RIGHT_CONTROL = 345
KEY_RIGHT_ALT = 346
KEY_RIGHT_SUPER = 347
KEY_MENU = 348
KEY_LAST = KEY_MENU
MOD_SHIFT = 0x0001
MOD_CONTROL = 0x0002
MOD_ALT = 0x0004
MOD_SUPER = 0x0008
MOUSE_BUTTON_1 = 0
MOUSE_BUTTON_2 = 1
MOUSE_BUTTON_3 = 2
MOUSE_BUTTON_4 = 3
MOUSE_BUTTON_5 = 4
MOUSE_BUTTON_6 = 5
MOUSE_BUTTON_7 = 6
MOUSE_BUTTON_8 = 7
MOUSE_BUTTON_LAST = MOUSE_BUTTON_8
MOUSE_BUTTON_LEFT = MOUSE_BUTTON_1
MOUSE_BUTTON_RIGHT = MOUSE_BUTTON_2
MOUSE_BUTTON_MIDDLE = MOUSE_BUTTON_3
JOYSTICK_1 = 0
JOYSTICK_2 = 1
JOYSTICK_3 = 2
JOYSTICK_4 = 3
JOYSTICK_5 = 4
JOYSTICK_6 = 5
JOYSTICK_7 = 6
JOYSTICK_8 = 7
JOYSTICK_9 = 8
JOYSTICK_10 = 9
JOYSTICK_11 = 10
JOYSTICK_12 = 11
JOYSTICK_13 = 12
JOYSTICK_14 = 13
JOYSTICK_15 = 14
JOYSTICK_16 = 15
JOYSTICK_LAST = JOYSTICK_16
NOT_INITIALIZED = 0x00010001
NO_CURRENT_CONTEXT = 0x00010002
INVALID_ENUM = 0x00010003
INVALID_VALUE = 0x00010004
OUT_OF_MEMORY = 0x00010005
API_UNAVAILABLE = 0x00010006
VERSION_UNAVAILABLE = 0x00010007
PLATFORM_ERROR = 0x00010008
FORMAT_UNAVAILABLE = 0x00010009
NO_WINDOW_CONTEXT = 0x0001000A
FOCUSED = 0x00020001
ICONIFIED = 0x00020002
RESIZABLE = 0x00020003
VISIBLE = 0x00020004
DECORATED = 0x00020005
AUTO_ICONIFY = 0x00020006
FLOATING = 0x00020007
MAXIMIZED = 0x00020008
RED_BITS = 0x00021001
GREEN_BITS = 0x00021002
BLUE_BITS = 0x00021003
ALPHA_BITS = 0x00021004
DEPTH_BITS = 0x00021005
STENCIL_BITS = 0x00021006
ACCUM_RED_BITS = 0x00021007
ACCUM_GREEN_BITS = 0x00021008
ACCUM_BLUE_BITS = 0x00021009
ACCUM_ALPHA_BITS = 0x0002100A
AUX_BUFFERS = 0x0002100B
STEREO = 0x0002100C
SAMPLES = 0x0002100D
SRGB_CAPABLE = 0x0002100E
REFRESH_RATE = 0x0002100F
DOUBLEBUFFER = 0x00021010
CLIENT_API = 0x00022001
CONTEXT_VERSION_MAJOR = 0x00022002
CONTEXT_VERSION_MINOR = 0x00022003
CONTEXT_REVISION = 0x00022004
CONTEXT_ROBUSTNESS = 0x00022005
OPENGL_FORWARD_COMPAT = 0x00022006
OPENGL_DEBUG_CONTEXT = 0x00022007
OPENGL_PROFILE = 0x00022008
CONTEXT_RELEASE_BEHAVIOR = 0x00022009
CONTEXT_NO_ERROR = 0x0002200A
CONTEXT_CREATION_API = 0x0002200B
NO_API = 0
OPENGL_API = 0x00030001
OPENGL_ES_API = 0x00030002
NO_ROBUSTNESS = 0
NO_RESET_NOTIFICATION = 0x00031001
LOSE_CONTEXT_ON_RESET = 0x00031002
OPENGL_ANY_PROFILE = 0
OPENGL_CORE_PROFILE = 0x00032001
OPENGL_COMPAT_PROFILE = 0x00032002
CURSOR = 0x00033001
STICKY_KEYS = 0x00033002
STICKY_MOUSE_BUTTONS = 0x00033003
CURSOR_NORMAL = 0x00034001
CURSOR_HIDDEN = 0x00034002
CURSOR_DISABLED = 0x00034003
ANY_RELEASE_BEHAVIOR = 0
RELEASE_BEHAVIOR_FLUSH = 0x00035001
RELEASE_BEHAVIOR_NONE = 0x00035002
NATIVE_CONTEXT_API = 0x00036001
EGL_CONTEXT_API = 0x00036002
ARROW_CURSOR = 0x00036001
IBEAM_CURSOR = 0x00036002
CROSSHAIR_CURSOR = 0x00036003
HAND_CURSOR = 0x00036004
HRESIZE_CURSOR = 0x00036005
VRESIZE_CURSOR = 0x00036006
CONNECTED = 0x00040001
DISCONNECTED = 0x00040002
DONT_CARE = -1
_exc_info_from_callback = None
def _callback_exception_decorator(func):
@functools.wraps(func)
def callback_wrapper(*args, **kwargs):
global _exc_info_from_callback
if _exc_info_from_callback is not None:
# We are on the way back to Python after an exception was raised.
# Do not call further callbacks and wait for the errcheck function
# to handle the exception first.
return
try:
return func(*args, **kwargs)
except (KeyboardInterrupt, SystemExit):
raise
except:
_exc_info_from_callback = sys.exc_info()
return callback_wrapper
def _prepare_errcheck():
"""
This function sets the errcheck attribute of all ctypes wrapped functions
to evaluate the _exc_info_from_callback global variable and re-raise any
exceptions that might have been raised in callbacks.
It also modifies all callback types to automatically wrap the function
using the _callback_exception_decorator.
"""
def errcheck(result, *args):
global _exc_info_from_callback
if _exc_info_from_callback is not None:
exc = _exc_info_from_callback
_exc_info_from_callback = None
_reraise(exc[1], exc[2])
return result
for symbol in dir(_glfw):
if symbol.startswith('glfw'):
getattr(_glfw, symbol).errcheck = errcheck
_globals = globals()
for symbol in _globals:
if symbol.startswith('_GLFW') and symbol.endswith('fun'):
def wrapper_cfunctype(func, cfunctype=_globals[symbol]):
return cfunctype(_callback_exception_decorator(func))
_globals[symbol] = wrapper_cfunctype
_GLFWerrorfun = ctypes.CFUNCTYPE(None,
ctypes.c_int,
ctypes.c_char_p)
_GLFWwindowposfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int)
_GLFWwindowsizefun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int)
_GLFWwindowclosefun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow))
_GLFWwindowrefreshfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow))
_GLFWwindowfocusfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int)
_GLFWwindowiconifyfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int)
_GLFWframebuffersizefun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int)
_GLFWmousebuttonfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int,
ctypes.c_int)
_GLFWcursorposfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_double,
ctypes.c_double)
_GLFWcursorenterfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int)
_GLFWscrollfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_double,
ctypes.c_double)
_GLFWkeyfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int)
_GLFWcharfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int)
_GLFWmonitorfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWmonitor),
ctypes.c_int)
_GLFWdropfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.POINTER(ctypes.c_char_p))
_GLFWcharmodsfun = ctypes.CFUNCTYPE(None,
ctypes.POINTER(_GLFWwindow),
ctypes.c_uint,
ctypes.c_int)
_GLFWjoystickfun = ctypes.CFUNCTYPE(None,
ctypes.c_int,
ctypes.c_int)
_glfw.glfwInit.restype = ctypes.c_int
_glfw.glfwInit.argtypes = []
def init():
"""
Initializes the GLFW library.
Wrapper for:
int glfwInit(void);
"""
cwd = _getcwd()
res = _glfw.glfwInit()
os.chdir(cwd)
return res
_glfw.glfwTerminate.restype = None
_glfw.glfwTerminate.argtypes = []
def terminate():
"""
Terminates the GLFW library.
Wrapper for:
void glfwTerminate(void);
"""
for callback_repository in _callback_repositories:
for window_addr in list(callback_repository.keys()):
del callback_repository[window_addr]
for window_addr in list(_window_user_data_repository.keys()):
del _window_user_data_repository[window_addr]
_glfw.glfwTerminate()
_glfw.glfwGetVersion.restype = None
_glfw.glfwGetVersion.argtypes = [ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_version():
"""
Retrieves the version of the GLFW library.
Wrapper for:
void glfwGetVersion(int* major, int* minor, int* rev);
"""
major_value = ctypes.c_int(0)
major = ctypes.pointer(major_value)
minor_value = ctypes.c_int(0)
minor = ctypes.pointer(minor_value)
rev_value = ctypes.c_int(0)
rev = ctypes.pointer(rev_value)
_glfw.glfwGetVersion(major, minor, rev)
return major_value.value, minor_value.value, rev_value.value
_glfw.glfwGetVersionString.restype = ctypes.c_char_p
_glfw.glfwGetVersionString.argtypes = []
def get_version_string():
"""
Returns a string describing the compile-time configuration.
Wrapper for:
const char* glfwGetVersionString(void);
"""
return _glfw.glfwGetVersionString()
@_callback_exception_decorator
def _raise_glfw_errors_as_exceptions(error_code, description):
"""
Default error callback that raises GLFWError exceptions for glfw errors.
Set an alternative error callback or set glfw.ERROR_REPORTING to False to
disable this behavior.
"""
global ERROR_REPORTING
if ERROR_REPORTING:
message = "(%d) %s" % (error_code, description)
raise GLFWError(message)
_default_error_callback = _GLFWerrorfun(_raise_glfw_errors_as_exceptions)
_error_callback = (_raise_glfw_errors_as_exceptions, _default_error_callback)
_glfw.glfwSetErrorCallback.restype = _GLFWerrorfun
_glfw.glfwSetErrorCallback.argtypes = [_GLFWerrorfun]
_glfw.glfwSetErrorCallback(_default_error_callback)
def set_error_callback(cbfun):
"""
Sets the error callback.
Wrapper for:
GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun);
"""
global _error_callback
previous_callback = _error_callback
if cbfun is None:
cbfun = _raise_glfw_errors_as_exceptions
c_cbfun = _default_error_callback
else:
c_cbfun = _GLFWerrorfun(cbfun)
_error_callback = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetErrorCallback(cbfun)
if previous_callback is not None and previous_callback[0] != _raise_glfw_errors_as_exceptions:
return previous_callback[0]
_glfw.glfwGetMonitors.restype = ctypes.POINTER(ctypes.POINTER(_GLFWmonitor))
_glfw.glfwGetMonitors.argtypes = [ctypes.POINTER(ctypes.c_int)]
def get_monitors():
"""
Returns the currently connected monitors.
Wrapper for:
GLFWmonitor** glfwGetMonitors(int* count);
"""
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetMonitors(count)
monitors = [result[i] for i in range(count_value.value)]
return monitors
_glfw.glfwGetPrimaryMonitor.restype = ctypes.POINTER(_GLFWmonitor)
_glfw.glfwGetPrimaryMonitor.argtypes = []
def get_primary_monitor():
"""
Returns the primary monitor.
Wrapper for:
GLFWmonitor* glfwGetPrimaryMonitor(void);
"""
return _glfw.glfwGetPrimaryMonitor()
_glfw.glfwGetMonitorPos.restype = None
_glfw.glfwGetMonitorPos.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_monitor_pos(monitor):
"""
Returns the position of the monitor's viewport on the virtual screen.
Wrapper for:
void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos);
"""
xpos_value = ctypes.c_int(0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_int(0)
ypos = ctypes.pointer(ypos_value)
_glfw.glfwGetMonitorPos(monitor, xpos, ypos)
return xpos_value.value, ypos_value.value
_glfw.glfwGetMonitorPhysicalSize.restype = None
_glfw.glfwGetMonitorPhysicalSize.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_monitor_physical_size(monitor):
"""
Returns the physical size of the monitor.
Wrapper for:
void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height);
"""
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetMonitorPhysicalSize(monitor, width, height)
return width_value.value, height_value.value
_glfw.glfwGetMonitorName.restype = ctypes.c_char_p
_glfw.glfwGetMonitorName.argtypes = [ctypes.POINTER(_GLFWmonitor)]
def get_monitor_name(monitor):
"""
Returns the name of the specified monitor.
Wrapper for:
const char* glfwGetMonitorName(GLFWmonitor* monitor);
"""
return _glfw.glfwGetMonitorName(monitor)
_monitor_callback = None
_glfw.glfwSetMonitorCallback.restype = _GLFWmonitorfun
_glfw.glfwSetMonitorCallback.argtypes = [_GLFWmonitorfun]
def set_monitor_callback(cbfun):
"""
Sets the monitor configuration callback.
Wrapper for:
GLFWmonitorfun glfwSetMonitorCallback(GLFWmonitorfun cbfun);
"""
global _monitor_callback
previous_callback = _monitor_callback
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWmonitorfun(cbfun)
_monitor_callback = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetMonitorCallback(cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_glfw.glfwGetVideoModes.restype = ctypes.POINTER(_GLFWvidmode)
_glfw.glfwGetVideoModes.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(ctypes.c_int)]
def get_video_modes(monitor):
"""
Returns the available video modes for the specified monitor.
Wrapper for:
const GLFWvidmode* glfwGetVideoModes(GLFWmonitor* monitor, int* count);
"""
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetVideoModes(monitor, count)
videomodes = [result[i].unwrap() for i in range(count_value.value)]
return videomodes
_glfw.glfwGetVideoMode.restype = ctypes.POINTER(_GLFWvidmode)
_glfw.glfwGetVideoMode.argtypes = [ctypes.POINTER(_GLFWmonitor)]
def get_video_mode(monitor):
"""
Returns the current mode of the specified monitor.
Wrapper for:
const GLFWvidmode* glfwGetVideoMode(GLFWmonitor* monitor);
"""
videomode = _glfw.glfwGetVideoMode(monitor).contents
return videomode.unwrap()
_glfw.glfwSetGamma.restype = None
_glfw.glfwSetGamma.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.c_float]
def set_gamma(monitor, gamma):
"""
Generates a gamma ramp and sets it for the specified monitor.
Wrapper for:
void glfwSetGamma(GLFWmonitor* monitor, float gamma);
"""
_glfw.glfwSetGamma(monitor, gamma)
_glfw.glfwGetGammaRamp.restype = ctypes.POINTER(_GLFWgammaramp)
_glfw.glfwGetGammaRamp.argtypes = [ctypes.POINTER(_GLFWmonitor)]
def get_gamma_ramp(monitor):
"""
Retrieves the current gamma ramp for the specified monitor.
Wrapper for:
const GLFWgammaramp* glfwGetGammaRamp(GLFWmonitor* monitor);
"""
gammaramp = _glfw.glfwGetGammaRamp(monitor).contents
return gammaramp.unwrap()
_glfw.glfwSetGammaRamp.restype = None
_glfw.glfwSetGammaRamp.argtypes = [ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(_GLFWgammaramp)]
def set_gamma_ramp(monitor, ramp):
"""
Sets the current gamma ramp for the specified monitor.
Wrapper for:
void glfwSetGammaRamp(GLFWmonitor* monitor, const GLFWgammaramp* ramp);
"""
gammaramp = _GLFWgammaramp()
gammaramp.wrap(ramp)
_glfw.glfwSetGammaRamp(monitor, ctypes.pointer(gammaramp))
_glfw.glfwDefaultWindowHints.restype = None
_glfw.glfwDefaultWindowHints.argtypes = []
def default_window_hints():
"""
Resets all window hints to their default values.
Wrapper for:
void glfwDefaultWindowHints(void);
"""
_glfw.glfwDefaultWindowHints()
_glfw.glfwWindowHint.restype = None
_glfw.glfwWindowHint.argtypes = [ctypes.c_int,
ctypes.c_int]
def window_hint(target, hint):
"""
Sets the specified window hint to the desired value.
Wrapper for:
void glfwWindowHint(int target, int hint);
"""
_glfw.glfwWindowHint(target, hint)
_glfw.glfwCreateWindow.restype = ctypes.POINTER(_GLFWwindow)
_glfw.glfwCreateWindow.argtypes = [ctypes.c_int,
ctypes.c_int,
ctypes.c_char_p,
ctypes.POINTER(_GLFWmonitor),
ctypes.POINTER(_GLFWwindow)]
def create_window(width, height, title, monitor, share):
"""
Creates a window and its associated context.
Wrapper for:
GLFWwindow* glfwCreateWindow(int width, int height, const char* title, GLFWmonitor* monitor, GLFWwindow* share);
"""
return _glfw.glfwCreateWindow(width, height, _to_char_p(title),
monitor, share)
_glfw.glfwDestroyWindow.restype = None
_glfw.glfwDestroyWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def destroy_window(window):
"""
Destroys the specified window and its context.
Wrapper for:
void glfwDestroyWindow(GLFWwindow* window);
"""
_glfw.glfwDestroyWindow(window)
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_ulong)).contents.value
for callback_repository in _callback_repositories:
if window_addr in callback_repository:
del callback_repository[window_addr]
if window_addr in _window_user_data_repository:
del _window_user_data_repository[window_addr]
_glfw.glfwWindowShouldClose.restype = ctypes.c_int
_glfw.glfwWindowShouldClose.argtypes = [ctypes.POINTER(_GLFWwindow)]
def window_should_close(window):
"""
Checks the close flag of the specified window.
Wrapper for:
int glfwWindowShouldClose(GLFWwindow* window);
"""
return _glfw.glfwWindowShouldClose(window)
_glfw.glfwSetWindowShouldClose.restype = None
_glfw.glfwSetWindowShouldClose.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def set_window_should_close(window, value):
"""
Sets the close flag of the specified window.
Wrapper for:
void glfwSetWindowShouldClose(GLFWwindow* window, int value);
"""
_glfw.glfwSetWindowShouldClose(window, value)
_glfw.glfwSetWindowTitle.restype = None
_glfw.glfwSetWindowTitle.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_char_p]
def set_window_title(window, title):
"""
Sets the title of the specified window.
Wrapper for:
void glfwSetWindowTitle(GLFWwindow* window, const char* title);
"""
_glfw.glfwSetWindowTitle(window, _to_char_p(title))
_glfw.glfwGetWindowPos.restype = None
_glfw.glfwGetWindowPos.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_window_pos(window):
"""
Retrieves the position of the client area of the specified window.
Wrapper for:
void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos);
"""
xpos_value = ctypes.c_int(0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_int(0)
ypos = ctypes.pointer(ypos_value)
_glfw.glfwGetWindowPos(window, xpos, ypos)
return xpos_value.value, ypos_value.value
_glfw.glfwSetWindowPos.restype = None
_glfw.glfwSetWindowPos.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int]
def set_window_pos(window, xpos, ypos):
"""
Sets the position of the client area of the specified window.
Wrapper for:
void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos);
"""
_glfw.glfwSetWindowPos(window, xpos, ypos)
_glfw.glfwGetWindowSize.restype = None
_glfw.glfwGetWindowSize.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_window_size(window):
"""
Retrieves the size of the client area of the specified window.
Wrapper for:
void glfwGetWindowSize(GLFWwindow* window, int* width, int* height);
"""
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetWindowSize(window, width, height)
return width_value.value, height_value.value
_glfw.glfwSetWindowSize.restype = None
_glfw.glfwSetWindowSize.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int]
def set_window_size(window, width, height):
"""
Sets the size of the client area of the specified window.
Wrapper for:
void glfwSetWindowSize(GLFWwindow* window, int width, int height);
"""
_glfw.glfwSetWindowSize(window, width, height)
_glfw.glfwGetFramebufferSize.restype = None
_glfw.glfwGetFramebufferSize.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def get_framebuffer_size(window):
"""
Retrieves the size of the framebuffer of the specified window.
Wrapper for:
void glfwGetFramebufferSize(GLFWwindow* window, int* width, int* height);
"""
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetFramebufferSize(window, width, height)
return width_value.value, height_value.value
_glfw.glfwIconifyWindow.restype = None
_glfw.glfwIconifyWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def iconify_window(window):
"""
Iconifies the specified window.
Wrapper for:
void glfwIconifyWindow(GLFWwindow* window);
"""
_glfw.glfwIconifyWindow(window)
_glfw.glfwRestoreWindow.restype = None
_glfw.glfwRestoreWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def restore_window(window):
"""
Restores the specified window.
Wrapper for:
void glfwRestoreWindow(GLFWwindow* window);
"""
_glfw.glfwRestoreWindow(window)
_glfw.glfwShowWindow.restype = None
_glfw.glfwShowWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def show_window(window):
"""
Makes the specified window visible.
Wrapper for:
void glfwShowWindow(GLFWwindow* window);
"""
_glfw.glfwShowWindow(window)
_glfw.glfwHideWindow.restype = None
_glfw.glfwHideWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def hide_window(window):
"""
Hides the specified window.
Wrapper for:
void glfwHideWindow(GLFWwindow* window);
"""
_glfw.glfwHideWindow(window)
_glfw.glfwGetWindowMonitor.restype = ctypes.POINTER(_GLFWmonitor)
_glfw.glfwGetWindowMonitor.argtypes = [ctypes.POINTER(_GLFWwindow)]
def get_window_monitor(window):
"""
Returns the monitor that the window uses for full screen mode.
Wrapper for:
GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window);
"""
return _glfw.glfwGetWindowMonitor(window)
_glfw.glfwGetWindowAttrib.restype = ctypes.c_int
_glfw.glfwGetWindowAttrib.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def get_window_attrib(window, attrib):
"""
Returns an attribute of the specified window.
Wrapper for:
int glfwGetWindowAttrib(GLFWwindow* window, int attrib);
"""
return _glfw.glfwGetWindowAttrib(window, attrib)
_window_user_data_repository = {}
_glfw.glfwSetWindowUserPointer.restype = None
_glfw.glfwSetWindowUserPointer.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_void_p]
def set_window_user_pointer(window, pointer):
"""
Sets the user pointer of the specified window. You may pass a normal python object into this function and it will
be wrapped automatically. The object will be kept in existence until the pointer is set to something else or
until the window is destroyed.
Wrapper for:
void glfwSetWindowUserPointer(GLFWwindow* window, void* pointer);
"""
data = (False, pointer)
if not isinstance(pointer, ctypes.c_void_p):
data = (True, pointer)
# Create a void pointer for the python object
pointer = ctypes.cast(ctypes.pointer(ctypes.py_object(pointer)), ctypes.c_void_p)
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
_window_user_data_repository[window_addr] = data
_glfw.glfwSetWindowUserPointer(window, pointer)
_glfw.glfwGetWindowUserPointer.restype = ctypes.c_void_p
_glfw.glfwGetWindowUserPointer.argtypes = [ctypes.POINTER(_GLFWwindow)]
def get_window_user_pointer(window):
"""
Returns the user pointer of the specified window.
Wrapper for:
void* glfwGetWindowUserPointer(GLFWwindow* window);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_user_data_repository:
data = _window_user_data_repository[window_addr]
is_wrapped_py_object = data[0]
if is_wrapped_py_object:
return data[1]
return _glfw.glfwGetWindowUserPointer(window)
_window_pos_callback_repository = {}
_callback_repositories.append(_window_pos_callback_repository)
_glfw.glfwSetWindowPosCallback.restype = _GLFWwindowposfun
_glfw.glfwSetWindowPosCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowposfun]
def set_window_pos_callback(window, cbfun):
"""
Sets the position callback for the specified window.
Wrapper for:
GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindowposfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_pos_callback_repository:
previous_callback = _window_pos_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowposfun(cbfun)
_window_pos_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowPosCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_size_callback_repository = {}
_callback_repositories.append(_window_size_callback_repository)
_glfw.glfwSetWindowSizeCallback.restype = _GLFWwindowsizefun
_glfw.glfwSetWindowSizeCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowsizefun]
def set_window_size_callback(window, cbfun):
"""
Sets the size callback for the specified window.
Wrapper for:
GLFWwindowsizefun glfwSetWindowSizeCallback(GLFWwindow* window, GLFWwindowsizefun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_size_callback_repository:
previous_callback = _window_size_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowsizefun(cbfun)
_window_size_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowSizeCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_close_callback_repository = {}
_callback_repositories.append(_window_close_callback_repository)
_glfw.glfwSetWindowCloseCallback.restype = _GLFWwindowclosefun
_glfw.glfwSetWindowCloseCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowclosefun]
def set_window_close_callback(window, cbfun):
"""
Sets the close callback for the specified window.
Wrapper for:
GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_close_callback_repository:
previous_callback = _window_close_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowclosefun(cbfun)
_window_close_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowCloseCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_refresh_callback_repository = {}
_callback_repositories.append(_window_refresh_callback_repository)
_glfw.glfwSetWindowRefreshCallback.restype = _GLFWwindowrefreshfun
_glfw.glfwSetWindowRefreshCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowrefreshfun]
def set_window_refresh_callback(window, cbfun):
"""
Sets the refresh callback for the specified window.
Wrapper for:
GLFWwindowrefreshfun glfwSetWindowRefreshCallback(GLFWwindow* window, GLFWwindowrefreshfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_refresh_callback_repository:
previous_callback = _window_refresh_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowrefreshfun(cbfun)
_window_refresh_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowRefreshCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_focus_callback_repository = {}
_callback_repositories.append(_window_focus_callback_repository)
_glfw.glfwSetWindowFocusCallback.restype = _GLFWwindowfocusfun
_glfw.glfwSetWindowFocusCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowfocusfun]
def set_window_focus_callback(window, cbfun):
"""
Sets the focus callback for the specified window.
Wrapper for:
GLFWwindowfocusfun glfwSetWindowFocusCallback(GLFWwindow* window, GLFWwindowfocusfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_focus_callback_repository:
previous_callback = _window_focus_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowfocusfun(cbfun)
_window_focus_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowFocusCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_window_iconify_callback_repository = {}
_callback_repositories.append(_window_iconify_callback_repository)
_glfw.glfwSetWindowIconifyCallback.restype = _GLFWwindowiconifyfun
_glfw.glfwSetWindowIconifyCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWwindowiconifyfun]
def set_window_iconify_callback(window, cbfun):
"""
Sets the iconify callback for the specified window.
Wrapper for:
GLFWwindowiconifyfun glfwSetWindowIconifyCallback(GLFWwindow* window, GLFWwindowiconifyfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_iconify_callback_repository:
previous_callback = _window_iconify_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWwindowiconifyfun(cbfun)
_window_iconify_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetWindowIconifyCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_framebuffer_size_callback_repository = {}
_callback_repositories.append(_framebuffer_size_callback_repository)
_glfw.glfwSetFramebufferSizeCallback.restype = _GLFWframebuffersizefun
_glfw.glfwSetFramebufferSizeCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWframebuffersizefun]
def set_framebuffer_size_callback(window, cbfun):
"""
Sets the framebuffer resize callback for the specified window.
Wrapper for:
GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _framebuffer_size_callback_repository:
previous_callback = _framebuffer_size_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWframebuffersizefun(cbfun)
_framebuffer_size_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetFramebufferSizeCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_glfw.glfwPollEvents.restype = None
_glfw.glfwPollEvents.argtypes = []
def poll_events():
"""
Processes all pending events.
Wrapper for:
void glfwPollEvents(void);
"""
_glfw.glfwPollEvents()
_glfw.glfwWaitEvents.restype = None
_glfw.glfwWaitEvents.argtypes = []
def wait_events():
"""
Waits until events are pending and processes them.
Wrapper for:
void glfwWaitEvents(void);
"""
_glfw.glfwWaitEvents()
_glfw.glfwGetInputMode.restype = ctypes.c_int
_glfw.glfwGetInputMode.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def get_input_mode(window, mode):
"""
Returns the value of an input option for the specified window.
Wrapper for:
int glfwGetInputMode(GLFWwindow* window, int mode);
"""
return _glfw.glfwGetInputMode(window, mode)
_glfw.glfwSetInputMode.restype = None
_glfw.glfwSetInputMode.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.c_int]
def set_input_mode(window, mode, value):
"""
Sets an input option for the specified window.
@param[in] window The window whose input mode to set.
@param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS` or
`GLFW_STICKY_MOUSE_BUTTONS`.
@param[in] value The new value of the specified input mode.
Wrapper for:
void glfwSetInputMode(GLFWwindow* window, int mode, int value);
"""
_glfw.glfwSetInputMode(window, mode, value)
_glfw.glfwGetKey.restype = ctypes.c_int
_glfw.glfwGetKey.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def get_key(window, key):
"""
Returns the last reported state of a keyboard key for the specified
window.
Wrapper for:
int glfwGetKey(GLFWwindow* window, int key);
"""
return _glfw.glfwGetKey(window, key)
_glfw.glfwGetMouseButton.restype = ctypes.c_int
_glfw.glfwGetMouseButton.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int]
def get_mouse_button(window, button):
"""
Returns the last reported state of a mouse button for the specified
window.
Wrapper for:
int glfwGetMouseButton(GLFWwindow* window, int button);
"""
return _glfw.glfwGetMouseButton(window, button)
_glfw.glfwGetCursorPos.restype = None
_glfw.glfwGetCursorPos.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double)]
def get_cursor_pos(window):
"""
Retrieves the last reported cursor position, relative to the client
area of the window.
Wrapper for:
void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos);
"""
xpos_value = ctypes.c_double(0.0)
xpos = ctypes.pointer(xpos_value)
ypos_value = ctypes.c_double(0.0)
ypos = ctypes.pointer(ypos_value)
_glfw.glfwGetCursorPos(window, xpos, ypos)
return xpos_value.value, ypos_value.value
_glfw.glfwSetCursorPos.restype = None
_glfw.glfwSetCursorPos.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_double,
ctypes.c_double]
def set_cursor_pos(window, xpos, ypos):
"""
Sets the position of the cursor, relative to the client area of the window.
Wrapper for:
void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos);
"""
_glfw.glfwSetCursorPos(window, xpos, ypos)
_key_callback_repository = {}
_callback_repositories.append(_key_callback_repository)
_glfw.glfwSetKeyCallback.restype = _GLFWkeyfun
_glfw.glfwSetKeyCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWkeyfun]
def set_key_callback(window, cbfun):
"""
Sets the key callback.
Wrapper for:
GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _key_callback_repository:
previous_callback = _key_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWkeyfun(cbfun)
_key_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetKeyCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_char_callback_repository = {}
_callback_repositories.append(_char_callback_repository)
_glfw.glfwSetCharCallback.restype = _GLFWcharfun
_glfw.glfwSetCharCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWcharfun]
def set_char_callback(window, cbfun):
"""
Sets the Unicode character callback.
Wrapper for:
GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _char_callback_repository:
previous_callback = _char_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWcharfun(cbfun)
_char_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCharCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_mouse_button_callback_repository = {}
_callback_repositories.append(_mouse_button_callback_repository)
_glfw.glfwSetMouseButtonCallback.restype = _GLFWmousebuttonfun
_glfw.glfwSetMouseButtonCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWmousebuttonfun]
def set_mouse_button_callback(window, cbfun):
"""
Sets the mouse button callback.
Wrapper for:
GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _mouse_button_callback_repository:
previous_callback = _mouse_button_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWmousebuttonfun(cbfun)
_mouse_button_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetMouseButtonCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_cursor_pos_callback_repository = {}
_callback_repositories.append(_cursor_pos_callback_repository)
_glfw.glfwSetCursorPosCallback.restype = _GLFWcursorposfun
_glfw.glfwSetCursorPosCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWcursorposfun]
def set_cursor_pos_callback(window, cbfun):
"""
Sets the cursor position callback.
Wrapper for:
GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _cursor_pos_callback_repository:
previous_callback = _cursor_pos_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWcursorposfun(cbfun)
_cursor_pos_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCursorPosCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_cursor_enter_callback_repository = {}
_callback_repositories.append(_cursor_enter_callback_repository)
_glfw.glfwSetCursorEnterCallback.restype = _GLFWcursorenterfun
_glfw.glfwSetCursorEnterCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWcursorenterfun]
def set_cursor_enter_callback(window, cbfun):
"""
Sets the cursor enter/exit callback.
Wrapper for:
GLFWcursorenterfun glfwSetCursorEnterCallback(GLFWwindow* window, GLFWcursorenterfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _cursor_enter_callback_repository:
previous_callback = _cursor_enter_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWcursorenterfun(cbfun)
_cursor_enter_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCursorEnterCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_scroll_callback_repository = {}
_callback_repositories.append(_scroll_callback_repository)
_glfw.glfwSetScrollCallback.restype = _GLFWscrollfun
_glfw.glfwSetScrollCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWscrollfun]
def set_scroll_callback(window, cbfun):
"""
Sets the scroll callback.
Wrapper for:
GLFWscrollfun glfwSetScrollCallback(GLFWwindow* window, GLFWscrollfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _scroll_callback_repository:
previous_callback = _scroll_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWscrollfun(cbfun)
_scroll_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetScrollCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
_glfw.glfwJoystickPresent.restype = ctypes.c_int
_glfw.glfwJoystickPresent.argtypes = [ctypes.c_int]
def joystick_present(joy):
"""
Returns whether the specified joystick is present.
Wrapper for:
int glfwJoystickPresent(int joy);
"""
return _glfw.glfwJoystickPresent(joy)
_glfw.glfwGetJoystickAxes.restype = ctypes.POINTER(ctypes.c_float)
_glfw.glfwGetJoystickAxes.argtypes = [ctypes.c_int,
ctypes.POINTER(ctypes.c_int)]
def get_joystick_axes(joy):
"""
Returns the values of all axes of the specified joystick.
Wrapper for:
const float* glfwGetJoystickAxes(int joy, int* count);
"""
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetJoystickAxes(joy, count)
return result, count_value.value
_glfw.glfwGetJoystickButtons.restype = ctypes.POINTER(ctypes.c_ubyte)
_glfw.glfwGetJoystickButtons.argtypes = [ctypes.c_int,
ctypes.POINTER(ctypes.c_int)]
def get_joystick_buttons(joy):
"""
Returns the state of all buttons of the specified joystick.
Wrapper for:
const unsigned char* glfwGetJoystickButtons(int joy, int* count);
"""
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetJoystickButtons(joy, count)
return result, count_value.value
_glfw.glfwGetJoystickName.restype = ctypes.c_char_p
_glfw.glfwGetJoystickName.argtypes = [ctypes.c_int]
def get_joystick_name(joy):
"""
Returns the name of the specified joystick.
Wrapper for:
const char* glfwGetJoystickName(int joy);
"""
return _glfw.glfwGetJoystickName(joy)
_glfw.glfwSetClipboardString.restype = None
_glfw.glfwSetClipboardString.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_char_p]
def set_clipboard_string(window, string):
"""
Sets the clipboard to the specified string.
Wrapper for:
void glfwSetClipboardString(GLFWwindow* window, const char* string);
"""
_glfw.glfwSetClipboardString(window, _to_char_p(string))
_glfw.glfwGetClipboardString.restype = ctypes.c_char_p
_glfw.glfwGetClipboardString.argtypes = [ctypes.POINTER(_GLFWwindow)]
def get_clipboard_string(window):
"""
Retrieves the contents of the clipboard as a string.
Wrapper for:
const char* glfwGetClipboardString(GLFWwindow* window);
"""
return _glfw.glfwGetClipboardString(window)
_glfw.glfwGetTime.restype = ctypes.c_double
_glfw.glfwGetTime.argtypes = []
def get_time():
"""
Returns the value of the GLFW timer.
Wrapper for:
double glfwGetTime(void);
"""
return _glfw.glfwGetTime()
_glfw.glfwSetTime.restype = None
_glfw.glfwSetTime.argtypes = [ctypes.c_double]
def set_time(time):
"""
Sets the GLFW timer.
Wrapper for:
void glfwSetTime(double time);
"""
_glfw.glfwSetTime(time)
_glfw.glfwMakeContextCurrent.restype = None
_glfw.glfwMakeContextCurrent.argtypes = [ctypes.POINTER(_GLFWwindow)]
def make_context_current(window):
"""
Makes the context of the specified window current for the calling
thread.
Wrapper for:
void glfwMakeContextCurrent(GLFWwindow* window);
"""
_glfw.glfwMakeContextCurrent(window)
_glfw.glfwGetCurrentContext.restype = ctypes.POINTER(_GLFWwindow)
_glfw.glfwGetCurrentContext.argtypes = []
def get_current_context():
"""
Returns the window whose context is current on the calling thread.
Wrapper for:
GLFWwindow* glfwGetCurrentContext(void);
"""
return _glfw.glfwGetCurrentContext()
_glfw.glfwSwapBuffers.restype = None
_glfw.glfwSwapBuffers.argtypes = [ctypes.POINTER(_GLFWwindow)]
def swap_buffers(window):
"""
Swaps the front and back buffers of the specified window.
Wrapper for:
void glfwSwapBuffers(GLFWwindow* window);
"""
_glfw.glfwSwapBuffers(window)
_glfw.glfwSwapInterval.restype = None
_glfw.glfwSwapInterval.argtypes = [ctypes.c_int]
def swap_interval(interval):
"""
Sets the swap interval for the current context.
Wrapper for:
void glfwSwapInterval(int interval);
"""
_glfw.glfwSwapInterval(interval)
_glfw.glfwExtensionSupported.restype = ctypes.c_int
_glfw.glfwExtensionSupported.argtypes = [ctypes.c_char_p]
def extension_supported(extension):
"""
Returns whether the specified extension is available.
Wrapper for:
int glfwExtensionSupported(const char* extension);
"""
return _glfw.glfwExtensionSupported(_to_char_p(extension))
_glfw.glfwGetProcAddress.restype = ctypes.c_void_p
_glfw.glfwGetProcAddress.argtypes = [ctypes.c_char_p]
def get_proc_address(procname):
"""
Returns the address of the specified function for the current
context.
Wrapper for:
GLFWglproc glfwGetProcAddress(const char* procname);
"""
return _glfw.glfwGetProcAddress(_to_char_p(procname))
if hasattr(_glfw, 'glfwSetDropCallback'):
_window_drop_callback_repository = {}
_callback_repositories.append(_window_drop_callback_repository)
_glfw.glfwSetDropCallback.restype = _GLFWdropfun
_glfw.glfwSetDropCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWdropfun]
def set_drop_callback(window, cbfun):
"""
Sets the file drop callback.
Wrapper for:
GLFWdropfun glfwSetDropCallback(GLFWwindow* window, GLFWdropfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_drop_callback_repository:
previous_callback = _window_drop_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
else:
def cb_wrapper(window, count, c_paths, cbfun=cbfun):
paths = [c_paths[i].decode('utf-8') for i in range(count)]
cbfun(window, paths)
cbfun = cb_wrapper
c_cbfun = _GLFWdropfun(cbfun)
_window_drop_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetDropCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
if hasattr(_glfw, 'glfwSetCharModsCallback'):
_window_char_mods_callback_repository = {}
_callback_repositories.append(_window_char_mods_callback_repository)
_glfw.glfwSetCharModsCallback.restype = _GLFWcharmodsfun
_glfw.glfwSetCharModsCallback.argtypes = [ctypes.POINTER(_GLFWwindow),
_GLFWcharmodsfun]
def set_char_mods_callback(window, cbfun):
"""
Sets the Unicode character with modifiers callback.
Wrapper for:
GLFWcharmodsfun glfwSetCharModsCallback(GLFWwindow* window, GLFWcharmodsfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.value
if window_addr in _window_char_mods_callback_repository:
previous_callback = _window_char_mods_callback_repository[window_addr]
else:
previous_callback = None
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWcharmodsfun(cbfun)
_window_char_mods_callback_repository[window_addr] = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetCharModsCallback(window, cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
if hasattr(_glfw, 'glfwVulkanSupported'):
_glfw.glfwVulkanSupported.restype = ctypes.c_int
_glfw.glfwVulkanSupported.argtypes = []
def vulkan_supported():
"""
Returns whether the Vulkan loader has been found.
Wrapper for:
int glfwVulkanSupported(void);
"""
return _glfw.glfwVulkanSupported() != 0
if hasattr(_glfw, 'glfwGetRequiredInstanceExtensions'):
_glfw.glfwGetRequiredInstanceExtensions.restype = ctypes.POINTER(ctypes.c_char_p)
_glfw.glfwGetRequiredInstanceExtensions.argtypes = [ctypes.POINTER(ctypes.c_uint32)]
def get_required_instance_extensions():
"""
Returns the Vulkan instance extensions required by GLFW.
Wrapper for:
const char** glfwGetRequiredInstanceExtensions(uint32_t* count);
"""
count_value = ctypes.c_uint32(0)
count = ctypes.pointer(count_value)
c_extensions = _glfw.glfwGetRequiredInstanceExtensions(count)
count = count_value.value
extensions = [c_extensions[i].decode('utf-8') for i in range(count)]
return extensions
if hasattr(_glfw, 'glfwGetTimerValue'):
_glfw.glfwGetTimerValue.restype = ctypes.c_uint64
_glfw.glfwGetTimerValue.argtypes = []
def get_timer_value():
"""
Returns the current value of the raw timer.
Wrapper for:
uint64_t glfwGetTimerValue(void);
"""
return int(_glfw.glfwGetTimerValue())
if hasattr(_glfw, 'glfwGetTimerFrequency'):
_glfw.glfwGetTimerFrequency.restype = ctypes.c_uint64
_glfw.glfwGetTimerFrequency.argtypes = []
def get_timer_frequency():
"""
Returns the frequency, in Hz, of the raw timer.
Wrapper for:
uint64_t glfwGetTimerFrequency(void);
"""
return int(_glfw.glfwGetTimerFrequency())
if hasattr(_glfw, 'glfwSetJoystickCallback'):
_joystick_callback = None
_glfw.glfwSetJoystickCallback.restype = _GLFWjoystickfun
_glfw.glfwSetJoystickCallback.argtypes = [_GLFWjoystickfun]
def set_joystick_callback(cbfun):
"""
Sets the error callback.
Wrapper for:
GLFWjoystickfun glfwSetJoystickCallback(GLFWjoystickfun cbfun);
"""
global _joystick_callback
previous_callback = _error_callback
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWjoystickfun(cbfun)
_joystick_callback = (cbfun, c_cbfun)
cbfun = c_cbfun
_glfw.glfwSetJoystickCallback(cbfun)
if previous_callback is not None and previous_callback[0] != 0:
return previous_callback[0]
if hasattr(_glfw, 'glfwGetKeyName'):
_glfw.glfwGetKeyName.restype = ctypes.c_char_p
_glfw.glfwGetKeyName.argtypes = [ctypes.c_int, ctypes.c_int]
def get_key_name(key, scancode):
"""
Returns the localized name of the specified printable key.
Wrapper for:
const char* glfwGetKeyName(int key, int scancode);
"""
key_name = _glfw.glfwGetKeyName(key, scancode)
if key_name:
return key_name.decode('utf-8')
return None
if hasattr(_glfw, 'glfwCreateCursor'):
_glfw.glfwCreateCursor.restype = ctypes.POINTER(_GLFWcursor)
_glfw.glfwCreateCursor.argtypes = [ctypes.POINTER(_GLFWimage),
ctypes.c_int,
ctypes.c_int]
def create_cursor(image, xhot, yhot):
"""
Creates a custom cursor.
Wrapper for:
GLFWcursor* glfwCreateCursor(const GLFWimage* image, int xhot, int yhot);
"""
c_image = _GLFWimage()
c_image.wrap(image)
return _glfw.glfwCreateCursor(ctypes.pointer(c_image), xhot, yhot)
if hasattr(_glfw, 'glfwCreateStandardCursor'):
_glfw.glfwCreateStandardCursor.restype = ctypes.POINTER(_GLFWcursor)
_glfw.glfwCreateStandardCursor.argtypes = [ctypes.c_int]
def create_standard_cursor(shape):
"""
Creates a cursor with a standard shape.
Wrapper for:
GLFWcursor* glfwCreateStandardCursor(int shape);
"""
return _glfw.glfwCreateStandardCursor(shape)
if hasattr(_glfw, 'glfwDestroyCursor'):
_glfw.glfwDestroyCursor.restype = None
_glfw.glfwDestroyCursor.argtypes = [ctypes.POINTER(_GLFWcursor)]
def destroy_cursor(cursor):
"""
Destroys a cursor.
Wrapper for:
void glfwDestroyCursor(GLFWcursor* cursor);
"""
_glfw.glfwDestroyCursor(cursor)
if hasattr(_glfw, 'glfwSetCursor'):
_glfw.glfwSetCursor.restype = None
_glfw.glfwSetCursor.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(_GLFWcursor)]
def set_cursor(window, cursor):
"""
Sets the cursor for the window.
Wrapper for:
void glfwSetCursor(GLFWwindow* window, GLFWcursor* cursor);
"""
_glfw.glfwSetCursor(window, cursor)
if hasattr(_glfw, 'glfwCreateWindowSurface'):
_glfw.glfwCreateWindowSurface.restype = ctypes.c_int
_glfw.glfwCreateWindowSurface.argtypes = [ctypes.c_void_p,
ctypes.POINTER(_GLFWwindow),
ctypes.c_void_p,
ctypes.c_void_p]
def create_window_surface(instance, window, allocator, surface):
"""
Creates a Vulkan surface for the specified window.
Wrapper for:
VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface);
"""
return _glfw.glfwCreateWindowSurface(instance, window, allocator, surface)
if hasattr(_glfw, 'glfwGetPhysicalDevicePresentationSupport'):
_glfw.glfwGetPhysicalDevicePresentationSupport.restype = ctypes.c_int
_glfw.glfwGetPhysicalDevicePresentationSupport.argtypes = [ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint32]
def get_physical_device_presentation_support(instance, device, queuefamily):
"""
Creates a Vulkan surface for the specified window.
Wrapper for:
int glfwGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice device, uint32_t queuefamily);
"""
return _glfw.glfwGetPhysicalDevicePresentationSupport(instance, device, queuefamily)
if hasattr(_glfw, 'glfwGetInstanceProcAddress'):
_glfw.glfwGetInstanceProcAddress.restype = ctypes.c_void_p
_glfw.glfwGetInstanceProcAddress.argtypes = [ctypes.c_void_p,
ctypes.c_char_p]
def get_instance_proc_address(instance, procname):
"""
Returns the address of the specified Vulkan instance function.
Wrapper for:
GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname);
"""
return _glfw.glfwGetInstanceProcAddress(instance, procname)
if hasattr(_glfw, 'glfwSetWindowIcon'):
_glfw.glfwSetWindowIcon.restype = None
_glfw.glfwSetWindowIcon.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int,
ctypes.POINTER(_GLFWimage)]
def set_window_icon(window, count, image):
"""
Sets the icon for the specified window.
Wrapper for:
void glfwSetWindowIcon(GLFWwindow* window, int count, const GLFWimage* images);
"""
_image = _GLFWimage()
_image.wrap(image)
_glfw.glfwSetWindowIcon(window, count, ctypes.pointer(_image))
if hasattr(_glfw, 'glfwSetWindowSizeLimits'):
_glfw.glfwSetWindowSizeLimits.restype = None
_glfw.glfwSetWindowSizeLimits.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int]
def set_window_size_limits(window,
minwidth, minheight,
maxwidth, maxheight):
"""
Sets the size limits of the specified window.
Wrapper for:
void glfwSetWindowSizeLimits(GLFWwindow* window, int minwidth, int minheight, int maxwidth, int maxheight);
"""
_glfw.glfwSetWindowSizeLimits(window,
minwidth, minheight,
maxwidth, maxheight)
if hasattr(_glfw, 'glfwSetWindowAspectRatio'):
_glfw.glfwSetWindowAspectRatio.restype = None
_glfw.glfwSetWindowAspectRatio.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.c_int, ctypes.c_int]
def set_window_aspect_ratio(window, numer, denom):
"""
Sets the aspect ratio of the specified window.
Wrapper for:
void glfwSetWindowAspectRatio(GLFWwindow* window, int numer, int denom);
"""
_glfw.glfwSetWindowAspectRatio(window, numer, denom)
if hasattr(_glfw, 'glfwGetWindowFrameSize'):
_glfw.glfwGetWindowFrameSize.restype = None
_glfw.glfwGetWindowFrameSize.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int)]
def set_get_window_frame_size(window):
"""
Retrieves the size of the frame of the window.
Wrapper for:
void glfwGetWindowFrameSize(GLFWwindow* window, int* left, int* top, int* right, int* bottom);
"""
left = ctypes.c_int(0)
top = ctypes.c_int(0)
right = ctypes.c_int(0)
bottom = ctypes.c_int(0)
_glfw.glfwGetWindowFrameSize(window,
ctypes.pointer(left),
ctypes.pointer(top),
ctypes.pointer(right),
ctypes.pointer(bottom))
return left.value, top.value, right.value, bottom.value
if hasattr(_glfw, 'glfwMaximizeWindow'):
_glfw.glfwMaximizeWindow.restype = None
_glfw.glfwMaximizeWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def maximize_window(window):
"""
Maximizes the specified window.
Wrapper for:
void glfwMaximizeWindow(GLFWwindow* window);
"""
_glfw.glfwMaximizeWindow(window)
if hasattr(_glfw, 'glfwFocusWindow'):
_glfw.glfwFocusWindow.restype = None
_glfw.glfwFocusWindow.argtypes = [ctypes.POINTER(_GLFWwindow)]
def focus_window(window):
"""
Brings the specified window to front and sets input focus.
Wrapper for:
void glfwFocusWindow(GLFWwindow* window);
"""
_glfw.glfwFocusWindow(window)
if hasattr(_glfw, 'glfwSetWindowMonitor'):
_glfw.glfwSetWindowMonitor.restype = None
_glfw.glfwSetWindowMonitor.argtypes = [ctypes.POINTER(_GLFWwindow),
ctypes.POINTER(_GLFWmonitor),
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int,
ctypes.c_int]
def set_window_monitor(window, monitor, xpos, ypos, width, height,
refresh_rate):
"""
Sets the mode, monitor, video mode and placement of a window.
Wrapper for:
void glfwSetWindowMonitor(GLFWwindow* window, GLFWmonitor* monitor, int xpos, int ypos, int width, int height, int refreshRate);
"""
_glfw.glfwSetWindowMonitor(window, monitor,
xpos, ypos, width, height, refresh_rate)
if hasattr(_glfw, 'glfwWaitEventsTimeout'):
_glfw.glfwWaitEventsTimeout.restype = None
_glfw.glfwWaitEventsTimeout.argtypes = [ctypes.c_double]
def wait_events_timeout(timeout):
"""
Waits with timeout until events are queued and processes them.
Wrapper for:
void glfwWaitEventsTimeout(double timeout);
"""
_glfw.glfwWaitEventsTimeout(timeout)
if hasattr(_glfw, 'glfwPostEmptyEvent'):
_glfw.glfwPostEmptyEvent.restype = None
_glfw.glfwPostEmptyEvent.argtypes = []
def post_empty_event():
"""
Posts an empty event to the event queue.
Wrapper for:
void glfwPostEmptyEvent();
"""
_glfw.glfwPostEmptyEvent()
_prepare_errcheck()
| ronhandler/gitroot | pyglfw/glfw.py | Python | unlicense | 77,583 |
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var appList = ['./app/index.tsx'];
if(process.env.NODE_ENV === 'development') {
appList.unshift('webpack/hot/only-dev-server');
}
var currentPath = process.cwd();
module.exports = {
entry: {
app: appList
},
output: {
path: path.resolve(__dirname, "build"),
publicPath: "/",
filename: "bundle.js"
},
plugins: [new HtmlWebpackPlugin({
template: './app/index.html'
})],
resolve: {
root: [
path.join(currentPath, 'app/assets/stylesheets')
],
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
},
module: {
loaders: [
{ test: /\.tsx?$/, loader: 'ts-loader' },
{ test: /\.less$/, loader: 'style!css!less?strictMath' },
{ test: /\.css$/, loader: 'style!css' }
]
},
devServer: {
contentBase: './app',
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}
};
| janaagaard75/framework-investigations | old-or-not-typescript/learn-redux/react-redux-counter/webpack.config.js | JavaScript | unlicense | 1,059 |
#include "simpleWebSocket.h"
#ifndef DEPENDING
#include PROXYMSGS_PB_H
#endif
#include <map>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#define DEBUG false
void *connection_thread(void*arg);
int main()
{
SimpleWebSocket::WebSocketServer srv(1081, INADDR_ANY, DEBUG);
if (srv.ok() == false)
{
printf("server setup fail\n");
return 3;
}
while (1)
{
SimpleWebSocket::WebSocketServerConn *nc = srv.handle_accept();
if (nc)
{
pthread_t id;
pthread_create(&id, NULL,
&connection_thread, (void*) nc);
}
}
return 0;
}
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int conns_pos = 1;
std::map<int,SimpleWebSocket::WebSocketServerConn *> conns;
void *connection_thread(void*arg)
{
::proxyTcp::ProxyMsg msg;
SimpleWebSocket::WebSocketServerConn *nc =
(SimpleWebSocket::WebSocketServerConn *) arg;
printf("got connection\n");
pthread_mutex_lock(&mutex);
int pos = conns_pos++;
conns[pos] = nc;
pthread_mutex_unlock(&mutex);
int fd = nc->get_fd();
fcntl( fd, F_SETFL,
fcntl( fd, F_GETFL, 0 ) | O_NONBLOCK );
bool doselect = false;
bool done = false;
while (!done)
{
if (doselect) {
bool doservice = false;
while (!doservice) {
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 1; // 1 second polling
tv.tv_usec = 0;
(void) select(fd+1, &rfds, NULL, NULL, &tv);
if (FD_ISSET(fd, &rfds))
doservice = true;
}
}
SimpleWebSocket::WebSocketRet ret = nc->handle_read(msg);
switch (ret)
{
case SimpleWebSocket::WEBSOCKET_CONNECTED:
{
std::string path;
doselect = false;
nc->get_path(path);
printf("WebSocket connected! path = '%s'\n",
path.c_str());
msg.Clear();
msg.set_type(proxyTcp::PMT_PROTOVERSION);
msg.set_sequence(0);
msg.mutable_protover()->set_version(1);
nc->sendMessage(msg);
break;
}
case SimpleWebSocket::WEBSOCKET_NO_MESSAGE:
// go round again
doselect = true;
break;
case SimpleWebSocket::WEBSOCKET_MESSAGE:
doselect = false;
switch (msg.type())
{
case proxyTcp::PMT_PROTOVERSION:
printf("remote proto version = %d\n",
msg.protover().version());
break;
case proxyTcp::PMT_CLOSING:
printf("remote side is closing, so we are too\n");
done = true;
break;
case proxyTcp::PMT_DATA:
{
printf("got data length %d\n",
(int) msg.data().data().size());
pthread_mutex_lock(&mutex);
for (int ind = 0; ind < conns_pos; ind++)
if (ind != pos && conns[ind] != NULL)
{
conns[ind]->sendMessage(msg);
}
pthread_mutex_unlock(&mutex);
break;
}
case proxyTcp::PMT_PING:
printf("got ping\n");
break;
default:
printf("msg.type() = %d\n", msg.type());
}
break;
case SimpleWebSocket::WEBSOCKET_CLOSED:
printf("WebSocket closed!\n");
done = true;
break;
}
}
printf("closing connection\n");
pthread_mutex_lock(&mutex);
conns[pos] = NULL;
pthread_mutex_unlock(&mutex);
delete nc;
return NULL;
}
| flipk/pfkutils | libWebAppServer/simpleWsTestServer.cc | C++ | unlicense | 3,939 |
var GamesList = React.createClass({
getInitialState: function() {
return {
games: this.props.initialGames
};
},
scoreChanged: function(gameId, teamNumber, score) {
var game = this.state.games.filter(function(game) {
return game.id == gameId;
})[0];
game['pool_entry_' + teamNumber + '_score'] = score;
this.setState({games:this.state.games});
},
saveGames: function() {
$.ajax({
url: 'admin/bracket/score/save',
dataType: 'json',
data: csrf({games: this.state.games}),
cache: false,
method: 'post',
success: function(data) {
// show a spinner instead
alert('saved');
}.bind(this),
});
},
render: function() {
var that = this;
var games = this.state.games.map(function(game) {
return (
<Game game={game} teams={that.props.teams} rolls={that.props.rolls} key={game.id} scoreChanged={that.scoreChanged}/>
);
});
return (
<div>
<h2>Round {this.props.round}</h2>
{games}
<button onClick={this.saveGames}>Save</button>
</div>
);
}
});
var Game = React.createClass({
getInitialState : function() {
if (!this.props.game.pool_entry_1_score) {
this.props.game.pool_entry_1_score = '';
}
if (!this.props.game.pool_entry_2_score) {
this.props.game.pool_entry_2_score = '';
}
return this.props.game;
},
scoreChanged: function(e) {
this.props.scoreChanged(this.state.id, e.target.dataset.team, e.target.value);
},
render: function() {
var team1Name;
var team2Name;
var state = this.state;
this.props.teams.forEach(function(team) {
if (team.id == state.pool_entry_1_id) {
team1Name = team.name;
}
if (team.id == state.pool_entry_2_id) {
team2Name = team.name;
}
});
var team1Roll, team2Roll;
this.props.rolls.forEach(function(roll) {
if (roll.rank == state.pool_entry_1_rank) {
team1Roll = roll.roll;
}
if (roll.rank == state.pool_entry_2_rank) {
team2Roll = roll.roll;
}
});
return (
<div className="game">
<div className="team"><div className="team-name">{team1Name} ({this.state.pool_entry_1_rank} : {team1Roll})</div> <input type="text" value={this.state.pool_entry_1_score} onChange={this.scoreChanged} data-team="1"/></div>
<div className="team"><div className="team-name">{team2Name} ({this.state.pool_entry_2_rank} : {team2Roll})</div> <input type="text" value={this.state.pool_entry_2_score} onChange={this.scoreChanged} data-team="2"/></div>
</div>
)
}
});
var teams = globals.pools[0].teams.concat(globals.pools[1].teams.concat(globals.pools[2].teams.concat(globals.pools[3].teams.concat())));
ReactDOM.render(
<div>
<a href={'admin/bracket/' + globals.bracket.id}>Back To Bracket</a>
<GamesList initialGames={globals.games} round={globals.round} teams={teams} rolls={globals.rolls}/>
</div>,
document.getElementById('bracket-round')
);
| austinhaws/custom-bracket | public/js/views/bracket-round.js | JavaScript | unlicense | 2,838 |
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
password: String,
facebook: String,
twitter: String,
google: String,
github: String,
instagram: String,
linkedin: String,
tokens: Array,
profile: {
name: { type: String, default: '' },
gender: { type: String, default: '' },
location: { type: String, default: '' },
website: { type: String, default: '' },
picture: { type: String, default: '' }
},
/*
* Data related to the Cards.
* This should be moved to a separate table
* as soon more than one language is supported
*/
cardsLastGenerated: Date, //have we generated cards for this user today
lastWordUsed: { type: Number, default: 0 }, //last word offset from database
resetPasswordToken: String,
resetPasswordExpires: Date
});
/**
* Password hashing Mongoose middleware.
*/
userSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) { return next(); }
bcrypt.genSalt(5, function(err, salt) {
if (err) { return next(err); }
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) { return next(err); }
user.password = hash;
next();
});
});
});
/**
* Helper method for validationg user's password.
*/
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) { return cb(err); }
cb(null, isMatch);
});
};
/**
* Helper method for getting user's gravatar.
*/
userSchema.methods.gravatar = function(size) {
if (!size) { size = 200; }
if (!this.email) {
return 'https://gravatar.com/avatar/?s=' + size + '&d=retro';
}
var md5 = crypto.createHash('md5').update(this.email).digest('hex');
return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro';
};
module.exports = mongoose.model('User', userSchema);
| guilhermeasg/outspeak | models/User.js | JavaScript | unlicense | 2,102 |
define([
'app',
'collections/tables',
'collections/connections',
'collections/rdf-entities',
'collections/rdf-attributes',
'models/connection',
'models/table',
'views/abstract/base',
'views/shared/message-dialog',
'views/editor/connection-form',
'views/editor/rdf-entity-list',
'views/editor/rdf-attribute-list',
'views/editor/table-list',
'views/editor/table'
], function(
app,
TablesCollection,
ConnectionsCollection,
RdfEntitiesCollection,
RdfAttributesCollection,
ConnectionModel,
TableModel,
BaseView,
MessageDialogView,
ConnectionFormView,
RdfEntityListView,
RdfAttributeListView,
TableListView,
TableView
) {
'use strict';
var EditorView = BaseView.extend({
className: 'editor container',
template: app.fetchTemplate('editor/editor'),
events: {
'click .entity-breadcrumb': 'onEntityBreadcrumbClick',
'click .rdf-settings-icon': 'onRdfSettingsIconClick',
'change .rdf-settings input': 'onRdfSettingsInputChange'
},
settingsSlideSpeed: 150,
initialize: function(options) {
options = options || {};
this.conn = new ConnectionModel();
this.table = new TableModel();
this.tables = new TablesCollection();
this.connections = new ConnectionsCollection();
this.rdfEntities = new RdfEntitiesCollection();
this.rdfAttributes = new RdfAttributesCollection();
this.connectionForm = new ConnectionFormView({
connections: this.connections,
conn: this.conn
});
this.rdfEntityListView = new RdfEntityListView({
collection: this.rdfEntities
});
this.rdfAttributeListView = new RdfAttributeListView({
collection: this.rdfAttributes
});
this.tableView = new TableView({
model: this.table,
rdfAttributes: this.rdfAttributes,
rdfEntities: this.rdfEntities
});
this.tableListView = new TableListView({
collection: this.tables
});
this.tables.fetch({
reset: true
});
window.tables = this.tables;
$(document).on('click', _.bind(function(e) {
if (!$(e.target).hasClass('rdf-settings')) {
this.$('.rdf-settings').slideUp(this.settingsSlideSpeed);
}
}, this));
},
setListeners: function() {
BaseView.prototype.setListeners.call(this);
this.listenTo(this.conn, 'connect:success', this.onConnect, this);
this.listenTo(this.conn, 'disconnect', this.onDisconnect, this);
this.listenTo(this.rdfEntityListView, 'selected-item:change', this.onRdfEntityListSelectedItemChange, this);
this.listenTo(this.tableListView, 'item:select', this.onTableListItemSelect, this);
this.listenTo(this.rdfEntityListView, 'item:branch', this.onRdfEntityListItemBranch, this);
this.listenTo(this.table, 'save:success', this.onTableSaveSuccess, this);
this.listenTo(this.table, 'save:error', this.defaultActionErrorHandler, this);
this.listenTo(this.table, 'save:validationError', this.onTableValidationError, this);
this.listenTo(this.table, 'delete:success', this.onTableDeleteSuccess, this);
this.listenTo(this.table, 'delete:error', this.defaultActionErrorHandler, this);
this.listenTo(this.rdfEntities, 'change:parents', this.onRdfEntitiesParentsChange, this);
},
onConnect: function() {
this.$('.editor-rdf').slideDown().addClass('collapsed');
this.$('.editor-rdf-title .collapse-arrow').addClass('collapsed');
this.$('.editor-connection').slideUp().removeClass('collapsed');
this.$('.editor-connection-title .collapse-arrow').removeClass('collapsed');
this.rdfEntities.setEndpoint(this.conn.get('endpoint'));
this.rdfAttributes.setEndpoint(this.conn.get('endpoint'));
this.rdfEntities.fetch();
},
onDisconnect: function() {
this.$('.editor-rdf').slideUp().removeClass('collapsed');
this.$('.editor-rdf-title .collapse-arrow').removeClass('collapsed');
this.$('.editor-connection').slideDown().addClass('collapsed');
this.$('.editor-connection-title .collapse-arrow').addClass('collapsed');
this.rdfEntities.reset();
this.rdfAttributes.reset();
},
render: function() {
this.$el.html(this.template({
attributesLimit: this.rdfAttributes.limit,
attributesOffset: this.rdfAttributes.offset,
attributesSort: this.rdfAttributes.sorting,
entitiesLimit: this.rdfEntities.limit,
entitiesOffset: this.rdfEntities.offset,
entitiesLoadRootAttributes: this.rdfEntities.loadRootAttributes
}));
this.$('.editor-connection-form').html(this.connectionForm.render().$el);
this.$('.editor-rdf-entity-list-container').html(this.rdfEntityListView.render().$el);
this.$('.editor-rdf-attribute-list-container').html(this.rdfAttributeListView.render().$el);
this.$('.editor-table-list-container').html(this.tableListView.render().$el);
this.$('.editor-table-container').html(this.tableView.render().$el);
this.$('.editor-rdf').resizable({
handles: 's',
minHeight: 100,
maxHeight: 500
});
this.$('.editor-connection-title').on('click', _.bind(function() {
if (this.$('.editor-connection').hasClass('collapsed')) {
this.$('.editor-connection').slideUp().removeClass('collapsed');
} else {
this.$('.editor-connection').slideDown().addClass('collapsed');
}
this.$('.editor-connection-title .collapse-arrow').toggleClass('collapsed');
}, this));
this.$('.editor-rdf-title').on('click', _.bind(function() {
if (this.conn.get('connected')) {
if (this.$('.editor-rdf').hasClass('collapsed')) {
this.$('.editor-rdf').slideUp().removeClass('collapsed');
} else {
this.$('.editor-rdf').slideDown().addClass('collapsed');
}
this.$('.editor-rdf-title .collapse-arrow').toggleClass('collapsed');
}
}, this));
this.$('.editor-relational-title').on('click', _.bind(function() {
if (this.$('.editor-relational').hasClass('collapsed')) {
this.$('.editor-relational').slideUp().removeClass('collapsed');
} else {
this.$('.editor-relational').slideDown().addClass('collapsed');
}
this.$('.editor-relational-title .collapse-arrow').toggleClass('collapsed');
}, this));
this.setListeners();
return this;
},
onRdfEntitiesParentsChange: function() {
var parents = this.rdfEntities.getParentLabels();
var $breadcrumbs = this.$('.entity-breadcrumbs').html('Entities: ');
for (var i = 0; i < this.rdfEntities.parents.length; i++) {
if (i > 0) {
$breadcrumbs.append('<img class="breadcrumb-divider" src="assets/images/arrow_right.png"></img>');
}
var en = this.rdfEntities.parents[i];
var $en = $('<li>').addClass('entity-breadcrumb').attr('data-uri', en.get('uri')).html(en.get('label'));
$breadcrumbs.append($en);
}
},
onRdfEntityListSelectedItemChange: function(rdfEntity) {
this.rdfAttributes.setRdfEntity(rdfEntity);
if (this.rdfEntities.shouldLoadAttributes()) {
this.rdfAttributes.fetch();
}
},
onTableListItemSelect: function(tableListItem, tableModel) {
this.table = tableModel;
this.tableView.setModel(tableModel);
this.table.loadTableDefinition();
},
onTableDelete: function(model) {
(new MessageDialogView()).showMessage('', 'Your relational table has been removed');
this.tables.remove(this.tables.findWhere({
name: model.get('name')
}));
},
onTableSaveSuccess: function(model) {
(new MessageDialogView()).showSuccessMessage('Your relational table has been saved');
this.tables.add(model);
},
onEntityBreadcrumbClick: function(e) {
var uri = $(e.target).attr('data-uri');
this.rdfEntities.setParentEntityUri(uri);
},
onRdfSettingsIconClick: function(e) {
var $sett = $(e.target).find('.rdf-settings');
if ($sett.css('display') === 'block') {
$sett.slideUp(this.settingsSlideSpeed);
} else {
$sett.slideDown(this.settingsSlideSpeed);
}
e.stopPropagation();
},
onRdfEntityListItemBranch: function(itemView, rdfEntity) {
this.rdfEntities.setParentEntity(rdfEntity);
},
onRdfSettingsInputChange: function(e) {
var $input = $(e.target);
if ($input.attr('data-type') === 'entities') {
if ($input.attr('data-property') === 'limit') {
this.rdfEntities.setLimit(parseInt($input.val(), 10));
} else if ($input.attr('data-property') === 'offset') {
this.rdfEntities.setOffset(parseInt($input.val(), 10));
} else {
this.rdfEntities.setLoadRootAttributes($input.prop('checked'));
}
} else {
if ($input.attr('data-property') === 'limit') {
this.rdfAttributes.setLimit(parseInt($input.val(), 10));
} else if ($input.attr('data-property') === 'sort') {
this.rdfAttributes.setSort($input.prop('checked'));
} else {
this.rdfAttributes.setOffset(parseInt($input.val(), 10));
}
}
this.$('.rdf-settings').slideUp(this.settingsSlideSpeed);
}
});
return EditorView;
}); | ilucin/relsem-bridge-frontend | app/views/editor/editor.js | JavaScript | unlicense | 9,433 |
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Helloworld {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); // use the Scanner class to read from stdin
String inputString = scan.nextLine(); // read a line of input and save it to a variable
scan.close(); // close the scanner
// Your first line of output goes here
System.out.println("Hello, World.");
// Write the second line of output
System.out.println(inputString);
}
}
| jerryasher/hackerrank30 | 0/Helloworld.java | Java | unlicense | 588 |
#include "Mesh.h"
#include "SyntopiaCore/Math/Vector3.h"
#include "../Logging/Logging.h"
using namespace SyntopiaCore::Logging;
using namespace SyntopiaCore::Math;
namespace SyntopiaCore {
namespace GLEngine {
Mesh::Mesh(SyntopiaCore::Math::Vector3f startBase,
SyntopiaCore::Math::Vector3f startDir1 ,
SyntopiaCore::Math::Vector3f startDir2,
SyntopiaCore::Math::Vector3f endBase,
SyntopiaCore::Math::Vector3f endDir1 ,
SyntopiaCore::Math::Vector3f endDir2) :
startBase(startBase), startDir1(startDir1), startDir2(startDir2),
endBase(endBase), endDir1(endDir1), endDir2(endDir2)
{
/// Bounding Mesh (not really accurate)
from = startBase;
to = endBase;
};
Mesh::~Mesh() { };
void Mesh::draw() const {
// --- TODO: Rewrite - way to many state changes...
glPushMatrix();
glTranslatef( startBase.x(), startBase.y(), startBase.z() );
GLfloat col[4] = {0.0f, 1.0f, 1.0f, 0.1f} ;
glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, col );
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
Vector3f O(0,0,0);
Vector3f end = endBase - startBase;
glEnable (GL_LIGHTING);
glDisable(GL_CULL_FACE); // TODO: do we need this?
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLfloat c3[4] = {0.3f, 0.3f, 0.3f, 0.5f};
glMaterialfv( GL_FRONT, GL_SPECULAR, c3 );
glMateriali(GL_FRONT, GL_SHININESS, 127);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
glBegin( GL_QUADS );
glColor4fv(primaryColor);
GLfloat secondaryColor[4] = {oldRgb[0], oldRgb[1], oldRgb[2], oldAlpha};
//vertex4n(O, startDir1,startDir2+startDir1,startDir2);
Vector3f c1(startDir1*0.5f+startDir2*0.5f);
Vector3f c2(end+endDir1*0.5f+endDir2*0.5f);
vertex4(primaryColor, c1, O, startDir1, secondaryColor,c2, end+endDir1,end,false);
vertex4(primaryColor,c1, O, startDir2, secondaryColor,c2, end+endDir2,end,false);
vertex4(primaryColor,c1, startDir1, startDir1+startDir2,secondaryColor,c2, end+endDir1+endDir2, end+endDir1,false);
vertex4(primaryColor,c1, startDir2, startDir1+startDir2,secondaryColor,c2, end+endDir1+endDir2, end+endDir2,false);
//vertex4n(O+end, endDir1+end,endDir2+endDir1+end,endDir2+end);
glEnd();
glDisable(GL_COLOR_MATERIAL);
glPopMatrix();
};
bool Mesh::intersectsRay(RayInfo* ri) {
if (triangles.count()==0) initTriangles();
for (int i = 0; i < triangles.count(); i++) {
if (triangles[i].intersectsRay(ri)) return true;
}
return false;
};
void Mesh::initTriangles() {
triangles.clear();
RaytraceTriangle::Vertex4(startBase, startBase+startDir1,endBase+endDir1,endBase, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]);
RaytraceTriangle::Vertex4(startBase, endBase,endBase+endDir2,startBase+startDir2, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]);
RaytraceTriangle::Vertex4(startBase+startDir1, startBase+startDir1+startDir2, endBase+endDir1+endDir2, endBase+endDir1, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]);
RaytraceTriangle::Vertex4(startBase+startDir2, endBase+endDir2, endBase+endDir1+endDir2, startBase+startDir1+startDir2, true,triangles,primaryColor[0],primaryColor[1],primaryColor[2],primaryColor[3]);
from = startBase;
to = startBase;
for (int i = 0; i < triangles.count(); i++) {
triangles[i].expandBoundingBox(from,to);
}
}
bool Mesh::intersectsAABB(Vector3f from2, Vector3f to2) {
if (triangles.count()==0) initTriangles();
return
(from.x() < to2.x()) && (to.x() > from2.x()) &&
(from.y() < to2.y()) && (to.y() > from2.y()) &&
(from.z() < to2.z()) && (to.z() > from2.z());
};
}
}
| mike10004/nbis-upstream | misc/nistmeshlab/meshlab/src/external/structuresynth/ssynth/SyntopiaCore/GLEngine/Mesh.cpp | C++ | unlicense | 4,001 |
package tasks;
import java.util.ArrayList;
import listeners.SuperMapListener;
import mapstuff.CartographersMap;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import plugin.SuperMap;
public class ConstantZoneCheck extends BukkitRunnable {
public ConstantZoneCheck(JavaPlugin plugin,SuperMapListener sml) {
this.plugin = plugin;
this.sml=sml;
playerList=new ArrayList<String>();
enabled=true;
dead=false;
}
private ConstantZoneCheck(JavaPlugin plugin, ArrayList<String> l){
this.plugin=plugin;
playerList=l;
}
public void disableMapCheck(){
enabled=false;
}
public void enableMapCheck(){
enabled=true;
}
public void run() {
if(!enabled){
cancel();
dead=true;
}
Player p;
for(String player:playerList){
p=Bukkit.getPlayer(player);
if(p.getItemInHand().hasItemMeta()&&p.getItemInHand().getType().equals(Material.MAP)){
if(p.getItemInHand().getItemMeta().getDisplayName().equals("Cartographer's Map")){
//this is where i do the zone checks
try{
CartographersMap cm=SuperMap.mapItemToCMap.get(Integer.valueOf(p.getItemInHand().getDurability()));
cm.mapCheck(p.getLocation(),p);
}catch(NullPointerException npe){
CartographersMap cm=new CartographersMap(p,p.getItemInHand(),sml);
cm.mapCheck(p.getLocation(), p);
}
}
}
}
}
public void addPlayer(Player p){
if(!playerList.contains(p.getDisplayName())){
playerList.add(p.getDisplayName());
}
}
public void removePlayer(Player p){
playerList.remove(p.getDisplayName());
}
public ConstantZoneCheck clone(){
ConstantZoneCheck newczc =new ConstantZoneCheck(plugin,playerList);
newczc.enabled=enabled;
newczc.dead=false;
return newczc;
}
public boolean isDead(){
return dead;
}
private final JavaPlugin plugin;
private SuperMapListener sml;
private ArrayList <String> playerList;
private boolean enabled,dead;
}
| GarrettCG/SuperMap | src/tasks/ConstantZoneCheck.java | Java | unlicense | 2,587 |
package crazypants.enderio.machine.farm;
import crazypants.enderio.config.Config;
import crazypants.enderio.machine.farm.farmers.*;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
public final class FarmersRegistry {
public static final PlantableFarmer DEFAULT_FARMER = new PlantableFarmer();
public static void addFarmers() {
addExtraUtilities();
addNatura();
addTiC();
addStillHungry();
addIC2();
addMFR();
addThaumcraft();
FarmersCommune.joinCommune(new StemFarmer(Blocks.reeds, new ItemStack(Items.reeds)));
FarmersCommune.joinCommune(new StemFarmer(Blocks.cactus, new ItemStack(Blocks.cactus)));
FarmersCommune.joinCommune(new TreeFarmer(Blocks.sapling, Blocks.log));
FarmersCommune.joinCommune(new TreeFarmer(Blocks.sapling, Blocks.log2));
FarmersCommune.joinCommune(new TreeFarmer(true,Blocks.red_mushroom, Blocks.red_mushroom_block));
FarmersCommune.joinCommune(new TreeFarmer(true,Blocks.brown_mushroom, Blocks.brown_mushroom_block));
//special case of plantables to get spacing correct
FarmersCommune.joinCommune(new MelonFarmer(Blocks.melon_stem, Blocks.melon_block, new ItemStack(Items.melon_seeds)));
FarmersCommune.joinCommune(new MelonFarmer(Blocks.pumpkin_stem, Blocks.pumpkin, new ItemStack(Items.pumpkin_seeds)));
//'BlockNetherWart' is not an IGrowable
FarmersCommune.joinCommune(new NetherWartFarmer());
//Cocoa is odd
FarmersCommune.joinCommune(new CocoaFarmer());
//Handles all 'vanilla' style crops
FarmersCommune.joinCommune(DEFAULT_FARMER);
}
public static void addPickable(String mod, String blockName, String itemName) {
Block cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, itemName);
if(seedItem != null) {
FarmersCommune.joinCommune(new PickableFarmer(cropBlock, new ItemStack(seedItem)));
}
}
}
public static CustomSeedFarmer addSeed(String mod, String blockName, String itemName, Block... extraFarmland) {
Block cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, itemName);
if(seedItem != null) {
CustomSeedFarmer farmer = new CustomSeedFarmer(cropBlock, new ItemStack(seedItem));
if(extraFarmland != null) {
for (Block farmland : extraFarmland) {
if(farmland != null) {
farmer.addTilledBlock(farmland);
}
}
}
FarmersCommune.joinCommune(farmer);
return farmer;
}
}
return null;
}
private static void addTiC() {
String mod = "TConstruct";
String blockName = "ore.berries.two";
Block cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, blockName);
if(seedItem != null) {
for (int i = 0; i < 2; i++) {
PickableFarmer farmer = new NaturaBerryFarmer(cropBlock, i, 12 + i, new ItemStack(seedItem, 1, 8 + i));
farmer.setRequiresFarmland(false);
FarmersCommune.joinCommune(farmer);
}
}
}
blockName = "ore.berries.one";
cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, blockName);
if(seedItem != null) {
for (int i = 0; i < 4; i++) {
PickableFarmer farmer = new NaturaBerryFarmer(cropBlock, i, 12 + i, new ItemStack(seedItem, 1, 8 + i));
farmer.setRequiresFarmland(false);
FarmersCommune.joinCommune(farmer);
}
}
}
}
private static void addNatura() {
String mod = "Natura";
String blockName = "N Crops";
Block cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
DEFAULT_FARMER.addHarvestExlude(cropBlock);
Item seedItem = GameRegistry.findItem(mod, "barley.seed");
if(seedItem != null) {
//barley
FarmersCommune.joinCommune(new CustomSeedFarmer(cropBlock, 3, new ItemStack(seedItem)));
// cotton
FarmersCommune.joinCommune(new PickableFarmer(cropBlock, 4, 8, new ItemStack(seedItem, 1, 1)));
}
}
blockName = "BerryBush";
cropBlock = GameRegistry.findBlock(mod, blockName);
if(cropBlock != null) {
Item seedItem = GameRegistry.findItem(mod, blockName);
if(seedItem != null) {
for (int i = 0; i < 4; i++) {
PickableFarmer farmer = new NaturaBerryFarmer(cropBlock, i, 12 + i, new ItemStack(seedItem, 1, 12 + i));
farmer.setRequiresFarmland(false);
FarmersCommune.joinCommune(farmer);
}
}
}
blockName = "florasapling";
Block saplingBlock = GameRegistry.findBlock(mod, blockName);
if(saplingBlock != null) {
FarmersCommune.joinCommune(new TreeFarmer(saplingBlock,
GameRegistry.findBlock(mod, "tree"),
GameRegistry.findBlock(mod, "willow"),
GameRegistry.findBlock(mod, "Dark Tree")));
}
blockName = "Rare Sapling";
saplingBlock = GameRegistry.findBlock(mod, blockName);
if(saplingBlock != null) {
FarmersCommune.joinCommune(new TreeFarmer(saplingBlock, GameRegistry.findBlock(mod, "Rare Tree")));
}
}
private static void addThaumcraft()
{
String mod = "Thaumcraft";
String manaBean = "ItemManaBean";
String manaPod = "blockManaPod";
Block block = GameRegistry.findBlock(mod,manaPod);
Item item = GameRegistry.findItem(mod,manaBean);
if (Config.farmManaBeansEnabled && block!=null && item!=null)
{
FarmersCommune.joinCommune(new ManaBeanFarmer(block, new ItemStack(item)));
}
}
private static void addMFR() {
String mod = "MineFactoryReloaded";
String blockName = "rubberwood.sapling";
Block saplingBlock = GameRegistry.findBlock(mod, blockName);
if(saplingBlock != null) {
FarmersCommune.joinCommune(new TreeFarmer(saplingBlock, GameRegistry.findBlock(mod, "rubberwood.log")));
}
}
private static void addIC2() {
RubberTreeFarmerIC2 rtf = new RubberTreeFarmerIC2();
if(rtf.isValid()) {
FarmersCommune.joinCommune(rtf);
}
}
private static void addStillHungry() {
String mod = "stillhungry";
addPickable(mod, "grapeBlock", "StillHungry_grapeSeed");
}
private static void addExtraUtilities() {
String mod = "ExtraUtilities";
String name = "plant/ender_lilly";
CustomSeedFarmer farmer = addSeed(mod, name, name, Blocks.end_stone, GameRegistry.findBlock(mod, "decorativeBlock1"));
if(farmer != null) {
farmer.setIgnoreGroundCanSustainCheck(true);
}
}
private FarmersRegistry() {
}
}
| Vexatos/EnderIO | src/main/java/crazypants/enderio/machine/farm/FarmersRegistry.java | Java | unlicense | 6,917 |
package com.ushaqi.zhuishushenqi.model;
import com.ushaqi.zhuishushenqi.api.ApiService;
import java.io.Serializable;
import java.util.Date;
public class UserInfo
implements Serializable
{
private static final long serialVersionUID = 2519451769850149545L;
private String _id;
private String avatar;
private UserInfo.BookListCount book_list_count;
private String code;
private int exp;
private String gender;
private boolean genderChanged;
private int lv;
private String nickname;
private Date nicknameUpdated;
private boolean ok;
private UserInfo.UserPostCount post_count;
private float rank;
private UserInfo.ThisWeekTasks this_week_tasks;
private UserInfo.UserTodayTask today_tasks;
public String getAvatar()
{
return this.avatar;
}
public UserInfo.BookListCount getBook_list_count()
{
return this.book_list_count;
}
public String getCode()
{
return this.code;
}
public int getExp()
{
return this.exp;
}
public String getGender()
{
return this.gender;
}
public String getId()
{
return this._id;
}
public int getLv()
{
return this.lv;
}
public String getNickname()
{
return this.nickname;
}
public Date getNicknameUpdated()
{
return this.nicknameUpdated;
}
public UserInfo.UserPostCount getPost_count()
{
return this.post_count;
}
public float getRank()
{
return this.rank;
}
public String getScaleAvatar(int paramInt)
{
if (paramInt == 2)
return ApiService.a + this.avatar + "-avatarl";
return ApiService.a + this.avatar + "-avatars";
}
public UserInfo.ThisWeekTasks getThis_week_tasks()
{
return this.this_week_tasks;
}
public UserInfo.UserTodayTask getToday_tasks()
{
return this.today_tasks;
}
public boolean isGenderChanged()
{
return this.genderChanged;
}
public boolean isOk()
{
return this.ok;
}
public void setAvatar(String paramString)
{
this.avatar = paramString;
}
public void setBook_list_count(UserInfo.BookListCount paramBookListCount)
{
this.book_list_count = paramBookListCount;
}
public void setCode(String paramString)
{
this.code = paramString;
}
public void setExp(int paramInt)
{
this.exp = paramInt;
}
public void setGender(String paramString)
{
this.gender = paramString;
}
public void setGenderChanged(boolean paramBoolean)
{
this.genderChanged = paramBoolean;
}
public void setId(String paramString)
{
this._id = paramString;
}
public void setLv(int paramInt)
{
this.lv = paramInt;
}
public void setNickname(String paramString)
{
this.nickname = paramString;
}
public void setNicknameUpdated(Date paramDate)
{
this.nicknameUpdated = paramDate;
}
public void setOk(boolean paramBoolean)
{
this.ok = paramBoolean;
}
public void setPost_count(UserInfo.UserPostCount paramUserPostCount)
{
this.post_count = paramUserPostCount;
}
public void setRank(float paramFloat)
{
this.rank = paramFloat;
}
public void setThis_week_tasks(UserInfo.ThisWeekTasks paramThisWeekTasks)
{
this.this_week_tasks = paramThisWeekTasks;
}
public void setToday_tasks(UserInfo.UserTodayTask paramUserTodayTask)
{
this.today_tasks = paramUserTodayTask;
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ushaqi.zhuishushenqi.model.UserInfo
* JD-Core Version: 0.6.0
*/ | clilystudio/NetBook | allsrc/com/ushaqi/zhuishushenqi/model/UserInfo.java | Java | unlicense | 3,520 |
#include "GameTextures.h"
#include <iostream>
GameTextures::GameTextures()
{
if (!_image.loadFromFile("assets/DungeonCrawl_ProjectUtumnoTileset.png"))
{
std::cout << "Error loading texture." << std::endl;
}
}
std::shared_ptr<sf::Texture> GameTextures::getTexture(std::string name, int x, int y)
{
std::cout << "Loading " << name << std::endl;
auto texture = _textures.find(name);
if (texture == _textures.end())
{
_textures[name]=getTexture(x, y);
}
return _textures[name];
}
std::shared_ptr<sf::Texture> GameTextures::getTexture(int x, int y)
{
auto texture = std::make_shared<sf::Texture>();
texture->loadFromImage(_image, sf::IntRect(x*32, y*32, 32, 32));
texture->setRepeated(true);
return texture;
}
| UAF-CS372-Spring-2015/the-platformer | src/GameTextures.cpp | C++ | unlicense | 744 |
a = 'a|b|c|d|e'
b = a.split('|', 3)
print(b)
"""<
['a', 'b', 'c', 'd|e']
>"""
| pythonpatterns/patterns | p0081.py | Python | unlicense | 81 |
package Chap05;
/*
* ÀÛ¼ºÀÏÀÚ:2017_03_09
* ÀÛ¼ºÀÚ:±æ°æ¿Ï
* ThreeArrays ÀÌ¿ë
* ¿¹Á¦ 5-43
*/
public class StaticInitalizerExample2 {
public static void main(String[] args){
for(int cnt=0;cnt<10;cnt++){
System.out.println(ThreeArrays.arr3[cnt]);
}
}
}
| WALDOISCOMING/Java_Study | Java_BP/src/Chap05/StaticInitalizerExample2.java | Java | unlicense | 279 |
//==============================================================================
#include <hgeresource.h>
#include <hgefont.h>
#include <hgesprite.h>
#include <sqlite3.h>
#include <Database.h>
#include <Query.h>
#include <score.hpp>
#include <engine.hpp>
//------------------------------------------------------------------------------
Score::Score( Engine * engine )
:
Context( engine ),
m_dark( 0 ),
m_calculate( false ),
m_lives( 0 ),
m_urchins( 0 ),
m_coins( 0 ),
m_time( 0 ),
m_timer( 0.0f ),
m_buffer( 0 ),
m_high_score()
{
}
//------------------------------------------------------------------------------
Score::~Score()
{
}
//------------------------------------------------------------------------------
// public:
//------------------------------------------------------------------------------
void
Score::init()
{
hgeResourceManager * rm( m_engine->getResourceManager() );
m_dark = new hgeSprite( 0, 0, 0, 1, 1 );
m_calculate = false;
HMUSIC music = m_engine->getResourceManager()->GetMusic( "score" );
m_engine->getHGE()->Music_Play( music, true, 100, 0, 0 );
_updateScore();
}
//------------------------------------------------------------------------------
void
Score::fini()
{
m_engine->getHGE()->Channel_StopAll();
delete m_dark;
m_dark = 0;
}
//------------------------------------------------------------------------------
bool
Score::update( float dt )
{
HGE * hge( m_engine->getHGE() );
hgeResourceManager * rm( m_engine->getResourceManager() );
hgeParticleManager * pm( m_engine->getParticleManager() );
if ( hge->Input_GetKey() != 0 && ! m_engine->isPaused() && ! m_calculate )
{
m_engine->switchContext( STATE_MENU );
}
if ( m_engine->isPaused() )
{
return false;
}
if ( m_calculate )
{
m_timer += dt;
if ( static_cast< int >( m_timer * 1000.0f ) % 2 == 0 )
{
if ( m_buffer > 0 )
{
m_buffer -= 1;
m_coins += 1;
float x( hge->Random_Float( 550.0f, 560.0f ) );
float y( hge->Random_Float( 268.0f, 278.0f ) );
hgeParticleSystem * particle =
pm->SpawnPS(& rm->GetParticleSystem("collect")->info, x, y);
if ( particle != 0 )
{
particle->SetScale( 1.0f );
}
hge->Effect_Play( rm->GetEffect( "bounce" ) );
}
else if ( m_lives > 0 )
{
m_lives -= 1;
m_buffer += 100;
hge->Effect_Play( rm->GetEffect( "collect" ) );
}
else if ( m_urchins > 0 )
{
m_urchins -= 1;
m_buffer += 10;
hge->Effect_Play( rm->GetEffect( "collect" ) );
}
else if ( m_time > 0 )
{
m_time -= 7;
if ( m_time < 0 )
{
m_time = 0;
}
m_buffer += 1;
hge->Effect_Play( rm->GetEffect( "collect" ) );
}
}
if ( m_buffer == 0 && m_lives == 0 && m_urchins == 0 && m_time == 0 )
{
int character( hge->Input_GetChar() );
if ( character != 0 )
{
if ( ( character == ' ' ||
character == '.' ||
character == '!' ||
character == '?' ||
( character >= '0' && character <= '9' ) ||
( character >= 'a' && character <= 'z' ) ||
( character >= 'A' && character <= 'Z' ) ) &&
m_name.size() <= 15 )
{
m_name.push_back( character );
}
}
if ( hge->Input_KeyDown( HGEK_BACKSPACE ) ||
hge->Input_KeyDown( HGEK_DELETE ) )
{
if ( m_name.size() > 0 )
{
m_name.erase( m_name.end() - 1 );
}
}
if ( hge->Input_KeyDown( HGEK_ENTER ) )
{
if ( m_name.size() == 0 )
{
m_name = "Anonymous";
}
Database db( "world.db3" );
Query q( db );
char query[1024];
sprintf_s( query, 1024, "INSERT INTO score(name, coins) "
"VALUES('%s',%d)", m_name.c_str(), m_coins );
q.execute( query );
_updateScore();
m_calculate = false;
}
}
}
else if ( dt > 0.0f && hge->Random_Float( 0.0f, 1.0f ) < 0.07f )
{
float x( hge->Random_Float( 0.0f, 800.0f ) );
float y( hge->Random_Float( 0.0f, 600.0f ) );
hgeParticleSystem * particle =
pm->SpawnPS( & rm->GetParticleSystem( "explode" )->info, x, y );
particle->SetScale( hge->Random_Float( 0.5f, 2.0f ) );
}
return false;
}
//------------------------------------------------------------------------------
void
Score::render()
{
hgeResourceManager * rm( m_engine->getResourceManager() );
if ( ! m_calculate )
{
m_engine->getParticleManager()->Render();
}
m_dark->SetColor( 0xCC000309 );
m_dark->RenderStretch( 100.0f, 50.0f, 700.0f, 550.0f );
hgeFont * font( rm->GetFont( "menu" ) );
if ( m_calculate )
{
font->printf( 400.0f, 80.0f, HGETEXT_CENTER, "G A M E O V E R" );
font->printf( 200.0f, 200.0f, HGETEXT_LEFT, "x %d", m_lives );
font->printf( 200.0f, 260.0f, HGETEXT_LEFT, "x %02d/99", m_urchins );
font->printf( 200.0f, 320.0f, HGETEXT_LEFT, "%03d", m_time );
font->printf( 580.0f, 260.0f, HGETEXT_LEFT, "x %04d", m_coins );
m_engine->getParticleManager()->Render();
rm->GetSprite( "ship" )->Render( 175.0f, 213.0f );
rm->GetSprite( "coin")->SetColor( 0xFFFFFFFF );
rm->GetSprite( "coin" )->Render( 555.0f, 273.0f );
rm->GetSprite( "urchin_green" )->Render( 175.0f, 273.0f );
if ( m_buffer == 0 && m_lives == 0 && m_urchins == 0 && m_time == 0 )
{
font->printf( 400.0f, 400.0f, HGETEXT_CENTER,
"%s", m_name.c_str() );
font->printf( 400.0f, 500.0f, HGETEXT_CENTER,
"(well done, you)" );
if ( static_cast<int>( m_timer * 2.0f ) % 2 != 0 )
{
float width = font->GetStringWidth( m_name.c_str() );
m_dark->SetColor( 0xFFFFFFFF );
m_dark->RenderStretch( 400.0f + width * 0.5f, 425.0f,
400.0f + width * 0.5f + 16.0f, 427.0f );
}
}
}
else
{
font->printf( 400.0f, 80.0f, HGETEXT_CENTER,
"H I G H S C O R E T A B L E" );
int i = 0;
std::vector< std::pair< std::string, int > >::iterator j;
for ( j = m_high_score.begin(); j != m_high_score.end(); ++j )
{
i += 1;
font->printf( 200.0f, 120.0f + i * 30.0f, HGETEXT_LEFT,
"(%d)", i );
font->printf( 400.0f, 120.0f + i * 30.0f, HGETEXT_CENTER,
"%s", j->first.c_str() );
font->printf( 600.0f, 120.0f + i * 30.0f, HGETEXT_RIGHT,
"%04d", j->second );
}
font->printf( 400.0f, 500.0f, HGETEXT_CENTER,
"(but you're all winners, really)" );
}
}
//------------------------------------------------------------------------------
void
Score::calculateScore( int lives, int urchins, int coins, int time )
{
m_timer = 0.0f;
m_buffer = 0;
m_calculate = true;
m_lives = lives;
m_urchins = urchins;
m_coins = coins;
m_time = time;
if ( lives == 0 || urchins == 0 )
{
m_time = 0;
}
m_name.clear();
if ( m_lives == 0 && m_time == 0 && m_coins == 0 && m_urchins == 0 )
{
m_calculate = false;
}
}
//------------------------------------------------------------------------------
// private:
//------------------------------------------------------------------------------
void
Score::_updateScore()
{
m_high_score.clear();
Database db( "world.db3" );
Query q( db );
q.get_result("SELECT coins, name FROM score ORDER BY coins DESC LIMIT 10");
while ( q.fetch_row() )
{
std::pair< std::string, int > pair( q.getstr(), q.getval() );
m_high_score.push_back( pair );
}
q.free_result();
}
| jasonhutchens/thrust_harder | score.cpp | C++ | unlicense | 9,032 |
/*
* SmartGWT Mobile
* Copyright 2008 and beyond, Isomorphic Software, Inc.
*
* SmartGWT Mobile is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3
* as published by the Free Software Foundation. SmartGWT Mobile is also
* available under typical commercial license terms - see
* http://smartclient.com/license
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
/**
*
*/
package com.smartgwt.mobile.client.widgets.tab;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.smartgwt.mobile.SGWTInternal;
import com.smartgwt.mobile.client.core.Function;
import com.smartgwt.mobile.client.data.Record;
import com.smartgwt.mobile.client.data.RecordList;
import com.smartgwt.mobile.client.internal.EventHandler;
import com.smartgwt.mobile.client.internal.theme.TabSetCssResourceBase;
import com.smartgwt.mobile.client.internal.util.AnimationUtil;
import com.smartgwt.mobile.client.internal.widgets.tab.TabSetItem;
import com.smartgwt.mobile.client.theme.ThemeResources;
import com.smartgwt.mobile.client.types.SelectionStyle;
import com.smartgwt.mobile.client.types.TableMode;
import com.smartgwt.mobile.client.widgets.Canvas;
import com.smartgwt.mobile.client.widgets.ContainerFeatures;
import com.smartgwt.mobile.client.widgets.Panel;
import com.smartgwt.mobile.client.widgets.PanelContainer;
import com.smartgwt.mobile.client.widgets.ScrollablePanel;
import com.smartgwt.mobile.client.widgets.events.DropEvent;
import com.smartgwt.mobile.client.widgets.events.DropHandler;
import com.smartgwt.mobile.client.widgets.events.HasDropHandlers;
import com.smartgwt.mobile.client.widgets.events.HasPanelHideHandlers;
import com.smartgwt.mobile.client.widgets.events.HasPanelShowHandlers;
import com.smartgwt.mobile.client.widgets.events.PanelHideEvent;
import com.smartgwt.mobile.client.widgets.events.PanelHideHandler;
import com.smartgwt.mobile.client.widgets.events.PanelShowEvent;
import com.smartgwt.mobile.client.widgets.events.PanelShowHandler;
import com.smartgwt.mobile.client.widgets.grid.CellFormatter;
import com.smartgwt.mobile.client.widgets.grid.ListGridField;
import com.smartgwt.mobile.client.widgets.icons.IconResources;
import com.smartgwt.mobile.client.widgets.layout.HLayout;
import com.smartgwt.mobile.client.widgets.layout.Layout;
import com.smartgwt.mobile.client.widgets.layout.NavStack;
import com.smartgwt.mobile.client.widgets.tab.events.HasTabDeselectedHandlers;
import com.smartgwt.mobile.client.widgets.tab.events.HasTabSelectedHandlers;
import com.smartgwt.mobile.client.widgets.tab.events.TabDeselectedEvent;
import com.smartgwt.mobile.client.widgets.tab.events.TabDeselectedHandler;
import com.smartgwt.mobile.client.widgets.tab.events.TabSelectedEvent;
import com.smartgwt.mobile.client.widgets.tab.events.TabSelectedHandler;
import com.smartgwt.mobile.client.widgets.tableview.TableView;
import com.smartgwt.mobile.client.widgets.tableview.events.RecordNavigationClickEvent;
import com.smartgwt.mobile.client.widgets.tableview.events.RecordNavigationClickHandler;
public class TabSet extends Layout implements PanelContainer, HasTabSelectedHandlers, HasTabDeselectedHandlers, HasPanelShowHandlers, HasPanelHideHandlers, HasDropHandlers {
@SGWTInternal
public static final TabSetCssResourceBase _CSS = ThemeResources.INSTANCE.tabsCSS();
private static final int NO_TAB_SELECTED = -1,
MORE_TAB_SELECTED = -2;
private static class More extends NavStack {
private static final String ID_PROPERTY = "_id",
ICON_PROPERTY = "icon",
TAB_PROPERTY = "tab";
private static final ListGridField TITLE_FIELD = new ListGridField("-title") {{
setCellFormatter(new CellFormatter() {
@Override
public String format(Object value, Record record, int rowNum, int fieldNum) {
final Tab tab = (Tab)record.getAttributeAsObject(TAB_PROPERTY);
if (tab.getTitle() != null) return tab.getTitle();
final Canvas pane = tab.getPane();
if (pane != null) return pane.getTitle();
return null;
}
});
}};
private static int nextMoreRecordID = 1;
private static Record createMoreRecord(Tab tab) {
assert tab != null;
final Canvas pane = tab.getPane();
final Record record = new Record();
record.setAttribute(ID_PROPERTY, Integer.toString(nextMoreRecordID++));
Object icon = tab.getIcon();
if (icon == null && pane instanceof Panel) {
icon = ((Panel)pane).getIcon();
}
record.setAttribute(ICON_PROPERTY, icon);
record.setAttribute(TAB_PROPERTY, tab);
return record;
}
private ScrollablePanel morePanel;
private RecordList recordList;
private TableView tableView;
private HandlerRegistration recordNavigationClickRegistration;
//TileLayout tileLayout = null;
public More() {
super("More", IconResources.INSTANCE.more());
morePanel = new ScrollablePanel("More", IconResources.INSTANCE.more());
morePanel.getElement().getStyle().setBackgroundColor("#f7f7f7");
recordList = new RecordList();
tableView = new TableView();
tableView.setTitleField(TITLE_FIELD.getName());
tableView.setShowNavigation(true);
tableView.setSelectionType(SelectionStyle.SINGLE);
tableView.setParentNavStack(this);
tableView.setTableMode(TableMode.PLAIN);
tableView.setShowIcons(true);
recordNavigationClickRegistration = tableView.addRecordNavigationClickHandler(new RecordNavigationClickHandler() {
@Override
public void onRecordNavigationClick(RecordNavigationClickEvent event) {
final Record record = event.getRecord();
final Tab tab = (Tab)record.getAttributeAsObject(TAB_PROPERTY);
final TabSet tabSet = tab.getTabSet();
assert tabSet != null;
tabSet.swapTabs(recordList.indexOf(record) + tabSet.moreTabCount, tabSet.moreTabCount - 1);
tabSet.selectTab(tabSet.moreTabCount - 1, true);
}
});
tableView.setFields(TITLE_FIELD);
tableView.setData(recordList);
morePanel.addMember(tableView);
push(morePanel);
}
@Override
public void destroy() {
if (recordNavigationClickRegistration != null) {
recordNavigationClickRegistration.removeHandler();
recordNavigationClickRegistration = null;
}
super.destroy();
}
public final boolean containsNoTabs() {
return recordList.isEmpty();
}
public void addTab(Tab tab, int position) {
if (tab == null) throw new NullPointerException("`tab' cannot be null.");
final Record moreRecord = createMoreRecord(tab);
recordList.add(position, moreRecord);
}
public Tab removeTab(int position) {
return (Tab)recordList.remove(position).getAttributeAsObject(TAB_PROPERTY);
}
public void setTab(int position, Tab tab) {
if (tab == null) throw new NullPointerException("`tab' cannot be null.");
recordList.set(position, createMoreRecord(tab));
}
public void swapTabs(int i, int j) {
recordList.swap(i, j);
}
}
private final List<Tab> tabs = new ArrayList<Tab>();
// Tab bar to show tab widgets
private HLayout tabBar = new HLayout();
private int moreTabCount = 4;
private boolean showMoreTab = true;
private More more;
private Tab moreTab;
// paneContainer panel to hold tab panes
private Layout paneContainer;
//private final HashMap<Element, Tab> draggableMap = new HashMap<Element, Tab>();
//private Canvas draggable, droppable;
// Currently selected tab
private int selectedTabIndex = NO_TAB_SELECTED;
private transient Timer clearHideTabBarDuringFocusTimer;
public TabSet() {
getElement().addClassName(_CSS.tabSetClass());
setWidth("100%");
setHeight("100%");
paneContainer = new Layout();
paneContainer._setClassName(_CSS.tabPaneClass(), false);
addMember(paneContainer);
tabBar._setClassName(_CSS.tabBarClass(), false);
tabBar._setClassName("sc-layout-box-pack-center", false);
addMember(tabBar);
//sinkEvents(Event.ONCLICK | Event.ONMOUSEWHEEL | Event.GESTUREEVENTS | Event.TOUCHEVENTS | Event.MOUSEEVENTS | Event.FOCUSEVENTS | Event.KEYEVENTS);
_sinkFocusInEvent();
_sinkFocusOutEvent();
}
@SGWTInternal
public final Tab _getMoreTab() {
return moreTab;
}
public final Tab[] getTabs() {
return tabs.toArray(new Tab[tabs.size()]);
}
/**
* Sets the pane of the given tab.
*
* @param tab
* @param pane
*/
public void updateTab(Tab tab, Canvas pane) {
if (tab == null) throw new NullPointerException("`tab' cannot be null.");
final TabSet otherTabSet = tab.getTabSet();
assert otherTabSet != null : "`tab' is not in any TabSet. In particular, it is not in this TabSet.";
if (otherTabSet == null) {
tab._setPane(pane);
} else {
assert this == otherTabSet : "`tab' is in a different TabSet.";
if (this != otherTabSet) {
assert otherTabSet != null;
otherTabSet.updateTab(tab, pane);
} else {
final int tabPosition = getTabPosition(tab);
if (tabPosition < 0) throw new IllegalArgumentException("`tab' is not in this TabSet.");
updateTab(tabPosition, pane);
}
}
}
public void updateTab(int index, Canvas pane) throws IndexOutOfBoundsException {
if (index < 0 || tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index);
final Tab tab = tabs.get(index);
assert tab != null;
final Canvas oldPane = tab.getPane();
if (oldPane != pane) {
if (oldPane != null) paneContainer.removeMember(oldPane);
if (pane != null) {
paneContainer.addMember(pane);
if (selectedTabIndex != index) paneContainer.hideMember(pane);
}
tab._setPane(pane);
}
}
/*******************************************************
* Event handler registrations
******************************************************/
/**
* Add a tabSelected handler.
* <p/>
* Notification fired when a tab is selected.
*
* @param handler the tabSelectedHandler
* @return {@link HandlerRegistration} used to remove this handler
*/
@Override
public HandlerRegistration addTabSelectedHandler(TabSelectedHandler handler) {
return addHandler(handler, TabSelectedEvent.getType());
}
@Override
public HandlerRegistration addDropHandler(DropHandler handler) {
return addHandler(handler, DropEvent.getType());
}
/**
* Add a tabDeselected handler.
* <p/>
* Notification fired when a tab is unselected.
*
* @param handler the tabDeselectedHandler
* @return {@link HandlerRegistration} used to remove this handler
*/
@Override
public HandlerRegistration addTabDeselectedHandler(TabDeselectedHandler handler) {
return addHandler(handler, TabDeselectedEvent.getType());
}
/**
* ****************************************************
* Settings
* ****************************************************
*/
@SuppressWarnings("unused")
private Tab findTarget(Event event) {
Tab tab = null;
final int Y = (event.getTouches() != null && event.getTouches().length() > 0) ? event.getTouches().get(0).getClientY(): event.getClientY();
final int X = (event.getTouches() != null && event.getTouches().length() > 0) ? event.getTouches().get(0).getClientX(): event.getClientX();
if (Y >= tabBar.getAbsoluteTop() && !tabs.isEmpty()) {
final int width = tabs.get(0)._getTabSetItem().getElement().getOffsetWidth();
final int index = X / width;
if (0 <= index &&
((showMoreTab && index < moreTabCount) ||
(!showMoreTab && index < tabs.size())))
{
tab = tabs.get(index);
}
}
return tab;
}
@Override
public void onBrowserEvent(Event event) {
/*switch(event.getTypeInt()) {
case Event.ONMOUSEOVER:
if (!touched) {
if (draggable != null) {
final Tab tab = findTarget(event);
if (tab != null) {
droppable = tab._getTabSetItem();
droppable.fireEvent(new DropOverEvent());
} else if (droppable != null) {
droppable.fireEvent(new DropOutEvent());
droppable = null;
}
}
}
break;
case Event.ONTOUCHMOVE:
case Event.ONGESTURECHANGE:
if (draggable != null) {
final Tab tab = findTarget(event);
if (tab != null) {
droppable = tab._getTabSetItem();
droppable.fireEvent(new DropOverEvent());
} else if (droppable != null) {
droppable.fireEvent(new DropOutEvent());
droppable = null;
}
}
super.onBrowserEvent(event);
break;
case Event.ONMOUSEUP:
if (!touched) {
super.onBrowserEvent(event);
if (more != null && more.tileLayout != null) {
more.tileLayout.onEnd(event);
}
if (draggable != null && droppable != null) {
droppable.fireEvent(new DropEvent(draggable));
droppable = null;
}
}
break;
case Event.ONTOUCHEND:
case Event.ONGESTUREEND:
super.onBrowserEvent(event);
if (draggable != null && droppable != null) {
droppable.fireEvent(new DropEvent(draggable));
droppable = null;
}
break;
default:
super.onBrowserEvent(event);
break;
}*/
if (Canvas._getHideTabBarDuringKeyboardFocus()) {
// On Android devices, SGWT.mobile uses a technique similar to jQuery Mobile's hideDuringFocus
// setting to fix the issue that the tabBar unnecessarily takes up a portion of the screen
// when the soft keyboard is open. To work around this problem, when certain elements receive
// keyboard focus, we add a special class to the TabSet element that hides the tabBar.
// This special class is removed on focusout.
//
// One important consideration is that the user can move between input elements (such as
// by using the Next/Previous buttons or by tapping on a different input) and the soft
// keyboard will remain on screen. We don't want to show the tabBar only to hide it again.
// See: JQM Issue 4724 - Moving through form in Mobile Safari with "Next" and "Previous"
// system controls causes fixed position, tap-toggle false Header to reveal itself
// https://github.com/jquery/jquery-mobile/issues/4724
final String eventType = event.getType();
if ("focusin".equals(eventType)) {
if (EventHandler.couldShowSoftKeyboard(event)) {
if (clearHideTabBarDuringFocusTimer != null) {
clearHideTabBarDuringFocusTimer.cancel();
clearHideTabBarDuringFocusTimer = null;
}
getElement().addClassName(_CSS.hideTabBarDuringFocusClass());
}
} else if ("focusout".equals(eventType)) {
// If the related event target cannot result in the soft keyboard showing, then
// there is no need to wait; we can remove the hideTabBarDuringFocus class now.
if (event.getRelatedEventTarget() != null && !EventHandler.couldShowSoftKeyboard(event)) {
if (clearHideTabBarDuringFocusTimer != null) {
clearHideTabBarDuringFocusTimer.cancel();
clearHideTabBarDuringFocusTimer = null;
}
getElement().removeClassName(_CSS.hideTabBarDuringFocusClass());
// We use a timeout to clear the special CSS class because on Android 4.0.3 (possibly
// affects other versions as well), there is an issue where tapping in the 48px above
// the soft keyboard (where the tabBar would be) dismisses the soft keyboard.
} else {
clearHideTabBarDuringFocusTimer = new Timer() {
@Override
public void run() {
clearHideTabBarDuringFocusTimer = null;
getElement().removeClassName(_CSS.hideTabBarDuringFocusClass());
}
};
clearHideTabBarDuringFocusTimer.schedule(1);
}
}
}
}
@Override
public void onLoad() {
super.onLoad();
// There is a very strange `TabSet' issue on iOS 6 Mobile Safari, but which does not appear
// in iOS 5.0 or 5.1. For some reason, if the tabSelectedClass() is added to a `TabSetItem',
// but the selected class is removed before the `TabSetItem' element is added to the document
// later on, then the SGWT.mobile app will fail to load. However, if Web Inspector is attached,
// then the app runs fine.
//
// This issue affects Showcase. In Showcase, the "Overview" tab is first selected when
// it is added to the app's `TabSet' instance. It is then deselected when the "Widgets"
// tab is programmatically selected.
// To see the issue, comment out the check `if (Canvas._isIOSMin6_0() && !isAttached()) return;' in TabSetItem.setSelected(), then
// compile & run Showcase in iOS 6 Mobile Safari.
if (Canvas._isIOSMin6_0() && selectedTabIndex > 0) {
tabs.get(selectedTabIndex)._getTabSetItem().setSelected(true);
}
}
/*******************************************************
* Add/Remove tabs
******************************************************/
@SGWTInternal
public void _onTabDrop(TabSetItem tabSetItem, DropEvent event) {
/*Object source = event.getSource();
if(source instanceof Tab) {
tab.getElement().getStyle().setProperty("backgroundImage", "none");
TileLayout.Tile draggable = (TileLayout.Tile)event.getData();
Record record = TabSet.this.more.recordList.find("title",draggable.getTitle());
if(record != null) {
Panel newPanel = (Panel)record.get("panel");
final int currentPosition = tabBar.getMemberNumber(tab);
TabSet.this.replacePanel(currentPosition, newPanel);
TileLayout tileLayout = (TileLayout)more.top();
tileLayout.replaceTile(draggable, tab.getTitle(), tab.getIcon());
more.recordList.remove(record);
// final Panel oldPanel = tab.getPane() instanceof NavStack ? ((NavStack)tab.getPane()).top() : (Panel)tab.getPane();
final Panel oldPanel = (Panel)tab.getPane();
oldPanel.getElement().getStyle().clearDisplay();
final Record finalRecord = record;
more.recordList.add(0,new Record() {{put("_id", finalRecord.getAttribute("_id")); put("title", tab.getTitle()); put("icon", tab.getIcon());put("panel", oldPanel);}});
more.tableView.setData(more.recordList);
}
}*/
}
private void swapTabs(int i, int j) {
final int numTabs = tabs.size();
assert 0 <= i && i < numTabs;
assert 0 <= j && j < numTabs;
if (i == j) return;
// Make sure that i < j.
if (!(i < j)) {
final int tmp = i;
i = j;
j = tmp;
}
assert i < j;
final Tab tabI = tabs.get(i), tabJ = tabs.get(j);
assert tabI != null && tabJ != null;
final TabSetItem tabSetItemI = tabI._getTabSetItem(),
tabSetItemJ = tabJ._getTabSetItem();
final Canvas paneI = tabI.getPane(), paneJ = tabJ.getPane();
tabs.set(i, tabJ);
tabs.set(j, tabI);
if (showMoreTab && numTabs > moreTabCount) {
assert more != null;
if (j >= moreTabCount) {
if (i >= moreTabCount) {
// Both tabs are in the More NavStack.
assert i != selectedTabIndex : "The tab at index " + i + " is supposed to be selected, but it is still in the More NavStack.";
assert j != selectedTabIndex : "The tab at index " + j + " is supposed to be selected, but it is still in the More NavStack.";
more.swapTabs(i - moreTabCount, j - moreTabCount);
} else {
// The Tab at `j' is in the More NavStack, but the Tab at `i' is not.
assert j != selectedTabIndex : "The tab at index " + j + " is supposed to be selected, but it is still in the More NavStack.";
if (i == selectedTabIndex) {
tabSetItemI.setSelected(false);
if (paneI != null) paneContainer.hideMember(paneI);
}
tabBar.removeMember(tabSetItemI);
more.setTab(j - moreTabCount, tabI);
tabBar.addMember(tabSetItemJ, i);
if (i == selectedTabIndex) {
tabSetItemJ.setSelected(true);
if (paneJ != null) paneContainer.showMember(paneJ);
TabDeselectedEvent._fire(this, tabI, j, tabJ);
TabSelectedEvent._fire(this, tabJ, i);
} else {
if (paneJ != null) paneContainer.hideMember(paneJ);
}
}
} else {
// Neither tab is in the More NavStack.
assert selectedTabIndex != MORE_TAB_SELECTED;
tabBar.removeMember(tabSetItemI);
// TODO Don't remove the panes to save on calls to onLoad(), onUnload(), onAttach(), and onDetach().
if (paneI != null && paneContainer.hasMember(paneI)) paneContainer.removeMember(paneI);
tabBar.removeMember(tabSetItemJ);
if (paneJ != null && paneContainer.hasMember(paneJ)) paneContainer.removeMember(paneJ);
tabSetItemJ.setSelected(i == selectedTabIndex);
tabBar.addMember(tabSetItemJ, i);
if (paneJ != null) {
paneContainer.addMember(paneJ);
if (i != selectedTabIndex) paneContainer.hideMember(paneJ);
}
tabSetItemI.setSelected(j == selectedTabIndex);
tabBar.addMember(tabSetItemI, j);
if (paneI != null) {
paneContainer.addMember(paneI);
if (j != selectedTabIndex) paneContainer.hideMember(paneI);
}
if (i == selectedTabIndex) {
selectedTabIndex = j;
TabDeselectedEvent._fire(this, tabI, j, tabJ);
TabSelectedEvent._fire(this, tabJ, i);
} else if (j == selectedTabIndex) {
selectedTabIndex = i;
TabDeselectedEvent._fire(this, tabJ, i, tabI);
TabSelectedEvent._fire(this, tabI, j);
}
}
}
}
/**
* Creates a {@link com.smartgwt.mobile.client.widgets.tab.Tab} and adds it to the end.
*
* <p>This is equivalent to:
* <pre>
* final Tab tab = new Tab(panel.getTitle(), panel.getIcon());
* tabSet.addTab(tab);
* </pre>
*
* @param panel the panel to add.
* @return the automatically created <code>Tab</code>.
*/
public Tab addPanel(Panel panel) {
final Tab tab = new Tab(panel.getTitle(), panel.getIcon());
tab.setPane(panel);
addTab(tab);
return tab;
}
/**
* Add a tab to the end.
*
* @param tab the tab to add.
*/
public void addTab(Tab tab) {
addTab(tab, tabs.size());
}
/**
* Add a tab at the given position.
*
* @param tab the tab to add.
* @param position the index where the tab should be added. It is clamped within range
* (0 through {@link #getNumTabs()}, inclusive) if out of bounds.
*/
public void addTab(Tab tab, int position) {
if (tab == null) throw new NullPointerException("`tab' cannot be null.");
assert tab != moreTab;
// Clamp `position' within range.
position = Math.max(0, Math.min(position, tabs.size()));
// Remove the tab if it exists.
final int existingIndex = getTabPosition(tab);
if (existingIndex >= 0) {
// If the tab is being added in the exact same place, then return early.
if (existingIndex == position) return;
removeTab(existingIndex);
if (existingIndex < position) --position;
}
final int currentNumTabs = tabs.size();
tabs.add(position, tab);
final TabSetItem tabSetItem = tab._ensureTabSetItem(this);
assert tab.getTabSet() == this;
// Add the tab's pane to `paneContainer'.
final Canvas pane = tab.getPane();
if (pane != null) {
paneContainer.addMember(pane);
paneContainer.hideMember(pane);
}
if (currentNumTabs + 1 > moreTabCount && showMoreTab) {
if (more == null) {
more = new More();
assert moreTab == null;
moreTab = new Tab(more.getTitle(), more.getIcon());
moreTab.setPane(more);
// The TabSetItem of `moreTab' and its pane (`more') are added to `tabBar' and
// `paneContainer', respectively, but we don't want to add `moreTab' to `tabs';
// we don't want to treat the More tab like a tab that was explicitly added.
tabBar.addMember(moreTab._ensureTabSetItem(this), moreTabCount);
paneContainer.addMember(more);
paneContainer.hideMember(more);
}
if (position >= moreTabCount) {
// Add to the More.
more.addTab(tab, position - moreTabCount);
} else {
// Add the TabSetItem to `tabBar'.
tabBar.addMember(tabSetItem, position);
// That pushes one of the visible tabs into More.
final Tab otherTab = tabs.get(moreTabCount);
final TabSetItem otherTabSetItem = otherTab._getTabSetItem();
if (moreTabCount == selectedTabIndex) {
otherTabSetItem.setSelected(false);
selectedTabIndex = NO_TAB_SELECTED;
}
tabBar.removeMember(otherTabSetItem);
final Canvas otherPane = otherTab.getPane();
if (otherPane != null) paneContainer.removeMember(otherPane);
more.addTab(otherTab, 0);
}
} else {
// Add the TabSetItem to `tabBar'.
tabBar.addMember(tabSetItem, position);
}
if (selectedTabIndex == NO_TAB_SELECTED) {
selectTab(position);
}
}
/**
* Remove a tab.
*
* @param tab to remove
*/
public void removeTab(Tab tab) {
assert tab == null || tab != moreTab;
int index = tabs.indexOf(tab);
if (index >= 0) {
removeTab(index);
}
}
/**
* Remove a tab at the specified index.
*
* @param position the index of the tab to remove
*/
public void removeTab(int position) {
final int currentNumTabs = tabs.size();
if (0 <= position && position < currentNumTabs) {
final Tab tab = tabs.get(position);
assert tab != null;
assert tab != moreTab;
tabs.remove(position);
final TabSetItem tabSetItem = tab._getTabSetItem();
if (!showMoreTab || position < moreTabCount) {
tabBar.removeMember(tabSetItem);
if (showMoreTab && currentNumTabs - 1 >= moreTabCount) {
// Move a tab from More to the tab bar.
final Tab firstMoreTab = more.removeTab(0);
final Tab otherTab = tabs.get(moreTabCount - 1);
assert firstMoreTab == otherTab;
final TabSetItem otherTabSetItem = otherTab._getTabSetItem();
tabBar.addMember(otherTabSetItem, moreTabCount - 1);
}
} else {
assert more != null;
more.removeTab(position - moreTabCount);
}
if (showMoreTab && currentNumTabs - 1 == moreTabCount) {
// The More tab is no longer needed. Remove & destroy it.
assert more.containsNoTabs();
final TabSetItem moreTabSetItem = moreTab._getTabSetItem();
tabBar.removeMember(moreTabSetItem);
assert paneContainer.hasMember(more);
paneContainer.removeMember(more);
if (selectedTabIndex == MORE_TAB_SELECTED) {
assert more != null && moreTab.getPane() == more;
selectedTabIndex = NO_TAB_SELECTED;
}
moreTab._destroyTabSetItem();
moreTab._setTabSet(null);
moreTab.setPane(null);
moreTab = null;
more.destroy();
more = null;
}
final Canvas pane = tab.getPane();
if (pane != null) paneContainer.removeMember(pane);
tab._setTabSet(null);
if (position == selectedTabIndex) {
selectedTabIndex = -1;
tabSetItem.setSelected(false);
TabDeselectedEvent._fire(this, tab, -1, null);
}
}
}
/**
* Remove one or more tabs at the specified indexes.
*
* @param tabIndexes array of tab indexes
*/
public void removeTabs(int[] tabIndexes) {
if (tabIndexes == null) return;
// Sort the indexes and remove the corresponding tabs in descending order.
Arrays.sort(tabIndexes);
for (int ri = tabIndexes.length; ri > 0; --ri) {
removeTab(tabIndexes[ri - 1]);
}
}
/*******************************************************
* Update tabs
******************************************************/
/*******************************************************
* Selections
******************************************************/
/**
* Returns the index of the currently selected tab.
*
* @return -2 if the More tab is selected; otherwise, the index of the currently selected tab,
* or -1 if no tab is selected.
*/
public final int getSelectedTabNumber() {
return selectedTabIndex;
}
/**
* Returns the currently selected tab.
*
* @return the currently selected tab, or <code>null</code> if the More tab is selected
* or no tab is selected.
*/
public final Tab getSelectedTab() {
final int index = selectedTabIndex;
return (index >= 0 ? tabs.get(index) : null);
}
@SGWTInternal
public void _selectMoreTab() {
assert more != null && moreTab != null;
if (selectedTabIndex != MORE_TAB_SELECTED) {
if (selectedTabIndex != NO_TAB_SELECTED) {
final Tab otherTab = tabs.get(selectedTabIndex);
final TabSetItem otherTabSetItem = otherTab._getTabSetItem();
final Canvas otherPane = otherTab.getPane();
otherTabSetItem.setSelected(false);
if (otherPane != null) paneContainer.hideMember(otherPane);
// Even though the event's `newTab' could be considered `moreTab', we don't
// pass `moreTab' as the third parameter to avoid exposing a reference to this
// internal object.
TabDeselectedEvent._fire(this, otherTab, selectedTabIndex, null);
}
final TabSetItem moreTabSetItem = moreTab._getTabSetItem();
assert moreTab.getPane() == more;
moreTabSetItem.setSelected(true);
paneContainer.showMember(more);
selectedTabIndex = MORE_TAB_SELECTED;
}
}
/**
* Select a tab by index
*
* @param index the tab index
*/
public void selectTab(int index) throws IndexOutOfBoundsException {
selectTab(index, false);
}
private void selectTab(int index, boolean animate) throws IndexOutOfBoundsException {
if (tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index);
final Tab tab;
if (index < 0) {
// Allow a negative `index' to mean deselect the currently selected Tab (if any).
tab = null;
index = NO_TAB_SELECTED;
} else {
tab = tabs.get(index);
if (tab.getDisabled()) return;
}
if (selectedTabIndex >= 0) {
final Tab oldSelectedTab = tabs.get(selectedTabIndex);
if (index == selectedTabIndex) return;
final TabSetItem oldSelectedTabSetItem = oldSelectedTab._getTabSetItem();
oldSelectedTabSetItem.setSelected(false);
final Canvas oldSelectedPane = oldSelectedTab.getPane();
if (oldSelectedPane != null) {
paneContainer.hideMember(oldSelectedPane);
if (oldSelectedPane instanceof Panel) PanelHideEvent.fire(this, (Panel)oldSelectedPane);
}
TabDeselectedEvent._fire(this, oldSelectedTab, selectedTabIndex, tab);
} else if (selectedTabIndex == MORE_TAB_SELECTED) {
assert more != null && moreTab != null;
final TabSetItem moreTabSetItem = moreTab._getTabSetItem();
moreTabSetItem.setSelected(false);
assert moreTab.getPane() == more;
if (!animate) paneContainer.hideMember(more);
}
if (index >= 0) {
assert tab != null;
final TabSetItem tabSetItem = tab._getTabSetItem();
if (showMoreTab && index >= moreTabCount) {
final Tab otherTab = tabs.get(moreTabCount - 1);
tabs.set(moreTabCount - 1, tab);
tabs.set(index, otherTab);
tabBar.removeMember(otherTab._getTabSetItem());
tabBar.addMember(tabSetItem, moreTabCount - 1);
assert more != null;
more.setTab(index - moreTabCount, otherTab);
index = moreTabCount - 1;
}
tabSetItem.setSelected(true);
final Canvas pane = tab.getPane();
if (pane != null) {
if (selectedTabIndex == MORE_TAB_SELECTED && animate) {
final Function<Void> callback;
if (!(pane instanceof Panel)) callback = null;
else {
callback = new Function<Void>() {
@Override
public Void execute() {
assert pane instanceof Panel;
PanelShowEvent.fire(TabSet.this, (Panel)pane);
return null;
}
};
}
AnimationUtil.slideTransition(more, pane, paneContainer, AnimationUtil.Direction.LEFT, null, callback, false);
} else {
paneContainer.showMember(pane);
if (pane instanceof Panel) PanelShowEvent.fire(this, (Panel)pane);
}
}
selectedTabIndex = index;
TabSelectedEvent._fire(this, tab, index);
if (_HISTORY_ENABLED) History.newItem(tab.getTitle());
} else selectedTabIndex = NO_TAB_SELECTED;
}
/**
* Select a tab.
*
* @param tab the canvas representing the tab
*/
public void selectTab(Tab tab) {
assert tab == null || tab != moreTab;
int index = tab == null ? -1 : getTabPosition(tab);
selectTab(index);
}
/*******************************************************
* Enable/disable tabs
******************************************************/
public void enableTab(String id) {
enableTab(getTab(id));
}
public void enableTab(Tab tab) {
final int position = getTabPosition(tab);
if (position >= 0) {
assert position < tabs.size();
enableTab(position);
}
}
/**
* Enable a tab if it is currently disabled.
*
* @param index the tab index
*/
public void enableTab(int index) throws IndexOutOfBoundsException {
if (index < 0 || tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index);
final Tab tab = tabs.get(index);
tab.setDisabled(false);
}
/**
* Disable a tab if it is currently enabled. If the tab is selected, it is deselected.
*
* @param index the tab index
*/
public void disableTab(int index) throws IndexOutOfBoundsException {
if (index < 0 || tabs.size() <= index) throw new IndexOutOfBoundsException("No tab exists at index " + index);
final Tab tab = tabs.get(index);
tab.setDisabled(true);
if (selectedTabIndex == index) {
selectTab(-1);
}
}
/*******************************************************
* State and tab query methods
******************************************************/
public final int getNumTabs() {
return tabs.size();
}
public final int getTabCount() {
return getNumTabs();
}
private final int getTabPosition(Tab other) {
if (other == null) return -1;
final int tabs_size = tabs.size();
for (int i = 0; i < tabs_size; ++i) {
if (tabs.get(i).equals(other)) return i;
}
return -1;
}
/**
* Returns the canvas representing a tab.
*
* @param tabIndex index of tab
* @return the tab widget or null if not found
*/
public final Tab getTab(int tabIndex) {
if (0 <= tabIndex && tabIndex < tabs.size()) {
return tabs.get(tabIndex);
}
return null;
}
public final Tab getTab(String id) {
if (id == null) return null;
final int tabs_size = tabs.size();
for (int i = 0; i < tabs_size; ++i) {
final Tab tab = tabs.get(i);
if (id.equals(tab.getID())) return tab;
}
return null;
}
/**
* ****************************************************
* Helper methods
* ****************************************************
*/
@Override
public ContainerFeatures getContainerFeatures() {
return new ContainerFeatures(this, true, false, false, true, 0);
}
@Override
public HandlerRegistration addPanelHideHandler(PanelHideHandler handler) {
return addHandler(handler, PanelHideEvent.getType());
}
@Override
public HandlerRegistration addPanelShowHandler(PanelShowHandler handler) {
return addHandler(handler, PanelShowEvent.getType());
}
public void setMoreTabCount(int moreTabCount) {
if (this.moreTabCount == moreTabCount) return;
// We need moreTabCount to be at least one so that we can swap out a non-More tab
// with the selected tab.
if (moreTabCount < 1) throw new IllegalArgumentException("`moreTabCount' must be at least 1.");
if (more != null) throw new IllegalStateException("`moreTabCount' cannot be changed once the More tab has been created.");
if (tabs.size() > moreTabCount && showMoreTab) throw new IllegalArgumentException("`moreTabCount` cannot be set to a number less than the current number of tabs.");
this.moreTabCount = moreTabCount;
}
public final int getMoreTabCount() {
return moreTabCount;
}
public void setShowMoreTab(boolean showMoreTab) {
if (this.showMoreTab == showMoreTab) return;
if (more != null) throw new IllegalStateException("`showMoreTab' cannot be changed once the More tab has been created.");
if (tabs.size() > moreTabCount && showMoreTab) throw new IllegalArgumentException("The More tab cannot be enabled now that there are already more than `this.getMoreTabCount()' tabs in this TabSet.");
this.showMoreTab = showMoreTab;
}
//public void setDraggable(Canvas draggable) {
// this.draggable = draggable;
//}
} | will-gilbert/SmartGWT-Mobile | mobile/src/main/java/com/smartgwt/mobile/client/widgets/tab/TabSet.java | Java | unlicense | 42,796 |
/**
*
*/
package com.rhcloud.zugospoint.DAO;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.rhcloud.zugospoint.model.*;
import com.rhcloud.zugospoint.util.HibernateUtil;
/**
* Klasa zawiera zbior niskopoziomowych metod dostepu do danych z bazy
* @author zugo
*
*/
public class ApplicationDAO {
private SessionFactory sessionF;
public ApplicationDAO (){
sessionF = HibernateUtil.getSessionFactory();
}
public void addAdres(Adres theAdres)
{
Session session = sessionF.getCurrentSession();
try{
session.beginTransaction();
session.save(theAdres);
session.getTransaction().commit();
session.close();
}catch (HibernateException e){
session.getTransaction().rollback();
e.printStackTrace();
session.close();
}
}
@SuppressWarnings("unchecked")
public List<Adres> getAllAdreses(){
Session s = sessionF.getCurrentSession();
List<Adres> res = null;
try{
s.beginTransaction();
res = s.createQuery("from Adres").list();
s.getTransaction().commit();
s.close();
}catch (HibernateException e){
s.getTransaction().rollback();
e.printStackTrace();// TODO throw apropriate exception when catch it, or not, considere it
s.close();
}
return res;
}
} | zugoth/1314-adb | src/main/java/com/rhcloud/zugospoint/DAO/ApplicationDAO.java | Java | unlicense | 1,320 |
var User = {
title : 'Customer',
LoginTitleText : 'Register yourself'
}
module.exports = User; | thakurarun/Basic-nodejs-express-app | samplenode/samplenode/server/model/User.js | JavaScript | unlicense | 104 |