repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
|---|---|---|---|---|
wquist/Horizon-Microkernel
|
lib/libh/include/stdint.h
|
469
|
#ifndef _STDINT_H
#define _STDINT_H
#include <features.h>
#include <inttypes.h>
typedef int8_t int_fast8_t;
typedef int64_t int_fast64_t;
typedef int8_t int_least8_t;
typedef int16_t int_least16_t;
typedef int32_t int_least32_t;
typedef int64_t int_least64_t;
typedef uint8_t uint_fast8_t;
typedef uint64_t uint_fast64_t;
typedef uint8_t uint_least8_t;
typedef uint16_t uint_least16_t;
typedef uint32_t uint_least32_t;
typedef uint64_t uint_least64_t;
#endif
|
gpl-3.0
|
dzonekl/oss2nms
|
plugins/com.netxforge.oss2.config.model/src/com/netxforge/oss2/config/linkd/descriptors/VlansDescriptor.java
|
5982
|
/*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML
* Schema.
* $Id$
*/
package com.netxforge.oss2.config.linkd.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import com.netxforge.oss2.config.linkd.Vlans;
/**
* Class VlansDescriptor.
*
* @version $Revision$ $Date$
*/
@SuppressWarnings("all") public class VlansDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public VlansDescriptor() {
super();
_nsURI = "http://xmlns.opennms.org/xsd/config/linkd";
_xmlName = "vlans";
_elementDefinition = true;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- initialize element descriptors
//-- _vendorList
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(com.netxforge.oss2.config.linkd.Vendor.class, "_vendorList", "vendor", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
Vlans target = (Vlans) object;
return target.getVendor();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
Vlans target = (Vlans) object;
target.addVendor( (com.netxforge.oss2.config.linkd.Vendor) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
try {
Vlans target = (Vlans) object;
target.removeAllVendor();
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new com.netxforge.oss2.config.linkd.Vendor();
}
};
desc.setSchemaType("com.netxforge.oss2.config.linkd.Vendor");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/linkd");
desc.setRequired(true);
desc.setMultivalued(true);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _vendorList
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class<?> getJavaClass(
) {
return com.netxforge.oss2.config.linkd.Vlans.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
|
gpl-3.0
|
Whatsit2yaa/vast-tundra-84597
|
include/service/media/renderers/slideshare_media_renderer.js
|
10832
|
/*
Copyright (C) 2016 PencilBlue, LLC
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/>.
*/
//dependencies
var url = require('url');
var https = require('https');
module.exports = function SlideShareMediaRendererModule(pb) {
//pb dependencies
var util = pb.util;
var BaseMediaRenderer = pb.media.renderers.BaseMediaRenderer;
/**
*
* @class SlideShareMediaRenderer
* @constructor
*/
function SlideShareMediaRenderer(){}
/**
* The media type supported by the provider
* @private
* @static
* @property TYPE
* @type {String}
*/
var TYPE = 'slideshare';
/**
* Provides the styles used by each type of view
* @private
* @static
* @property STYLES
* @type {Object}
*/
var STYLES = Object.freeze({
view: {
width: "100%"
},
editor: {
width: "427px",
height: "356px"
},
post: {
width: "427px",
height: "356px"
}
});
/**
* Retrieves the supported extension types for the renderer.
* @static
* @method getSupportedExtensions
* @return {Array}
*/
SlideShareMediaRenderer.getSupportedExtensions = function() {
return [];
};
/**
* Retrieves the style for the specified type of view
* @static
* @method getStyle
* @param {String} viewType The view type calling for a styling
* @return {Object} a hash of style properties
*/
SlideShareMediaRenderer.getStyle = function(viewType) {
return STYLES[viewType] || STYLES.view;
};
/**
* Retrieves the supported media types as a hash.
* @static
* @method getSupportedTypes
* @return {Object}
*/
SlideShareMediaRenderer.getSupportedTypes = function() {
var types = {};
types[TYPE] = true;
return types;
};
/**
* Retrieves the name of the renderer.
* @static
* @method getName
* @return {String}
*/
SlideShareMediaRenderer.getName = function() {
return 'SlideShareMediaRenderer';
};
/**
* Determines if the URL to a media object is supported by this renderer
* @static
* @method isSupported
* @param {String} urlStr
* @return {Boolean} TRUE if the URL is supported by the renderer, FALSE if not
*/
SlideShareMediaRenderer.isSupported = function(urlStr) {
var details = url.parse(urlStr, true, true);
return SlideShareMediaRenderer.isFullSite(details);
};
/**
* Indicates if the passed URL to a media resource points to the main website
* that provides the media represented by this media renderer
* @static
* @method isFullSite
* @param {Object|String} parsedUrl The URL string or URL object
* @return {Boolean} TRUE if URL points to the main domain and media resource, FALSE if not
*/
SlideShareMediaRenderer.isFullSite = function(parsedUrl) {
if (util.isString(parsedUrl)) {
parsedUrl = url.parse(urlStr, true, true);
}
return parsedUrl.host && (parsedUrl.host.indexOf('slideshare.com') >= 0 || parsedUrl.host.indexOf('slideshare.net') >= 0) && parsedUrl.pathname.indexOf('/') >= 0;
};
/**
* Gets the specific type of the media resource represented by the provided URL
* @static
* @method getType
* @param {String} urlStr
* @return {String}
*/
SlideShareMediaRenderer.getType = function(urlStr) {
return SlideShareMediaRenderer.isSupported(urlStr) ? TYPE : null;
}
/**
* Retrieves the Font Awesome icon class. It is safe to assume that the type
* provided will be a supported type by the renderer.
* @static
* @method getIcon
* @param {String} type
* @return {String}
*/
SlideShareMediaRenderer.getIcon = function(type) {
return 'list-alt';
};
/**
* Renders the media resource via the raw URL to the resource
* @static
* @method renderByUrl
* @param {String} urlStr
* @param {Object} [options]
* @param {Object} [options.attrs] A hash of all attributes (excluding style)
* that will be applied to the element generated by the rendering
* @param {Object} [options.style] A hash of all attributes that will be
* applied to the style of the element generated by the rendering.
* @param {Function} cb A callback where the first parameter is an Error if
* occurred and the second is the rendering of the media resource as a HTML
* formatted string
*/
SlideShareMediaRenderer.renderByUrl = function(urlStr, options, cb) {
SlideShareMediaRenderer.getMediaId(urlStr, function(err, mediaId) {
if (util.isError(err)) {
return cb(err);
}
SlideShareMediaRenderer.render({location: mediaId}, options, cb);
});
};
/**
* Renders the media resource via the media descriptor object. It is only
* guaranteed that the "location" property will be available at the time of
* rendering.
* @static
* @method render
* @param {Object} media
* @param {String} media.location The unique resource identifier (only to the
* media type) for the media resource
* @param {Object} [options]
* @param {Object} [options.attrs] A hash of all attributes (excluding style)
* that will be applied to the element generated by the rendering
* @param {Object} [options.style] A hash of all attributes that will be
* applied to the style of the element generated by the rendering.
* @param {Function} cb A callback where the first parameter is an Error if
* occurred and the second is the rendering of the media resource as a HTML
* formatted string
*/
SlideShareMediaRenderer.render = function(media, options, cb) {
if (util.isFunction(options)) {
cb = options;
options = {};
}
var embedUrl = SlideShareMediaRenderer.getEmbedUrl(media.location);
cb(null, BaseMediaRenderer.renderIFrameEmbed(embedUrl, options.attrs, options.style));
};
/**
* Retrieves the source URI that will be used when generating the rendering
* @static
* @method getEmbedUrl
* @param {String} mediaId The unique (only to the type) media identifier
* @return {String} A properly formatted URI string that points to the resource
* represented by the media Id
*/
SlideShareMediaRenderer.getEmbedUrl = function(mediaId) {
return '//www.slideshare.net/slideshow/embed_code/' + mediaId;
};
/**
* Retrieves the unique identifier from the URL provided. The value should
* distinguish the media resource from the others of this type and provide
* insight on how to generate the embed URL.
* @static
* @method getMediaId
*/
SlideShareMediaRenderer.getMediaId = function(urlStr, cb) {
SlideShareMediaRenderer.getDetails(urlStr, function(err, details) {
if (util.isError(err)) {
return cb(err);
}
cb(null, details.slideshow_id);
});
};
/**
* Retrieves any meta data about the media represented by the URL.
* @static
* @method getMeta
* @param {String} urlStr
* @param {Boolean} isFile indicates if the URL points to a file that was
* uploaded to the PB server
* @param {Function} cb A callback that provides an Error if occurred and an
* Object if meta was collected. NULL if no meta was collected
*/
SlideShareMediaRenderer.getMeta = function(urlStr, isFile, cb) {
var details = url.parse(urlStr, true, true);
var meta = details.query;
cb(null, meta);
};
/**
* Retrieves a URI to a thumbnail for the media resource
* @static
* @method getThumbnail
* @param {String} urlStr
* @param {Function} cb A callback where the first parameter is an Error if
* occurred and the second is the URI string to the thumbnail. Empty string or
* NULL if no thumbnail is available
*/
SlideShareMediaRenderer.getThumbnail = function(urlStr, cb) {
SlideShareMediaRenderer.getDetails(urlStr, function(err, details) {
if (util.isError(err)) {
return cb(err);
}
cb(null, details.thumbnail);
});
};
/**
* Retrieves the native URL for the media resource. This can be the raw page
* where it was found or a direct link to the content.
* @static
* @method getNativeUrl
*/
SlideShareMediaRenderer.getNativeUrl = function(media) {
return 'http://slideshare.net/slideshow/embed_code/' + media.location;
};
/**
* Retrieves details about the media resource via SlideShare's API because they
* are inconsistent about how they reference things.
* @static
* @method getDetails
* @param {String} urlStr
* @param {Function} cb Provides two parameters. First is an Error if occurred
* and the second is an object with the data returned by the SlideShare API
*/
SlideShareMediaRenderer.getDetails = function(urlStr, cb) {
var options = {
host: 'www.slideshare.net',
path: '/api/oembed/2?url=' + encodeURIComponent(urlStr) + '&format=jsonp&callback=?'
};
var callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.once('error', cb);
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
try {
var data = JSON.parse(str);
cb(null, data);
}
catch(err) {
cb(err);
}
});
};
https.request(options, callback).end();
};
//exports
return SlideShareMediaRenderer;
};
|
gpl-3.0
|
BukkitPE/BukkitPE
|
src/main/java/net/BukkitPE/block/BlockFarmland.java
|
2452
|
package net.BukkitPE.block;
import net.BukkitPE.item.Item;
import net.BukkitPE.item.ItemTool;
import net.BukkitPE.level.Level;
import net.BukkitPE.math.AxisAlignedBB;
import net.BukkitPE.math.Vector3;
import net.BukkitPE.utils.BlockColor;
/**
* Created on 2015/12/2 by xtypr.
* Package net.BukkitPE.block in project BukkitPE .
*/
public class BlockFarmland extends BlockTransparent {
public BlockFarmland() {
this(0);
}
public BlockFarmland(int meta) {
super(meta);
}
@Override
public String getName() {
return "Farmland";
}
@Override
public int getId() {
return FARMLAND;
}
@Override
public double getResistance() {
return 3;
}
@Override
public double getHardness() {
return 0.6;
}
@Override
public int getToolType() {
return ItemTool.TYPE_SHOVEL;
}
@Override
protected AxisAlignedBB recalculateBoundingBox() {
return new AxisAlignedBB(
this.x,
this.y,
this.z,
this.x + 1,
this.y + 0.9375,
this.z + 1
);
}
@Override
public int onUpdate(int type) {
if (type == Level.BLOCK_UPDATE_RANDOM) {
boolean found = false;
Vector3 v = new Vector3();
for (int x = (int) this.x - 1; x <= this.x + 1; x++) {
for (int z = (int) this.z - 1; z <= this.z + 1; z++) {
if (z == this.z && x == this.x) {
continue;
}
Block block = this.level.getBlock(v.setComponents(x, this.y, z));
if (block instanceof BlockWater) {
found = true;
break;
}
}
}
Block block = this.level.getBlock(v.setComponents(x, y - 1, z));
if (found || block instanceof BlockWater) {
return Level.BLOCK_UPDATE_RANDOM;
}
this.level.setBlock(this, new BlockDirt(), true, true);
return Level.BLOCK_UPDATE_RANDOM;
}
return 0;
}
@Override
public int[][] getDrops(Item item) {
return new int[][]{
{Item.DIRT, 0, 1}
};
}
@Override
public BlockColor getColor() {
return BlockColor.DIRT_BLOCK_COLOR;
}
}
|
gpl-3.0
|
tjhorner/schema.tl
|
docs/methods/auth.signIn.md
|
199
|
This method is used to authenticate an existing Telegram user. If the user needs to register an account, they should use [auth.signUp](#!/method/auth.signUp) to register their number with the system.
|
gpl-3.0
|
svschub/Symbolix
|
src/AST/Exception/UnknownIdentifierException.h
|
565
|
#ifndef AST__EXCEPTION__UNKNOWNIDENTIFIEREXCEPTION_H_
#define AST__EXCEPTION__UNKNOWNIDENTIFIEREXCEPTION_H_
#include <exception>
namespace AST { namespace Exception {
class UnknownIdentifierException: public std::exception {
std::string identifierName;
public:
UnknownIdentifierException() throw();
UnknownIdentifierException(std::string identifier) throw();
virtual ~UnknownIdentifierException() throw();
virtual const char* what() const throw();
};
}} /* namespace AST::Exception */
#endif /* AST__EXCEPTION__UNKNOWNIDENTIFIEREXCEPTION_H_ */
|
gpl-3.0
|
Donkyhotay/MoonPy
|
twisted/web/test/test_static.py
|
53951
|
# -*- test-case-name: twisted.web.test.test_web -*-
# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.web.static}.
"""
import os, re, StringIO
from zope.interface.verify import verifyObject
from twisted.internet import abstract, interfaces
from twisted.python.compat import set
from twisted.python.runtime import platform
from twisted.python.filepath import FilePath
from twisted.python import log
from twisted.trial.unittest import TestCase
from twisted.web import static, http, script, resource
from twisted.web.test.test_web import DummyRequest
from twisted.web.test._util import _render
class StaticFileTests(TestCase):
"""
Tests for the basic behavior of L{File}.
"""
def _render(self, resource, request):
return _render(resource, request)
def test_notFound(self):
"""
If a request is made which encounters a L{File} before a final segment
which does not correspond to any file in the path the L{File} was
created with, a not found response is sent.
"""
base = FilePath(self.mktemp())
base.makedirs()
file = static.File(base.path)
request = DummyRequest(['foobar'])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(request.responseCode, 404)
d.addCallback(cbRendered)
return d
def test_emptyChild(self):
"""
The C{''} child of a L{File} which corresponds to a directory in the
filesystem is a L{DirectoryLister}.
"""
base = FilePath(self.mktemp())
base.makedirs()
file = static.File(base.path)
request = DummyRequest([''])
child = resource.getChildForRequest(file, request)
self.assertIsInstance(child, static.DirectoryLister)
self.assertEqual(child.path, base.path)
def test_securityViolationNotFound(self):
"""
If a request is made which encounters a L{File} before a final segment
which cannot be looked up in the filesystem due to security
considerations, a not found response is sent.
"""
base = FilePath(self.mktemp())
base.makedirs()
file = static.File(base.path)
request = DummyRequest(['..'])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(request.responseCode, 404)
d.addCallback(cbRendered)
return d
def test_forbiddenResource(self):
"""
If the file in the filesystem which would satisfy a request cannot be
read, L{File.render} sets the HTTP response code to I{FORBIDDEN}.
"""
base = FilePath(self.mktemp())
base.setContent('')
# Make sure we can delete the file later.
self.addCleanup(base.chmod, 0700)
# Get rid of our own read permission.
base.chmod(0)
file = static.File(base.path)
request = DummyRequest([''])
d = self._render(file, request)
def cbRendered(ignored):
self.assertEqual(request.responseCode, 403)
d.addCallback(cbRendered)
return d
if platform.isWindows():
test_forbiddenResource.skip = "Cannot remove read permission on Windows"
def test_indexNames(self):
"""
If a request is made which encounters a L{File} before a final empty
segment, a file in the L{File} instance's C{indexNames} list which
exists in the path the L{File} was created with is served as the
response to the request.
"""
base = FilePath(self.mktemp())
base.makedirs()
base.child("foo.bar").setContent("baz")
file = static.File(base.path)
file.indexNames = ['foo.bar']
request = DummyRequest([''])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(''.join(request.written), 'baz')
self.assertEqual(request.outgoingHeaders['content-length'], '3')
d.addCallback(cbRendered)
return d
def test_staticFile(self):
"""
If a request is made which encounters a L{File} before a final segment
which names a file in the path the L{File} was created with, that file
is served as the response to the request.
"""
base = FilePath(self.mktemp())
base.makedirs()
base.child("foo.bar").setContent("baz")
file = static.File(base.path)
request = DummyRequest(['foo.bar'])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(''.join(request.written), 'baz')
self.assertEqual(request.outgoingHeaders['content-length'], '3')
d.addCallback(cbRendered)
return d
def test_staticFileDeletedGetChild(self):
"""
A L{static.File} created for a directory which does not exist should
return childNotFound from L{static.File.getChild}.
"""
staticFile = static.File(self.mktemp())
request = DummyRequest(['foo.bar'])
child = staticFile.getChild("foo.bar", request)
self.assertEquals(child, staticFile.childNotFound)
def test_staticFileDeletedRender(self):
"""
A L{static.File} created for a file which does not exist should render
its C{childNotFound} page.
"""
staticFile = static.File(self.mktemp())
request = DummyRequest(['foo.bar'])
request2 = DummyRequest(['foo.bar'])
d = self._render(staticFile, request)
d2 = self._render(staticFile.childNotFound, request2)
def cbRendered2(ignored):
def cbRendered(ignored):
self.assertEquals(''.join(request.written),
''.join(request2.written))
d.addCallback(cbRendered)
return d
d2.addCallback(cbRendered2)
return d2
def test_processors(self):
"""
If a request is made which encounters a L{File} before a final segment
which names a file with an extension which is in the L{File}'s
C{processors} mapping, the processor associated with that extension is
used to serve the response to the request.
"""
base = FilePath(self.mktemp())
base.makedirs()
base.child("foo.bar").setContent(
"from twisted.web.static import Data\n"
"resource = Data('dynamic world','text/plain')\n")
file = static.File(base.path)
file.processors = {'.bar': script.ResourceScript}
request = DummyRequest(["foo.bar"])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(''.join(request.written), 'dynamic world')
self.assertEqual(request.outgoingHeaders['content-length'], '13')
d.addCallback(cbRendered)
return d
def test_ignoreExt(self):
"""
The list of ignored extensions can be set by passing a value to
L{File.__init__} or by calling L{File.ignoreExt} later.
"""
file = static.File(".")
self.assertEqual(file.ignoredExts, [])
file.ignoreExt(".foo")
file.ignoreExt(".bar")
self.assertEqual(file.ignoredExts, [".foo", ".bar"])
file = static.File(".", ignoredExts=(".bar", ".baz"))
self.assertEqual(file.ignoredExts, [".bar", ".baz"])
def test_ignoredExtensionsIgnored(self):
"""
A request for the I{base} child of a L{File} succeeds with a resource
for the I{base<extension>} file in the path the L{File} was created
with if such a file exists and the L{File} has been configured to
ignore the I{<extension>} extension.
"""
base = FilePath(self.mktemp())
base.makedirs()
base.child('foo.bar').setContent('baz')
base.child('foo.quux').setContent('foobar')
file = static.File(base.path, ignoredExts=(".bar",))
request = DummyRequest(["foo"])
child = resource.getChildForRequest(file, request)
d = self._render(child, request)
def cbRendered(ignored):
self.assertEqual(''.join(request.written), 'baz')
d.addCallback(cbRendered)
return d
def test_createPickleChild(self):
"""
L{static.File.createPickleChild} is deprecated.
"""
path = FilePath(self.mktemp())
path.makedirs()
static.File(path.path).createPickleChild("foo", None)
warnings = self.flushWarnings([self.test_createPickleChild])
self.assertEqual(warnings[0]['category'], DeprecationWarning)
self.assertEqual(
warnings[0]['message'],
"File.createPickleChild is deprecated since Twisted 9.0. "
"Resource persistence is beyond the scope of Twisted Web.")
self.assertEqual(len(warnings), 1)
class StaticMakeProducerTests(TestCase):
"""
Tests for L{File.makeProducer}.
"""
def makeResourceWithContent(self, content, type=None, encoding=None):
"""
Make a L{static.File} resource that has C{content} for its content.
@param content: The bytes to use as the contents of the resource.
@param type: Optional value for the content type of the resource.
"""
fileName = self.mktemp()
fileObject = open(fileName, 'w')
fileObject.write(content)
fileObject.close()
resource = static.File(fileName)
resource.encoding = encoding
resource.type = type
return resource
def contentHeaders(self, request):
"""
Extract the content-* headers from the L{DummyRequest} C{request}.
This returns the subset of C{request.outgoingHeaders} of headers that
start with 'content-'.
"""
contentHeaders = {}
for k, v in request.outgoingHeaders.iteritems():
if k.startswith('content-'):
contentHeaders[k] = v
return contentHeaders
def test_noRangeHeaderGivesNoRangeStaticProducer(self):
"""
makeProducer when no Range header is set returns an instance of
NoRangeStaticProducer.
"""
resource = self.makeResourceWithContent('')
request = DummyRequest([])
producer = resource.makeProducer(request, resource.openForReading())
self.assertIsInstance(producer, static.NoRangeStaticProducer)
def test_noRangeHeaderSets200OK(self):
"""
makeProducer when no Range header is set sets the responseCode on the
request to 'OK'.
"""
resource = self.makeResourceWithContent('')
request = DummyRequest([])
resource.makeProducer(request, resource.openForReading())
self.assertEqual(http.OK, request.responseCode)
def test_noRangeHeaderSetsContentHeaders(self):
"""
makeProducer when no Range header is set sets the Content-* headers
for the response.
"""
length = 123
contentType = "text/plain"
contentEncoding = 'gzip'
resource = self.makeResourceWithContent(
'a'*length, type=contentType, encoding=contentEncoding)
request = DummyRequest([])
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
{'content-type': contentType, 'content-length': str(length),
'content-encoding': contentEncoding},
self.contentHeaders(request))
def test_singleRangeGivesSingleRangeStaticProducer(self):
"""
makeProducer when the Range header requests a single byte range
returns an instance of SingleRangeStaticProducer.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=1-3'
resource = self.makeResourceWithContent('abcdef')
producer = resource.makeProducer(request, resource.openForReading())
self.assertIsInstance(producer, static.SingleRangeStaticProducer)
def test_singleRangeSets206PartialContent(self):
"""
makeProducer when the Range header requests a single, satisfiable byte
range sets the response code on the request to 'Partial Content'.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=1-3'
resource = self.makeResourceWithContent('abcdef')
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
http.PARTIAL_CONTENT, request.responseCode)
def test_singleRangeSetsContentHeaders(self):
"""
makeProducer when the Range header requests a single, satisfiable byte
range sets the Content-* headers appropriately.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=1-3'
contentType = "text/plain"
contentEncoding = 'gzip'
resource = self.makeResourceWithContent('abcdef', type=contentType, encoding=contentEncoding)
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
{'content-type': contentType, 'content-encoding': contentEncoding,
'content-range': 'bytes 1-3/6', 'content-length': '3'},
self.contentHeaders(request))
def test_singleUnsatisfiableRangeReturnsSingleRangeStaticProducer(self):
"""
makeProducer still returns an instance of L{SingleRangeStaticProducer}
when the Range header requests a single unsatisfiable byte range.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=4-10'
resource = self.makeResourceWithContent('abc')
producer = resource.makeProducer(request, resource.openForReading())
self.assertIsInstance(producer, static.SingleRangeStaticProducer)
def test_singleUnsatisfiableRangeSets416ReqestedRangeNotSatisfiable(self):
"""
makeProducer sets the response code of the request to of 'Requested
Range Not Satisfiable' when the Range header requests a single
unsatisfiable byte range.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=4-10'
resource = self.makeResourceWithContent('abc')
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
http.REQUESTED_RANGE_NOT_SATISFIABLE, request.responseCode)
def test_singleUnsatisfiableRangeSetsContentHeaders(self):
"""
makeProducer when the Range header requests a single, unsatisfiable
byte range sets the Content-* headers appropriately.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=4-10'
contentType = "text/plain"
resource = self.makeResourceWithContent('abc', type=contentType)
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
{'content-type': 'text/plain', 'content-length': '0',
'content-range': 'bytes */3'},
self.contentHeaders(request))
def test_singlePartiallyOverlappingRangeSetsContentHeaders(self):
"""
makeProducer when the Range header requests a single byte range that
partly overlaps the resource sets the Content-* headers appropriately.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=2-10'
contentType = "text/plain"
resource = self.makeResourceWithContent('abc', type=contentType)
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
{'content-type': 'text/plain', 'content-length': '1',
'content-range': 'bytes 2-2/3'},
self.contentHeaders(request))
def test_multipleRangeGivesMultipleRangeStaticProducer(self):
"""
makeProducer when the Range header requests a single byte range
returns an instance of MultipleRangeStaticProducer.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=1-3,5-6'
resource = self.makeResourceWithContent('abcdef')
producer = resource.makeProducer(request, resource.openForReading())
self.assertIsInstance(producer, static.MultipleRangeStaticProducer)
def test_multipleRangeSets206PartialContent(self):
"""
makeProducer when the Range header requests a multiple satisfiable
byte ranges sets the response code on the request to 'Partial
Content'.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=1-3,5-6'
resource = self.makeResourceWithContent('abcdef')
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
http.PARTIAL_CONTENT, request.responseCode)
def test_mutipleRangeSetsContentHeaders(self):
"""
makeProducer when the Range header requests a single, satisfiable byte
range sets the Content-* headers appropriately.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=1-3,5-6'
resource = self.makeResourceWithContent(
'abcdefghijkl', encoding='gzip')
producer = resource.makeProducer(request, resource.openForReading())
contentHeaders = self.contentHeaders(request)
# The only content-* headers set are content-type and content-length.
self.assertEqual(
set(['content-length', 'content-type']),
set(contentHeaders.keys()))
# The content-length depends on the boundary used in the response.
expectedLength = 5
for boundary, offset, size in producer.rangeInfo:
expectedLength += len(boundary)
self.assertEqual(expectedLength, contentHeaders['content-length'])
# Content-type should be set to a value indicating a multipart
# response and the boundary used to separate the parts.
self.assertIn('content-type', contentHeaders)
contentType = contentHeaders['content-type']
self.assertNotIdentical(
None, re.match(
'multipart/byteranges; boundary="[^"]*"\Z', contentType))
# Content-encoding is not set in the response to a multiple range
# response, which is a bit wussy but works well enough with the way
# static.File does content-encodings...
self.assertNotIn('content-encoding', contentHeaders)
def test_multipleUnsatisfiableRangesReturnsMultipleRangeStaticProducer(self):
"""
makeProducer still returns an instance of L{SingleRangeStaticProducer}
when the Range header requests multiple ranges, none of which are
satisfiable.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=10-12,15-20'
resource = self.makeResourceWithContent('abc')
producer = resource.makeProducer(request, resource.openForReading())
self.assertIsInstance(producer, static.MultipleRangeStaticProducer)
def test_multipleUnsatisfiableRangesSets416ReqestedRangeNotSatisfiable(self):
"""
makeProducer sets the response code of the request to of 'Requested
Range Not Satisfiable' when the Range header requests multiple ranges,
none of which are satisfiable.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=10-12,15-20'
resource = self.makeResourceWithContent('abc')
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
http.REQUESTED_RANGE_NOT_SATISFIABLE, request.responseCode)
def test_multipleUnsatisfiableRangeSetsContentHeaders(self):
"""
makeProducer when the Range header requests multiple ranges, none of
which are satisfiable, sets the Content-* headers appropriately.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=4-10'
contentType = "text/plain"
request.headers['range'] = 'bytes=10-12,15-20'
resource = self.makeResourceWithContent('abc', type=contentType)
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
{'content-length': '0', 'content-range': 'bytes */3'},
self.contentHeaders(request))
def test_oneSatisfiableRangeIsEnough(self):
"""
makeProducer when the Range header requests multiple ranges, at least
one of which matches, sets the response code to 'Partial Content'.
"""
request = DummyRequest([])
request.headers['range'] = 'bytes=1-3,100-200'
resource = self.makeResourceWithContent('abcdef')
resource.makeProducer(request, resource.openForReading())
self.assertEqual(
http.PARTIAL_CONTENT, request.responseCode)
class StaticProducerTests(TestCase):
"""
Tests for the abstract L{StaticProducer}.
"""
def test_stopProducingClosesFile(self):
"""
L{StaticProducer.stopProducing} closes the file object the producer is
producing data from.
"""
fileObject = StringIO.StringIO()
producer = static.StaticProducer(None, fileObject)
producer.stopProducing()
self.assertTrue(fileObject.closed)
def test_stopProducingSetsRequestToNone(self):
"""
L{StaticProducer.stopProducing} sets the request instance variable to
None, which indicates to subclasses' resumeProducing methods that no
more data should be produced.
"""
fileObject = StringIO.StringIO()
producer = static.StaticProducer(DummyRequest([]), fileObject)
producer.stopProducing()
self.assertIdentical(None, producer.request)
class NoRangeStaticProducerTests(TestCase):
"""
Tests for L{NoRangeStaticProducer}.
"""
def test_implementsIPullProducer(self):
"""
L{NoRangeStaticProducer} implements L{IPullProducer}.
"""
verifyObject(
interfaces.IPullProducer,
static.NoRangeStaticProducer(None, None))
def test_resumeProducingProducesContent(self):
"""
L{NoRangeStaticProducer.resumeProducing} writes content from the
resource to the request.
"""
request = DummyRequest([])
content = 'abcdef'
producer = static.NoRangeStaticProducer(
request, StringIO.StringIO(content))
# start calls registerProducer on the DummyRequest, which pulls all
# output from the producer and so we just need this one call.
producer.start()
self.assertEqual(content, ''.join(request.written))
def test_resumeProducingBuffersOutput(self):
"""
L{NoRangeStaticProducer.start} writes at most
C{abstract.FileDescriptor.bufferSize} bytes of content from the
resource to the request at once.
"""
request = DummyRequest([])
bufferSize = abstract.FileDescriptor.bufferSize
content = 'a' * (2*bufferSize + 1)
producer = static.NoRangeStaticProducer(
request, StringIO.StringIO(content))
# start calls registerProducer on the DummyRequest, which pulls all
# output from the producer and so we just need this one call.
producer.start()
expected = [
content[0:bufferSize],
content[bufferSize:2*bufferSize],
content[2*bufferSize:]
]
self.assertEqual(expected, request.written)
def test_finishCalledWhenDone(self):
"""
L{NoRangeStaticProducer.resumeProducing} calls finish() on the request
after it is done producing content.
"""
request = DummyRequest([])
finishDeferred = request.notifyFinish()
callbackList = []
finishDeferred.addCallback(callbackList.append)
producer = static.NoRangeStaticProducer(
request, StringIO.StringIO('abcdef'))
# start calls registerProducer on the DummyRequest, which pulls all
# output from the producer and so we just need this one call.
producer.start()
self.assertEqual([None], callbackList)
class SingleRangeStaticProducerTests(TestCase):
"""
Tests for L{SingleRangeStaticProducer}.
"""
def test_implementsIPullProducer(self):
"""
L{SingleRangeStaticProducer} implements L{IPullProducer}.
"""
verifyObject(
interfaces.IPullProducer,
static.SingleRangeStaticProducer(None, None, None, None))
def test_resumeProducingProducesContent(self):
"""
L{SingleRangeStaticProducer.resumeProducing} writes the given amount
of content, starting at the given offset, from the resource to the
request.
"""
request = DummyRequest([])
content = 'abcdef'
producer = static.SingleRangeStaticProducer(
request, StringIO.StringIO(content), 1, 3)
# DummyRequest.registerProducer pulls all output from the producer, so
# we just need to call start.
producer.start()
self.assertEqual(content[1:4], ''.join(request.written))
def test_resumeProducingBuffersOutput(self):
"""
L{SingleRangeStaticProducer.start} writes at most
C{abstract.FileDescriptor.bufferSize} bytes of content from the
resource to the request at once.
"""
request = DummyRequest([])
bufferSize = abstract.FileDescriptor.bufferSize
content = 'abc' * bufferSize
producer = static.SingleRangeStaticProducer(
request, StringIO.StringIO(content), 1, bufferSize+10)
# DummyRequest.registerProducer pulls all output from the producer, so
# we just need to call start.
producer.start()
expected = [
content[1:bufferSize+1],
content[bufferSize+1:bufferSize+11],
]
self.assertEqual(expected, request.written)
def test_finishCalledWhenDone(self):
"""
L{SingleRangeStaticProducer.resumeProducing} calls finish() on the
request after it is done producing content.
"""
request = DummyRequest([])
finishDeferred = request.notifyFinish()
callbackList = []
finishDeferred.addCallback(callbackList.append)
producer = static.SingleRangeStaticProducer(
request, StringIO.StringIO('abcdef'), 1, 1)
# start calls registerProducer on the DummyRequest, which pulls all
# output from the producer and so we just need this one call.
producer.start()
self.assertEqual([None], callbackList)
class MultipleRangeStaticProducerTests(TestCase):
"""
Tests for L{MultipleRangeStaticProducer}.
"""
def test_implementsIPullProducer(self):
"""
L{MultipleRangeStaticProducer} implements L{IPullProducer}.
"""
verifyObject(
interfaces.IPullProducer,
static.MultipleRangeStaticProducer(None, None, None))
def test_resumeProducingProducesContent(self):
"""
L{MultipleRangeStaticProducer.resumeProducing} writes the requested
chunks of content from the resource to the request, with the supplied
boundaries in between each chunk.
"""
request = DummyRequest([])
content = 'abcdef'
producer = static.MultipleRangeStaticProducer(
request, StringIO.StringIO(content), [('1', 1, 3), ('2', 5, 1)])
# DummyRequest.registerProducer pulls all output from the producer, so
# we just need to call start.
producer.start()
self.assertEqual('1bcd2f', ''.join(request.written))
def test_resumeProducingBuffersOutput(self):
"""
L{MultipleRangeStaticProducer.start} writes about
C{abstract.FileDescriptor.bufferSize} bytes of content from the
resource to the request at once.
To be specific about the 'about' above: it can write slightly more,
for example in the case where the first boundary plus the first chunk
is less than C{bufferSize} but first boundary plus the first chunk
plus the second boundary is more, but this is unimportant as in
practice the boundaries are fairly small. On the other side, it is
important for performance to bundle up several small chunks into one
call to request.write.
"""
request = DummyRequest([])
content = '0123456789' * 2
producer = static.MultipleRangeStaticProducer(
request, StringIO.StringIO(content),
[('a', 0, 2), ('b', 5, 10), ('c', 0, 0)])
producer.bufferSize = 10
# DummyRequest.registerProducer pulls all output from the producer, so
# we just need to call start.
producer.start()
expected = [
'a' + content[0:2] + 'b' + content[5:11],
content[11:15] + 'c',
]
self.assertEqual(expected, request.written)
def test_finishCalledWhenDone(self):
"""
L{MultipleRangeStaticProducer.resumeProducing} calls finish() on the
request after it is done producing content.
"""
request = DummyRequest([])
finishDeferred = request.notifyFinish()
callbackList = []
finishDeferred.addCallback(callbackList.append)
producer = static.MultipleRangeStaticProducer(
request, StringIO.StringIO('abcdef'), [('', 1, 2)])
# start calls registerProducer on the DummyRequest, which pulls all
# output from the producer and so we just need this one call.
producer.start()
self.assertEqual([None], callbackList)
class RangeTests(TestCase):
"""
Tests for I{Range-Header} support in L{twisted.web.static.File}.
@type file: L{file}
@ivar file: Temporary (binary) file containing the content to be served.
@type resource: L{static.File}
@ivar resource: A leaf web resource using C{file} as content.
@type request: L{DummyRequest}
@ivar request: A fake request, requesting C{resource}.
@type catcher: L{list}
@ivar catcher: List which gathers all log information.
"""
def setUp(self):
"""
Create a temporary file with a fixed payload of 64 bytes. Create a
resource for that file and create a request which will be for that
resource. Each test can set a different range header to test different
aspects of the implementation.
"""
path = FilePath(self.mktemp())
# This is just a jumble of random stuff. It's supposed to be a good
# set of data for this test, particularly in order to avoid
# accidentally seeing the right result by having a byte sequence
# repeated at different locations or by having byte values which are
# somehow correlated with their position in the string.
self.payload = ('\xf8u\xf3E\x8c7\xce\x00\x9e\xb6a0y0S\xf0\xef\xac\xb7'
'\xbe\xb5\x17M\x1e\x136k{\x1e\xbe\x0c\x07\x07\t\xd0'
'\xbckY\xf5I\x0b\xb8\x88oZ\x1d\x85b\x1a\xcdk\xf2\x1d'
'&\xfd%\xdd\x82q/A\x10Y\x8b')
path.setContent(self.payload)
self.file = path.open()
self.resource = static.File(self.file.name)
self.resource.isLeaf = 1
self.request = DummyRequest([''])
self.request.uri = self.file.name
self.catcher = []
log.addObserver(self.catcher.append)
def tearDown(self):
"""
Clean up the resource file and the log observer.
"""
self.file.close()
log.removeObserver(self.catcher.append)
def _assertLogged(self, expected):
"""
Asserts that a given log message occurred with an expected message.
"""
logItem = self.catcher.pop()
self.assertEquals(logItem["message"][0], expected)
self.assertEqual(
self.catcher, [], "An additional log occured: %r" % (logItem,))
def test_invalidRanges(self):
"""
L{File._parseRangeHeader} raises L{ValueError} when passed
syntactically invalid byte ranges.
"""
f = self.resource._parseRangeHeader
# there's no =
self.assertRaises(ValueError, f, 'bytes')
# unknown isn't a valid Bytes-Unit
self.assertRaises(ValueError, f, 'unknown=1-2')
# there's no - in =stuff
self.assertRaises(ValueError, f, 'bytes=3')
# both start and end are empty
self.assertRaises(ValueError, f, 'bytes=-')
# start isn't an integer
self.assertRaises(ValueError, f, 'bytes=foo-')
# end isn't an integer
self.assertRaises(ValueError, f, 'bytes=-foo')
# end isn't equal to or greater than start
self.assertRaises(ValueError, f, 'bytes=5-4')
def test_rangeMissingStop(self):
"""
A single bytes range without an explicit stop position is parsed into a
two-tuple giving the start position and C{None}.
"""
self.assertEqual(
self.resource._parseRangeHeader('bytes=0-'), [(0, None)])
def test_rangeMissingStart(self):
"""
A single bytes range without an explicit start position is parsed into
a two-tuple of C{None} and the end position.
"""
self.assertEqual(
self.resource._parseRangeHeader('bytes=-3'), [(None, 3)])
def test_range(self):
"""
A single bytes range with explicit start and stop positions is parsed
into a two-tuple of those positions.
"""
self.assertEqual(
self.resource._parseRangeHeader('bytes=2-5'), [(2, 5)])
def test_rangeWithSpace(self):
"""
A single bytes range with whitespace in allowed places is parsed in
the same way as it would be without the whitespace.
"""
self.assertEqual(
self.resource._parseRangeHeader(' bytes=1-2 '), [(1, 2)])
self.assertEqual(
self.resource._parseRangeHeader('bytes =1-2 '), [(1, 2)])
self.assertEqual(
self.resource._parseRangeHeader('bytes= 1-2'), [(1, 2)])
self.assertEqual(
self.resource._parseRangeHeader('bytes=1 -2'), [(1, 2)])
self.assertEqual(
self.resource._parseRangeHeader('bytes=1- 2'), [(1, 2)])
self.assertEqual(
self.resource._parseRangeHeader('bytes=1-2 '), [(1, 2)])
def test_nullRangeElements(self):
"""
If there are multiple byte ranges but only one is non-null, the
non-null range is parsed and its start and stop returned.
"""
self.assertEqual(
self.resource._parseRangeHeader('bytes=1-2,\r\n, ,\t'), [(1, 2)])
def test_multipleRanges(self):
"""
If multiple byte ranges are specified their starts and stops are
returned.
"""
self.assertEqual(
self.resource._parseRangeHeader('bytes=1-2,3-4'),
[(1, 2), (3, 4)])
def test_bodyLength(self):
"""
A correct response to a range request is as long as the length of the
requested range.
"""
self.request.headers['range'] = 'bytes=0-43'
self.resource.render(self.request)
self.assertEquals(len(''.join(self.request.written)), 44)
def test_invalidRangeRequest(self):
"""
An incorrect range request (RFC 2616 defines a correct range request as
a Bytes-Unit followed by a '=' character followed by a specific range.
Only 'bytes' is defined) results in the range header value being logged
and a normal 200 response being sent.
"""
self.request.headers['range'] = range = 'foobar=0-43'
self.resource.render(self.request)
expected = "Ignoring malformed Range header %r" % (range,)
self._assertLogged(expected)
self.assertEquals(''.join(self.request.written), self.payload)
self.assertEquals(self.request.responseCode, http.OK)
self.assertEquals(
self.request.outgoingHeaders['content-length'],
str(len(self.payload)))
def parseMultipartBody(self, body, boundary):
"""
Parse C{body} as a multipart MIME response separated by C{boundary}.
Note that this with fail the calling test on certain syntactic
problems.
"""
sep = "\r\n--" + boundary
parts = ''.join(body).split(sep)
self.assertEquals('', parts[0])
self.assertEquals('--\r\n', parts[-1])
parsed_parts = []
for part in parts[1:-1]:
before, header1, header2, blank, partBody = part.split('\r\n', 4)
headers = header1 + '\n' + header2
self.assertEqual('', before)
self.assertEqual('', blank)
partContentTypeValue = re.search(
'^content-type: (.*)$', headers, re.I|re.M).group(1)
start, end, size = re.search(
'^content-range: bytes ([0-9]+)-([0-9]+)/([0-9]+)$',
headers, re.I|re.M).groups()
parsed_parts.append(
{'contentType': partContentTypeValue,
'contentRange': (start, end, size),
'body': partBody})
return parsed_parts
def test_multipleRangeRequest(self):
"""
The response to a request for multipe bytes ranges is a MIME-ish
multipart response.
"""
startEnds = [(0, 2), (20, 30), (40, 50)]
rangeHeaderValue = ','.join(["%s-%s"%(s,e) for (s, e) in startEnds])
self.request.headers['range'] = 'bytes=' + rangeHeaderValue
self.resource.render(self.request)
self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT)
boundary = re.match(
'^multipart/byteranges; boundary="(.*)"$',
self.request.outgoingHeaders['content-type']).group(1)
parts = self.parseMultipartBody(''.join(self.request.written), boundary)
self.assertEquals(len(startEnds), len(parts))
for part, (s, e) in zip(parts, startEnds):
self.assertEqual(self.resource.type, part['contentType'])
start, end, size = part['contentRange']
self.assertEqual(int(start), s)
self.assertEqual(int(end), e)
self.assertEqual(int(size), self.resource.getFileSize())
self.assertEqual(self.payload[s:e+1], part['body'])
def test_multipleRangeRequestWithRangeOverlappingEnd(self):
"""
The response to a request for multipe bytes ranges is a MIME-ish
multipart response, even when one of the ranged falls off the end of
the resource.
"""
startEnds = [(0, 2), (40, len(self.payload) + 10)]
rangeHeaderValue = ','.join(["%s-%s"%(s,e) for (s, e) in startEnds])
self.request.headers['range'] = 'bytes=' + rangeHeaderValue
self.resource.render(self.request)
self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT)
boundary = re.match(
'^multipart/byteranges; boundary="(.*)"$',
self.request.outgoingHeaders['content-type']).group(1)
parts = self.parseMultipartBody(''.join(self.request.written), boundary)
self.assertEquals(len(startEnds), len(parts))
for part, (s, e) in zip(parts, startEnds):
self.assertEqual(self.resource.type, part['contentType'])
start, end, size = part['contentRange']
self.assertEqual(int(start), s)
self.assertEqual(int(end), min(e, self.resource.getFileSize()-1))
self.assertEqual(int(size), self.resource.getFileSize())
self.assertEqual(self.payload[s:e+1], part['body'])
def test_implicitEnd(self):
"""
If the end byte position is omitted, then it is treated as if the
length of the resource was specified by the end byte position.
"""
self.request.headers['range'] = 'bytes=23-'
self.resource.render(self.request)
self.assertEquals(''.join(self.request.written), self.payload[23:])
self.assertEquals(len(''.join(self.request.written)), 41)
self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT)
self.assertEquals(
self.request.outgoingHeaders['content-range'], 'bytes 23-63/64')
self.assertEquals(self.request.outgoingHeaders['content-length'], '41')
def test_implicitStart(self):
"""
If the start byte position is omitted but the end byte position is
supplied, then the range is treated as requesting the last -N bytes of
the resource, where N is the end byte position.
"""
self.request.headers['range'] = 'bytes=-17'
self.resource.render(self.request)
self.assertEquals(''.join(self.request.written), self.payload[-17:])
self.assertEquals(len(''.join(self.request.written)), 17)
self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT)
self.assertEquals(
self.request.outgoingHeaders['content-range'], 'bytes 47-63/64')
self.assertEquals(self.request.outgoingHeaders['content-length'], '17')
def test_explicitRange(self):
"""
A correct response to a bytes range header request from A to B starts
with the A'th byte and ends with (including) the B'th byte. The first
byte of a page is numbered with 0.
"""
self.request.headers['range'] = 'bytes=3-43'
self.resource.render(self.request)
written = ''.join(self.request.written)
self.assertEquals(written, self.payload[3:44])
self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT)
self.assertEquals(
self.request.outgoingHeaders['content-range'], 'bytes 3-43/64')
self.assertEquals(
str(len(written)), self.request.outgoingHeaders['content-length'])
def test_explicitRangeOverlappingEnd(self):
"""
A correct response to a bytes range header request from A to B when B
is past the end of the resource starts with the A'th byte and ends
with the last byte of the resource. The first byte of a page is
numbered with 0.
"""
self.request.headers['range'] = 'bytes=40-100'
self.resource.render(self.request)
written = ''.join(self.request.written)
self.assertEquals(written, self.payload[40:])
self.assertEquals(self.request.responseCode, http.PARTIAL_CONTENT)
self.assertEquals(
self.request.outgoingHeaders['content-range'], 'bytes 40-63/64')
self.assertEquals(
str(len(written)), self.request.outgoingHeaders['content-length'])
def test_statusCodeRequestedRangeNotSatisfiable(self):
"""
If a range is syntactically invalid due to the start being greater than
the end, the range header is ignored (the request is responded to as if
it were not present).
"""
self.request.headers['range'] = 'bytes=20-13'
self.resource.render(self.request)
self.assertEquals(self.request.responseCode, http.OK)
self.assertEquals(''.join(self.request.written), self.payload)
self.assertEquals(
self.request.outgoingHeaders['content-length'],
str(len(self.payload)))
def test_invalidStartBytePos(self):
"""
If a range is unsatisfiable due to the start not being less than the
length of the resource, the response is 416 (Requested range not
satisfiable) and no data is written to the response body (RFC 2616,
section 14.35.1).
"""
self.request.headers['range'] = 'bytes=67-108'
self.resource.render(self.request)
self.assertEquals(
self.request.responseCode, http.REQUESTED_RANGE_NOT_SATISFIABLE)
self.assertEquals(''.join(self.request.written), '')
self.assertEquals(self.request.outgoingHeaders['content-length'], '0')
# Sections 10.4.17 and 14.16
self.assertEquals(
self.request.outgoingHeaders['content-range'],
'bytes */%d' % (len(self.payload),))
class DirectoryListerTest(TestCase):
"""
Tests for L{static.DirectoryLister}.
"""
def _request(self, uri):
request = DummyRequest([''])
request.uri = uri
return request
def test_renderHeader(self):
"""
L{static.DirectoryLister} prints the request uri as header of the
rendered content.
"""
path = FilePath(self.mktemp())
path.makedirs()
lister = static.DirectoryLister(path.path)
data = lister.render(self._request('foo'))
self.assertIn("<h1>Directory listing for foo</h1>", data)
self.assertIn("<title>Directory listing for foo</title>", data)
def test_renderUnquoteHeader(self):
"""
L{static.DirectoryLister} unquote the request uri before printing it.
"""
path = FilePath(self.mktemp())
path.makedirs()
lister = static.DirectoryLister(path.path)
data = lister.render(self._request('foo%20bar'))
self.assertIn("<h1>Directory listing for foo bar</h1>", data)
self.assertIn("<title>Directory listing for foo bar</title>", data)
def test_escapeHeader(self):
"""
L{static.DirectoryLister} escape "&", "<" and ">" after unquoting the
request uri.
"""
path = FilePath(self.mktemp())
path.makedirs()
lister = static.DirectoryLister(path.path)
data = lister.render(self._request('foo%26bar'))
self.assertIn("<h1>Directory listing for foo&bar</h1>", data)
self.assertIn("<title>Directory listing for foo&bar</title>", data)
def test_renderFiles(self):
"""
L{static.DirectoryLister} is able to list all the files inside a
directory.
"""
path = FilePath(self.mktemp())
path.makedirs()
path.child('file1').setContent("content1")
path.child('file2').setContent("content2" * 1000)
lister = static.DirectoryLister(path.path)
data = lister.render(self._request('foo'))
body = """<tr class="odd">
<td><a href="file1">file1</a></td>
<td>8B</td>
<td>[text/html]</td>
<td></td>
</tr>
<tr class="even">
<td><a href="file2">file2</a></td>
<td>7K</td>
<td>[text/html]</td>
<td></td>
</tr>"""
self.assertIn(body, data)
def test_renderDirectories(self):
"""
L{static.DirectoryLister} is able to list all the directories inside
a directory.
"""
path = FilePath(self.mktemp())
path.makedirs()
path.child('dir1').makedirs()
path.child('dir2 & 3').makedirs()
lister = static.DirectoryLister(path.path)
data = lister.render(self._request('foo'))
body = """<tr class="odd">
<td><a href="dir1/">dir1/</a></td>
<td></td>
<td>[Directory]</td>
<td></td>
</tr>
<tr class="even">
<td><a href="dir2%20%26%203/">dir2 & 3/</a></td>
<td></td>
<td>[Directory]</td>
<td></td>
</tr>"""
self.assertIn(body, data)
def test_renderFiltered(self):
"""
L{static.DirectoryLister} takes a optional C{dirs} argument that
filter out the list of of directories and files printed.
"""
path = FilePath(self.mktemp())
path.makedirs()
path.child('dir1').makedirs()
path.child('dir2').makedirs()
path.child('dir3').makedirs()
lister = static.DirectoryLister(path.path, dirs=["dir1", "dir3"])
data = lister.render(self._request('foo'))
body = """<tr class="odd">
<td><a href="dir1/">dir1/</a></td>
<td></td>
<td>[Directory]</td>
<td></td>
</tr>
<tr class="even">
<td><a href="dir3/">dir3/</a></td>
<td></td>
<td>[Directory]</td>
<td></td>
</tr>"""
self.assertIn(body, data)
def test_oddAndEven(self):
"""
L{static.DirectoryLister} gives an alternate class for each odd and
even rows in the table.
"""
lister = static.DirectoryLister(None)
elements = [{"href": "", "text": "", "size": "", "type": "",
"encoding": ""} for i in xrange(5)]
content = lister._buildTableContent(elements)
self.assertEquals(len(content), 5)
self.assertTrue(content[0].startswith('<tr class="odd">'))
self.assertTrue(content[1].startswith('<tr class="even">'))
self.assertTrue(content[2].startswith('<tr class="odd">'))
self.assertTrue(content[3].startswith('<tr class="even">'))
self.assertTrue(content[4].startswith('<tr class="odd">'))
def test_mimeTypeAndEncodings(self):
"""
L{static.DirectoryLister} is able to detect mimetype and encoding of
listed files.
"""
path = FilePath(self.mktemp())
path.makedirs()
path.child('file1.txt').setContent("file1")
path.child('file2.py').setContent("python")
path.child('file3.conf.gz').setContent("conf compressed")
path.child('file4.diff.bz2').setContent("diff compressed")
directory = os.listdir(path.path)
directory.sort()
contentTypes = {
".txt": "text/plain",
".py": "text/python",
".conf": "text/configuration",
".diff": "text/diff"
}
lister = static.DirectoryLister(path.path, contentTypes=contentTypes)
dirs, files = lister._getFilesAndDirectories(directory)
self.assertEquals(dirs, [])
self.assertEquals(files, [
{'encoding': '',
'href': 'file1.txt',
'size': '5B',
'text': 'file1.txt',
'type': '[text/plain]'},
{'encoding': '',
'href': 'file2.py',
'size': '6B',
'text': 'file2.py',
'type': '[text/python]'},
{'encoding': '[gzip]',
'href': 'file3.conf.gz',
'size': '15B',
'text': 'file3.conf.gz',
'type': '[text/configuration]'},
{'encoding': '[bzip2]',
'href': 'file4.diff.bz2',
'size': '15B',
'text': 'file4.diff.bz2',
'type': '[text/diff]'}])
def test_brokenSymlink(self):
"""
If on the file in the listing points to a broken symlink, it should not
be returned by L{static.DirectoryLister._getFilesAndDirectories}.
"""
path = FilePath(self.mktemp())
path.makedirs()
file1 = path.child('file1')
file1.setContent("file1")
file1.linkTo(path.child("file2"))
file1.remove()
lister = static.DirectoryLister(path.path)
directory = os.listdir(path.path)
directory.sort()
dirs, files = lister._getFilesAndDirectories(directory)
self.assertEquals(dirs, [])
self.assertEquals(files, [])
if getattr(os, "symlink", None) is None:
test_brokenSymlink.skip = "No symlink support"
def test_childrenNotFound(self):
"""
Any child resource of L{static.DirectoryLister} renders an HTTP
I{NOT FOUND} response code.
"""
path = FilePath(self.mktemp())
path.makedirs()
lister = static.DirectoryLister(path.path)
request = self._request('')
child = resource.getChildForRequest(lister, request)
result = _render(child, request)
def cbRendered(ignored):
self.assertEquals(request.responseCode, http.NOT_FOUND)
result.addCallback(cbRendered)
return result
def test_repr(self):
"""
L{static.DirectoryLister.__repr__} gives the path of the lister.
"""
path = FilePath(self.mktemp())
lister = static.DirectoryLister(path.path)
self.assertEquals(repr(lister),
"<DirectoryLister of %r>" % (path.path,))
self.assertEquals(str(lister),
"<DirectoryLister of %r>" % (path.path,))
def test_formatFileSize(self):
"""
L{static.formatFileSize} format an amount of bytes into a more readable
format.
"""
self.assertEquals(static.formatFileSize(0), "0B")
self.assertEquals(static.formatFileSize(123), "123B")
self.assertEquals(static.formatFileSize(4567), "4K")
self.assertEquals(static.formatFileSize(8900000), "8M")
self.assertEquals(static.formatFileSize(1234000000), "1G")
self.assertEquals(static.formatFileSize(1234567890000), "1149G")
class TestFileTransferDeprecated(TestCase):
"""
L{static.FileTransfer} is deprecated.
"""
def test_deprecation(self):
"""
Instantiation of L{FileTransfer} produces a deprecation warning.
"""
static.FileTransfer(StringIO.StringIO(), 0, DummyRequest([]))
warnings = self.flushWarnings([self.test_deprecation])
self.assertEqual(len(warnings), 1)
self.assertEqual(warnings[0]['category'], DeprecationWarning)
self.assertEqual(
warnings[0]['message'],
'FileTransfer is deprecated since Twisted 9.0. '
'Use a subclass of StaticProducer instead.')
|
gpl-3.0
|
pongsakcu/particlevis
|
VectorRenderer.h
|
1065
|
/*
VectorRenderer
This class facilitates particle data vector rendering. Various vector types, defined in
Particle.h, are supported. All vectors are rendered using lines and an arrowhead that is
determined by the vector type. Color classification is also tied to the vector type, using
the gradient approach.
By Vincent Hoon, 2007
See copyright notice in copyright.txt for conditions of distribution and use.
*/
#pragma once
#include "Renderer.h"
#include "GLLineBuffer.h"
class VectorRenderer :
public Renderer
{
public:
VectorRenderer(void);
~VectorRenderer(void);
void SetSize(int size); // possible resizing logic
void Clear(); // call before new frame
void Load(triple* position, quad* orientation, triple* d_pos, triple* d_theta, Particle* p); // load in particle data
void Render(); // call to render
void SetType(int vectortype) { type = vectortype; }
protected:
int type;
bool bound;
GLLineBuffer vBuf;
TransVelocityClassifier vel_coloring;
RotVelocityClassifier rot_coloring;
VectorFieldClassifier field_coloring;
};
|
gpl-3.0
|
ozaretskyi/bash-scripts
|
README.md
|
121
|
# bash-scripts
centos-router.sh - Script to run on centos router VM
ubuntu-client.sh - Script to run on ubuntu client VM
|
gpl-3.0
|
Niky4000/UsefulUtils
|
projects/tutorials-master/tutorials-master/raml/modularization/README.md
|
221
|
=========
## Modular RESTful API Modeling Language
### Relevant Articles:
- [Modular RAML Using Includes, Libraries, Overlays and Extensions](http://www.baeldung.com/modular-raml-includes-overlays-libraries-extensions)
|
gpl-3.0
|
kshark27/UltraExplorer
|
filebrowserULTRA/src/com/mirrorlabs/filebrowser/ProcessManager.java
|
24569
|
package com.mirrorlabs.filebrowser;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.IntentAction;
import com.mirrorlabs.filebrowser.FilebrowserULTRAActivity.Fonts;
import com.mirrorlabs.menupopup.MenuItem;
import com.mirrorlabs.menupopup.PopupMenu;
import com.mirrorlabs.menupopup.PopupMenu.OnItemSelectedListener;
import com.mirrorlabs.quickaction.ActionItem;
import com.mirrorlabs.quickaction.QuickAction;
public class ProcessManager extends ListActivity {
private final int CONVERT = 1024;
private static final String STAR_STATES = "mylist:star_states";
private boolean[] mStarStates=null;
private static final String[] Q = new String[]{"B", "KB", "MB", "GB", "T", "P", "E"};
private static PackageManager pk;
private static List<RunningAppProcessInfo> display_process;
private static ActivityManager activity_man;
private static TextView availMem_label, numProc_label;
private static ListView mylist;
private ApplicationInfo appinfo = null;
private PackageInfo pkginfo = null;
private static final int ID_LAUNCH = 1;
private static final int ID_DETAILS = 2;
private static final int ID_INFO = 3;
private static final int ID_UNINSTAL = 4;
private static final int ID_KILL = 5;
public static int[] pidvalue;
private static List<String> multiSelectData=null;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.manage_layout);
//Toast.makeText(ProcessManager.this," allocated size = " + getAsString(Debug.getNativeHeapAllocatedSize()), 1).show();
pk = getPackageManager();
availMem_label = (TextView)findViewById(R.id.available_mem_label);
availMem_label.setTypeface(Fonts.ICS);
numProc_label = (TextView)findViewById(R.id.num_processes_label);
numProc_label.setTypeface(Fonts.ICS);
Button killall_button = (Button)findViewById(R.id.killall_button);
killall_button.setTypeface(Fonts.ICS);
Button cancel_button = (Button)findViewById(R.id.cancel_button);
cancel_button.setTypeface(Fonts.ICS);
activity_man = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
display_process = new ArrayList<RunningAppProcessInfo>();
//setup ActionBar
final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
actionBar.setTitle("Process Manager");
actionBar.setHomeAction(new IntentAction(this, FilebrowserULTRAActivity.createIntent(this), R.drawable.ic_title_home_default));
actionBar.setDisplayHomeAsUpEnabled(true);
final AsyncTask loadAppsTask = new AsyncTask<String[], Long, Long>(){
@Override
protected Long doInBackground(String[]... params) {
update_list();
return null;
}
protected void onPreExecute() {
actionBar.setProgressBarVisibility(View.VISIBLE);
availMem_label.setText("calculating...");
numProc_label.setText("Listing Processes...");
}
@Override
protected void onProgressUpdate(Long... updatedSize){
}
@Override
protected void onPostExecute(Long result){
actionBar.setProgressBarVisibility(View.GONE);
setListAdapter(new MyListAdapter());
if (savedInstanceState != null) {
mStarStates = savedInstanceState.getBooleanArray(STAR_STATES);
} else {
mStarStates = new boolean[display_process.size()];
}
update_labels();
}
}.execute();
mylist = getListView();
mylist.setFastScrollEnabled(true);
mylist.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> av, View v,
final int position , long id) {
// TODO Auto-generated method stub
getoptions(position,v);
return false;
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBooleanArray(STAR_STATES, mStarStates);
}
public void getoptions(final int position , View view){
String processname = display_process.get(position).processName.toString();
PopupMenu menu = new PopupMenu(ProcessManager.this);
menu.setHeaderTitle("Process Options");
menu.setHeaderIcon(getProcessIcon(processname));
// Set Listener
menu.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case ID_LAUNCH:
Intent i = pk.getLaunchIntentForPackage(display_process.get(position).processName);
if(i != null)
startActivity(i);
else
Toast.makeText(ProcessManager.this, "Could not launch", Toast.LENGTH_SHORT).show();
break;
case ID_KILL:
try {
killProcess(ProcessManager.this, display_process.get(position).pid, display_process.get(position).processName);
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(ProcessManager.this, "couldn't kill the process ",Toast.LENGTH_SHORT).show();
}
@SuppressWarnings("unchecked")
final ArrayAdapter<RunningAppProcessInfo> adapter = (ArrayAdapter<RunningAppProcessInfo>) getListAdapter();
Toast.makeText(ProcessManager.this,display_process.get(position).processName + " was killed !", Toast.LENGTH_SHORT).show();
adapter.remove(display_process.get(position));
update_labels();
break;
case ID_DETAILS:
final int apiLevel = Build.VERSION.SDK_INT;
Intent intent = new Intent();
if (apiLevel >= 9) {
//TODO get working on gb
//Toast.makeText(SDMove.this, "Gingerbread Not Currently Supported", Toast.LENGTH_LONG).show();
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + display_process.get(position).processName)));
} else {
final String appPkgName = (apiLevel == 8 ? "pkg" : "com.android.settings.ApplicationPkgName");
intent.setAction(Intent.ACTION_VIEW);
intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
intent.putExtra(appPkgName, display_process.get(position).processName);
startActivity(intent);
}
break;
case ID_UNINSTAL:
try{
Intent uninstall_intent= new Intent(Intent.ACTION_DELETE);
uninstall_intent.setData(Uri.parse("package:"+display_process.get(position).processName));
startActivity(uninstall_intent);
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(ProcessManager.this,"Can't Uninstall" , Toast.LENGTH_SHORT).show();
}
break;
case ID_INFO:
//Toast.makeText(ProcessManager.this, "Process : "+display_process.get(position).processName +" lru : " +display_process.get(position).lru + " Pid : " +display_process.get(position).pid, Toast.LENGTH_SHORT).show();
final AlertDialog alert1 = new AlertDialog.Builder(ProcessManager.this).create();
alert1.setTitle("Process Info");
alert1.setIcon(getProcessIcon(display_process.get(position).processName));
alert1.setMessage("Process : "+display_process.get(position).processName+ " \nlru : "+display_process.get(position).lru + "\nPid : " +display_process.get(position).pid );
alert1.show();
}
}
});
// Add Menu (Android menu like style)
menu.add(ID_LAUNCH, R.string.launch).setIcon(
getResources().getDrawable(R.drawable.install));
menu.add(ID_DETAILS, R.string.details).setIcon(
getResources().getDrawable(R.drawable.advancedsettings));
menu.add(ID_INFO, R.string.info).setIcon(
getResources().getDrawable(R.drawable.info));
// menu.add(ID_UNINSTAL, R.string.uninstall).setIcon(
// getResources().getDrawable(R.drawable.uninstall));
menu.add(ID_KILL, R.string.kill).setIcon(
getResources().getDrawable(R.drawable.delete));
menu.show(view);
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
System.gc();
}
@Override
protected void onResume() {
super.onResume();
}
public void onClick(View view){
switch (view.getId()) {
case R.id.cancel_button :
finish();
break;
case R.id.killall_button:
//i hate this method it doesn't work...but still.
//have to change it and write another code..
List<RunningAppProcessInfo> total_process = activity_man.getRunningAppProcesses();
int len;
len = total_process.size();
int count=0;
for (int i = 0; i < len; i++){
if(total_process.get(i).importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
total_process.get(i).importance != RunningAppProcessInfo.IMPORTANCE_SERVICE){
count++;
}
}
for (int i = 0;i<count;i++){
try {
killProcess(ProcessManager.this, display_process.get(i).pid, display_process.get(i).processName);
@SuppressWarnings("unchecked")
final ArrayAdapter<RunningAppProcessInfo> adapter = (ArrayAdapter<RunningAppProcessInfo>) getListAdapter();
adapter.remove(display_process.get(i));
} catch (Exception e) {
e.printStackTrace();
}
}
update_labels();
Toast.makeText(ProcessManager.this, count + " processes were killed !", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
protected void onListItemClick(ListView mylist, View view, final int position, long id) {
ActionItem killItem = new ActionItem(ID_KILL, "Kill this", getResources().getDrawable(R.drawable.delete));
ActionItem launchItem = new ActionItem(ID_LAUNCH, "Launch", getResources().getDrawable(R.drawable.install));
ActionItem unisntallItem = new ActionItem(ID_UNINSTAL, "Uninstall", getResources().getDrawable(R.drawable.uninstall));
ActionItem infoItem = new ActionItem(ID_INFO, "Info", getResources().getDrawable(R.drawable.info));
ActionItem detailsItem = new ActionItem(ID_DETAILS, "Manage", getResources().getDrawable(R.drawable.advancedsettings));
final QuickAction quickAction = new QuickAction(this);
//add action items into QuickAction
quickAction.addActionItem(launchItem);
quickAction.addActionItem(detailsItem);
//quickAction.addActionItem(searchItem);
quickAction.addActionItem(infoItem);
// quickAction.addActionItem(unisntallItem);
//quickAction.addActionItem(eraseItem);
quickAction.addActionItem(killItem);
//Set listener for action item clicked
quickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
public void onItemClick(QuickAction source, int pos, int actionId) {
//here we can filter which action item was clicked with pos or actionId parameter
ActionItem actionItem = quickAction.getActionItem(pos);
switch (actionId) {
case ID_KILL:
try {
killProcess(ProcessManager.this, display_process.get(position).pid, display_process.get(position).processName);
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(ProcessManager.this, "couldn't kill the process ",Toast.LENGTH_SHORT).show();
}
@SuppressWarnings("unchecked")
final ArrayAdapter<RunningAppProcessInfo> adapter = (ArrayAdapter<RunningAppProcessInfo>) getListAdapter();
Toast.makeText(ProcessManager.this,display_process.get(position).processName + " was killed !", Toast.LENGTH_SHORT).show();
adapter.remove(display_process.get(position));
update_labels();
break;
case ID_DETAILS:
final int apiLevel = Build.VERSION.SDK_INT;
Intent intent = new Intent();
if (apiLevel >= 9) {
//TODO get working on gb
//Toast.makeText(SDMove.this, "Gingerbread Not Currently Supported", Toast.LENGTH_LONG).show();
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + display_process.get(position).processName)));
} else {
final String appPkgName = (apiLevel == 8 ? "pkg" : "com.android.settings.ApplicationPkgName");
intent.setAction(Intent.ACTION_VIEW);
intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
intent.putExtra(appPkgName, display_process.get(position).processName);
startActivity(intent);
}
break;
case ID_LAUNCH:
Intent i = pk.getLaunchIntentForPackage(display_process.get(position).processName);
if(i != null)
startActivity(i);
else
Toast.makeText(ProcessManager.this, "Could not launch", Toast.LENGTH_SHORT).show();
break;
case ID_UNINSTAL:
try{
Intent uninstall_intent= new Intent(Intent.ACTION_DELETE);
uninstall_intent.setData(Uri.parse("package:"+display_process.get(position).processName));
startActivity(uninstall_intent);
}
catch (Exception e) {
// TODO: handle exception
Toast.makeText(ProcessManager.this,"Can't Uninstall" , Toast.LENGTH_SHORT).show();
}
break;
case ID_INFO:
//Toast.makeText(ProcessManager.this, "Process : "+display_process.get(position).processName +" lru : " +display_process.get(position).lru + " Pid : " +display_process.get(position).pid, Toast.LENGTH_SHORT).show();
final AlertDialog alert1 = new AlertDialog.Builder(ProcessManager.this).create();
alert1.setTitle("Process Info");
alert1.setIcon(getProcessIcon(display_process.get(position).processName));
alert1.setMessage("Process : "+display_process.get(position).processName+ " \nlru : "+display_process.get(position).lru + "\nPid : " +display_process.get(position).pid );
alert1.show();
break;
default:
Toast.makeText(ProcessManager.this, actionItem.getTitle() + " selected", Toast.LENGTH_SHORT).show();
break;
}
}
});
//set listnener for on dismiss event, this listener will be called only if QuickAction dialog was dismissed
//by clicking the area outside the dialog.
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
public void onDismiss() {
}
});
quickAction.show(view);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)){ //Back key pressed
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean killProcess(Context context, int pid, String packageName) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (pid <= 0) { return false; }
if (pid == android.os.Process.myPid()) {
System.out.println("Killing own process");
android.os.Process.killProcess(pid);
return true;
}
Method method = null;
try {
// Since API_LEVEL 8 : v2.2
method = manager.getClass().getMethod("killBackgroundProcesses", new Class[] { String.class});
} catch (NoSuchMethodException e) {
// less than 2.2
try {
method = manager.getClass().getMethod("restartPackage", new Class[] { String.class });
} catch (NoSuchMethodException ee) {
ee.printStackTrace();
}
}
if (method != null) {
try {
method.invoke(manager, packageName);
System.out.println("kill method " + method.getName()+ " invoked " + packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
android.os.Process.killProcess(pid);
return true;
}
private void update_labels() {
MemoryInfo mem_info;
double mem_size;
mem_info = new ActivityManager.MemoryInfo();
activity_man.getMemoryInfo(mem_info);
mem_size = (mem_info.availMem / (CONVERT * CONVERT));
availMem_label.setText(String.format("Available memory:\t %.2f Mb", mem_size));
numProc_label.setText("Number of processes:\t " + display_process.size());
}
public Drawable getProcessIcon(String pkg_name){
try {
return pk.getApplicationIcon(pkg_name);
}catch (Exception e) {
// TODO: handle exception
return getResources().getDrawable(R.drawable.apk_file);
}
}
private void update_list() {
List<RunningAppProcessInfo> total_process = activity_man.getRunningAppProcesses();
int len;
total_process = activity_man.getRunningAppProcesses();
len = total_process.size();
for (int i = 0; i < len; i++){
if(total_process.get(i).importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
total_process.get(i).importance != RunningAppProcessInfo.IMPORTANCE_SERVICE)
display_process.add(total_process.get(i));
}
}
public String getAsString(long bytes)
{
for (int i = 6; i > 0; i--)
{
double step = Math.pow(1024, i);
if (bytes > step) return String.format("%3.1f %s", bytes / step, Q[i]);
}
return Long.toString(bytes);
}
class ViewHolder {
public ImageView image=null;
public TextView name=null;
public CheckBox select=null;
public TextView version =null;
public TextView state=null;
ViewHolder(View row){
name = (TextView)row.findViewById(R.id.app_name);
name.setTypeface(Fonts.ICS);
select = (CheckBox)row.findViewById(R.id.select_icon);
select.setVisibility(View.GONE);
version = (TextView)row.findViewById(R.id.version);
version.setTypeface(Fonts.ICS);
state = (TextView)row.findViewById(R.id.installdate);
state.setTypeface(Fonts.ICS);
image = (ImageView)row.findViewById(R.id.icon);
}
void populateFrom(String s)
{
name.setText(s);
}
}
private class MyListAdapter extends ArrayAdapter<RunningAppProcessInfo> {
public MyListAdapter() {
super(ProcessManager.this, R.layout.app_row, display_process);
}
public String parse_name(String pkgName) {
String[] items = pkgName.split("\\.");
String name = "";
int len = items.length;
for (int i = 0; i < len; i++){
if(!items[i].equalsIgnoreCase("com") && !items[i].equalsIgnoreCase("android") &&
!items[i].equalsIgnoreCase("google") && !items[i].equalsIgnoreCase("process") &&
!items[i].equalsIgnoreCase("htc") && !items[i].equalsIgnoreCase("coremobility"))
name = items[i];
}
return name;
}
@Override
public View getView(int position,View convertView, ViewGroup parent) {
ViewHolder holder;
String pkg_name = display_process.get(position).processName;
CharSequence processName;
try {
appinfo = pk.getApplicationInfo(pkg_name, 0);
processName = appinfo.loadLabel(pk);
} catch (NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
processName = parse_name(pkg_name);
}
if(convertView == null) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.app_row, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.select.setOnCheckedChangeListener(null);
holder.select.setChecked(mStarStates[position]);
holder.select.setOnCheckedChangeListener(mStarCheckedChanceChangeListener);
holder.name.setText(processName);
holder.version.setText(String.format("%s",
display_process.get(position).processName));
if(display_process.get(position).importance==RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
holder.state.setText("Foreground");
}
else if(display_process.get(position).importance==RunningAppProcessInfo.IMPORTANCE_BACKGROUND)
{
holder.state.setText("Background");
}
else if(display_process.get(position).importance==RunningAppProcessInfo.IMPORTANCE_VISIBLE)
{
holder.state.setText("Visible");
}
else if(display_process.get(position).importance==RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE)
{
holder.state.setText("Perceptible");
}
try {
holder.image.setImageDrawable(pk.getApplicationIcon(pkg_name));
} catch (NameNotFoundException e) {
holder.image.setImageResource(R.drawable.apk_file);
}
return convertView;
}
}
private OnCheckedChangeListener mStarCheckedChanceChangeListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final int position = getListView().getPositionForView(buttonView);
if (position != ListView.INVALID_POSITION) {
mStarStates[position] = isChecked;
}
}
};
}
|
gpl-3.0
|
stefaweb/XAMS-0.3.x
|
gui/footer.php
|
206
|
<?php
if (_DEBUGMODE)
{
$creation_time = getmt() - script_start_time;
echo sprintf("<p/><hr/><p>Script took %1.0f ms for generation\n</p>", $creation_time);
}
?>
</body>
</html>
|
gpl-3.0
|
KarlHeitmann/PlanificacionHorarios
|
src/ae/eda/TProfesor.cpp
|
1195
|
#include <string>
#include <vector>
#include "TProfesor.h"
TProfesor::TProfesor(std::string _strNombre, int _intCodigo) {
intCodigo = _intCodigo;
strNombre = _strNombre;
}
TProfesor::TProfesor(const char* _pchrNombre, int _intCodigo) {
intCodigo = _intCodigo;
strNombre = _pchrNombre;
}
void TProfesor::PutCostAsigProf (TCostAsigProf CostAsigProf) {
LCostAsigProf.push_back(CostAsigProf);
}
unsigned TProfesor::FindAsigPos(int intSearchTerm){
unsigned uintIndex=0;
for (unsigned i=0; i<LCostAsigProf.size(); i++) {
if (LCostAsigProf[i].GetCodAsig() == intSearchTerm) {
uintIndex=i;
return uintIndex;
}
}
return (unsigned) 0;
}
std::string TProfesor::GetSummary() {
std::string strTemp="Profesor: " + strNombre + "\n";
for (unsigned i=0; i<LCostAsigProf.size(); i++) {
strTemp+=LCostAsigProf[i].Show()+"\n";
}
return strTemp;
}
int TProfesor::GetCodProf() {
return intCodigo;
}
std::string TProfesor::GetNombre() {
return strNombre;
}
unsigned TProfesor::EscogeHorarioDisplonibleDeAsignatura(unsigned pos) {
return LCostAsigProf[pos].ChooseHorario();
}
TCostHoraProf *TProfesor::EscogeCostHoraProf(unsigned pos) {
return LCostAsigProf[pos].ChooseCostHoraProf();
}
|
gpl-3.0
|
samsitconsulting/TimeKeeper
|
ITT_Admin/ITT_Admin/Database1DataSet2.Designer.vb
|
108780
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.17929
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict Off
Option Explicit On
'''<summary>
'''Represents a strongly typed in-memory cache of data.
'''</summary>
<Global.System.Serializable(), _
Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema"), _
Global.System.Xml.Serialization.XmlRootAttribute("Database1DataSet"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")> _
Partial Public Class Database1DataSet
Inherits Global.System.Data.DataSet
Private tablelogin As loginDataTable
Private tabletimesheet As timesheetDataTable
Private _schemaSerializationMode As Global.System.Data.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.BeginInit
Me.InitClass
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler MyBase.Relations.CollectionChanged, schemaChangedHandler
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context, false)
If (Me.IsBinarySerialized(info, context) = true) Then
Me.InitVars(false)
Dim schemaChangedHandler1 As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler Me.Tables.CollectionChanged, schemaChangedHandler1
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler1
Return
End If
Dim strSchema As String = CType(info.GetValue("XmlSchema", GetType(String)),String)
If (Me.DetermineSchemaSerializationMode(info, context) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet()
ds.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
If (Not (ds.Tables("login")) Is Nothing) Then
MyBase.Tables.Add(New loginDataTable(ds.Tables("login")))
End If
If (Not (ds.Tables("timesheet")) Is Nothing) Then
MyBase.Tables.Add(New timesheetDataTable(ds.Tables("timesheet")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
End If
Me.GetSerializationData(info, context)
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false), _
Global.System.ComponentModel.DesignerSerializationVisibility(Global.System.ComponentModel.DesignerSerializationVisibility.Content)> _
Public ReadOnly Property login() As loginDataTable
Get
Return Me.tablelogin
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false), _
Global.System.ComponentModel.DesignerSerializationVisibility(Global.System.ComponentModel.DesignerSerializationVisibility.Content)> _
Public ReadOnly Property timesheet() As timesheetDataTable
Get
Return Me.tabletimesheet
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.BrowsableAttribute(true), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Visible)> _
Public Overrides Property SchemaSerializationMode() As Global.System.Data.SchemaSerializationMode
Get
Return Me._schemaSerializationMode
End Get
Set
Me._schemaSerializationMode = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Tables() As Global.System.Data.DataTableCollection
Get
Return MyBase.Tables
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Relations() As Global.System.Data.DataRelationCollection
Get
Return MyBase.Relations
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub InitializeDerivedDataSet()
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataSet
Dim cln As Database1DataSet = CType(MyBase.Clone,Database1DataSet)
cln.InitVars
cln.SchemaSerializationMode = Me.SchemaSerializationMode
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function ShouldSerializeTables() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function ShouldSerializeRelations() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub ReadXmlSerializable(ByVal reader As Global.System.Xml.XmlReader)
If (Me.DetermineSchemaSerializationMode(reader) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Me.Reset
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet()
ds.ReadXml(reader)
If (Not (ds.Tables("login")) Is Nothing) Then
MyBase.Tables.Add(New loginDataTable(ds.Tables("login")))
End If
If (Not (ds.Tables("timesheet")) Is Nothing) Then
MyBase.Tables.Add(New timesheetDataTable(ds.Tables("timesheet")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXml(reader)
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetSchemaSerializable() As Global.System.Xml.Schema.XmlSchema
Dim stream As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Me.WriteXmlSchema(New Global.System.Xml.XmlTextWriter(stream, Nothing))
stream.Position = 0
Return Global.System.Xml.Schema.XmlSchema.Read(New Global.System.Xml.XmlTextReader(stream), Nothing)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Overloads Sub InitVars()
Me.InitVars(true)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Overloads Sub InitVars(ByVal initTable As Boolean)
Me.tablelogin = CType(MyBase.Tables("login"),loginDataTable)
If (initTable = true) Then
If (Not (Me.tablelogin) Is Nothing) Then
Me.tablelogin.InitVars
End If
End If
Me.tabletimesheet = CType(MyBase.Tables("timesheet"),timesheetDataTable)
If (initTable = true) Then
If (Not (Me.tabletimesheet) Is Nothing) Then
Me.tabletimesheet.InitVars
End If
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.DataSetName = "Database1DataSet"
Me.Prefix = ""
Me.Namespace = "http://tempuri.org/Database1DataSet2.xsd"
Me.EnforceConstraints = true
Me.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
Me.tablelogin = New loginDataTable()
MyBase.Tables.Add(Me.tablelogin)
Me.tabletimesheet = New timesheetDataTable()
MyBase.Tables.Add(Me.tabletimesheet)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function ShouldSerializelogin() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function ShouldSerializetimesheet() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub SchemaChanged(ByVal sender As Object, ByVal e As Global.System.ComponentModel.CollectionChangeEventArgs)
If (e.Action = Global.System.ComponentModel.CollectionChangeAction.Remove) Then
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedDataSetSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim ds As Database1DataSet = New Database1DataSet()
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim any As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any.Namespace = ds.Namespace
sequence.Items.Add(any)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Delegate Sub loginRowChangeEventHandler(ByVal sender As Object, ByVal e As loginRowChangeEvent)
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Delegate Sub timesheetRowChangeEventHandler(ByVal sender As Object, ByVal e As timesheetRowChangeEvent)
'''<summary>
'''Represents the strongly named DataTable class.
'''</summary>
<Global.System.Serializable(), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")> _
Partial Public Class loginDataTable
Inherits Global.System.Data.TypedTableBase(Of loginRow)
Private columnuser_id As Global.System.Data.DataColumn
Private columnname As Global.System.Data.DataColumn
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.TableName = "login"
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal table As Global.System.Data.DataTable)
MyBase.New
Me.TableName = table.TableName
If (table.CaseSensitive <> table.DataSet.CaseSensitive) Then
Me.CaseSensitive = table.CaseSensitive
End If
If (table.Locale.ToString <> table.DataSet.Locale.ToString) Then
Me.Locale = table.Locale
End If
If (table.Namespace <> table.DataSet.Namespace) Then
Me.Namespace = table.Namespace
End If
Me.Prefix = table.Prefix
Me.MinimumCapacity = table.MinimumCapacity
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
Me.InitVars
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property user_idColumn() As Global.System.Data.DataColumn
Get
Return Me.columnuser_id
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property nameColumn() As Global.System.Data.DataColumn
Get
Return Me.columnname
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property Count() As Integer
Get
Return Me.Rows.Count
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Default ReadOnly Property Item(ByVal index As Integer) As loginRow
Get
Return CType(Me.Rows(index),loginRow)
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event loginRowChanging As loginRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event loginRowChanged As loginRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event loginRowDeleting As loginRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event loginRowDeleted As loginRowChangeEventHandler
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Sub AddloginRow(ByVal row As loginRow)
Me.Rows.Add(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Function AddloginRow(ByVal user_id As String, ByVal name As String) As loginRow
Dim rowloginRow As loginRow = CType(Me.NewRow,loginRow)
Dim columnValuesArray() As Object = New Object() {user_id, name}
rowloginRow.ItemArray = columnValuesArray
Me.Rows.Add(rowloginRow)
Return rowloginRow
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function FindByuser_id(ByVal user_id As String) As loginRow
Return CType(Me.Rows.Find(New Object() {user_id}),loginRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataTable
Dim cln As loginDataTable = CType(MyBase.Clone,loginDataTable)
cln.InitVars
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function CreateInstance() As Global.System.Data.DataTable
Return New loginDataTable()
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub InitVars()
Me.columnuser_id = MyBase.Columns("user_id")
Me.columnname = MyBase.Columns("name")
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.columnuser_id = New Global.System.Data.DataColumn("user_id", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnuser_id)
Me.columnname = New Global.System.Data.DataColumn("name", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnname)
Me.Constraints.Add(New Global.System.Data.UniqueConstraint("Constraint1", New Global.System.Data.DataColumn() {Me.columnuser_id}, true))
Me.columnuser_id.AllowDBNull = false
Me.columnuser_id.Unique = true
Me.columnuser_id.MaxLength = 100
Me.columnname.MaxLength = 100
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function NewloginRow() As loginRow
Return CType(Me.NewRow,loginRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function NewRowFromBuilder(ByVal builder As Global.System.Data.DataRowBuilder) As Global.System.Data.DataRow
Return New loginRow(builder)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetRowType() As Global.System.Type
Return GetType(loginRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanged(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanged(e)
If (Not (Me.loginRowChangedEvent) Is Nothing) Then
RaiseEvent loginRowChanged(Me, New loginRowChangeEvent(CType(e.Row,loginRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanging(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanging(e)
If (Not (Me.loginRowChangingEvent) Is Nothing) Then
RaiseEvent loginRowChanging(Me, New loginRowChangeEvent(CType(e.Row,loginRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleted(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleted(e)
If (Not (Me.loginRowDeletedEvent) Is Nothing) Then
RaiseEvent loginRowDeleted(Me, New loginRowChangeEvent(CType(e.Row,loginRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleting(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleting(e)
If (Not (Me.loginRowDeletingEvent) Is Nothing) Then
RaiseEvent loginRowDeleting(Me, New loginRowChangeEvent(CType(e.Row,loginRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub RemoveloginRow(ByVal row As loginRow)
Me.Rows.Remove(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedTableSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim ds As Database1DataSet = New Database1DataSet()
Dim any1 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any1.Namespace = "http://www.w3.org/2001/XMLSchema"
any1.MinOccurs = New Decimal(0)
any1.MaxOccurs = Decimal.MaxValue
any1.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any1)
Dim any2 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"
any2.MinOccurs = New Decimal(1)
any2.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any2)
Dim attribute1 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute1.Name = "namespace"
attribute1.FixedValue = ds.Namespace
type.Attributes.Add(attribute1)
Dim attribute2 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute2.Name = "tableTypeName"
attribute2.FixedValue = "loginDataTable"
type.Attributes.Add(attribute2)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
End Class
'''<summary>
'''Represents the strongly named DataTable class.
'''</summary>
<Global.System.Serializable(), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")> _
Partial Public Class timesheetDataTable
Inherits Global.System.Data.TypedTableBase(Of timesheetRow)
Private columntime_in As Global.System.Data.DataColumn
Private columntime_out As Global.System.Data.DataColumn
Private columnwork_date As Global.System.Data.DataColumn
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.TableName = "timesheet"
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal table As Global.System.Data.DataTable)
MyBase.New
Me.TableName = table.TableName
If (table.CaseSensitive <> table.DataSet.CaseSensitive) Then
Me.CaseSensitive = table.CaseSensitive
End If
If (table.Locale.ToString <> table.DataSet.Locale.ToString) Then
Me.Locale = table.Locale
End If
If (table.Namespace <> table.DataSet.Namespace) Then
Me.Namespace = table.Namespace
End If
Me.Prefix = table.Prefix
Me.MinimumCapacity = table.MinimumCapacity
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
Me.InitVars
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property time_inColumn() As Global.System.Data.DataColumn
Get
Return Me.columntime_in
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property time_outColumn() As Global.System.Data.DataColumn
Get
Return Me.columntime_out
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property work_dateColumn() As Global.System.Data.DataColumn
Get
Return Me.columnwork_date
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property Count() As Integer
Get
Return Me.Rows.Count
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Default ReadOnly Property Item(ByVal index As Integer) As timesheetRow
Get
Return CType(Me.Rows(index),timesheetRow)
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event timesheetRowChanging As timesheetRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event timesheetRowChanged As timesheetRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event timesheetRowDeleting As timesheetRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event timesheetRowDeleted As timesheetRowChangeEventHandler
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Sub AddtimesheetRow(ByVal row As timesheetRow)
Me.Rows.Add(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Function AddtimesheetRow(ByVal time_in As Date, ByVal time_out As String, ByVal work_date As Date) As timesheetRow
Dim rowtimesheetRow As timesheetRow = CType(Me.NewRow,timesheetRow)
Dim columnValuesArray() As Object = New Object() {time_in, time_out, work_date}
rowtimesheetRow.ItemArray = columnValuesArray
Me.Rows.Add(rowtimesheetRow)
Return rowtimesheetRow
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataTable
Dim cln As timesheetDataTable = CType(MyBase.Clone,timesheetDataTable)
cln.InitVars
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function CreateInstance() As Global.System.Data.DataTable
Return New timesheetDataTable()
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub InitVars()
Me.columntime_in = MyBase.Columns("time_in")
Me.columntime_out = MyBase.Columns("time_out")
Me.columnwork_date = MyBase.Columns("work_date")
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.columntime_in = New Global.System.Data.DataColumn("time_in", GetType(Date), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columntime_in)
Me.columntime_out = New Global.System.Data.DataColumn("time_out", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columntime_out)
Me.columnwork_date = New Global.System.Data.DataColumn("work_date", GetType(Date), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnwork_date)
Me.columntime_out.MaxLength = 100
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function NewtimesheetRow() As timesheetRow
Return CType(Me.NewRow,timesheetRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function NewRowFromBuilder(ByVal builder As Global.System.Data.DataRowBuilder) As Global.System.Data.DataRow
Return New timesheetRow(builder)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetRowType() As Global.System.Type
Return GetType(timesheetRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanged(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanged(e)
If (Not (Me.timesheetRowChangedEvent) Is Nothing) Then
RaiseEvent timesheetRowChanged(Me, New timesheetRowChangeEvent(CType(e.Row,timesheetRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanging(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanging(e)
If (Not (Me.timesheetRowChangingEvent) Is Nothing) Then
RaiseEvent timesheetRowChanging(Me, New timesheetRowChangeEvent(CType(e.Row,timesheetRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleted(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleted(e)
If (Not (Me.timesheetRowDeletedEvent) Is Nothing) Then
RaiseEvent timesheetRowDeleted(Me, New timesheetRowChangeEvent(CType(e.Row,timesheetRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleting(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleting(e)
If (Not (Me.timesheetRowDeletingEvent) Is Nothing) Then
RaiseEvent timesheetRowDeleting(Me, New timesheetRowChangeEvent(CType(e.Row,timesheetRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub RemovetimesheetRow(ByVal row As timesheetRow)
Me.Rows.Remove(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedTableSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim ds As Database1DataSet = New Database1DataSet()
Dim any1 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any1.Namespace = "http://www.w3.org/2001/XMLSchema"
any1.MinOccurs = New Decimal(0)
any1.MaxOccurs = Decimal.MaxValue
any1.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any1)
Dim any2 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"
any2.MinOccurs = New Decimal(1)
any2.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any2)
Dim attribute1 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute1.Name = "namespace"
attribute1.FixedValue = ds.Namespace
type.Attributes.Add(attribute1)
Dim attribute2 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute2.Name = "tableTypeName"
attribute2.FixedValue = "timesheetDataTable"
type.Attributes.Add(attribute2)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
End Class
'''<summary>
'''Represents strongly named DataRow class.
'''</summary>
Partial Public Class loginRow
Inherits Global.System.Data.DataRow
Private tablelogin As loginDataTable
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal rb As Global.System.Data.DataRowBuilder)
MyBase.New(rb)
Me.tablelogin = CType(Me.Table,loginDataTable)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property user_id() As String
Get
Return CType(Me(Me.tablelogin.user_idColumn),String)
End Get
Set
Me(Me.tablelogin.user_idColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property name() As String
Get
Try
Return CType(Me(Me.tablelogin.nameColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'name' in table 'login' is DBNull.", e)
End Try
End Get
Set
Me(Me.tablelogin.nameColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsnameNull() As Boolean
Return Me.IsNull(Me.tablelogin.nameColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetnameNull()
Me(Me.tablelogin.nameColumn) = Global.System.Convert.DBNull
End Sub
End Class
'''<summary>
'''Represents strongly named DataRow class.
'''</summary>
Partial Public Class timesheetRow
Inherits Global.System.Data.DataRow
Private tabletimesheet As timesheetDataTable
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal rb As Global.System.Data.DataRowBuilder)
MyBase.New(rb)
Me.tabletimesheet = CType(Me.Table,timesheetDataTable)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property time_in() As Date
Get
Try
Return CType(Me(Me.tabletimesheet.time_inColumn),Date)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'time_in' in table 'timesheet' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletimesheet.time_inColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property time_out() As String
Get
Try
Return CType(Me(Me.tabletimesheet.time_outColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'time_out' in table 'timesheet' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletimesheet.time_outColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property work_date() As Date
Get
Try
Return CType(Me(Me.tabletimesheet.work_dateColumn),Date)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'work_date' in table 'timesheet' is DBNull.", e)
End Try
End Get
Set
Me(Me.tabletimesheet.work_dateColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function Istime_inNull() As Boolean
Return Me.IsNull(Me.tabletimesheet.time_inColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub Settime_inNull()
Me(Me.tabletimesheet.time_inColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function Istime_outNull() As Boolean
Return Me.IsNull(Me.tabletimesheet.time_outColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub Settime_outNull()
Me(Me.tabletimesheet.time_outColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function Iswork_dateNull() As Boolean
Return Me.IsNull(Me.tabletimesheet.work_dateColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub Setwork_dateNull()
Me(Me.tabletimesheet.work_dateColumn) = Global.System.Convert.DBNull
End Sub
End Class
'''<summary>
'''Row event argument class
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Class loginRowChangeEvent
Inherits Global.System.EventArgs
Private eventRow As loginRow
Private eventAction As Global.System.Data.DataRowAction
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New(ByVal row As loginRow, ByVal action As Global.System.Data.DataRowAction)
MyBase.New
Me.eventRow = row
Me.eventAction = action
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Row() As loginRow
Get
Return Me.eventRow
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Action() As Global.System.Data.DataRowAction
Get
Return Me.eventAction
End Get
End Property
End Class
'''<summary>
'''Row event argument class
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Class timesheetRowChangeEvent
Inherits Global.System.EventArgs
Private eventRow As timesheetRow
Private eventAction As Global.System.Data.DataRowAction
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New(ByVal row As timesheetRow, ByVal action As Global.System.Data.DataRowAction)
MyBase.New
Me.eventRow = row
Me.eventAction = action
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Row() As timesheetRow
Get
Return Me.eventRow
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Action() As Global.System.Data.DataRowAction
Get
Return Me.eventAction
End Get
End Property
End Class
End Class
Namespace Database1DataSetTableAdapters
'''<summary>
'''Represents the connection and commands used to retrieve and save data.
'''</summary>
<Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.ComponentModel.DataObjectAttribute(true), _
Global.System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner"& _
", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Partial Public Class loginTableAdapter
Inherits Global.System.ComponentModel.Component
Private WithEvents _adapter As Global.System.Data.SqlServerCe.SqlCeDataAdapter
Private _connection As Global.System.Data.SqlServerCe.SqlCeConnection
Private _transaction As Global.System.Data.SqlServerCe.SqlCeTransaction
Private _commandCollection() As Global.System.Data.SqlServerCe.SqlCeCommand
Private _clearBeforeFill As Boolean
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.ClearBeforeFill = true
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Friend ReadOnly Property Adapter() As Global.System.Data.SqlServerCe.SqlCeDataAdapter
Get
If (Me._adapter Is Nothing) Then
Me.InitAdapter
End If
Return Me._adapter
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Property Connection() As Global.System.Data.SqlServerCe.SqlCeConnection
Get
If (Me._connection Is Nothing) Then
Me.InitConnection
End If
Return Me._connection
End Get
Set
Me._connection = value
If (Not (Me.Adapter.InsertCommand) Is Nothing) Then
Me.Adapter.InsertCommand.Connection = value
End If
If (Not (Me.Adapter.DeleteCommand) Is Nothing) Then
Me.Adapter.DeleteCommand.Connection = value
End If
If (Not (Me.Adapter.UpdateCommand) Is Nothing) Then
Me.Adapter.UpdateCommand.Connection = value
End If
Dim i As Integer = 0
Do While (i < Me.CommandCollection.Length)
If (Not (Me.CommandCollection(i)) Is Nothing) Then
CType(Me.CommandCollection(i),Global.System.Data.SqlServerCe.SqlCeCommand).Connection = value
End If
i = (i + 1)
Loop
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Property Transaction() As Global.System.Data.SqlServerCe.SqlCeTransaction
Get
Return Me._transaction
End Get
Set
Me._transaction = value
Dim i As Integer = 0
Do While (i < Me.CommandCollection.Length)
Me.CommandCollection(i).Transaction = Me._transaction
i = (i + 1)
Loop
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.DeleteCommand) Is Nothing)) Then
Me.Adapter.DeleteCommand.Transaction = Me._transaction
End If
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.InsertCommand) Is Nothing)) Then
Me.Adapter.InsertCommand.Transaction = Me._transaction
End If
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.UpdateCommand) Is Nothing)) Then
Me.Adapter.UpdateCommand.Transaction = Me._transaction
End If
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected ReadOnly Property CommandCollection() As Global.System.Data.SqlServerCe.SqlCeCommand()
Get
If (Me._commandCollection Is Nothing) Then
Me.InitCommandCollection
End If
Return Me._commandCollection
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property ClearBeforeFill() As Boolean
Get
Return Me._clearBeforeFill
End Get
Set
Me._clearBeforeFill = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitAdapter()
Me._adapter = New Global.System.Data.SqlServerCe.SqlCeDataAdapter()
Dim tableMapping As Global.System.Data.Common.DataTableMapping = New Global.System.Data.Common.DataTableMapping()
tableMapping.SourceTable = "Table"
tableMapping.DataSetTable = "login"
tableMapping.ColumnMappings.Add("user_id", "user_id")
tableMapping.ColumnMappings.Add("name", "name")
Me._adapter.TableMappings.Add(tableMapping)
Me._adapter.DeleteCommand = New Global.System.Data.SqlServerCe.SqlCeCommand()
Me._adapter.DeleteCommand.Connection = Me.Connection
Me._adapter.DeleteCommand.CommandText = "DELETE FROM [login] WHERE (([user_id] = @Original_user_id))"
Me._adapter.DeleteCommand.CommandType = Global.System.Data.CommandType.Text
Me._adapter.DeleteCommand.Parameters.Add(New Global.System.Data.SqlServerCe.SqlCeParameter("@Original_user_id", Global.System.Data.SqlDbType.NVarChar, 0, Global.System.Data.ParameterDirection.Input, true, 0, 0, "user_id", Global.System.Data.DataRowVersion.Original, Nothing))
Me._adapter.UpdateCommand = New Global.System.Data.SqlServerCe.SqlCeCommand()
Me._adapter.UpdateCommand.Connection = Me.Connection
Me._adapter.UpdateCommand.CommandText = "UPDATE [login] SET [user_id] = @user_id, [name] = @name WHERE (([user_id] = @Orig"& _
"inal_user_id))"
Me._adapter.UpdateCommand.CommandType = Global.System.Data.CommandType.Text
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlServerCe.SqlCeParameter("@user_id", Global.System.Data.SqlDbType.NVarChar, 0, Global.System.Data.ParameterDirection.Input, true, 0, 0, "user_id", Global.System.Data.DataRowVersion.Current, Nothing))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlServerCe.SqlCeParameter("@name", Global.System.Data.SqlDbType.NVarChar, 0, Global.System.Data.ParameterDirection.Input, true, 0, 0, "name", Global.System.Data.DataRowVersion.Current, Nothing))
Me._adapter.UpdateCommand.Parameters.Add(New Global.System.Data.SqlServerCe.SqlCeParameter("@Original_user_id", Global.System.Data.SqlDbType.NVarChar, 0, Global.System.Data.ParameterDirection.Input, true, 0, 0, "user_id", Global.System.Data.DataRowVersion.Original, Nothing))
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitConnection()
Me._connection = New Global.System.Data.SqlServerCe.SqlCeConnection()
Me._connection.ConnectionString = Global.ITT_Admin.My.MySettings.Default.Database1ConnectionString
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitCommandCollection()
Me._commandCollection = New Global.System.Data.SqlServerCe.SqlCeCommand(0) {}
Me._commandCollection(0) = New Global.System.Data.SqlServerCe.SqlCeCommand()
Me._commandCollection(0).Connection = Me.Connection
Me._commandCollection(0).CommandText = "SELECT [user_id], [name] FROM [login]"
Me._commandCollection(0).CommandType = Global.System.Data.CommandType.Text
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Fill, true)> _
Public Overloads Overridable Function Fill(ByVal dataTable As Database1DataSet.loginDataTable) As Integer
Me.Adapter.SelectCommand = Me.CommandCollection(0)
If (Me.ClearBeforeFill = true) Then
dataTable.Clear
End If
Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Return returnValue
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.[Select], true)> _
Public Overloads Overridable Function GetData() As Database1DataSet.loginDataTable
Me.Adapter.SelectCommand = Me.CommandCollection(0)
Dim dataTable As Database1DataSet.loginDataTable = New Database1DataSet.loginDataTable()
Me.Adapter.Fill(dataTable)
Return dataTable
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataTable As Database1DataSet.loginDataTable) As Integer
Return Me.Adapter.Update(dataTable)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataSet As Database1DataSet) As Integer
Return Me.Adapter.Update(dataSet, "login")
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataRow As Global.System.Data.DataRow) As Integer
Return Me.Adapter.Update(New Global.System.Data.DataRow() {dataRow})
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Public Overloads Overridable Function Update(ByVal dataRows() As Global.System.Data.DataRow) As Integer
Return Me.Adapter.Update(dataRows)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Delete, true)> _
Public Overloads Overridable Function Delete(ByVal Original_user_id As String) As Integer
If (Original_user_id Is Nothing) Then
Throw New Global.System.ArgumentNullException("Original_user_id")
Else
Me.Adapter.DeleteCommand.Parameters(0).Value = CType(Original_user_id,String)
End If
Dim previousConnectionState As Global.System.Data.ConnectionState = Me.Adapter.DeleteCommand.Connection.State
If ((Me.Adapter.DeleteCommand.Connection.State And Global.System.Data.ConnectionState.Open) _
<> Global.System.Data.ConnectionState.Open) Then
Me.Adapter.DeleteCommand.Connection.Open
End If
Try
Dim returnValue As Integer = Me.Adapter.DeleteCommand.ExecuteNonQuery
Return returnValue
Finally
If (previousConnectionState = Global.System.Data.ConnectionState.Closed) Then
Me.Adapter.DeleteCommand.Connection.Close
End If
End Try
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Update, true)> _
Public Overloads Overridable Function Update(ByVal user_id As String, ByVal name As String, ByVal Original_user_id As String) As Integer
If (user_id Is Nothing) Then
Throw New Global.System.ArgumentNullException("user_id")
Else
Me.Adapter.UpdateCommand.Parameters(0).Value = CType(user_id,String)
End If
If (name Is Nothing) Then
Me.Adapter.UpdateCommand.Parameters(1).Value = Global.System.DBNull.Value
Else
Me.Adapter.UpdateCommand.Parameters(1).Value = CType(name,String)
End If
If (Original_user_id Is Nothing) Then
Throw New Global.System.ArgumentNullException("Original_user_id")
Else
Me.Adapter.UpdateCommand.Parameters(2).Value = CType(Original_user_id,String)
End If
Dim previousConnectionState As Global.System.Data.ConnectionState = Me.Adapter.UpdateCommand.Connection.State
If ((Me.Adapter.UpdateCommand.Connection.State And Global.System.Data.ConnectionState.Open) _
<> Global.System.Data.ConnectionState.Open) Then
Me.Adapter.UpdateCommand.Connection.Open
End If
Try
Dim returnValue As Integer = Me.Adapter.UpdateCommand.ExecuteNonQuery
Return returnValue
Finally
If (previousConnectionState = Global.System.Data.ConnectionState.Closed) Then
Me.Adapter.UpdateCommand.Connection.Close
End If
End Try
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Update, true)> _
Public Overloads Overridable Function Update(ByVal name As String, ByVal Original_user_id As String) As Integer
Return Me.Update(Original_user_id, name, Original_user_id)
End Function
End Class
'''<summary>
'''Represents the connection and commands used to retrieve and save data.
'''</summary>
<Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.ComponentModel.DataObjectAttribute(true), _
Global.System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner"& _
", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")> _
Partial Public Class timesheetTableAdapter
Inherits Global.System.ComponentModel.Component
Private WithEvents _adapter As Global.System.Data.SqlServerCe.SqlCeDataAdapter
Private _connection As Global.System.Data.SqlServerCe.SqlCeConnection
Private _transaction As Global.System.Data.SqlServerCe.SqlCeTransaction
Private _commandCollection() As Global.System.Data.SqlServerCe.SqlCeCommand
Private _clearBeforeFill As Boolean
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.ClearBeforeFill = true
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Friend ReadOnly Property Adapter() As Global.System.Data.SqlServerCe.SqlCeDataAdapter
Get
If (Me._adapter Is Nothing) Then
Me.InitAdapter
End If
Return Me._adapter
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Property Connection() As Global.System.Data.SqlServerCe.SqlCeConnection
Get
If (Me._connection Is Nothing) Then
Me.InitConnection
End If
Return Me._connection
End Get
Set
Me._connection = value
If (Not (Me.Adapter.InsertCommand) Is Nothing) Then
Me.Adapter.InsertCommand.Connection = value
End If
If (Not (Me.Adapter.DeleteCommand) Is Nothing) Then
Me.Adapter.DeleteCommand.Connection = value
End If
If (Not (Me.Adapter.UpdateCommand) Is Nothing) Then
Me.Adapter.UpdateCommand.Connection = value
End If
Dim i As Integer = 0
Do While (i < Me.CommandCollection.Length)
If (Not (Me.CommandCollection(i)) Is Nothing) Then
CType(Me.CommandCollection(i),Global.System.Data.SqlServerCe.SqlCeCommand).Connection = value
End If
i = (i + 1)
Loop
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Property Transaction() As Global.System.Data.SqlServerCe.SqlCeTransaction
Get
Return Me._transaction
End Get
Set
Me._transaction = value
Dim i As Integer = 0
Do While (i < Me.CommandCollection.Length)
Me.CommandCollection(i).Transaction = Me._transaction
i = (i + 1)
Loop
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.DeleteCommand) Is Nothing)) Then
Me.Adapter.DeleteCommand.Transaction = Me._transaction
End If
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.InsertCommand) Is Nothing)) Then
Me.Adapter.InsertCommand.Transaction = Me._transaction
End If
If ((Not (Me.Adapter) Is Nothing) _
AndAlso (Not (Me.Adapter.UpdateCommand) Is Nothing)) Then
Me.Adapter.UpdateCommand.Transaction = Me._transaction
End If
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected ReadOnly Property CommandCollection() As Global.System.Data.SqlServerCe.SqlCeCommand()
Get
If (Me._commandCollection Is Nothing) Then
Me.InitCommandCollection
End If
Return Me._commandCollection
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property ClearBeforeFill() As Boolean
Get
Return Me._clearBeforeFill
End Get
Set
Me._clearBeforeFill = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitAdapter()
Me._adapter = New Global.System.Data.SqlServerCe.SqlCeDataAdapter()
Dim tableMapping As Global.System.Data.Common.DataTableMapping = New Global.System.Data.Common.DataTableMapping()
tableMapping.SourceTable = "Table"
tableMapping.DataSetTable = "timesheet"
tableMapping.ColumnMappings.Add("time_in", "time_in")
tableMapping.ColumnMappings.Add("time_out", "time_out")
tableMapping.ColumnMappings.Add("work_date", "work_date")
Me._adapter.TableMappings.Add(tableMapping)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitConnection()
Me._connection = New Global.System.Data.SqlServerCe.SqlCeConnection()
Me._connection.ConnectionString = Global.ITT_Admin.My.MySettings.Default.Database1ConnectionString
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitCommandCollection()
Me._commandCollection = New Global.System.Data.SqlServerCe.SqlCeCommand(0) {}
Me._commandCollection(0) = New Global.System.Data.SqlServerCe.SqlCeCommand()
Me._commandCollection(0).Connection = Me.Connection
Me._commandCollection(0).CommandText = "SELECT [time_in], [time_out], [work_date] FROM [timesheet]"
Me._commandCollection(0).CommandType = Global.System.Data.CommandType.Text
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.Fill, true)> _
Public Overloads Overridable Function Fill(ByVal dataTable As Database1DataSet.timesheetDataTable) As Integer
Me.Adapter.SelectCommand = Me.CommandCollection(0)
If (Me.ClearBeforeFill = true) Then
dataTable.Clear
End If
Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Return returnValue
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter"), _
Global.System.ComponentModel.DataObjectMethodAttribute(Global.System.ComponentModel.DataObjectMethodType.[Select], true)> _
Public Overloads Overridable Function GetData() As Database1DataSet.timesheetDataTable
Me.Adapter.SelectCommand = Me.CommandCollection(0)
Dim dataTable As Database1DataSet.timesheetDataTable = New Database1DataSet.timesheetDataTable()
Me.Adapter.Fill(dataTable)
Return dataTable
End Function
End Class
'''<summary>
'''TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios
'''</summary>
<Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSD"& _
"esigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapterManager")> _
Partial Public Class TableAdapterManager
Inherits Global.System.ComponentModel.Component
Private _updateOrder As UpdateOrderOption
Private _loginTableAdapter As loginTableAdapter
Private _backupDataSetBeforeUpdate As Boolean
Private _connection As Global.System.Data.IDbConnection
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property UpdateOrder() As UpdateOrderOption
Get
Return Me._updateOrder
End Get
Set
Me._updateOrder = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso"& _
"ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3"& _
"a", "System.Drawing.Design.UITypeEditor")> _
Public Property loginTableAdapter() As loginTableAdapter
Get
Return Me._loginTableAdapter
End Get
Set
Me._loginTableAdapter = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property BackupDataSetBeforeUpdate() As Boolean
Get
Return Me._backupDataSetBeforeUpdate
End Get
Set
Me._backupDataSetBeforeUpdate = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public Property Connection() As Global.System.Data.IDbConnection
Get
If (Not (Me._connection) Is Nothing) Then
Return Me._connection
End If
If ((Not (Me._loginTableAdapter) Is Nothing) _
AndAlso (Not (Me._loginTableAdapter.Connection) Is Nothing)) Then
Return Me._loginTableAdapter.Connection
End If
Return Nothing
End Get
Set
Me._connection = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property TableAdapterInstanceCount() As Integer
Get
Dim count As Integer = 0
If (Not (Me._loginTableAdapter) Is Nothing) Then
count = (count + 1)
End If
Return count
End Get
End Property
'''<summary>
'''Update rows in top-down order.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function UpdateUpdatedRows(ByVal dataSet As Database1DataSet, ByVal allChangedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow), ByVal allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Integer
Dim result As Integer = 0
If (Not (Me._loginTableAdapter) Is Nothing) Then
Dim updatedRows() As Global.System.Data.DataRow = dataSet.login.Select(Nothing, Nothing, Global.System.Data.DataViewRowState.ModifiedCurrent)
updatedRows = Me.GetRealUpdatedRows(updatedRows, allAddedRows)
If ((Not (updatedRows) Is Nothing) _
AndAlso (0 < updatedRows.Length)) Then
result = (result + Me._loginTableAdapter.Update(updatedRows))
allChangedRows.AddRange(updatedRows)
End If
End If
Return result
End Function
'''<summary>
'''Insert rows in top-down order.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function UpdateInsertedRows(ByVal dataSet As Database1DataSet, ByVal allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Integer
Dim result As Integer = 0
If (Not (Me._loginTableAdapter) Is Nothing) Then
Dim addedRows() As Global.System.Data.DataRow = dataSet.login.Select(Nothing, Nothing, Global.System.Data.DataViewRowState.Added)
If ((Not (addedRows) Is Nothing) _
AndAlso (0 < addedRows.Length)) Then
result = (result + Me._loginTableAdapter.Update(addedRows))
allAddedRows.AddRange(addedRows)
End If
End If
Return result
End Function
'''<summary>
'''Delete rows in bottom-up order.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function UpdateDeletedRows(ByVal dataSet As Database1DataSet, ByVal allChangedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Integer
Dim result As Integer = 0
If (Not (Me._loginTableAdapter) Is Nothing) Then
Dim deletedRows() As Global.System.Data.DataRow = dataSet.login.Select(Nothing, Nothing, Global.System.Data.DataViewRowState.Deleted)
If ((Not (deletedRows) Is Nothing) _
AndAlso (0 < deletedRows.Length)) Then
result = (result + Me._loginTableAdapter.Update(deletedRows))
allChangedRows.AddRange(deletedRows)
End If
End If
Return result
End Function
'''<summary>
'''Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function GetRealUpdatedRows(ByVal updatedRows() As Global.System.Data.DataRow, ByVal allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)) As Global.System.Data.DataRow()
If ((updatedRows Is Nothing) _
OrElse (updatedRows.Length < 1)) Then
Return updatedRows
End If
If ((allAddedRows Is Nothing) _
OrElse (allAddedRows.Count < 1)) Then
Return updatedRows
End If
Dim realUpdatedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow) = New Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)()
Dim i As Integer = 0
Do While (i < updatedRows.Length)
Dim row As Global.System.Data.DataRow = updatedRows(i)
If (allAddedRows.Contains(row) = false) Then
realUpdatedRows.Add(row)
End If
i = (i + 1)
Loop
Return realUpdatedRows.ToArray
End Function
'''<summary>
'''Update all changes to the dataset.
'''</summary>
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overridable Function UpdateAll(ByVal dataSet As Database1DataSet) As Integer
If (dataSet Is Nothing) Then
Throw New Global.System.ArgumentNullException("dataSet")
End If
If (dataSet.HasChanges = false) Then
Return 0
End If
If ((Not (Me._loginTableAdapter) Is Nothing) _
AndAlso (Me.MatchTableAdapterConnection(Me._loginTableAdapter.Connection) = false)) Then
Throw New Global.System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s"& _
"tring.")
End If
Dim workConnection As Global.System.Data.IDbConnection = Me.Connection
If (workConnection Is Nothing) Then
Throw New Global.System.ApplicationException("TableAdapterManager contains no connection information. Set each TableAdapterMana"& _
"ger TableAdapter property to a valid TableAdapter instance.")
End If
Dim workConnOpened As Boolean = false
If ((workConnection.State And Global.System.Data.ConnectionState.Broken) _
= Global.System.Data.ConnectionState.Broken) Then
workConnection.Close
End If
If (workConnection.State = Global.System.Data.ConnectionState.Closed) Then
workConnection.Open
workConnOpened = true
End If
Dim workTransaction As Global.System.Data.IDbTransaction = workConnection.BeginTransaction
If (workTransaction Is Nothing) Then
Throw New Global.System.ApplicationException("The transaction cannot begin. The current data connection does not support transa"& _
"ctions or the current state is not allowing the transaction to begin.")
End If
Dim allChangedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow) = New Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)()
Dim allAddedRows As Global.System.Collections.Generic.List(Of Global.System.Data.DataRow) = New Global.System.Collections.Generic.List(Of Global.System.Data.DataRow)()
Dim adaptersWithAcceptChangesDuringUpdate As Global.System.Collections.Generic.List(Of Global.System.Data.Common.DataAdapter) = New Global.System.Collections.Generic.List(Of Global.System.Data.Common.DataAdapter)()
Dim revertConnections As Global.System.Collections.Generic.Dictionary(Of Object, Global.System.Data.IDbConnection) = New Global.System.Collections.Generic.Dictionary(Of Object, Global.System.Data.IDbConnection)()
Dim result As Integer = 0
Dim backupDataSet As Global.System.Data.DataSet = Nothing
If Me.BackupDataSetBeforeUpdate Then
backupDataSet = New Global.System.Data.DataSet()
backupDataSet.Merge(dataSet)
End If
Try
'---- Prepare for update -----------
'
If (Not (Me._loginTableAdapter) Is Nothing) Then
revertConnections.Add(Me._loginTableAdapter, Me._loginTableAdapter.Connection)
Me._loginTableAdapter.Connection = CType(workConnection,Global.System.Data.SqlServerCe.SqlCeConnection)
Me._loginTableAdapter.Transaction = CType(workTransaction,Global.System.Data.SqlServerCe.SqlCeTransaction)
If Me._loginTableAdapter.Adapter.AcceptChangesDuringUpdate Then
Me._loginTableAdapter.Adapter.AcceptChangesDuringUpdate = false
adaptersWithAcceptChangesDuringUpdate.Add(Me._loginTableAdapter.Adapter)
End If
End If
'
'---- Perform updates -----------
'
If (Me.UpdateOrder = UpdateOrderOption.UpdateInsertDelete) Then
result = (result + Me.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows))
result = (result + Me.UpdateInsertedRows(dataSet, allAddedRows))
Else
result = (result + Me.UpdateInsertedRows(dataSet, allAddedRows))
result = (result + Me.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows))
End If
result = (result + Me.UpdateDeletedRows(dataSet, allChangedRows))
'
'---- Commit updates -----------
'
workTransaction.Commit
If (0 < allAddedRows.Count) Then
Dim rows((allAddedRows.Count) - 1) As Global.System.Data.DataRow
allAddedRows.CopyTo(rows)
Dim i As Integer = 0
Do While (i < rows.Length)
Dim row As Global.System.Data.DataRow = rows(i)
row.AcceptChanges
i = (i + 1)
Loop
End If
If (0 < allChangedRows.Count) Then
Dim rows((allChangedRows.Count) - 1) As Global.System.Data.DataRow
allChangedRows.CopyTo(rows)
Dim i As Integer = 0
Do While (i < rows.Length)
Dim row As Global.System.Data.DataRow = rows(i)
row.AcceptChanges
i = (i + 1)
Loop
End If
Catch ex As Global.System.Exception
workTransaction.Rollback
'---- Restore the dataset -----------
If Me.BackupDataSetBeforeUpdate Then
Global.System.Diagnostics.Debug.Assert((Not (backupDataSet) Is Nothing))
dataSet.Clear
dataSet.Merge(backupDataSet)
Else
If (0 < allAddedRows.Count) Then
Dim rows((allAddedRows.Count) - 1) As Global.System.Data.DataRow
allAddedRows.CopyTo(rows)
Dim i As Integer = 0
Do While (i < rows.Length)
Dim row As Global.System.Data.DataRow = rows(i)
row.AcceptChanges
row.SetAdded
i = (i + 1)
Loop
End If
End If
Throw ex
Finally
If workConnOpened Then
workConnection.Close
End If
If (Not (Me._loginTableAdapter) Is Nothing) Then
Me._loginTableAdapter.Connection = CType(revertConnections(Me._loginTableAdapter),Global.System.Data.SqlServerCe.SqlCeConnection)
Me._loginTableAdapter.Transaction = Nothing
End If
If (0 < adaptersWithAcceptChangesDuringUpdate.Count) Then
Dim adapters((adaptersWithAcceptChangesDuringUpdate.Count) - 1) As Global.System.Data.Common.DataAdapter
adaptersWithAcceptChangesDuringUpdate.CopyTo(adapters)
Dim i As Integer = 0
Do While (i < adapters.Length)
Dim adapter As Global.System.Data.Common.DataAdapter = adapters(i)
adapter.AcceptChangesDuringUpdate = true
i = (i + 1)
Loop
End If
End Try
Return result
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overridable Sub SortSelfReferenceRows(ByVal rows() As Global.System.Data.DataRow, ByVal relation As Global.System.Data.DataRelation, ByVal childFirst As Boolean)
Global.System.Array.Sort(Of Global.System.Data.DataRow)(rows, New SelfReferenceComparer(relation, childFirst))
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overridable Function MatchTableAdapterConnection(ByVal inputConnection As Global.System.Data.IDbConnection) As Boolean
If (Not (Me._connection) Is Nothing) Then
Return true
End If
If ((Me.Connection Is Nothing) _
OrElse (inputConnection Is Nothing)) Then
Return true
End If
If String.Equals(Me.Connection.ConnectionString, inputConnection.ConnectionString, Global.System.StringComparison.Ordinal) Then
Return true
End If
Return false
End Function
'''<summary>
'''Update Order Option
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Enum UpdateOrderOption
InsertUpdateDelete = 0
UpdateInsertDelete = 1
End Enum
'''<summary>
'''Used to sort self-referenced table's rows
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Class SelfReferenceComparer
Inherits Object
Implements Global.System.Collections.Generic.IComparer(Of Global.System.Data.DataRow)
Private _relation As Global.System.Data.DataRelation
Private _childFirst As Integer
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal relation As Global.System.Data.DataRelation, ByVal childFirst As Boolean)
MyBase.New
Me._relation = relation
If childFirst Then
Me._childFirst = -1
Else
Me._childFirst = 1
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function GetRoot(ByVal row As Global.System.Data.DataRow, ByRef distance As Integer) As Global.System.Data.DataRow
Global.System.Diagnostics.Debug.Assert((Not (row) Is Nothing))
Dim root As Global.System.Data.DataRow = row
distance = 0
Dim traversedRows As Global.System.Collections.Generic.IDictionary(Of Global.System.Data.DataRow, Global.System.Data.DataRow) = New Global.System.Collections.Generic.Dictionary(Of Global.System.Data.DataRow, Global.System.Data.DataRow)()
traversedRows(row) = row
Dim parent As Global.System.Data.DataRow = row.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.[Default])
Do While ((Not (parent) Is Nothing) _
AndAlso (traversedRows.ContainsKey(parent) = false))
distance = (distance + 1)
root = parent
traversedRows(parent) = parent
parent = parent.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.[Default])
Loop
If (distance = 0) Then
traversedRows.Clear
traversedRows(row) = row
parent = row.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.Original)
Do While ((Not (parent) Is Nothing) _
AndAlso (traversedRows.ContainsKey(parent) = false))
distance = (distance + 1)
root = parent
traversedRows(parent) = parent
parent = parent.GetParentRow(Me._relation, Global.System.Data.DataRowVersion.Original)
Loop
End If
Return root
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function Compare(ByVal row1 As Global.System.Data.DataRow, ByVal row2 As Global.System.Data.DataRow) As Integer Implements Global.System.Collections.Generic.IComparer(Of Global.System.Data.DataRow).Compare
If Object.ReferenceEquals(row1, row2) Then
Return 0
End If
If (row1 Is Nothing) Then
Return -1
End If
If (row2 Is Nothing) Then
Return 1
End If
Dim distance1 As Integer = 0
Dim root1 As Global.System.Data.DataRow = Me.GetRoot(row1, distance1)
Dim distance2 As Integer = 0
Dim root2 As Global.System.Data.DataRow = Me.GetRoot(row2, distance2)
If Object.ReferenceEquals(root1, root2) Then
Return (Me._childFirst * distance1.CompareTo(distance2))
Else
Global.System.Diagnostics.Debug.Assert(((Not (root1.Table) Is Nothing) _
AndAlso (Not (root2.Table) Is Nothing)))
If (root1.Table.Rows.IndexOf(root1) < root2.Table.Rows.IndexOf(root2)) Then
Return -1
Else
Return 1
End If
End If
End Function
End Class
End Class
End Namespace
|
gpl-3.0
|
ChrisBAshton/smartresolution
|
webapp/core/model/dispute_states/DisputeStateDisputeOpened.php
|
416
|
<?php
/**
* All law firms and agents have been assigned. Now a lifespan must be negotiated.
*/
class DisputeOpened extends DisputeDefaults implements DisputeStateInterface {
public function getStateDescription() {
return 'Negotiating lifespan.';
}
public function canOpenDispute() {
return false;
}
public function canAssignDisputeToAgent() {
return false;
}
}
|
gpl-3.0
|
robocomp/robocomp
|
libs/dsr/gui/viewers/graph_viewer/graph_node.cpp
|
12408
|
/*
* Copyright 2018 <copyright holder> <email>
*
* 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.
*/
#include <dsr/gui/viewers/graph_viewer/graph_node.h>
//#include <dsr/gui/viewers/graph_viewer/node_colors.h>
#include <dsr/gui/viewers/graph_viewer/graph_colors.h>
#include <dsr/gui/viewers/graph_viewer/graph_node_laser_widget.h>
#include <dsr/gui/viewers/graph_viewer/graph_node_widget.h>
#include <dsr/gui/viewers/graph_viewer/graph_node_rgbd_widget.h>
#include <dsr/gui/viewers/graph_viewer/graph_node_person_widget.h>
GraphNode::GraphNode(const std::shared_ptr<DSR::GraphViewer>&
graph_viewer_):QGraphicsEllipseItem(0,0,DEFAULT_DIAMETER,DEFAULT_DIAMETER), graph_viewer(graph_viewer_)
{
auto flags = ItemIsMovable | ItemIsSelectable | ItemSendsGeometryChanges | ItemUsesExtendedStyleOption | ItemIsFocusable;
setFlags(flags);
setCacheMode(DeviceCoordinateCache);
setAcceptHoverEvents(true);
setZValue(-1);
node_brush.setStyle(Qt::SolidPattern);
animation = new QPropertyAnimation(this, "node_color");
animation->setDuration(animation_time);
animation->setStartValue(plain_color);
animation->setEndValue(dark_color);
animation->setLoopCount(ANIMATION_REPEAT);
QObject::connect(graph_viewer_->getGraph().get(), &DSR::DSRGraph::update_node_attr_signal, this, &GraphNode::update_node_attr_slot, Qt::QueuedConnection);
}
void GraphNode::setTag(const std::string &tag_)
{
QString c = QString::fromStdString(tag_);
tag = new QGraphicsSimpleTextItem(c, this);
tag->setX(DEFAULT_DIAMETER);
tag->setY(-10);
}
void GraphNode::setType(const std::string &type_)
{
type = type_;
if(type == "laser" or type == "rgbd" or type == "person")
{
contextMenu = new QMenu();
QAction *table_action = new QAction("View table");
contextMenu->addAction(table_action);
connect(table_action, &QAction::triggered, this, [this](){ this->show_node_widget("table");});
QAction *stuff_action = new QAction("View data");
contextMenu->addAction(stuff_action);
connect(stuff_action, &QAction::triggered, this, [this, type_](){ this->show_node_widget(type_);});
}
auto color = GraphColors<DSR::Node>()[type];
set_color(color);
}
void GraphNode::addEdge(GraphEdge *edge)
{
qDebug()<<"====================================";
int same_count = 0;
int bend_factor = 0;
// look for edges with the same dest
qDebug()<<__FUNCTION__ <<"Checking edges for node: "<<this->id_in_graph;
for (auto old_edge: edgeList)
{
if(old_edge == edge)
throw std::runtime_error("Trying to add an already existing edge " + std::to_string(edge->sourceNode()->id_in_graph)+"--"+std::to_string(edge->destNode()->id_in_graph));
// qDebug()<<__FUNCTION__ <<"\tExisting EDGE: "<<edge->sourceNode()->id_in_graph<<edge->destNode()->id_in_graph<<"OTHER: "<<old_edge->sourceNode()->id_in_graph<<old_edge->destNode()->id_in_graph;
qDebug()<<"\t"<<__FUNCTION__ <<"Existing EDGE: "<<old_edge->sourceNode()->id_in_graph<<"--"<<old_edge->destNode()->id_in_graph;
qDebug()<<"\t"<<__FUNCTION__ <<" New EDGE: "<<edge->sourceNode()->id_in_graph<<"--"<<edge->destNode()->id_in_graph;
if((edge->sourceNode()->id_in_graph==old_edge->sourceNode()->id_in_graph or edge->sourceNode()->id_in_graph==old_edge->destNode()->id_in_graph)
and (edge->destNode()->id_in_graph==old_edge->sourceNode()->id_in_graph or edge->destNode()->id_in_graph==old_edge->destNode()->id_in_graph))
{
same_count++;
qDebug()<<"\t\t"<<__FUNCTION__ <<"SAME EDGE"<<same_count;
}
}
// https://www.wolframalpha.com/input/?i=0%2C+1%2C+-1%2C+2%2C+-2%2C+3%2C+-3
bend_factor = (pow(-1,same_count)*(-1 + pow(-1,same_count) - 2*same_count))/4;
qDebug()<<__FUNCTION__ <<__LINE__<<"ID: "<<id_in_graph<<"SAME: "<<same_count<<"FACTOR: "<<bend_factor;
edge->set_bend_factor(bend_factor);
edgeList << edge;
edge->adjust();
qDebug()<<"====================================";
}
void GraphNode::deleteEdge(GraphEdge *edge)
{
edgeList.removeAll(edge);
}
QList<GraphEdge *> GraphNode::edges() const
{
return edgeList;
}
void GraphNode::calculateForces()
{
if (!scene() || scene()->mouseGrabberItem() == this)
{
newPos = pos();
return;
}
// Sum up all forces pushing this item away
qreal xvel = 0;
qreal yvel = 0;
//foreach (QGraphicsItem *item, scene()->items())
for( auto &[k,node] : graph_viewer->getGMap())
{
//GraphNode *node = qgraphicsitem_cast<GraphNode *>(item);
//if (!node)
// continue;
(void)k;
QPointF vec = mapToItem(node, 0, 0);
qreal dx = vec.x();
qreal dy = vec.y();
double l = 2.0 * (dx * dx + dy * dy);
if (l > 0)
{
xvel += (dx * force_velocity_factor) / l;
yvel += (dy * force_velocity_factor) / l;
}
}
// Now subtract all forces pulling items together
double weight = (edgeList.size() + 1) * EDGE_PULL_FACTOR;
foreach (GraphEdge *edge, edgeList)
{
QPointF vec;
if (edge->sourceNode() == this)
vec = mapToItem(edge->destNode(), 0, 0);
else
vec = mapToItem(edge->sourceNode(), 0, 0);
xvel -= vec.x() / weight;
yvel -= vec.y() / weight;
}
// Subtract force from central pos pulling item to the center of the image
QPointF to_central_point = mapFromItem(graph_viewer->getCentralPoint(), 0, 0);
xvel += to_central_point.x() / (weight/2) ;
yvel += to_central_point.y() / (weight/2) ;
// sludge
if (qAbs(xvel) < 0.1 && qAbs(yvel) < 0.1)
xvel = yvel = 0;
QRectF sceneRect = scene()->sceneRect();
newPos = pos() + QPointF(xvel, yvel);
newPos.setX(qMin(qMax(newPos.x(), sceneRect.left() + SCENE_MARGIN), sceneRect.right() - SCENE_MARGIN));
newPos.setY(qMin(qMax(newPos.y(), sceneRect.top() + SCENE_MARGIN), sceneRect.bottom() - SCENE_MARGIN));
}
bool GraphNode::advancePosition()
{
if (newPos == pos())
return false;
setPos(newPos);
return true;
}
QRectF GraphNode::boundingRect() const
{
qreal adjust = 2;
return QRectF(
-DEFAULT_RADIUS - adjust,
-DEFAULT_RADIUS - adjust,
DEFAULT_DIAMETER + 3 + adjust,
DEFAULT_DIAMETER + 3 + adjust
);
}
QPainterPath GraphNode::shape() const
{
QPainterPath path;
path.addEllipse(-DEFAULT_RADIUS, -DEFAULT_RADIUS, DEFAULT_DIAMETER, DEFAULT_DIAMETER);
return path;
}
void GraphNode::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
{
painter->setPen(Qt::NoPen);
painter->setBrush(SUNKEN_COLOR);
// painter->drawEllipse(-7, -7, node_width, node_width);
QRadialGradient gradient(-3, -3, 10);
if (option->state & QStyle::State_Sunken)
{
gradient.setColorAt(0, QColor(Qt::darkGray).light(LUMINOSITY_FACTOR));
gradient.setColorAt(1, QColor(Qt::darkGray));
} else
{
gradient.setColorAt(0, node_brush.color());
gradient.setColorAt(1, QColor(node_brush.color().dark(LUMINOSITY_FACTOR)));
}
painter->setBrush(gradient);
if(isSelected())
painter->setPen(QPen(Qt::green, 0, Qt::DashLine));
else
painter->setPen(QPen(Qt::black, 0));
painter->drawEllipse(-DEFAULT_RADIUS, -DEFAULT_RADIUS, DEFAULT_DIAMETER, DEFAULT_DIAMETER);
}
QVariant GraphNode::itemChange(GraphicsItemChange change, const QVariant &value)
{
switch (change)
{
case ItemPositionHasChanged:
{
foreach (GraphEdge *edge, edgeList)
edge->adjust(this, value.toPointF());
break;
}
default:
break;
}
return QGraphicsItem::itemChange(change, value);
}
void GraphNode::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
//if (tag->text() != "") return; // Explota sin esto
// animation->start();
if( event->button()== Qt::RightButton)
{
if (contextMenu != nullptr)
contextMenu->exec(event->screenPos());
else
show_node_widget("table");
}
// update();
QGraphicsEllipseItem::mouseDoubleClickEvent(event);
}
void GraphNode::show_node_widget(const std::string &show_type)
{
//static std::unique_ptr<QWidget> do_stuff;
const auto graph = graph_viewer->getGraph();
if(show_type=="laser")
node_widget = std::make_unique<GraphNodeLaserWidget>(graph, id_in_graph);
else if(show_type=="rgbd")
node_widget = std::make_unique<GraphNodeRGBDWidget>(graph, id_in_graph);
else if(show_type=="person")
node_widget = std::make_unique<GraphNodePersonWidget>(graph, id_in_graph);
else
node_widget = std::make_unique<GraphNodeWidget>(graph, id_in_graph);
}
void GraphNode::change_detected()
{
animation->start();
}
void GraphNode::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if( event->button()== Qt::LeftButton)
{
auto g = graph_viewer->getGraph();
qDebug() << __FILE__ <<":"<<__FUNCTION__<< " node id in graphnode: " << id_in_graph ;
std::optional<Node> n = g->get_node(id_in_graph);
if (n.has_value()) {
// qDebug()<<"ScenePos X"<<(float) event->scenePos().x()<<" Width "<<(this->rect())<<" this "<<this->pos().x();
// qDebug()<<"ScenePos Y"<<(float) event->scenePos().y()<<" Height "<<(this->rect())<<" this "<<this->pos().y();
g->add_or_modify_attrib_local<pos_x_att>(n.value(), (float) this->pos().x());
g->add_or_modify_attrib_local<pos_y_att>(n.value(), (float) this->pos().y());
g->update_node(n.value());
}
// this->dsr_to_graph_viewer->itemMoved();
}
QGraphicsItem::mouseReleaseEvent(event);
}
QColor GraphNode::_node_color()
{
return this->brush().color();
}
void GraphNode::set_node_color(const QColor& c)
{
node_brush.setColor(c);
this->setBrush( node_brush );
}
void GraphNode::set_color(const std::string &plain)
{
QString c = QString::fromStdString(plain);
plain_color = c;
dark_color = "dark" + c;
set_node_color(QColor(c));
animation->setStartValue(QColor("green").lighter());
animation->setEndValue(c);
}
/////////////////////////////////////////////////////////////////////////////////////////7
////
/////////////////////////////////////////////////////////////////////////////////////////
void GraphNode::update_node_attr_slot(std::uint64_t node_id, const std::vector<std::string> &type)
{
if (node_id != this->id_in_graph)
return;
// if(std::find(type.begin(), type.end(), "color") != type.end())
// {
// std::optional<Node> n = graph_viewer->getGraph()->get_node(node_id);
// if (n.has_value()) {
//// auto &attrs = n.value().attrs();
//// auto value = attrs.find("color");
//// if (value != attrs.end()) {
//// this->setColor(value->second.str());
//// }
// }
// }
}
/* void GraphNode::NodeAttrsChangedSLOT(const DSR::IDType &node, const DSR::Attribs &attr)
{
std::cout << "do cool stuff" << std::endl;
}
*/
// void GraphNode::hoverEnterEvent(QGraphicsSceneHoverEvent* event)
// {
// // label = new QTableWidget(graph);
// //label->setText(tag->text().toStdString());
// //label->show();
// //label->exec();
// std::cout << "entering node: " << tag->text().toStdString() << std::endl;
// update (boundingRect());
// }
// void GraphNode::hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
// {
// // QDialog *label = new QDialog(graph);
// // label->exec();
// //label->close();
// //lable->delete();
// std::cout << "exiting node: " << tag->text().toStdString() << std::endl;
// update (boundingRect());
// }
|
gpl-3.0
|
BenjoCowley/dca
|
README.md
|
741
|
# dca
Distance Covariance Analysis
This readme will be updated soon with a user-friendly way to run DCA!
Reference:
"Distance covariance analysis." BR Cowley, JD Semedo, A Zandvakili, A Kohn, MA Smith, BM Yu (*AISTATS*, pp. 242-251, 2017).
# Example code (Matlab)
```matlab
% DCA will identify a nonlinear interaction between X1 and X2
Xs{1} = randn(20,1000);
Xs{2} = Xs{1}(1:5,:).^2;
Ds{1} = squareform(pdist(Xs{1}(1,:)' + Xs{2}(1,:)'));
[U, dcovs] = dca(Xs, Ds, 'num_dca_dimensions', 5);
% plot first DCA dimension in Xs{1} vs Xs{2}
x1 = U{1}(:,1)' * Xs{1}
x2 = U{2}(:,1)' * Xs{2}
plot(x1, x2, '.k'); xlabel('DCA dim 1 for X1'); ylabel('DCA dim 1 for X2')
```
<img src="./figures/dca_example_x1_vs_x2.png" width="442" height="348">
|
gpl-3.0
|
kamura098/echo-srv
|
errs.c
|
194
|
#include "myhead.h"
int errcode=0;
void err_quit(const char *str)
{
switch(errcode){
case ERNO:
perror(str);
break;
default:
printf("err: %s\n",str);
}//switch
exit(1);
}//err_quit
|
gpl-3.0
|
ExpressBaseSystems/ExpressBase.Common
|
sqlscripts/pgsql/datadb/tablecreate/eb_form_drafts.sql
|
732
|
-- Table: public.eb_form_drafts
-- DROP TABLE public.eb_form_drafts;
CREATE TABLE public.eb_form_drafts
(
id SERIAL,
title text,
form_data_json text,
form_ref_id text,
form_data_id integer,
draft_type integer,
message text,
stack_trace text,
eb_signin_log_id integer,
is_submitted "char" DEFAULT 'F'::"char",
eb_loc_id integer,
eb_created_by integer,
eb_created_at timestamp without time zone,
eb_lastmodified_at timestamp without time zone,
eb_del "char" DEFAULT 'F'::"char",
CONSTRAINT eb_form_drafts_pkey PRIMARY KEY (id)
);
-- Index: public.eb_form_drafts_id_idx
-- DROP INDEX public.eb_form_drafts_id_idx;
CREATE INDEX eb_form_drafts_id_idx
ON eb_form_drafts(id);
|
gpl-3.0
|
aramisw/DoNSA_nsga2
|
DoNSA_nsga2/nondomination_selection.c
|
8571
|
/*
DESCRIPTION:
This function is used for selecting the solutions from the combined population
*/
#pragma once
#include "dsc_file.h"
void nondomination_selection()
{
struct obj_array
{
int index;
double obj_1;
double obj_2;
double dist_crowd;
};
int cnt_1 = 0;
int cnt_2 = 0;
int cnt_3 = 0;
int cnt_4 = 0;
int cnt_5 = 0;
int cnt_6 = 0;
int* domi_cnt = NULL; //this array is used for recording the number of the individual that dominates the current individual
int* indic_added = NULL; //this array is used for indicating whether the individuals has been added to the PF
int* level_PF = NULL; //this array records the PF level of the individuals. The '0' is the best level.
int* amount_indiv_level = NULL; //this array record the number of individuals in each level
int** domi_indiv_array = NULL; //this array is used for recording the domination indicator of each dominating individual
double tmp_1 = 0;
double tmp_2 = 0;
double tmp_3 = 0;
struct obj_array* indiv_sort_array = NULL; //this is the individual level
struct para_copy_pop_info para_1;
//RAN ALLOCATION
domi_cnt = (int*)calloc(2 * Amount_pop_total, sizeof(int));
indic_added= (int*)calloc(2 * Amount_pop_total, sizeof(int));
level_PF = (int*)calloc(2 * Amount_pop_total, sizeof(int));
amount_indiv_level = (int*)calloc(2 * Amount_pop_total, sizeof(int));
domi_indiv_array = (int**)calloc(2 * Amount_pop_total, sizeof(int*));
for (cnt_1 = 0; cnt_1 < 2 * Amount_pop_total; cnt_1++)
{
domi_indiv_array[cnt_1] = (int*)calloc(2 * Amount_pop_total, sizeof(int));
}
//PARAMETER PREPARATION
para_1.amount_airship = Cfg_opti.amount_airship;
//CHECK THE DOMINATION STATUS
for (cnt_1 = 0; cnt_1 < 2 * Amount_pop_total; cnt_1++) //for each individual, we check the domination status
{
for (cnt_2 = cnt_1 + 1; cnt_2 < 2 * Amount_pop_total; cnt_2++)
{
//domination check
cnt_3 = dominant_single(&Pop_array_comb[cnt_1], &Pop_array_comb[cnt_2]);
//result record
switch (cnt_3)
{
case 1:
domi_cnt[cnt_2]++;
domi_indiv_array[cnt_2][cnt_1] = 1; //the cnt_1 individual dominate the No. cnt_2 individual
break;
case 2:
domi_cnt[cnt_1]++;
domi_indiv_array[cnt_1][cnt_2] = 1;
break;
default:
break;
}
}
}
//FORM DIFFERENT PARETO FRONTS
cnt_3 = 0; //I use this counter to record how many individual have been assigned the PF level
for (cnt_1 = 0; cnt_1 < 2 * Amount_pop_total; cnt_1++) //this is the maximum number of PF
{
if (cnt_3 == 2 * Amount_pop_total) //if all the individuals have been assigned to a PF level
{
break;
}
else
{
//if some individuals have not been assigned to a PF level
for (cnt_2 = 0; cnt_2 < 2 * Amount_pop_total; cnt_2++)
{
if ((domi_cnt[cnt_2] == 0)&&(indic_added[cnt_2]==0)) //if the domination counter of the current individual is '0', that is to say, there is no individual dominating the current individual
{
//record the level info
level_PF[cnt_2] = cnt_1;
indic_added[cnt_2] = 1;
//update the individual counter
cnt_3++;
}
}
//update the domination counter of the current individual
for (cnt_5 = 0; cnt_5 < 2 * Amount_pop_total; cnt_5++) //all the individuals need to be checked
{
for (cnt_6 = 0; cnt_6 < 2 * Amount_pop_total; cnt_6++)
{
if ((domi_indiv_array[cnt_5][cnt_6] == 1)&&(level_PF[cnt_6]==cnt_1)) //if the current individual is dominated by the individual being assigned, the update the counter of the current individual
{
domi_cnt[cnt_5]--;
}
}
}
}
}
//CALCULATE THE NUMBER OF INDIVIDUALS IN EACH LEVEL
for (cnt_1 = 0; cnt_1 < 2 * Amount_pop_total; cnt_1++)
{
amount_indiv_level[level_PF[cnt_1]]++;
}
//FORM THE POPULATION FOR THE NEXT GENERATION
//check the required PF needed to form the new population
cnt_2 = 0;
for (cnt_1 = 0; cnt_1 < 2 * Amount_pop_total; cnt_1++)
{
cnt_2 = cnt_2 + amount_indiv_level[cnt_1];
if (cnt_2 >= Amount_pop_total)
{
break;
}
}
if(amount_indiv_level[cnt_1]==1)
{
//COLLECT THE INDIVIDUAL OF THE NEW GENERATION
//the individuals in the completed copied PFs
cnt_3 = 0;
for (cnt_2 = 0; cnt_2 < 2 * Amount_pop_total; cnt_2++) //search all the individuals in the combined population
{
if (level_PF[cnt_2] <= cnt_1)
{
copy_pop_info(&Pop_array[cnt_3], &Pop_array_comb[cnt_2], ¶_1);
cnt_3++;
}
}
}
else
{
//retreive the individuals in the selected level
indiv_sort_array = (struct obj_array*)calloc(amount_indiv_level[cnt_1], sizeof(struct obj_array));
cnt_4 = 0;
for (cnt_3 = 0; cnt_3 < 2 * Amount_pop_total; cnt_3++)
{
if (level_PF[cnt_3] == cnt_1)
{
indiv_sort_array[cnt_4].index = cnt_3;
indiv_sort_array[cnt_4].obj_1 = Pop_array_comb[cnt_3].obj_1;
indiv_sort_array[cnt_4].obj_2 = Pop_array_comb[cnt_3].obj_2;
cnt_4++;
}
}
//sort the individuals in ascending order according to the first objective
//bubble sort
for (cnt_3 = 0; cnt_3 < amount_indiv_level[cnt_1] - 1; cnt_3++)
{
cnt_4 = 0; //use cnt_4 to indicate whether a new sorting loop is required
for (cnt_5 = 0; cnt_5 < amount_indiv_level[cnt_1] - 1; cnt_5++)
{
if (indiv_sort_array[cnt_5].obj_1 > indiv_sort_array[cnt_5+1].obj_1)
{
cnt_6 = indiv_sort_array[cnt_5].index;
tmp_1 = indiv_sort_array[cnt_5].obj_1;
tmp_2 = indiv_sort_array[cnt_5].obj_2;
indiv_sort_array[cnt_5].index = indiv_sort_array[cnt_5 + 1].index;
indiv_sort_array[cnt_5].obj_1 = indiv_sort_array[cnt_5 + 1].obj_1;
indiv_sort_array[cnt_5].obj_2 = indiv_sort_array[cnt_5 + 1].obj_2;
indiv_sort_array[cnt_5 + 1].index = cnt_6;
indiv_sort_array[cnt_5 + 1].obj_1 = tmp_1;
indiv_sort_array[cnt_5 + 1].obj_2 = tmp_2;
cnt_4 = 1;
}
}
if (cnt_4 == 0)
{
break;
}
}
//calculate the crowd distance of each individual
for (cnt_3 = 0; cnt_3 < amount_indiv_level[cnt_1]; cnt_3++)
{
if (cnt_3 == 0)
{
indiv_sort_array[cnt_3].dist_crowd = (indiv_sort_array[cnt_3].obj_2 - indiv_sort_array[cnt_3 + 1].obj_2) + (indiv_sort_array[cnt_3 + 1].obj_1 - indiv_sort_array[cnt_3].obj_1);
}
if (cnt_3 == (amount_indiv_level[cnt_1] - 1))
{
indiv_sort_array[cnt_3].dist_crowd = (indiv_sort_array[cnt_3].obj_1 - indiv_sort_array[cnt_3 - 1].obj_1) + (indiv_sort_array[cnt_3 - 1].obj_2 - indiv_sort_array[cnt_3].obj_2);
}
if ((cnt_3 > 0) && (cnt_3 < amount_indiv_level[cnt_1] - 1))
{
indiv_sort_array[cnt_3].dist_crowd = 0.5*(indiv_sort_array[cnt_3 + 1].obj_1 - indiv_sort_array[cnt_3 - 1].obj_1 + indiv_sort_array[cnt_3 - 1].obj_2 - indiv_sort_array[cnt_3 + 1].obj_2);
}
}
//sort the individuals in descending order
for (cnt_3 = 0; cnt_3 < amount_indiv_level[cnt_1] - 1; cnt_3++)
{
cnt_4 = 0;
for (cnt_5 = 0; cnt_5 < amount_indiv_level[cnt_1]-1; cnt_5++)
{
if (indiv_sort_array[cnt_5].dist_crowd < indiv_sort_array[cnt_5+1].dist_crowd)
{
cnt_6 = indiv_sort_array[cnt_5].index;
tmp_1 = indiv_sort_array[cnt_5].obj_1;
tmp_2 = indiv_sort_array[cnt_5].obj_2;
tmp_3 = indiv_sort_array[cnt_5].dist_crowd;
indiv_sort_array[cnt_5].index = indiv_sort_array[cnt_5 + 1].index;
indiv_sort_array[cnt_5].obj_1 = indiv_sort_array[cnt_5 + 1].obj_1;
indiv_sort_array[cnt_5].obj_2 = indiv_sort_array[cnt_5 + 1].obj_2;
indiv_sort_array[cnt_5].dist_crowd = indiv_sort_array[cnt_5 + 1].dist_crowd;
indiv_sort_array[cnt_5 + 1].index = cnt_6;
indiv_sort_array[cnt_5 + 1].obj_1 = tmp_1;
indiv_sort_array[cnt_5 + 1].obj_2 = tmp_2;
indiv_sort_array[cnt_5 + 1].dist_crowd = tmp_3;
cnt_4 = 1;
}
}
if (cnt_4 == 0)
{
break;
}
}
//COLLECT THE INDIVIDUAL OF THE NEW GENERATION
//the individuals in the completed copied PFs
cnt_3 = 0;
for (cnt_2 = 0; cnt_2 < 2 * Amount_pop_total; cnt_2++) //search all the individuals in the combined population
{
if (level_PF[cnt_2] < cnt_1)
{
copy_pop_info(&Pop_array[cnt_3], &Pop_array_comb[cnt_2], ¶_1);
cnt_3++;
}
}
//the individuals in the uncompleted copied PFs
cnt_4 = 0;
for (cnt_2 = cnt_3; cnt_2 < Amount_pop_total; cnt_2++)
{
copy_pop_info(&Pop_array[cnt_2], &Pop_array_comb[indiv_sort_array[cnt_4].index], ¶_1);
cnt_4++;
}
//RAN RECYCLE
free(indiv_sort_array);
}
//RAN RECYCLE
free(domi_cnt);
free(indic_added);
free(level_PF);
free(amount_indiv_level);
for (cnt_1 = 0; cnt_1 < 2 * Amount_pop_total; cnt_1++)
{
free(domi_indiv_array[cnt_1]);
}
free(domi_indiv_array);
}
|
gpl-3.0
|
baconbum/GradeTracker
|
GradeTracker/Forms/CourseGradeableTasksForm.cs
|
4165
|
using System;
using System.Drawing;
using System.Windows.Forms;
using GradeTracker.Data;
namespace GradeTracker.Forms
{
public class CourseGradeableTasksForm : Form
{
Course course;
#region Form elements
private Button addNewTaskButton;
private DataGridView tasksGrid;
#endregion
/// <summary>
/// Maps the columns of the Tasks grid.
/// </summary>
private enum GradeableTasksGridColumn {
Edit = 4,
Delete = 5
};
public CourseGradeableTasksForm(Course course)
{
this.course = course;
Text = String.Format("Course Tasks: {0}", this.course.Name);
MinimumSize = new Size(600, 600);
InitializeAddNewTaskButton();
InitializeTasksGrid();
Refresh();
}
/// <summary>
/// Initializes the Add New Task button.
/// </summary>
private void InitializeAddNewTaskButton()
{
addNewTaskButton = new Button() {
Text = "Add New Task",
Width = 200,
Location = new Point(0, 10)
};
addNewTaskButton.Click += new EventHandler(AddNewTaskButton_Click);
Controls.Add(addNewTaskButton);
}
/// <summary>
/// Handles the Add New Task button's click event.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void AddNewTaskButton_Click(object sender, EventArgs e)
{
new GradeableTaskForm(course).Show();
}
/// <summary>
/// Initializes the Tasks grid.
/// </summary>
private void InitializeTasksGrid()
{
tasksGrid = new DataGridView() {
ReadOnly = true,
AllowUserToAddRows = false,
Location = new Point(addNewTaskButton.Left, addNewTaskButton.Height + addNewTaskButton.Top + 10),
Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right
};
tasksGrid.Columns.Add(new DataGridViewTextBoxColumn(){ HeaderText = "Task" });
tasksGrid.Columns.Add(new DataGridViewTextBoxColumn(){ HeaderText = "Due Date" });
tasksGrid.Columns.Add(new DataGridViewTextBoxColumn(){ HeaderText = "Marks" });
tasksGrid.Columns.Add(new DataGridViewTextBoxColumn(){ HeaderText = "Weight" });
tasksGrid.Columns.Add(new DataGridViewButtonColumn() {
HeaderText = "Edit",
Text = "Edit",
UseColumnTextForButtonValue = true
});
tasksGrid.Columns.Add(new DataGridViewButtonColumn() {
HeaderText = "Delete",
Text = "Delete",
UseColumnTextForButtonValue = true
});
tasksGrid.CellClick += TasksGrid_CellClick;
Controls.Add(tasksGrid);
}
/// <summary>
/// Handles the Task grid's click event.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="DataGridViewCellEventArgs"/> instance containing the event data.</param>
private void TasksGrid_CellClick (object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow row = tasksGrid.Rows[e.RowIndex];
GradeableTask task = (GradeableTask)row.Tag;
switch (e.ColumnIndex)
{
case (int)GradeableTasksGridColumn.Edit:
new GradeableTaskForm(task).Show();
break;
case (int)GradeableTasksGridColumn.Delete:
switch (MessageBox.Show(this, String.Format("Are you sure you want to delete {0}", task.Name),
"Delete Task", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
{
case DialogResult.OK:
task.Delete();
break;
default:
break;
}
Refresh();
break;
}
}
/// <summary>
/// Refresh the form, and ensure the Tasks grid is up to date.
/// </summary>
public override void Refresh()
{
base.Refresh();
tasksGrid.Rows.Clear();
foreach(GradeableTask task in course.GetTasks())
{
DataGridViewRow row = new DataGridViewRow(){ Tag = task };
row.Cells.Add(new DataGridViewTextBoxCell(){ Value = task.Name });
row.Cells.Add(new DataGridViewTextBoxCell(){ Value = task.DueDate.ToShortDateString() });
row.Cells.Add(new DataGridViewTextBoxCell(){ Value = task.PotentialMarks.ToString() });
row.Cells.Add(new DataGridViewTextBoxCell(){ Value = String.Format("{0}%", task.Weight.ToString()) });
tasksGrid.Rows.Add(row);
}
}
}
}
|
gpl-3.0
|
erikzenker/alpaka-examples
|
alpaka/include/alpaka/core/Fold.hpp
|
4795
|
/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka 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.
*
* alpaka 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 alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <alpaka/core/Common.hpp> // ALPAKA_FN_HOST_ACC
#if !defined(__CUDA_ARCH__)
#include <boost/core/ignore_unused.hpp> // boost::ignore_unused
#endif
#if !(__cplusplus >= 201402L)
#include <type_traits> // std::result_of
#endif
namespace alpaka
{
namespace core
{
//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TFnObj,
typename T>
ALPAKA_FN_HOST_ACC auto foldr(
TFnObj const & f,
T const & t)
-> T
{
#if !defined(__CUDA_ARCH__)
boost::ignore_unused(f);
#endif
return t;
}
#if __cplusplus >= 201402L
//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TFnObj,
typename T0,
typename T1,
typename... Ts>
ALPAKA_FN_HOST_ACC auto foldr(
TFnObj const & f,
T0 const & t0,
T1 const & t1,
Ts const & ... ts)
{
return f(t0, foldr(f, t1, ts...));
}
#else
namespace detail
{
//#############################################################################
//!
//#############################################################################
template<
typename TFnObj,
typename... T>
struct TypeOfFold;
//#############################################################################
//!
//#############################################################################
template<
typename TFnObj,
typename T>
struct TypeOfFold<
TFnObj,
T>
{
using type = T;
};
//#############################################################################
//!
//#############################################################################
template<
typename TFnObj,
typename T,
typename... P>
struct TypeOfFold<
TFnObj,
T,
P...>
{
using type =
typename std::result_of<
TFnObj(T, typename TypeOfFold<TFnObj, P...>::type)>::type;
};
}
//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TFnObj,
typename T0,
typename T1,
typename... Ts>
ALPAKA_FN_HOST_ACC auto foldr(
TFnObj const & f,
T0 const & t0,
T1 const & t1,
Ts const & ... ts)
// NOTE: The following line is not allowed because the point of function declaration is after the trailing return type.
// Thus the function itself is not available inside its return type declaration.
// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#1433
// http://stackoverflow.com/questions/3744400/trailing-return-type-using-decltype-with-a-variadic-template-function
// http://stackoverflow.com/questions/11596898/variadic-template-and-inferred-return-type-in-concat/11597196#11597196
//-> decltype(f(t0, foldr(f, t1, ts...)))
-> typename detail::TypeOfFold<TFnObj, T0, T1, Ts...>::type
{
return f(t0, foldr(f, t1, ts...));
}
#endif
}
}
|
gpl-3.0
|
Cheezegami/Mod-Sources-Cheezes-Content-Pack
|
CheezeMod/Items/Weapons/Ratchet/LavaGun.cs
|
2175
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using CheezeMod.NPCs;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace CheezeMod.Items.Weapons.Ratchet
{
public class LavaGun : ModItem
{
public override void SetDefaults()
{
item.damage = 5;
item.ranged = true;
item.width = 50;
item.height = 30;
item.scale = 0.875f;
item.channel = true;
item.useTime = 5;
item.useAnimation = 10;
item.useStyle = 5;
item.channel = true;
item.noMelee = true; //so the item's animation doesn't do damage
item.knockBack = 1;
item.value = 33000;
item.rare = CheezeItem.ratchetRarity[0];
item.UseSound = mod.GetLegacySoundSlot(SoundType.Item, "Sounds/Item/LavaGun");
item.autoReuse = true;
item.shoot = mod.ProjectileType("LavaGun");
item.shootSpeed = 0f;
item.useAmmo = 931;
}
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Lava Gun");
Tooltip.SetDefault("Uses Flares, now also made at the MegaCorp Vendor with Musket Balls.\nOriginally from Ratchet and Clank: Going Commando.");
}
public override bool Shoot(Player player, ref Microsoft.Xna.Framework.Vector2 position, ref float speedX, ref float speedY, ref int type, ref int damage, ref float knockBack)
{
type = mod.ProjectileType("LavaGun");
return true;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(null, "MeteoriteBolt", 50);
recipe.AddIngredient(ItemID.LavaBucket);
recipe.AddTile(null, "MegaCorpVendor");
recipe.SetResult(this, 1);
recipe.AddRecipe();
}
public override void UpdateInventory(Player player)
{
CheezePlayer.sellFlare = true;
base.UpdateInventory(player);
}
public override bool ConsumeAmmo(Player p)
{
return Main.rand.Next(10) < 1; // 90% not to consume ammo.
}
}
}
|
gpl-3.0
|
jeffersonmolleri/sesra
|
apps/adm/modules/users/templates/_list.php
|
2540
|
<?php use_helper('Date', 'Text', 'I18N', 'myWidgets', 'enMessageBox'); ?>
<div class="page-header">
<h1><?php echo __('Usuários do sistema') ?></h1>
</div>
<?php if ($sf_request->hasParameter('name')) : ?>
<div class="msg alert"><?php echo __('Procurando pelo termo') ?> <strong>"<?php echo $sf_request->getParameter('name')?>"</strong></div>
<?php endif ?>
<table class="table table-striped">
<thead>
<tr>
<?php $dir = ($dir == 'asc')?'desc':'asc'; ?>
<th><?php echo link_to(__('Usuário'), 'users/index?order='.sfGuardUserPeer::USERNAME.'&dir='.$dir, array ('class' => ($order == sfGuardUserPeer::USERNAME ? $dir : ''))) ?></th>
<th><?php echo link_to(__('Nome'), 'users/index?order='.sfGuardUserProfilePeer::NAME.'&dir='.$dir, array ('class' => ($order == sfGuardUserProfilePeer::NAME ? $dir : ''))) ?></th>
<th><?php echo link_to(__('Ativo?'), 'users/index?order='.sfGuardUserPeer::IS_ACTIVE.'&dir='.$dir, array ('class' => ($order == sfGuardUserPeer::IS_ACTIVE ? $dir : ''))) ?></th>
<th><?php echo link_to(__('Último acesso'), 'users/index?order='.sfGuardUserPeer::LAST_LOGIN.'&dir='.$dir, array ('class' => ($order == sfGuardUserPeer::LAST_LOGIN ? $dir : ''))) ?></th>
<th><?php echo __('Ações') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($users->getResults() as $user) : ?>
<tr>
<td><?php echo $user[1] ?></td>
<td><?php echo truncate_text($user[3]) ?></td>
<td><?php echo ($user[5] ? '<i class="icon-ok-sign"></i>' : '<i class="icon-remove-sign"></i>') ?></td>
<td><?php echo en_distance_of_time_in_words($user[4]) ?></td>
<?php if ($sf_user->hasCredential('users')) : ?>
<td class="ctrls">
<div class="btn-group">
<?php echo link_to('<i class="icon-pencil"></i> editar', 'users/edit?id=' . $user[0], array ('class' => 'btn btn-mini btn-info')) ?>
<?php echo ($user[1] == 'admin') ? '' : link_to('<i class="icon-remove-sign"></i> excluir', 'users/delete?id=' . $user[0], array ('class' => 'btn btn-mini btn-danger')) ?>
</div>
</td>
<?php else : ?>
<td></td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
<?php if (!$users->getNbResults()) : ?>
<tr>
<td colspan="5" class="emptyCell"><?php echo __('Nenhum usuário encontrado') ?></td>
</tr>
<?php endif; ?>
</tbody>
</table>
<?php echo form_pager_display($users, "users/index?page="); ?>
|
gpl-3.0
|
henryeherman/libopencm3
|
examples/stm32/f1/obldc/led/Makefile
|
832
|
##
## This file is part of the libopencm3 project.
##
## Copyright (C) 2009 Uwe Hermann <uwe@hermann-uwe.de>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
BINARY = led
LDSCRIPT = ../obldc.ld
include ../../Makefile.include
|
gpl-3.0
|
ecattez/da2i-boggle
|
sources/boggle/gui/decorateur/DecorateurBouton.java
|
1109
|
/**
* This file is part of da2i-boggle.
*
* da2i-boggle 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.
*
* da2i-boggle 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 da2i-boggle. If not, see <http://www.gnu.org/licenses/>.
*
* @author Edouard CATTEZ <edouard.cattez@sfr.fr> (La 7 Production)
*/
package boggle.gui.decorateur;
import javax.swing.JButton;
/**
* Ajoute une décoration sur un JButton.
*/
public class DecorateurBouton extends JButton {
private static final long serialVersionUID = 772827254096143798L;
public DecorateurBouton(JButton bouton) {
super(bouton.getText());
}
}
|
gpl-3.0
|
Metalcon/imageStorageServer
|
src/test/java/de/metalcon/imageServer/protocol/ReadScaledRequestTest.java
|
4366
|
package de.metalcon.imageServer.protocol;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import de.metalcon.imageStorageServer.protocol.ProtocolConstants;
import de.metalcon.imageStorageServer.protocol.read.ReadResponse;
import de.metalcon.imageStorageServer.protocol.read.ReadScaledRequest;
import de.metalcon.utils.formItemList.FormItemList;
public class ReadScaledRequestTest extends RequestTest {
private ReadScaledRequest readScaledRequest;
private void fillRequest(
final String imageIdentifier,
final String width,
final String height) {
FormItemList formItemList = new FormItemList();
if (imageIdentifier != null) {
formItemList.addField(
ProtocolConstants.Parameters.Read.IMAGE_IDENTIFIER,
imageIdentifier);
}
if (width != null) {
formItemList.addField(
ProtocolConstants.Parameters.Read.IMAGE_WIDTH, width);
}
if (height != null) {
formItemList.addField(
ProtocolConstants.Parameters.Read.IMAGE_HEIGHT, height);
}
final ReadResponse readResponse = new ReadResponse();
readScaledRequest =
ReadScaledRequest.checkRequest(formItemList, readResponse);
extractJson(readResponse);
}
@Test
public void testReadScaledRequest() {
fillRequest(VALID_IDENTIFIER,
ProtocolTestConstants.VALID_SCALING_WIDTH,
ProtocolTestConstants.VALID_SCALING_HEIGHT);
assertNotNull(readScaledRequest);
assertEquals(VALID_IDENTIFIER, readScaledRequest.getImageIdentifier());
assertEquals(ProtocolTestConstants.VALID_SCALING_WIDTH,
String.valueOf(readScaledRequest.getImageWidth()));
assertEquals(ProtocolTestConstants.VALID_SCALING_HEIGHT,
String.valueOf(readScaledRequest.getImageHeight()));
}
@Test
public void testImageIdentifierMissing() {
fillRequest(null, ProtocolTestConstants.VALID_SCALING_WIDTH,
ProtocolTestConstants.VALID_SCALING_HEIGHT);
checkForMissingParameterMessage(ProtocolConstants.Parameters.Read.IMAGE_IDENTIFIER);
assertNull(readScaledRequest);
}
@Test
public void testWidthMissing() {
fillRequest(VALID_IDENTIFIER, null,
ProtocolTestConstants.VALID_SCALING_HEIGHT);
checkForMissingParameterMessage(ProtocolConstants.Parameters.Read.IMAGE_WIDTH);
assertNull(readScaledRequest);
}
@Test
public void testWidthMalformed() {
fillRequest(VALID_IDENTIFIER,
ProtocolTestConstants.MALFORMED_SCALING_VALUE,
ProtocolTestConstants.VALID_SCALING_HEIGHT);
checkForStatusMessage(ProtocolConstants.StatusMessage.Read.SCALING_WIDTH_MALFORMED);
assertNull(readScaledRequest);
}
@Test
public void testWidthInvalid() {
fillRequest(VALID_IDENTIFIER,
ProtocolTestConstants.INVALID_SCALING_WIDTH,
ProtocolTestConstants.VALID_SCALING_HEIGHT);
checkForStatusMessage(ProtocolConstants.StatusMessage.Read.SCALING_WIDTH_INVALID);
assertNull(readScaledRequest);
}
@Test
public void testHeightMissing() {
fillRequest(VALID_IDENTIFIER,
ProtocolTestConstants.VALID_SCALING_WIDTH, null);
checkForMissingParameterMessage(ProtocolConstants.Parameters.Read.IMAGE_HEIGHT);
assertNull(readScaledRequest);
}
@Test
public void testHeightMalformed() {
fillRequest(VALID_IDENTIFIER,
ProtocolTestConstants.VALID_SCALING_WIDTH,
ProtocolTestConstants.MALFORMED_SCALING_VALUE);
checkForStatusMessage(ProtocolConstants.StatusMessage.Read.SCALING_HEIGHT_MALFORMED);
assertNull(readScaledRequest);
}
@Test
public void testHeightInvalid() {
fillRequest(VALID_IDENTIFIER,
ProtocolTestConstants.VALID_SCALING_WIDTH,
ProtocolTestConstants.INVALID_SCALING_HEIGHT);
checkForStatusMessage(ProtocolConstants.StatusMessage.Read.SCALING_HEIGHT_INVALID);
assertNull(readScaledRequest);
}
}
|
gpl-3.0
|
x2wing/android
|
RatingImages/app/src/main/java/tk/natallymp/ratingimages/MainActivity.java
|
1981
|
package tk.natallymp.ratingimages;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity {
private String url_image;
private ImageView imageView1;
private EditText edit_message1;
private ImageButton imageButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_message1 = (EditText) findViewById(R.id.edit_message);
WebView webView = (WebView) findViewById(R.id.web_view1);
webView.loadUrl("http://ya.ru");
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setClickable(true);
imageView1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toLink("https://mail.ru");
}
});
}
public void onClickGO(View v){
String url_image = edit_message1.getText().toString();
//вывод картинки в imageview
Picasso
.with(this)
.load(url_image)
.placeholder(R.drawable.errormessage)
.error(R.drawable.errormessage)
.into(imageView1);
}
public void onClick_go_url(View v) {
String url_image = edit_message1.getText().toString();
toLink(url_image);
}
//перейти по ссылке рабочи код
private void toLink(String url){
Uri address = Uri.parse(url);
Intent openlinkIntent = new Intent(Intent.ACTION_VIEW, address);
startActivity(openlinkIntent);
}
}
|
gpl-3.0
|
bamill/fillit
|
lib/libft/src/ft_isalnum.c
|
1003
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_isalnum.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bmiller <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/29 09:38:10 by bmiller #+# #+# */
/* Updated: 2016/11/29 09:40:33 by bmiller ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_isalnum(int c)
{
if (ft_isalpha(c) || ft_isdigit(c))
return (1);
return (0);
}
|
gpl-3.0
|
ruibarreira/linuxtrail
|
usr/lib/python2.7/dist-packages/numpy/ctypeslib.py
|
14076
|
"""
============================
``ctypes`` Utility Functions
============================
See Also
---------
load_library : Load a C library.
ndpointer : Array restype/argtype with verification.
as_ctypes : Create a ctypes array from an ndarray.
as_array : Create an ndarray from a ctypes array.
References
----------
.. [1] "SciPy Cookbook: ctypes", http://www.scipy.org/Cookbook/Ctypes
Examples
--------
Load the C library:
>>> _lib = np.ctypeslib.load_library('libmystuff', '.') #doctest: +SKIP
Our result type, an ndarray that must be of type double, be 1-dimensional
and is C-contiguous in memory:
>>> array_1d_double = np.ctypeslib.ndpointer(
... dtype=np.double,
... ndim=1, flags='CONTIGUOUS') #doctest: +SKIP
Our C-function typically takes an array and updates its values
in-place. For example::
void foo_func(double* x, int length)
{
int i;
for (i = 0; i < length; i++) {
x[i] = i*i;
}
}
We wrap it using:
>>> _lib.foo_func.restype = None #doctest: +SKIP
>>> _lib.foo_func.argtypes = [array_1d_double, c_int] #doctest: +SKIP
Then, we're ready to call ``foo_func``:
>>> out = np.empty(15, dtype=np.double)
>>> _lib.foo_func(out, len(out)) #doctest: +SKIP
"""
from __future__ import division, absolute_import, print_function
__all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library',
'c_intp', 'as_ctypes', 'as_array']
import sys, os
from numpy import integer, ndarray, dtype as _dtype, deprecate, array
from numpy.core.multiarray import _flagdict, flagsobj
try:
import ctypes
except ImportError:
ctypes = None
if ctypes is None:
def _dummy(*args, **kwds):
"""
Dummy object that raises an ImportError if ctypes is not available.
Raises
------
ImportError
If ctypes is not available.
"""
raise ImportError("ctypes is not available.")
ctypes_load_library = _dummy
load_library = _dummy
as_ctypes = _dummy
as_array = _dummy
from numpy import intp as c_intp
_ndptr_base = object
else:
import numpy.core._internal as nic
c_intp = nic._getintp_ctype()
del nic
_ndptr_base = ctypes.c_void_p
# Adapted from Albert Strasheim
def load_library(libname, loader_path):
if ctypes.__version__ < '1.0.1':
import warnings
warnings.warn("All features of ctypes interface may not work " \
"with ctypes < 1.0.1")
ext = os.path.splitext(libname)[1]
if not ext:
# Try to load library with platform-specific name, otherwise
# default to libname.[so|pyd]. Sometimes, these files are built
# erroneously on non-linux platforms.
from numpy.distutils.misc_util import get_shared_lib_extension
so_ext = get_shared_lib_extension()
libname_ext = [libname + so_ext]
# mac, windows and linux >= py3.2 shared library and loadable
# module have different extensions so try both
so_ext2 = get_shared_lib_extension(is_python_ext=True)
if not so_ext2 == so_ext:
libname_ext.insert(0, libname + so_ext2)
try:
import sysconfig
so_ext3 = '.%s-%s.so' % (sysconfig.get_config_var('SOABI'),
sysconfig.get_config_var('MULTIARCH'))
libname_ext.insert(0, libname + so_ext3)
except (KeyError, ImportError):
pass
else:
libname_ext = [libname]
loader_path = os.path.abspath(loader_path)
if not os.path.isdir(loader_path):
libdir = os.path.dirname(loader_path)
else:
libdir = loader_path
for ln in libname_ext:
libpath = os.path.join(libdir, ln)
if os.path.exists(libpath):
try:
return ctypes.cdll[libpath]
except OSError:
## defective lib file
raise
## if no successful return in the libname_ext loop:
raise OSError("no file with expected extension")
ctypes_load_library = deprecate(load_library, 'ctypes_load_library',
'load_library')
def _num_fromflags(flaglist):
num = 0
for val in flaglist:
num += _flagdict[val]
return num
_flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE',
'OWNDATA', 'UPDATEIFCOPY']
def _flags_fromnum(num):
res = []
for key in _flagnames:
value = _flagdict[key]
if (num & value):
res.append(key)
return res
class _ndptr(_ndptr_base):
def _check_retval_(self):
"""This method is called when this class is used as the .restype
asttribute for a shared-library function. It constructs a numpy
array from a void pointer."""
return array(self)
@property
def __array_interface__(self):
return {'descr': self._dtype_.descr,
'__ref': self,
'strides': None,
'shape': self._shape_,
'version': 3,
'typestr': self._dtype_.descr[0][1],
'data': (self.value, False),
}
@classmethod
def from_param(cls, obj):
if not isinstance(obj, ndarray):
raise TypeError("argument must be an ndarray")
if cls._dtype_ is not None \
and obj.dtype != cls._dtype_:
raise TypeError("array must have data type %s" % cls._dtype_)
if cls._ndim_ is not None \
and obj.ndim != cls._ndim_:
raise TypeError("array must have %d dimension(s)" % cls._ndim_)
if cls._shape_ is not None \
and obj.shape != cls._shape_:
raise TypeError("array must have shape %s" % str(cls._shape_))
if cls._flags_ is not None \
and ((obj.flags.num & cls._flags_) != cls._flags_):
raise TypeError("array must have flags %s" %
_flags_fromnum(cls._flags_))
return obj.ctypes
# Factory for an array-checking class with from_param defined for
# use with ctypes argtypes mechanism
_pointer_type_cache = {}
def ndpointer(dtype=None, ndim=None, shape=None, flags=None):
"""
Array-checking restype/argtypes.
An ndpointer instance is used to describe an ndarray in restypes
and argtypes specifications. This approach is more flexible than
using, for example, ``POINTER(c_double)``, since several restrictions
can be specified, which are verified upon calling the ctypes function.
These include data type, number of dimensions, shape and flags. If a
given array does not satisfy the specified restrictions,
a ``TypeError`` is raised.
Parameters
----------
dtype : data-type, optional
Array data-type.
ndim : int, optional
Number of array dimensions.
shape : tuple of ints, optional
Array shape.
flags : str or tuple of str
Array flags; may be one or more of:
- C_CONTIGUOUS / C / CONTIGUOUS
- F_CONTIGUOUS / F / FORTRAN
- OWNDATA / O
- WRITEABLE / W
- ALIGNED / A
- UPDATEIFCOPY / U
Returns
-------
klass : ndpointer type object
A type object, which is an ``_ndtpr`` instance containing
dtype, ndim, shape and flags information.
Raises
------
TypeError
If a given array does not satisfy the specified restrictions.
Examples
--------
>>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,
... ndim=1,
... flags='C_CONTIGUOUS')]
... #doctest: +SKIP
>>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64))
... #doctest: +SKIP
"""
if dtype is not None:
dtype = _dtype(dtype)
num = None
if flags is not None:
if isinstance(flags, str):
flags = flags.split(',')
elif isinstance(flags, (int, integer)):
num = flags
flags = _flags_fromnum(num)
elif isinstance(flags, flagsobj):
num = flags.num
flags = _flags_fromnum(num)
if num is None:
try:
flags = [x.strip().upper() for x in flags]
except:
raise TypeError("invalid flags specification")
num = _num_fromflags(flags)
try:
return _pointer_type_cache[(dtype, ndim, shape, num)]
except KeyError:
pass
if dtype is None:
name = 'any'
elif dtype.names:
name = str(id(dtype))
else:
name = dtype.str
if ndim is not None:
name += "_%dd" % ndim
if shape is not None:
try:
strshape = [str(x) for x in shape]
except TypeError:
strshape = [str(shape)]
shape = (shape,)
shape = tuple(shape)
name += "_"+"x".join(strshape)
if flags is not None:
name += "_"+"_".join(flags)
else:
flags = []
klass = type("ndpointer_%s"%name, (_ndptr,),
{"_dtype_": dtype,
"_shape_" : shape,
"_ndim_" : ndim,
"_flags_" : num})
_pointer_type_cache[dtype] = klass
return klass
if ctypes is not None:
ct = ctypes
################################################################
# simple types
# maps the numpy typecodes like '<f8' to simple ctypes types like
# c_double. Filled in by prep_simple.
_typecodes = {}
def prep_simple(simple_type, dtype):
"""Given a ctypes simple type, construct and attach an
__array_interface__ property to it if it does not yet have one.
"""
try: simple_type.__array_interface__
except AttributeError: pass
else: return
typestr = _dtype(dtype).str
_typecodes[typestr] = simple_type
def __array_interface__(self):
return {'descr': [('', typestr)],
'__ref': self,
'strides': None,
'shape': (),
'version': 3,
'typestr': typestr,
'data': (ct.addressof(self), False),
}
simple_type.__array_interface__ = property(__array_interface__)
simple_types = [
((ct.c_byte, ct.c_short, ct.c_int, ct.c_long, ct.c_longlong), "i"),
((ct.c_ubyte, ct.c_ushort, ct.c_uint, ct.c_ulong, ct.c_ulonglong), "u"),
((ct.c_float, ct.c_double), "f"),
]
# Prep that numerical ctypes types:
for types, code in simple_types:
for tp in types:
prep_simple(tp, "%c%d" % (code, ct.sizeof(tp)))
################################################################
# array types
_ARRAY_TYPE = type(ct.c_int * 1)
def prep_array(array_type):
"""Given a ctypes array type, construct and attach an
__array_interface__ property to it if it does not yet have one.
"""
try: array_type.__array_interface__
except AttributeError: pass
else: return
shape = []
ob = array_type
while type(ob) is _ARRAY_TYPE:
shape.append(ob._length_)
ob = ob._type_
shape = tuple(shape)
ai = ob().__array_interface__
descr = ai['descr']
typestr = ai['typestr']
def __array_interface__(self):
return {'descr': descr,
'__ref': self,
'strides': None,
'shape': shape,
'version': 3,
'typestr': typestr,
'data': (ct.addressof(self), False),
}
array_type.__array_interface__ = property(__array_interface__)
def prep_pointer(pointer_obj, shape):
"""Given a ctypes pointer object, construct and
attach an __array_interface__ property to it if it does not
yet have one.
"""
try: pointer_obj.__array_interface__
except AttributeError: pass
else: return
contents = pointer_obj.contents
dtype = _dtype(type(contents))
inter = {'version': 3,
'typestr': dtype.str,
'data': (ct.addressof(contents), False),
'shape': shape}
pointer_obj.__array_interface__ = inter
################################################################
# public functions
def as_array(obj, shape=None):
"""Create a numpy array from a ctypes array or a ctypes POINTER.
The numpy array shares the memory with the ctypes object.
The size parameter must be given if converting from a ctypes POINTER.
The size parameter is ignored if converting from a ctypes array
"""
tp = type(obj)
try: tp.__array_interface__
except AttributeError:
if hasattr(obj, 'contents'):
prep_pointer(obj, shape)
else:
prep_array(tp)
return array(obj, copy=False)
def as_ctypes(obj):
"""Create and return a ctypes object from a numpy array. Actually
anything that exposes the __array_interface__ is accepted."""
ai = obj.__array_interface__
if ai["strides"]:
raise TypeError("strided arrays not supported")
if ai["version"] != 3:
raise TypeError("only __array_interface__ version 3 supported")
addr, readonly = ai["data"]
if readonly:
raise TypeError("readonly arrays unsupported")
tp = _typecodes[ai["typestr"]]
for dim in ai["shape"][::-1]:
tp = tp * dim
result = tp.from_address(addr)
result.__keep = ai
return result
|
gpl-3.0
|
majestic53/nesasm
|
src/core/nasm_language_type.h
|
1719
|
/*
* NESASM NES Assembler
* Copyright (C) 2014 David Jolly
* ----------------------
*
* NESASM 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.
*
* NESASM 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/>.
*/
#ifndef NASM_LANGUAGE_TYPE_H_
#define NASM_LANGUAGE_TYPE_H_
namespace NASM_NS {
namespace NASM_LANG_NS {
enum {
NASM_LANGUAGE_EXCEPTION_EXCEEDS_MAX_LENGTH = 0,
NASM_LANGUAGE_EXCEPTION_HEADER_CONFIG_FAILED,
NASM_LANGUAGE_EXCEPTION_OPCODE_NOT_FOUND,
};
static const std::string NASM_LANGUAGE_EXCEPTION_STR[] = {
"Integer exceeds maximum length",
"Failed to configure header",
"Opcode was not found",
};
#define MAX_NASM_LANGUAGE_EXCEPTION NASM_LANGUAGE_EXCEPTION_OPCODE_NOT_FOUND
#define NASM_LANGUAGE_EXCEPTION_STRING(_TYPE_)\
((_TYPE_) > MAX_NASM_LANGUAGE_EXCEPTION ? UNKNOWN_EXCEPTION : NASM_LANGUAGE_EXCEPTION_STR[_TYPE_].c_str())
#define THROW_NASM_LANGUAGE_EXCEPTION(_EXCEPT_)\
THROW_EXCEPTION(NASM_LANGUAGE_EXCEPTION_STRING(_EXCEPT_))
#define THROW_NASM_LANGUAGE_EXCEPTION_MESSAGE(_EXCEPT_, _FORMAT_, ...)\
THROW_EXCEPTION_MESSAGE(NASM_LANGUAGE_EXCEPTION_STRING(_EXCEPT_), _FORMAT_, __VA_ARGS__)
}
}
#endif // NASM_LANGUAGE_TYPE_H_
|
gpl-3.0
|
robsonsmartins/acaas
|
source/acaas.jboss7/AcaaSweb/WebContent/doc/java/com/robsonmartins/acaas/util/AudioBuffer.html
|
16671
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pt">
<head>
<!-- Generated by javadoc (version 1.7.0_09) on Mon Sep 16 13:13:38 BRT 2013 -->
<title>AudioBuffer</title>
<meta name="date" content="2013-09-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="AudioBuffer";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/AudioBuffer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../com/robsonmartins/acaas/util/AudioFormats.html" title="enum in com.robsonmartins.acaas.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/robsonmartins/acaas/util/AudioBuffer.html" target="_top">Frames</a></li>
<li><a href="AudioBuffer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.robsonmartins.acaas.util</div>
<h2 title="Class AudioBuffer" class="title">Class AudioBuffer</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.robsonmartins.acaas.util.AudioBuffer</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">AudioBuffer</span>
extends java.lang.Object</pre>
<div class="block">Buffer em memoria para dados de audio.</div>
<dl><dt><span class="strong">Author:</span></dt>
<dd>Robson Martins (robson@robsonmartins.com)</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#AudioBuffer()">AudioBuffer</a></strong>()</code>
<div class="block">Construtor.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#AudioBuffer(int, int, int, java.nio.ByteOrder)">AudioBuffer</a></strong>(int sampleRate,
int bitsPerSample,
int numChannels,
java.nio.ByteOrder byteOrder)</code>
<div class="block">Construtor.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#getBitsPerSample()">getBitsPerSample</a></strong>()</code>
<div class="block">Retorna o numero de bits de uma amostra.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.nio.ByteOrder</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#getByteOrder()">getByteOrder</a></strong>()</code>
<div class="block">Retorna o alinhamento de bytes de uma amostra.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#getBytesPerSample()">getBytesPerSample</a></strong>()</code>
<div class="block">Retorna o numero de bytes de uma amostra.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#getNumChannels()">getNumChannels</a></strong>()</code>
<div class="block">Retorna o numero de canais da amostragem.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#getSampleRate()">getSampleRate</a></strong>()</code>
<div class="block">Retorna a taxa de amostragem.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>byte[]</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#getSamples()">getSamples</a></strong>()</code>
<div class="block">Retorna os dados (buffer) do audio.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#setBitsPerSample(int)">setBitsPerSample</a></strong>(int bitsPerSample)</code>
<div class="block">Configura o numero de bits de uma amostra.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#setByteOrder(java.nio.ByteOrder)">setByteOrder</a></strong>(java.nio.ByteOrder byteOrder)</code>
<div class="block">Configura o alinhamento de bytes de uma amostra.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#setNumChannels(int)">setNumChannels</a></strong>(int numChannels)</code>
<div class="block">Configura o numero de canais da amostragem.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#setSampleRate(int)">setSampleRate</a></strong>(int sampleRate)</code>
<div class="block">Configura a taxa de amostragem.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/robsonmartins/acaas/util/AudioBuffer.html#setSamples(byte[])">setSamples</a></strong>(byte[] samples)</code>
<div class="block">Configura os dados (buffer) do audio.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="AudioBuffer()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>AudioBuffer</h4>
<pre>public AudioBuffer()</pre>
<div class="block">Construtor.</div>
</li>
</ul>
<a name="AudioBuffer(int, int, int, java.nio.ByteOrder)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>AudioBuffer</h4>
<pre>public AudioBuffer(int sampleRate,
int bitsPerSample,
int numChannels,
java.nio.ByteOrder byteOrder)</pre>
<div class="block">Construtor.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>sampleRate</code> - Taxa de amostragem, em samples/second.</dd><dd><code>bitsPerSample</code> - Numero de bits de uma amostra.</dd><dd><code>numChannels</code> - Numero de canais da amostragem.</dd><dd><code>byteOrder</code> - Alinhamento de bytes de uma amostra.</dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getSamples()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getSamples</h4>
<pre>public byte[] getSamples()</pre>
<div class="block">Retorna os dados (buffer) do audio.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>Dados binarios.</dd></dl>
</li>
</ul>
<a name="setSamples(byte[])">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setSamples</h4>
<pre>public void setSamples(byte[] samples)</pre>
<div class="block">Configura os dados (buffer) do audio.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>samples</code> - Dados binarios do audio.</dd></dl>
</li>
</ul>
<a name="getNumChannels()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getNumChannels</h4>
<pre>public int getNumChannels()</pre>
<div class="block">Retorna o numero de canais da amostragem.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>Numero de canais.</dd></dl>
</li>
</ul>
<a name="setNumChannels(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setNumChannels</h4>
<pre>public void setNumChannels(int numChannels)</pre>
<div class="block">Configura o numero de canais da amostragem.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>numChannels</code> - Numero de canais.</dd></dl>
</li>
</ul>
<a name="getSampleRate()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getSampleRate</h4>
<pre>public int getSampleRate()</pre>
<div class="block">Retorna a taxa de amostragem.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>Taxa de amostragem, em samples/second.</dd></dl>
</li>
</ul>
<a name="setSampleRate(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setSampleRate</h4>
<pre>public void setSampleRate(int sampleRate)</pre>
<div class="block">Configura a taxa de amostragem.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>sampleRate</code> - Taxa de amostragem, em samples/second.</dd></dl>
</li>
</ul>
<a name="getBitsPerSample()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getBitsPerSample</h4>
<pre>public int getBitsPerSample()</pre>
<div class="block">Retorna o numero de bits de uma amostra.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>Numero de bits.</dd></dl>
</li>
</ul>
<a name="setBitsPerSample(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setBitsPerSample</h4>
<pre>public void setBitsPerSample(int bitsPerSample)</pre>
<div class="block">Configura o numero de bits de uma amostra.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>bitsPerSample</code> - Numero de bits.</dd></dl>
</li>
</ul>
<a name="getBytesPerSample()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getBytesPerSample</h4>
<pre>public int getBytesPerSample()</pre>
<div class="block">Retorna o numero de bytes de uma amostra.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>Numero de bytes.</dd></dl>
</li>
</ul>
<a name="getByteOrder()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getByteOrder</h4>
<pre>public java.nio.ByteOrder getByteOrder()</pre>
<div class="block">Retorna o alinhamento de bytes de uma amostra.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>Alinhamento de bytes.</dd></dl>
</li>
</ul>
<a name="setByteOrder(java.nio.ByteOrder)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setByteOrder</h4>
<pre>public void setByteOrder(java.nio.ByteOrder byteOrder)</pre>
<div class="block">Configura o alinhamento de bytes de uma amostra.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>byteOrder</code> - Alinhamento de bytes.</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/AudioBuffer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../com/robsonmartins/acaas/util/AudioFormats.html" title="enum in com.robsonmartins.acaas.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/robsonmartins/acaas/util/AudioBuffer.html" target="_top">Frames</a></li>
<li><a href="AudioBuffer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
gpl-3.0
|
CRG-Barcelona/libbeato
|
jkweb/bwgQuery.c
|
11554
|
/* bwgQuery - implements the query side of bigWig. See bwgInternal.h for definition of file
* format. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "common.h"
#include "linefile.h"
#include "hash.h"
#include "options.h"
#include "sig.h"
#include "sqlNum.h"
#include "obscure.h"
#include "dystring.h"
#include "bPlusTree.h"
#include "cirTree.h"
#include "rangeTree.h"
#include "udc.h"
#include "zlibFace.h"
#include "bbiFile.h"
#include "bwgInternal.h"
#include "bigWig.h"
#include "bigBed.h"
struct bbiFile *bigWigFileOpen(char *fileName)
/* Open up big wig file. */
{
return bbiFileOpen(fileName, bigWigSig, "big wig");
}
boolean bigWigFileCheckSigs(char *fileName)
/* check file signatures at beginning and end of file */
{
return bbiFileCheckSigs(fileName, bigWigSig, "big wig");
}
#ifdef OLD
static void bwgSectionHeadRead(struct bbiFile *bwf, struct bwgSectionHead *head)
/* Read section header. */
{
struct udcFile *udc = bwf->udc;
boolean isSwapped = bwf->isSwapped;
head->chromId = udcReadBits32(udc, isSwapped);
head->start = udcReadBits32(udc, isSwapped);
head->end = udcReadBits32(udc, isSwapped);
head->itemStep = udcReadBits32(udc, isSwapped);
head->itemSpan = udcReadBits32(udc, isSwapped);
head->type = udcGetChar(udc);
head->reserved = udcGetChar(udc);
head->itemCount = udcReadBits16(udc, isSwapped);
}
#endif /* OLD */
void bwgSectionHeadFromMem(char **pPt, struct bwgSectionHead *head, boolean isSwapped)
/* Read section header. */
{
char *pt = *pPt;
head->chromId = memReadBits32(&pt, isSwapped);
head->start = memReadBits32(&pt, isSwapped);
head->end = memReadBits32(&pt, isSwapped);
head->itemStep = memReadBits32(&pt, isSwapped);
head->itemSpan = memReadBits32(&pt, isSwapped);
head->type = *pt++;
head->reserved = *pt++;
head->itemCount = memReadBits16(&pt, isSwapped);
*pPt = pt;
}
static int bigWigBlockDumpIntersectingRange(boolean isSwapped, char *blockPt, char *blockEnd,
char *chrom, bits32 rangeStart, bits32 rangeEnd, int maxCount, FILE *out)
/* Print out info on parts of block that intersect start-end, block starting at current position. */
{
struct bwgSectionHead head;
bwgSectionHeadFromMem(&blockPt, &head, isSwapped);
bits16 i;
float val;
int outCount = 0;
switch (head.type)
{
case bwgTypeBedGraph:
{
fprintf(out, "#bedGraph section %s:%u-%u\n", chrom, head.start, head.end);
for (i=0; i<head.itemCount; ++i)
{
bits32 start = memReadBits32(&blockPt, isSwapped);
bits32 end = memReadBits32(&blockPt, isSwapped);
val = memReadFloat(&blockPt, isSwapped);
if (rangeIntersection(rangeStart, rangeEnd, start, end) > 0)
{
fprintf(out, "%s\t%u\t%u\t%g\n", chrom, start, end, val);
++outCount;
if (maxCount != 0 && outCount >= maxCount)
break;
}
}
break;
}
case bwgTypeVariableStep:
{
fprintf(out, "variableStep chrom=%s span=%u\n", chrom, head.itemSpan);
for (i=0; i<head.itemCount; ++i)
{
bits32 start = memReadBits32(&blockPt, isSwapped);
val = memReadFloat(&blockPt, isSwapped);
if (rangeIntersection(rangeStart, rangeEnd, start, start+head.itemSpan) > 0)
{
fprintf(out, "%u\t%g\n", start+1, val);
++outCount;
if (maxCount != 0 && outCount >= maxCount)
break;
}
}
break;
}
case bwgTypeFixedStep:
{
boolean gotStart = FALSE;
bits32 start = head.start;
for (i=0; i<head.itemCount; ++i)
{
val = memReadFloat(&blockPt, isSwapped);
if (rangeIntersection(rangeStart, rangeEnd, start, start+head.itemSpan) > 0)
{
if (!gotStart)
{
fprintf(out, "fixedStep chrom=%s start=%u step=%u span=%u\n",
chrom, start+1, head.itemStep, head.itemSpan);
gotStart = TRUE;
}
fprintf(out, "%g\n", val);
++outCount;
if (maxCount != 0 && outCount >= maxCount)
break;
}
start += head.itemStep;
}
break;
}
default:
internalErr();
break;
}
assert( (maxCount != 0 && outCount >= maxCount) || (blockPt == blockEnd));
return outCount;
}
struct bbiInterval *bigWigIntervalQuery(struct bbiFile *bwf, char *chrom, bits32 start, bits32 end,
struct lm *lm)
/* Get data for interval. Return list allocated out of lm. */
{
if (bwf->typeSig != bigWigSig)
errAbort("Trying to do bigWigIntervalQuery on a non big-wig file.");
bbiAttachUnzoomedCir(bwf);
struct bbiInterval *el, *list = NULL;
struct fileOffsetSize *blockList = bbiOverlappingBlocks(bwf, bwf->unzoomedCir,
chrom, start, end, NULL);
struct fileOffsetSize *block, *beforeGap, *afterGap;
struct udcFile *udc = bwf->udc;
boolean isSwapped = bwf->isSwapped;
float val;
int i;
/* Set up for uncompression optionally. */
char *uncompressBuf = NULL;
if (bwf->uncompressBufSize > 0)
uncompressBuf = needLargeMem(bwf->uncompressBufSize);
/* This loop is a little complicated because we merge the read requests for efficiency, but we
* have to then go back through the data one unmerged block at a time. */
for (block = blockList; block != NULL; )
{
/* Find contigious blocks and read them into mergedBuf. */
fileOffsetSizeFindGap(block, &beforeGap, &afterGap);
bits64 mergedOffset = block->offset;
bits64 mergedSize = beforeGap->offset + beforeGap->size - mergedOffset;
udcSeek(udc, mergedOffset);
char *mergedBuf = needLargeMem(mergedSize);
udcMustRead(udc, mergedBuf, mergedSize);
char *blockBuf = mergedBuf;
/* Loop through individual blocks within merged section. */
for (;block != afterGap; block = block->next)
{
/* Uncompress if necessary. */
char *blockPt, *blockEnd;
if (uncompressBuf)
{
blockPt = uncompressBuf;
int uncSize = zUncompress(blockBuf, block->size, uncompressBuf, bwf->uncompressBufSize);
blockEnd = blockPt + uncSize;
}
else
{
blockPt = blockBuf;
blockEnd = blockPt + block->size;
}
/* Deal with insides of block. */
struct bwgSectionHead head;
bwgSectionHeadFromMem(&blockPt, &head, isSwapped);
switch (head.type)
{
case bwgTypeBedGraph:
{
for (i=0; i<head.itemCount; ++i)
{
bits32 s = memReadBits32(&blockPt, isSwapped);
bits32 e = memReadBits32(&blockPt, isSwapped);
val = memReadFloat(&blockPt, isSwapped);
if (s < start) s = start;
if (e > end) e = end;
if (s < e)
{
lmAllocVar(lm, el);
el->start = s;
el->end = e;
el->val = val;
slAddHead(&list, el);
}
}
break;
}
case bwgTypeVariableStep:
{
for (i=0; i<head.itemCount; ++i)
{
bits32 s = memReadBits32(&blockPt, isSwapped);
bits32 e = s + head.itemSpan;
val = memReadFloat(&blockPt, isSwapped);
if (s < start) s = start;
if (e > end) e = end;
if (s < e)
{
lmAllocVar(lm, el);
el->start = s;
el->end = e;
el->val = val;
slAddHead(&list, el);
}
}
break;
}
case bwgTypeFixedStep:
{
bits32 s = head.start;
bits32 e = s + head.itemSpan;
for (i=0; i<head.itemCount; ++i)
{
val = memReadFloat(&blockPt, isSwapped);
bits32 clippedS = s, clippedE = e;
if (clippedS < start) clippedS = start;
if (clippedE > end) clippedE = end;
if (clippedS < clippedE)
{
lmAllocVar(lm, el);
el->start = clippedS;
el->end = clippedE;
el->val = val;
slAddHead(&list, el);
}
s += head.itemStep;
e += head.itemStep;
}
break;
}
default:
internalErr();
break;
}
assert(blockPt == blockEnd);
blockBuf += block->size;
}
freeMem(mergedBuf);
}
freeMem(uncompressBuf);
slFreeList(&blockList);
slReverse(&list);
return list;
}
int bigWigIntervalDump(struct bbiFile *bwf, char *chrom, bits32 start, bits32 end, int maxCount,
FILE *out)
/* Print out info on bigWig parts that intersect chrom:start-end. Set maxCount to 0 if you
* don't care how many are printed. Returns number printed. */
{
if (bwf->typeSig != bigWigSig)
errAbort("Trying to do bigWigIntervalDump on a non big-wig file.");
bbiAttachUnzoomedCir(bwf);
struct fileOffsetSize *blockList = bbiOverlappingBlocks(bwf, bwf->unzoomedCir,
chrom, start, end, NULL);
struct fileOffsetSize *block, *beforeGap, *afterGap;
struct udcFile *udc = bwf->udc;
int printCount = 0;
/* Set up for uncompression optionally. */
char *uncompressBuf = NULL;
if (bwf->uncompressBufSize > 0)
uncompressBuf = needLargeMem(bwf->uncompressBufSize);
/* This loop is a little complicated because we merge the read requests for efficiency, but we
* have to then go back through the data one unmerged block at a time. */
for (block = blockList; block != NULL; )
{
/* Find contigious blocks and read them into mergedBuf. */
fileOffsetSizeFindGap(block, &beforeGap, &afterGap);
bits64 mergedOffset = block->offset;
bits64 mergedSize = beforeGap->offset + beforeGap->size - mergedOffset;
udcSeek(udc, mergedOffset);
char *mergedBuf = needLargeMem(mergedSize);
udcMustRead(udc, mergedBuf, mergedSize);
char *blockBuf = mergedBuf;
/* Loop through individual blocks within merged section. */
for (;block != afterGap; block = block->next)
{
/* Uncompress if necessary. */
char *blockPt, *blockEnd;
if (uncompressBuf)
{
blockPt = uncompressBuf;
int uncSize = zUncompress(blockBuf, block->size, uncompressBuf, bwf->uncompressBufSize);
blockEnd = blockPt + uncSize;
}
else
{
blockPt = blockBuf;
blockEnd = blockPt + block->size;
}
/* Do the actual dump. */
int oneCount = bigWigBlockDumpIntersectingRange(bwf->isSwapped, blockPt, blockEnd,
chrom, start, end, maxCount, out);
/* Keep track of how many dumped, not exceeding maximum. */
printCount += oneCount;
if (maxCount != 0)
{
if (oneCount >= maxCount)
{
block = NULL; // we want to drop out of the outer loop too
break;
}
maxCount -= oneCount;
}
blockBuf += block->size;
}
freeMem(mergedBuf);
}
freeMem(uncompressBuf);
slFreeList(&blockList);
return printCount;
}
boolean bigWigSummaryArray(struct bbiFile *bwf, char *chrom, bits32 start, bits32 end,
enum bbiSummaryType summaryType, int summarySize, double *summaryValues)
/* Fill in summaryValues with data from indicated chromosome range in bigWig file.
* Be sure to initialize summaryValues to a default value, which will not be touched
* for regions without data in file. (Generally you want the default value to either
* be 0.0 or nan("") depending on the application.) Returns FALSE if no data
* at that position. */
{
boolean ret = bbiSummaryArray(bwf, chrom, start, end, bigWigIntervalQuery,
summaryType, summarySize, summaryValues);
return ret;
}
boolean bigWigSummaryArrayExtended(struct bbiFile *bwf, char *chrom, bits32 start, bits32 end,
int summarySize, struct bbiSummaryElement *summary)
/* Get extended summary information for summarySize evenely spaced elements into
* the summary array. */
{
boolean ret = bbiSummaryArrayExtended(bwf, chrom, start, end, bigWigIntervalQuery,
summarySize, summary);
return ret;
}
double bigWigSingleSummary(struct bbiFile *bwf, char *chrom, int start, int end,
enum bbiSummaryType summaryType, double defaultVal)
/* Return the summarized single value for a range. */
{
double arrayOfOne = defaultVal;
bigWigSummaryArray(bwf, chrom, start, end, summaryType, 1, &arrayOfOne);
return arrayOfOne;
}
boolean isBigWig(char *fileName)
/* Peak at a file to see if it's bigWig */
{
FILE *f = mustOpen(fileName, "rb");
bits32 sig;
mustReadOne(f, sig);
fclose(f);
if (sig == bigWigSig)
return TRUE;
sig = byteSwap32(sig);
return sig == bigWigSig;
}
|
gpl-3.0
|
scarrazza/apfel
|
src/DIS/ReportParametersDIS.f
|
5524
|
************************************************************************
*
* ReportParametersDIS.f:
*
* This subroutine reports the DIS parameters.
*
************************************************************************
subroutine ReportParametersDIS
*
implicit none
*
include "../commons/Welcome.h"
include "../commons/MassScheme.h"
include "../commons/ProcessDIS.h"
include "../commons/PolarizationDIS.h"
include "../commons/ProjectileDIS.h"
include "../commons/TargetDIS.h"
include "../commons/ZedMass.h"
include "../commons/WMass.h"
include "../commons/ProtonMass.h"
include "../commons/Sin2ThetaW.h"
include "../commons/GFermi.h"
include "../commons/CKM.h"
include "../commons/TMC.h"
include "../commons/DampingFONLL.h"
include "../commons/SelectedCharge.h"
include "../commons/krenQ.h"
include "../commons/kfacQ.h"
include "../commons/PropagatorCorrection.h"
include "../commons/EWCouplings.h"
include "../commons/DynScVar.h"
include "../commons/IntrinsicCharm.h"
include "../commons/NLOQEDCorrections.h"
include "../commons/ScaleVariationProcedure.h"
*
* Print welcome message and report of the parameters (if enabled)
*
if(Welcome)then
write(6,*) achar(27)//"[34m"//
1 "Report of the electroweak parameters:"
write(6,*) " "
write(6,"(a,f7.3,a)") " Mass of the Z =",MZ," GeV"
write(6,"(a,f7.3,a)") " Mass of the W =",MW," GeV"
write(6,"(a,f7.4,a)") " Mass of the proton =",MProton," GeV"
write(6,"(a,f7.4)") " sin^2(thetaW) =",Sin2ThetaW
write(6,"(a,es12.5)") " GFermi =",GFermi
write(6,"(a,3f7.4,a)") " |",V_ud,V_us,V_ub," |"
write(6,"(a,3f7.4,a)") " CKM = |",V_cd,V_cs,V_cb," |"
write(6,"(a,3f7.4,a)") " |",V_td,V_ts,V_tb," |"
write(6,"(a,f7.5)") " Z propagator correction = ",DeltaR
if(ExtCoup) write(6,*) "External EW couplings will be used"
write(6,*) " "
*
write(6,*) "Report of the DIS parameters:"
write(6,*) " "
*
write(6,"(a,a,a)") " Computation in the ",trim(MassScheme),
1 " mass scheme"
*
if(ProcessDIS.eq."EM")then
write(6,"(a,a,a)") " Electromagnetic (EM) process"
elseif(ProcessDIS.eq."NC")then
write(6,"(a,a,a)") " Neutral Current (NC) process"
elseif(ProcessDIS.eq."CC")then
write(6,"(a,a,a)") " Charged Current (CC) process"
endif
*
write(6,"(a,a,a,a)") " Scattering ",trim(ProjectileDIS),
1 " - ",TargetDIS
*
if(PolarizationDIS.ne.0d0)
1 write(6,"(a,f7.3)") " Polarization fraction =",PolarizationDIS
*
if(SelectedCharge(1:3).ne."all")
1 write(6,*) "Selected Charge: ",trim(SelectedCharge)
*
if(DynScVAr)then
write(6,*) "Dynamical scale variations enabled"
else
write(6,"(a,f7.4)") " muR / Q = ",dsqrt(krenQ)
write(6,"(a,f7.4)") " muF / Q = ",dsqrt(kfacQ)
endif
*
if(ScVarProc.eq.1)then
write(6,*) "No scale variations in the evolution"
endif
*
if(TMC)then
write(6,*) "Target Mass corrections enabled"
else
write(6,*) "Target Mass corrections disabled"
endif
*
if(MassScheme(1:5).eq."FONLL")then
if(DampingFONLL)then
if(DampPowerFONLL(4).gt.0)then
write(6,"(a,a,i1)") " FONLL damping factor ",
1 "for charm enabled with suppression power = ",
2 DampPowerFONLL(4)
elseif(DampPowerFONLL(4).eq.0)then
write(6,"(a,a,i1)") " FONLL damping factor ",
1 "for charm disbled"
else
write(6,*) "Using BGMPU prescription for charm"
endif
if(DampPowerFONLL(5).gt.0)then
write(6,"(a,a,i1)") " FONLL damping factor ",
1 "for bottom enabled with suppression power = ",
2 DampPowerFONLL(5)
elseif(DampPowerFONLL(5).eq.0)then
write(6,"(a,a,i1)") " FONLL damping factor ",
1 "for bottom disbled"
else
write(6,*) "Using BGMPU prescription for bottom"
endif
if(DampPowerFONLL(6).gt.0)then
write(6,"(a,a,i1)") " FONLL damping factor ",
1 "for top enabled with suppression power = ",
2 DampPowerFONLL(6)
elseif(DampPowerFONLL(6).eq.0)then
write(6,"(a,a,i1)") " FONLL damping factor ",
1 "for top disbled"
else
write(6,*) "Using BGMPU prescription for top"
endif
else
write(6,*) "FONLL damping factor disabled",
1 " for all heavy quarks"
endif
endif
*
if(IntrinsicCharm)then
write(6,*) "Intrinsic charm enabled"
else
write(6,*) "Intrinsic charm disabled"
endif
*
if(.not.SFNLOQED)then
write(6,*) "NLO QED Corrections disabled",
1 " in the stucture functions"
endif
write(6,*) achar(27)//"[0m"
endif
*
return
end
|
gpl-3.0
|
Wohlhabend-Networks/PGE-Project
|
Editor/networking/engine_intproc.cpp
|
5233
|
/*
* Platformer Game Engine by Wohlstand, a free platform for game making
* Copyright (c) 2014-2019 Vitaly Novichkov <admin@wohlnet.ru>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "engine_intproc.h"
#include <PGE_File_Formats/file_formats.h>
#include <common_features/main_window_ptr.h>
#include <common_features/app_path.h>
#include <common_features/logger.h>
#include <QSharedPointer>
static void base64_encode(QByteArray &out, const char *msg)
{
QByteArray ba(msg);
out = ba.toBase64();
}
static void base64_encode(QByteArray &out, QString &string)
{
QByteArray ba(string.toUtf8());
out = ba.toBase64();
}
IntEngine::IntEngine()
{}
IntEngine::~IntEngine()
{}
void IntEngine::onData()
{
if(isWorking())
{
QByteArray strdata = engine->readAllStandardOutput();
QByteArray msg = QByteArray::fromBase64(strdata);
if(msg.startsWith("CMD:"))
{
char *msgP = msg.data() + 4; //"CMD:"
LogDebug("ENGINE COMMAND: >>");
LogDebug(msgP);
LogDebug("<<ENGINE COMMAND END");
if(strcmp(msgP, "CONNECT_TO_ENGINE") == 0)
sendLevelBuffer();
else if(strcmp(msgP, "ENGINE_CLOSED") == 0)
{
MainWinConnect::pMainWin->show();
MainWinConnect::pMainWin->raise();
}
}
else
emit engineInputMsg(QString::fromUtf8(msg));
}
}
LevelData IntEngine::testBuffer;
QProcess *IntEngine::engine = nullptr;
static QSharedPointer<IntEngine> IntEngine_helper(nullptr);
void IntEngine::init(QProcess *engine_proc)
{
if(IntEngine_helper.isNull())
IntEngine_helper = QSharedPointer<IntEngine>(new IntEngine);
if(!engine)
{
engine = engine_proc;
engine->connect(engine, SIGNAL(readyReadStandardOutput()),
&(*IntEngine_helper), SLOT(onData()));
}
}
void IntEngine::quit()
{
FileFormats::CreateLevelData(testBuffer);
if(engine)
engine->close();
engine = nullptr;
}
bool IntEngine::isWorking()
{
return ((engine != nullptr) && (engine->state() == QProcess::Running));
}
bool IntEngine::sendCheat(QString _args)
{
if(isWorking())
{
if(_args.isEmpty())
return false;
_args.replace('\n', "\\n");
QString out = QString("CHEAT: %1").arg(_args);
return sendMessage(out);
}
else
return false;
}
bool IntEngine::sendMessageBox(QString _args)
{
if(isWorking())
{
if(_args.isEmpty())
return false;
_args.replace('\n', "\\n");
QString out = QString("MSGBOX: %1").arg(_args);
return sendMessage(out);
}
else
return false;
}
bool IntEngine::sendItemPlacing(QString _args)
{
if(isWorking())
{
LogDebug("ENGINE: Place item command: " + _args);
QString out = QString("PLACEITEM: %1").arg(_args);
bool ret = sendMessage(out);
return ret;
}
return false;
}
void IntEngine::sendLevelBuffer()
{
if(isWorking())
{
LogDebug("Attempt to send LVLX buffer");
QString output;
FileFormats::WriteExtendedLvlFileRaw(testBuffer, output);
QString sendLvlx;
if(!testBuffer.meta.path.isEmpty())
sendLvlx = QString("SEND_LVLX: %1/%2\n")
.arg(testBuffer.meta.path)
.arg(testBuffer.meta.filename + ".lvlx");
else
sendLvlx = QString("SEND_LVLX: %1/%2\n")
.arg(ApplicationPath)
.arg("_untitled.lvlx");
if(output.size() <= 0)
output = "HEAD\nEMPTY:1\nHEAD_END\n";
//#ifdef DEBUG_BUILD
// qDebug() << "Sent File data BEGIN >>>>>>>>>>>\n" << output << "\n<<<<<<<<<<<<Sent File data END";
//#endif
sendMessage(sendLvlx);
QByteArray output_e;
base64_encode(output_e, output);
output_e.append('\n');
engine->write(output_e);
sendMessage("PARSE_LVLX");
LogDebug("LVLX buffer sent");
}
}
void IntEngine::setTestLvlBuffer(LevelData &buffer)
{
testBuffer = buffer;
}
bool IntEngine::sendMessage(const char *msg)
{
if(!isWorking())
return false;
QByteArray output_e;
base64_encode(output_e, msg);
output_e.append('\n');
return (engine->write(output_e) > 0);
}
bool IntEngine::sendMessage(QString &msg)
{
if(!isWorking())
return false;
QByteArray output_e;
base64_encode(output_e, msg);
output_e.append('\n');
return (engine->write(output_e) > 0);
}
|
gpl-3.0
|
maxon887/Cross
|
Sources/Utils/Cubemap.cpp
|
2855
|
/* Copyright © 2018 Maksim Lukyanov
This file is part of Cross++ Game Engine.
Cross++ Game Engine 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.
Cross++ 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 Cross++. If not, see <http://www.gnu.org/licenses/> */
#include "Cubemap.h"
#include "Texture.h"
#include "Internals/GraphicsGL.h"
using namespace cross;
Cubemap::Cubemap( const String& right,
const String& left,
const String& top,
const String& bottom,
const String& back,
const String& front)
{
SAFE(glGenTextures(1, (GLuint*)&textureID));
SAFE(glActiveTexture(GL_TEXTURE0));
SAFE(glBindTexture(GL_TEXTURE_CUBE_MAP, (GLuint)textureID));
int width, height, channels;
Byte* image;
image = Texture::LoadRawData(right, width, height, channels);
SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image));
//delete[] image;
image = Texture::LoadRawData(left, width, height, channels);
SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 1, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image));
//delete image;
image = Texture::LoadRawData(top, width, height, channels);
SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 2, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image));
//delete image;
image = Texture::LoadRawData(bottom, width, height, channels);
SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 3, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image));
//delete image;
image = Texture::LoadRawData(back, width, height, channels);
SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 4, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image));
//delete image;
image = Texture::LoadRawData(front, width, height, channels);
SAFE(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + 5, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image));
//delete image;
SAFE(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
SAFE(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
SAFE(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
SAFE(glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
SAFE(glBindTexture(GL_TEXTURE_CUBE_MAP, 0));
}
Cubemap::~Cubemap(){
SAFE(glDeleteTextures(1, (GLuint*)&textureID));
}
U64 Cubemap::GetTextureID() const{
return textureID;
}
|
gpl-3.0
|
Traderain/Wolven-kit
|
CP77.CR2W/Types/cp77/enteventsEntityResize.cs
|
355
|
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class enteventsEntityResize : redEvent
{
[Ordinal(0)] [RED("extents")] public Vector3 Extents { get; set; }
public enteventsEntityResize(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
|
gpl-3.0
|
davqvist/Faeries
|
src/main/java/com/ernstlustig/faeries/jei/FaeryProducts/FaeryProductsCategory.java
|
2053
|
package com.ernstlustig.faeries.jei.FaeryProducts;
import mezz.jei.api.IGuiHelper;
import mezz.jei.api.gui.IDrawable;
import mezz.jei.api.gui.IGuiItemStackGroup;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.recipe.IRecipeCategory;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import javax.annotation.Nonnull;
import java.awt.*;
import java.util.*;
import java.util.List;
public class FaeryProductsCategory implements IRecipeCategory<FaeryProductsWrapper> {
@Nonnull
private final IDrawable background;
@Nonnull
private final String localizedName;
public FaeryProductsCategory(IGuiHelper guiHelper) {
ResourceLocation location = new ResourceLocation( "faeries", "textures/gui/guifaeryhousejei.png" );
background = guiHelper.createDrawable( location, 0, 0, 163, 55, 0, 0, 0, 0 ); //guiHelper.createDrawable( location, 8, 5, 163, 55, 0, 0, 0, 0 );
localizedName = "Faery Products"; //Translate
}
@Nonnull
@Override
public IDrawable getBackground() {
return background;
}
@Override
public void drawExtras( @Nonnull Minecraft minecraft ) { }
@Override
public void drawAnimations( @Nonnull Minecraft minecraft ) { }
@Nonnull
@Override
public String getUid() {
return "faeries.products";
}
@Nonnull
@Override
public String getTitle() {
return localizedName;
}
@Override
public void setRecipe( @Nonnull IRecipeLayout recipeLayout, @Nonnull FaeryProductsWrapper recipeWrapper ){
IGuiItemStackGroup itemStacks = recipeLayout.getItemStacks();
itemStacks.init( 0, true, 9, 0 );
itemStacks.setFromRecipe( 0, recipeWrapper.getInputs().get(0) );
int i = 0;
for( ItemStack is : recipeWrapper.getOutputs() ){
i++;
itemStacks.init( i, true, 65 + 20 * ( ( i - 1 ) % 5 ), 27 * ( ( i - 1 ) / 5 ) );
itemStacks.setFromRecipe( i, is );
}
}
}
|
gpl-3.0
|
Pneumaticat/Aperture
|
Aperture.Parser/HTML/StringComparisons.cs
|
3096
|
using Aperture.Parser.HTML.Microsyntaxes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aperture.Parser.HTML
{
/// <summary>
/// Case-sensitivity and string comparison.
/// </summary>
public static class StringComparisons // Must end with s to avoid ambiguity
{ // with System.StringComparison
// HTML spec 2.3 Case-sensitivity and string comparisons
public static bool CompareCaseSensitive(string str1, string str2)
{
return str1 == str2;
}
/// <summary>
/// Compares strings, where A-Z == a-z.
/// </summary>
public static bool CompareASCIICaseInsensitive(string str1, string str2)
{
return ConvertToASCIILowercase(str1) == ConvertToASCIILowercase(str2);
}
/// <summary>
/// Unicode string comparing, with no regard for capitalization.
/// </summary>
public static bool CompareCompatibilityCaseless(string str1, string str2)
{
// Unicode spec version 7.0, page 158, D146
// TODO: ToLowerInvariant() may not match the spec's toCasefold method exactly.
return str1.Normalize(NormalizationForm.FormD)
.ToLowerInvariant()
.Normalize(NormalizationForm.FormKD)
.ToLowerInvariant()
.Normalize(NormalizationForm.FormKD)
==
str2.Normalize(NormalizationForm.FormD)
.ToLowerInvariant()
.Normalize(NormalizationForm.FormKD)
.ToLowerInvariant()
.Normalize(NormalizationForm.FormKD);
}
/// <summary>
/// Converts a-z to A-Z.
/// </summary>
public static string ConvertToASCIIUppercase(string input)
{
char[] inputArr = input.ToCharArray();
for (int i = 0; i < inputArr.Length; i++)
{
if (ParserIdioms.LowercaseASCIILetters.Contains(inputArr[i]))
{
int charIndex = Array.IndexOf(
ParserIdioms.LowercaseASCIILetters, inputArr[i]);
inputArr[i] = ParserIdioms.UppercaseASCIILetters[charIndex];
}
}
return new string(inputArr);
}
/// <summary>
/// Converts A-Z to a-z.
/// </summary>
public static string ConvertToASCIILowercase(string input)
{
char[] inputArr = input.ToCharArray();
for (int i = 0; i < inputArr.Length; i++)
{
if (ParserIdioms.UppercaseASCIILetters.Contains(inputArr[i]))
{
int charIndex = Array.IndexOf(
ParserIdioms.UppercaseASCIILetters, inputArr[i]);
inputArr[i] = ParserIdioms.LowercaseASCIILetters[charIndex];
}
}
return new string(inputArr);
}
}
}
|
gpl-3.0
|
RossGammon/the-gammons.net
|
RossFamilyTree/ppl/9/b/d15f604bd5f3aa4b244366af1b9.html
|
15493
|
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - LONG, Herbert William</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
<link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="IndividualDetail">
<h3>LONG, Herbert William<sup><small></small></sup></h3>
<div id="summaryarea">
<table class="infolist">
<tr>
<td class="ColumnAttribute">Birth Name</td>
<td class="ColumnValue">
LONG, Herbert William <a href="#sref1a">1a</a>
</td>
</tr>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">I11190</td>
</tr>
<tr>
<td class="ColumnAttribute">Gender</td>
<td class="ColumnValue">male</td>
</tr>
<tr>
<td class="ColumnAttribute">Age at Death</td>
<td class="ColumnValue">83 years, 4 months, 4 days</td>
</tr>
</table>
</div>
<div class="subsection" id="events">
<h4>Events</h4>
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/1/d/d15f604bd6cb0954abbf5d31d1.html" title="Birth">
Birth
<span class="grampsid"> [E13333]</span>
</a>
</td>
<td class="ColumnDate">1897</td>
<td class="ColumnPlace">
<a href="../../../plc/2/9/d15f601a85a4234a08031f8a092.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/e/7/d15f604bd7a6c0fb97ea6ddb27e.html" title="Death">
Death
<span class="grampsid"> [E13334]</span>
</a>
</td>
<td class="ColumnDate">1980-05-05</td>
<td class="ColumnPlace">
<a href="../../../plc/c/3/d15f5ffe48b7f852ef30d4e013c.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="parents">
<h4>Parents</h4>
<table class="infolist">
<thead>
<tr>
<th class="ColumnAttribute">Relation to main person</th>
<th class="ColumnValue">Name</th>
<th class="ColumnValue">Relation within this family (if not by birth)</th>
</tr>
</thead>
<tbody>
</tbody>
<tr>
<td class="ColumnAttribute">Father</td>
<td class="ColumnValue">
<a href="../../../ppl/b/f/d15f604bcdb264c75b8f30769fb.html">HORTLE, Herbert William<span class="grampsid"> [I11188]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute">Mother</td>
<td class="ColumnValue">
<a href="../../../ppl/d/8/d15f604bd206ac398af8176a18d.html">LONG, Frances Isabella<span class="grampsid"> [I11189]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"> <a href="../../../ppl/9/b/d15f604bd5f3aa4b244366af1b9.html">LONG, Herbert William<span class="grampsid"> [I11190]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/5/0/d15f604bddd78f46a7461fbda05.html">LONG, Wilfred Condell<span class="grampsid"> [I11192]</span></a></td>
<td class="ColumnValue"></td>
</tr>
</table>
</div>
<div class="subsection" id="families">
<h4>Families</h4>
<table class="infolist">
<tr class="BeginFamily">
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"><a href="../../../fam/a/4/d15f604bd92195ff1a5d035ea4a.html" title="Family of LONG, Herbert William and CAMERON, Hilda Frances">Family of LONG, Herbert William and CAMERON, Hilda Frances<span class="grampsid"> [F3484]</span></a></td>
</tr>
<tr class="BeginFamily">
<td class="ColumnType">Married</td>
<td class="ColumnAttribute">Wife</td>
<td class="ColumnValue">
<a href="../../../ppl/8/0/d15f604bdac24602e4761968608.html">CAMERON, Hilda Frances<span class="grampsid"> [I11191]</span></a>
</td>
</tr>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue">
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/7/f/d15f60d48c55393be4a49492bf7.html" title="Marriage">
Marriage
<span class="grampsid"> [E25361]</span>
</a>
</td>
<td class="ColumnDate">1924</td>
<td class="ColumnPlace"> </td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/c/7/d15f60d48c9101254666c16867c.html" title="Family (Primary)">
Family (Primary)
<span class="grampsid"> [E25362]</span>
</a>
</td>
<td class="ColumnDate"> </td>
<td class="ColumnPlace"> </td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1b">1b</a>
</td>
</tr>
</tbody>
</table>
</td>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute">Attributes</td>
<td class="ColumnValue">
<table class="infolist attrlist">
<thead>
<tr>
<th class="ColumnType">Type</th>
<th class="ColumnValue">Value</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnType">_UID</td>
<td class="ColumnValue">09510914424E8B4DAE9C1D4D19313CE3FC9B</td>
<td class="ColumnNotes"><div></div></td>
<td class="ColumnSources"> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tr>
</table>
</div>
<div class="subsection" id="attributes">
<h4>Attributes</h4>
<table class="infolist attrlist">
<thead>
<tr>
<th class="ColumnType">Type</th>
<th class="ColumnValue">Value</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnType">_UID</td>
<td class="ColumnValue">E1EE6EF30283FE4796AC8BCF9AEA0FB0D926</td>
<td class="ColumnNotes"><div></div></td>
<td class="ColumnSources"> </td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="pedigree">
<h4>Pedigree</h4>
<ol class="pedigreegen">
<li>
<a href="../../../ppl/b/f/d15f604bcdb264c75b8f30769fb.html">HORTLE, Herbert William<span class="grampsid"> [I11188]</span></a>
<ol>
<li class="spouse">
<a href="../../../ppl/d/8/d15f604bd206ac398af8176a18d.html">LONG, Frances Isabella<span class="grampsid"> [I11189]</span></a>
<ol>
<li class="thisperson">
LONG, Herbert William
<ol class="spouselist">
<li class="spouse">
<a href="../../../ppl/8/0/d15f604bdac24602e4761968608.html">CAMERON, Hilda Frances<span class="grampsid"> [I11191]</span></a>
</li>
</ol>
</li>
<li>
<a href="../../../ppl/5/0/d15f604bddd78f46a7461fbda05.html">LONG, Wilfred Condell<span class="grampsid"> [I11192]</span></a>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</div>
<div class="subsection" id="tree">
<h4>Ancestors</h4>
<div id="treeContainer" style="width:735px; height:602px;">
<div class="boxbg male AncCol0" style="top: 269px; left: 6px;">
<a class="noThumb" href="../../../ppl/9/b/d15f604bd5f3aa4b244366af1b9.html">
LONG, Herbert William
</a>
</div>
<div class="shadow" style="top: 274px; left: 10px;"></div>
<div class="bvline" style="top: 301px; left: 165px; width: 15px"></div>
<div class="gvline" style="top: 306px; left: 165px; width: 20px"></div>
<div class="boxbg male AncCol1" style="top: 119px; left: 196px;">
<a class="noThumb" href="../../../ppl/b/f/d15f604bcdb264c75b8f30769fb.html">
HORTLE, Herbert William
</a>
</div>
<div class="shadow" style="top: 124px; left: 200px;"></div>
<div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div>
<div class="bvline" style="top: 151px; left: 355px; width: 15px"></div>
<div class="gvline" style="top: 156px; left: 355px; width: 20px"></div>
<div class="boxbg male AncCol2" style="top: 44px; left: 386px;">
<a class="noThumb" href="../../../ppl/a/8/d15f604bc7234fda1194212a18a.html">
HORTLE, Henry William
</a>
</div>
<div class="shadow" style="top: 49px; left: 390px;"></div>
<div class="bvline" style="top: 76px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 81px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 76px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 81px; left: 375px; height: 75px;"></div>
<div class="bvline" style="top: 76px; left: 545px; width: 15px"></div>
<div class="gvline" style="top: 81px; left: 545px; width: 20px"></div>
<div class="boxbg male AncCol3" style="top: 7px; left: 576px;">
<a class="noThumb" href="../../../ppl/9/c/d15f604bbdf2bead4572e5c5c9.html">
HORTLE, John
</a>
</div>
<div class="shadow" style="top: 12px; left: 580px;"></div>
<div class="bvline" style="top: 39px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 44px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 39px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 44px; left: 565px; height: 37px;"></div>
<div class="boxbg female AncCol3" style="top: 81px; left: 576px;">
<a class="noThumb" href="../../../ppl/e/8/d15f604bc2c77968da76465f08e.html">
SMITH, Jane Ann
</a>
</div>
<div class="shadow" style="top: 86px; left: 580px;"></div>
<div class="bvline" style="top: 113px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 118px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 76px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 81px; left: 565px; height: 37px;"></div>
<div class="boxbg female AncCol2" style="top: 194px; left: 386px;">
<a class="noThumb" href="../../../ppl/b/f/d15f604bcaf2a251246f642c3fb.html">
REILLEY, Barbara Ann
</a>
</div>
<div class="shadow" style="top: 199px; left: 390px;"></div>
<div class="bvline" style="top: 226px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 231px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 151px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 156px; left: 375px; height: 75px;"></div>
<div class="boxbg female AncCol1" style="top: 419px; left: 196px;">
<a class="noThumb" href="../../../ppl/d/8/d15f604bd206ac398af8176a18d.html">
LONG, Frances Isabella
</a>
</div>
<div class="shadow" style="top: 424px; left: 200px;"></div>
<div class="bvline" style="top: 451px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 456px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 301px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 306px; left: 185px; height: 150px;"></div>
</div>
</div>
<div class="subsection" id="sourcerefs">
<h4>Source References</h4>
<ol>
<li>
<a href="../../../src/4/2/d15f601149a2d1261a52adff124.html" title="Frank Lee: GEDCOM File : SarahLUCAS.ged" name ="sref1">
Frank Lee: GEDCOM File : SarahLUCAS.ged
<span class="grampsid"> [S0304]</span>
</a>
<ol>
<li id="sref1a">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1b">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
</ol>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:58<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
|
gpl-3.0
|
RossGammon/the-gammons.net
|
RossFamilyTree/ppl/f/e/d15f60972b7257fb0d56e778eef.html
|
22042
|
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - GAMMON, Samuel</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
<link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="IndividualDetail">
<h3>GAMMON, Samuel<sup><small></small></sup></h3>
<div id="summaryarea">
<table class="infolist">
<tr>
<td class="ColumnAttribute">Birth Name</td>
<td class="ColumnValue">
GAMMON, Samuel
</td>
</tr>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">I18202</td>
</tr>
<tr>
<td class="ColumnAttribute">Gender</td>
<td class="ColumnValue">male</td>
</tr>
<tr>
<td class="ColumnAttribute">Age at Death</td>
<td class="ColumnValue">52 years, 11 months, 17 days</td>
</tr>
</table>
</div>
<div class="subsection" id="events">
<h4>Events</h4>
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/0/4/d15f60972bb7f98d3561aaab340.html" title="Birth">
Birth
<span class="grampsid"> [E18482]</span>
</a>
</td>
<td class="ColumnDate">1865</td>
<td class="ColumnPlace">
<a href="../../../plc/1/0/d15f6096b4279107571578db801.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1a">1a</a>
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/0/1/d15f60972d516f30ac117879010.html" title="Death">
Death
<span class="grampsid"> [E18483]</span>
</a>
</td>
<td class="ColumnDate">1917-12-18</td>
<td class="ColumnPlace">
<a href="../../../plc/d/2/d15f60972de2c0e3c09733aab2d.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1b">1b</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="parents">
<h4>Parents</h4>
<table class="infolist">
<thead>
<tr>
<th class="ColumnAttribute">Relation to main person</th>
<th class="ColumnValue">Name</th>
<th class="ColumnValue">Relation within this family (if not by birth)</th>
</tr>
</thead>
<tbody>
</tbody>
<tr>
<td class="ColumnAttribute">Father</td>
<td class="ColumnValue">
<a href="../../../ppl/a/c/d15f6096f634ed8fc67380061ca.html">GAMMON, Thomas<span class="grampsid"> [I18191]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute">Mother</td>
<td class="ColumnValue">
<a href="../../../ppl/6/9/d15f6096fd0447f9d286881d896.html">GIBBS, Elizabeth<span class="grampsid"> [I18192]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/7/d/d15f6097039ffa83d995087d7.html">GAMMON, Thomas<span class="grampsid"> [I18193]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/7/0/d15f60970c25ab3bbe434cd2b07.html">GAMMON, Elizabeth<span class="grampsid"> [I18194]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/1/b/d15f609722b12a15916ef584bb1.html">GAMMON, Ellen<span class="grampsid"> [I18200]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"> <a href="../../../ppl/f/e/d15f60972b7257fb0d56e778eef.html">GAMMON, Samuel<span class="grampsid"> [I18202]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/b/d/d15f6097636721526e525db94db.html">GAMMON, William Richard<span class="grampsid"> [I18214]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/2/d/d15f6097692d9321e6e2ffc7d2.html">GAMMON, George Henry<span class="grampsid"> [I18215]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/6/8/d15f60977121e5ee84d169ebb86.html">GAMMON, Arthur<span class="grampsid"> [I18216]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/5/d/d15f609798971b996d30a61a4d5.html">GAMMON, Alfred James<span class="grampsid"> [I18222]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/1/d/d15f6097ad05a0051deb86980d1.html">GAMMON, Louisa Mary<span class="grampsid"> [I18224]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/7/3/d15f609842b10be5e4f5ef28437.html">GAMMON, Albert Eli<span class="grampsid"> [I18228]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/c/3/d15f60985a138a628ab7080383c.html">GAMMON, Agnes Rachel Rebecca<span class="grampsid"> [I18231]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/7/0/d15f60989de78e08bda11ecaf07.html">GAMMON, Ernest Charles<span class="grampsid"> [I18246]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/e/7/d15f6098a3e500ba3566c2b3b7e.html">GAMMON, Walter Frederick<span class="grampsid"> [I18247]</span></a></td>
<td class="ColumnValue"></td>
</tr>
</table>
</div>
<div class="subsection" id="families">
<h4>Families</h4>
<table class="infolist">
<tr class="BeginFamily">
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"><a href="../../../fam/a/4/d15f60973106c053be79325894a.html" title="Family of GAMMON, Samuel and GREEN, Esther">Family of GAMMON, Samuel and GREEN, Esther<span class="grampsid"> [F6009]</span></a></td>
</tr>
<tr class="BeginFamily">
<td class="ColumnType">Married</td>
<td class="ColumnAttribute">Wife</td>
<td class="ColumnValue">
<a href="../../../ppl/5/8/d15f609733e2a62f5acd5c2e985.html">GREEN, Esther<span class="grampsid"> [I18203]</span></a>
</td>
</tr>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue">
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/a/5/d15f60df7f35eba5f5ab0c5065a.html" title="Marriage">
Marriage
<span class="grampsid"> [E26395]</span>
</a>
</td>
<td class="ColumnDate">1891-06-28</td>
<td class="ColumnPlace">
<a href="../../../plc/8/0/d15f60df7fd1f7baabb88d2f208.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
<a href="#sref1c">1c</a>
</td>
</tr>
</tbody>
</table>
</td>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute">Children</td>
<td class="ColumnValue">
<ol>
<li>
<a href="../../../ppl/6/6/d15f60973792aadc6bf2db39866.html">GAMMON, Florence May<span class="grampsid"> [I18204]</span></a>
</li>
<li>
<a href="../../../ppl/9/5/d15f60973fb5883809f92d0cc59.html">GAMMON, Samuel Alfred James<span class="grampsid"> [I18206]</span></a>
</li>
<li>
<a href="../../../ppl/8/f/d15f60974757be2f7d55928a5f8.html">GAMMON, Ellen Constance<span class="grampsid"> [I18208]</span></a>
</li>
<li>
<a href="../../../ppl/5/c/d15f609751c2dec587fd3d665c5.html">GAMMON, Ethel Maude<span class="grampsid"> [I18210]</span></a>
</li>
<li>
<a href="../../../ppl/2/8/d15f609759d4f6da02e362f1582.html">GAMMON, Albert Ernest Victor<span class="grampsid"> [I18212]</span></a>
</li>
</ol>
</td>
</tr>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute">Attributes</td>
<td class="ColumnValue">
<table class="infolist attrlist">
<thead>
<tr>
<th class="ColumnType">Type</th>
<th class="ColumnValue">Value</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnType">_UID</td>
<td class="ColumnValue">6B72A222233F29418A6A5503CBA1064A75D8</td>
<td class="ColumnNotes"><div></div></td>
<td class="ColumnSources"> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tr>
</table>
</div>
<div class="subsection" id="attributes">
<h4>Attributes</h4>
<table class="infolist attrlist">
<thead>
<tr>
<th class="ColumnType">Type</th>
<th class="ColumnValue">Value</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnType">_UID</td>
<td class="ColumnValue">B5FB3CBC24F5834C8E911323155E79AC7D6E</td>
<td class="ColumnNotes"><div></div></td>
<td class="ColumnSources"> </td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="pedigree">
<h4>Pedigree</h4>
<ol class="pedigreegen">
<li>
<a href="../../../ppl/a/c/d15f6096f634ed8fc67380061ca.html">GAMMON, Thomas<span class="grampsid"> [I18191]</span></a>
<ol>
<li class="spouse">
<a href="../../../ppl/6/9/d15f6096fd0447f9d286881d896.html">GIBBS, Elizabeth<span class="grampsid"> [I18192]</span></a>
<ol>
<li>
<a href="../../../ppl/7/d/d15f6097039ffa83d995087d7.html">GAMMON, Thomas<span class="grampsid"> [I18193]</span></a>
</li>
<li>
<a href="../../../ppl/7/0/d15f60970c25ab3bbe434cd2b07.html">GAMMON, Elizabeth<span class="grampsid"> [I18194]</span></a>
</li>
<li>
<a href="../../../ppl/1/b/d15f609722b12a15916ef584bb1.html">GAMMON, Ellen<span class="grampsid"> [I18200]</span></a>
</li>
<li class="thisperson">
GAMMON, Samuel
<ol class="spouselist">
<li class="spouse">
<a href="../../../ppl/5/8/d15f609733e2a62f5acd5c2e985.html">GREEN, Esther<span class="grampsid"> [I18203]</span></a>
<ol>
<li>
<a href="../../../ppl/6/6/d15f60973792aadc6bf2db39866.html">GAMMON, Florence May<span class="grampsid"> [I18204]</span></a>
</li>
<li>
<a href="../../../ppl/9/5/d15f60973fb5883809f92d0cc59.html">GAMMON, Samuel Alfred James<span class="grampsid"> [I18206]</span></a>
</li>
<li>
<a href="../../../ppl/8/f/d15f60974757be2f7d55928a5f8.html">GAMMON, Ellen Constance<span class="grampsid"> [I18208]</span></a>
</li>
<li>
<a href="../../../ppl/5/c/d15f609751c2dec587fd3d665c5.html">GAMMON, Ethel Maude<span class="grampsid"> [I18210]</span></a>
</li>
<li>
<a href="../../../ppl/2/8/d15f609759d4f6da02e362f1582.html">GAMMON, Albert Ernest Victor<span class="grampsid"> [I18212]</span></a>
</li>
</ol>
</li>
</ol>
</li>
<li>
<a href="../../../ppl/b/d/d15f6097636721526e525db94db.html">GAMMON, William Richard<span class="grampsid"> [I18214]</span></a>
</li>
<li>
<a href="../../../ppl/2/d/d15f6097692d9321e6e2ffc7d2.html">GAMMON, George Henry<span class="grampsid"> [I18215]</span></a>
</li>
<li>
<a href="../../../ppl/6/8/d15f60977121e5ee84d169ebb86.html">GAMMON, Arthur<span class="grampsid"> [I18216]</span></a>
</li>
<li>
<a href="../../../ppl/5/d/d15f609798971b996d30a61a4d5.html">GAMMON, Alfred James<span class="grampsid"> [I18222]</span></a>
</li>
<li>
<a href="../../../ppl/1/d/d15f6097ad05a0051deb86980d1.html">GAMMON, Louisa Mary<span class="grampsid"> [I18224]</span></a>
</li>
<li>
<a href="../../../ppl/7/3/d15f609842b10be5e4f5ef28437.html">GAMMON, Albert Eli<span class="grampsid"> [I18228]</span></a>
</li>
<li>
<a href="../../../ppl/c/3/d15f60985a138a628ab7080383c.html">GAMMON, Agnes Rachel Rebecca<span class="grampsid"> [I18231]</span></a>
</li>
<li>
<a href="../../../ppl/7/0/d15f60989de78e08bda11ecaf07.html">GAMMON, Ernest Charles<span class="grampsid"> [I18246]</span></a>
</li>
<li>
<a href="../../../ppl/e/7/d15f6098a3e500ba3566c2b3b7e.html">GAMMON, Walter Frederick<span class="grampsid"> [I18247]</span></a>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</div>
<div class="subsection" id="tree">
<h4>Ancestors</h4>
<div id="treeContainer" style="width:735px; height:602px;">
<div class="boxbg male AncCol0" style="top: 269px; left: 6px;">
<a class="noThumb" href="../../../ppl/f/e/d15f60972b7257fb0d56e778eef.html">
GAMMON, Samuel
</a>
</div>
<div class="shadow" style="top: 274px; left: 10px;"></div>
<div class="bvline" style="top: 301px; left: 165px; width: 15px"></div>
<div class="gvline" style="top: 306px; left: 165px; width: 20px"></div>
<div class="boxbg male AncCol1" style="top: 119px; left: 196px;">
<a class="noThumb" href="../../../ppl/a/c/d15f6096f634ed8fc67380061ca.html">
GAMMON, Thomas
</a>
</div>
<div class="shadow" style="top: 124px; left: 200px;"></div>
<div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div>
<div class="bvline" style="top: 151px; left: 355px; width: 15px"></div>
<div class="gvline" style="top: 156px; left: 355px; width: 20px"></div>
<div class="boxbg male AncCol2" style="top: 44px; left: 386px;">
<a class="noThumb" href="../../../ppl/5/e/d15f607ce932d1ed3a6113d03e5.html">
CLARK, William
</a>
</div>
<div class="shadow" style="top: 49px; left: 390px;"></div>
<div class="bvline" style="top: 76px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 81px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 76px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 81px; left: 375px; height: 75px;"></div>
<div class="boxbg female AncCol2" style="top: 194px; left: 386px;">
<a class="noThumb" href="../../../ppl/1/8/d15f607ce2863464121068ed81.html">
GAMMON, Maria Anne
</a>
</div>
<div class="shadow" style="top: 199px; left: 390px;"></div>
<div class="bvline" style="top: 226px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 231px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 151px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 156px; left: 375px; height: 75px;"></div>
<div class="bvline" style="top: 226px; left: 545px; width: 15px"></div>
<div class="gvline" style="top: 231px; left: 545px; width: 20px"></div>
<div class="boxbg male AncCol3" style="top: 157px; left: 576px;">
<a class="noThumb" href="../../../ppl/b/8/d15f607cb025aa9b1de4950388b.html">
GAMMON, George
</a>
</div>
<div class="shadow" style="top: 162px; left: 580px;"></div>
<div class="bvline" style="top: 189px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 194px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 189px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 194px; left: 565px; height: 37px;"></div>
<div class="boxbg female AncCol3" style="top: 231px; left: 576px;">
<a class="noThumb" href="../../../ppl/4/a/d15f607cb4a12895958f954d4a4.html">
QUINNELL, Elizabeth
</a>
</div>
<div class="shadow" style="top: 236px; left: 580px;"></div>
<div class="bvline" style="top: 263px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 268px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 226px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 231px; left: 565px; height: 37px;"></div>
<div class="boxbg female AncCol1" style="top: 419px; left: 196px;">
<a class="noThumb" href="../../../ppl/6/9/d15f6096fd0447f9d286881d896.html">
GIBBS, Elizabeth
</a>
</div>
<div class="shadow" style="top: 424px; left: 200px;"></div>
<div class="bvline" style="top: 451px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 456px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 301px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 306px; left: 185px; height: 150px;"></div>
</div>
</div>
<div class="subsection" id="sourcerefs">
<h4>Source References</h4>
<ol>
<li>
<a href="../../../src/7/b/d15f60787994aaacae323820cb7.html" title="Letter from Mary Avery 15/06/07" name ="sref1">
Letter from Mary Avery 15/06/07
<span class="grampsid"> [S0385]</span>
</a>
<ol>
<li id="sref1a">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1b">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
<li id="sref1c">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
</ol>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:28<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
|
gpl-3.0
|
alfaluck/qrl-node-docker
|
tools/resources_usage.cmd
|
58
|
docker exec -it qrl-node bash -c "top -p $(pgrep python)"
|
gpl-3.0
|
michaelpb/omnithumb
|
omnithumb/types/typestring.py
|
2012
|
'''
TypeString is a core class that extends mimetypes
'''
import re
import os
import mimetypes
import magic
UNKNOWN_MIMETYPE = ('application/x-empty', 'application/octet-stream', 'text/plain')
class TypeString:
def __init__(self, s):
self.str = s
# Extract arguments
if ':' in s:
self.ts_format, _, arguments_str = s.partition(':')
self.arguments = tuple(arguments_str.split(','))
else:
self.ts_format = s
self.arguments = tuple()
# Check if is mimetype, extension or qualifier
self.is_qualifier = False
self.mimetype = None
self.extension = None
if '/' in self.ts_format:
self.mimetype = self.ts_format
ext = mimetypes.guess_extension(self.mimetype)
if ext:
self.extension = ext.strip('.').upper()
elif self.ts_format.isupper():
self.extension = self.ts_format
fn = 'fn.%s' % self.extension
self.mimetype, _ = mimetypes.guess_type(fn) # discard encoding
else:
# Is qualifier, can't determine mimetype
self.is_qualifier = True
def modify_basename(self, basename):
if self.extension:
ext = self.extension.lower()
else:
ext = self.ts_format.replace('/', ':')
if self.arguments:
ext = '.'.join(self.arguments + (ext,))
return '%s.%s' % (basename, ext)
def __str__(self):
return self.str
def __repr__(self):
return "TypeString(%s)" % repr(str(self))
def guess_typestring(path):
'''
Guesses a TypeString from the given path
'''
with open(path, 'rb') as fd:
mimetype = magic.from_buffer(fd.read(128), mime=True)
if mimetype and mimetype not in UNKNOWN_MIMETYPE:
return TypeString(mimetype)
# Otherwise, tries based on extension
_, ext = os.path.splitext(path)
return TypeString(ext.strip('.').upper())
|
gpl-3.0
|
nickg/rbib
|
bibtex/test_bibliography.rb
|
1361
|
require 'bibtex/bibliography'
require 'test/unit'
class TestBibliography < Test::Unit::TestCase
include BibTeX
def setup
@b = Bibliography.new
@foo01 = Entry.new(EntryType::Book, 'foo01')
@foo01.add_field :author, 'C. Doof'
@foo01.add_field :year, 2007
@foo01.add_field Field.new(:url, 'www.doof.me.uk')
@bar99 = Entry.new(EntryType::Article, 'bar99')
@bar99.add_field :author, 'N. Cakesniffer'
@bar99.add_field :year, 1999
@bar99.add_field Field.new(:url, 'www.cakesniffer.co.uk')
@b << @foo01
@b << @bar99
end
def test_basic
assert_equal 2, @b.entries.length
assert_equal @foo01, @b['foo01']
end
def test_map
expect = <<END
@article{bar99,
author = {N. Cakesniffer},
year = {1999}
}
@book{foo01,
author = {C. Doof},
year = {2007}
}
END
urlless = @b.map do |e|
e.reject_fields [:url]
end
assert_equal expect, urlless.to_s
end
def test_to_s
expect = <<END
@article{bar99,
author = {N. Cakesniffer},
url = {www.cakesniffer.co.uk},
year = {1999}
}
@book{foo01,
author = {C. Doof},
url = {www.doof.me.uk},
year = {2007}
}
END
assert_equal expect, @b.to_s
end
def test_save
fname = '/tmp/_test.bib'
@b.save fname
f = File.new(fname)
assert_equal @b.to_s, f.read
f.close
File.delete fname
end
end
|
gpl-3.0
|
thelia-modules/Keyword
|
Model/KeywordI18n.php
|
136
|
<?php
namespace Keyword\Model;
use Keyword\Model\Base\KeywordI18n as BaseKeywordI18n;
class KeywordI18n extends BaseKeywordI18n
{
}
|
gpl-3.0
|
rvega/morphasynth
|
vendors/pd-extended-0.43.4/externals/moocow/gfsm/gfsm/src/libgfsm/gnulib/vasprintf.h
|
2140
|
/* vsprintf with automatic memory allocation.
Copyright (C) 2002-2003 Free Software Foundation, Inc.
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 2.1, 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. */
#ifndef _VASPRINTF_H
#define _VASPRINTF_H
#if HAVE_VASPRINTF
/* Get asprintf(), vasprintf() declarations. */
#include <stdio.h>
#else
/* Get va_list. */
#include <stdarg.h>
#ifndef __attribute__
/* This feature is available in gcc versions 2.5 and later. */
# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__
# define __attribute__(Spec) /* empty */
# endif
/* The __-protected variants of `format' and `printf' attributes
are accepted by gcc versions 2.6.4 (effectively 2.7) and later. */
# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
# define __format__ format
# define __printf__ printf
# endif
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Write formatted output to a string dynamically allocated with malloc().
If the memory allocation succeeds, store the address of the string in
*RESULT and return the number of resulting bytes, excluding the trailing
NUL. Upon memory allocation error, or some other error, return -1. */
extern int asprintf (char **result, const char *format, ...)
__attribute__ ((__format__ (__printf__, 2, 3)));
extern int vasprintf (char **result, const char *format, va_list args)
__attribute__ ((__format__ (__printf__, 2, 0)));
#ifdef __cplusplus
}
#endif
#endif
#endif /* _VASPRINTF_H */
|
gpl-3.0
|
kfix/MacPin
|
modules/WebKitPrivates/WKType.h
|
2573
|
/*
* https://github.com/WebKit/webkit/blob/main/Source/WebKit2/Shared/API/c/WKType.h
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WKType_h
#define WKType_h
#import "WKBase.h"
#ifdef __cplusplus
extern "C" {
#endif
WK_EXPORT WKTypeID WKGetTypeID(WKTypeRef type);
WK_EXPORT WKTypeRef WKRetain(WKTypeRef type);
WK_EXPORT void WKRelease(WKTypeRef type);
/* https://lists.webkit.org/pipermail/webkit-help/2011-March/002000.html
>> All WK*Ref types are ref-counted. WKRetain and WKRelease work on any WK*Ref type. WebKit2's C API is modeled after CoreFoundation. You can find more information (including information about memory management) here:
https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFDesignConcepts/CFDesignConcepts.html#//apple_ref/doc/uid/10000122
https://lists.webkit.org/pipermail/webkit-help/2010-April/000956.html
Uses of CF/JS/WKRetain and Release should follow the "Create Rule" - if you used a Create() function, you are the owner (by default) and will need to release it later.
https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-103029
*/
#ifdef __cplusplus
}
#endif
#endif /* WKType_h */
|
gpl-3.0
|
FrankLIKE/il2bc
|
PEAssemblyReader/MetadataGenericContext.cs
|
7903
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MetadataGenericContext.cs" company="">
//
// </copyright>
// <summary>
//
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace PEAssemblyReader
{
using System.Collections.Generic;
/// <summary>
/// </summary>
public class MetadataGenericContext : IGenericContext
{
/// <summary>
/// </summary>
private IMethod methodSpecialization;
/// <summary>
/// </summary>
private IType typeSpecialization;
/// <summary>
/// </summary>
public MetadataGenericContext()
: this(new SortedList<IType, IType>())
{
}
/// <summary>
/// </summary>
/// <param name="map">
/// </param>
public MetadataGenericContext(IDictionary<IType, IType> map)
{
this.Map = map;
}
/// <summary>
/// </summary>
/// <param name="type">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
public MetadataGenericContext(IType type, bool allowToUseDefinitionAsSpecialization = false)
: this()
{
this.Init(type, allowToUseDefinitionAsSpecialization);
if (this.TypeSpecialization != null)
{
this.TypeSpecialization.GenericMap(this.Map);
}
}
/// <summary>
/// </summary>
/// <param name="method">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
public MetadataGenericContext(IMethod method, bool allowToUseDefinitionAsSpecialization = false)
: this(method.DeclaringType, allowToUseDefinitionAsSpecialization)
{
this.Init(method, allowToUseDefinitionAsSpecialization);
if (this.MethodSpecialization != null)
{
this.MethodSpecialization.GenericMap(this.Map);
}
}
/// <summary>
/// </summary>
public bool IsEmpty
{
get
{
return this.Map.Count == 0 && this.TypeDefinition == null && this.TypeSpecialization == null && this.MethodDefinition == null
&& this.MethodSpecialization == null;
}
}
/// <summary>
/// </summary>
public IDictionary<IType, IType> Map { get; private set; }
/// <summary>
/// </summary>
public IMethod MethodDefinition { get; set; }
/// <summary>
/// </summary>
public IMethod MethodSpecialization
{
get
{
return this.methodSpecialization;
}
set
{
this.methodSpecialization = value;
if (this.MethodSpecialization != null)
{
this.MethodSpecialization.GenericMap(this.Map);
}
}
}
/// <summary>
/// </summary>
public IType TypeDefinition { get; set; }
/// <summary>
/// </summary>
public IType TypeSpecialization
{
get
{
return this.typeSpecialization;
}
set
{
this.typeSpecialization = value;
if (this.TypeSpecialization != null)
{
this.TypeSpecialization.GenericMap(this.Map);
}
}
}
/// <summary>
/// </summary>
/// <param name="definitionMethod">
/// </param>
/// <param name="specializationMethod">
/// </param>
/// <returns>
/// </returns>
public static IGenericContext CreateMap(IMethod definitionMethod, IMethod specializationMethod)
{
var context = new MetadataGenericContext();
context.Map.GenericMap(definitionMethod.GetGenericParameters(), specializationMethod.GetGenericArguments());
context.Map.GenericMap(definitionMethod.DeclaringType.GenericTypeParameters, specializationMethod.DeclaringType.GenericTypeArguments);
return context;
}
/// <summary>
/// </summary>
/// <param name="method">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
/// <returns>
/// </returns>
public static IGenericContext DiscoverFrom(IMethod method, bool allowToUseDefinitionAsSpecialization = false)
{
if (method.IsGenericMethod || method.IsGenericMethodDefinition)
{
return new MetadataGenericContext(method, allowToUseDefinitionAsSpecialization);
}
var declType = method.DeclaringType;
while (declType != null)
{
if (declType.IsGenericType || declType.IsGenericTypeDefinition)
{
return new MetadataGenericContext(declType, allowToUseDefinitionAsSpecialization);
}
if (declType.IsNested)
{
declType = declType.DeclaringType;
continue;
}
break;
}
return null;
}
/// <summary>
/// </summary>
/// <param name="typeParameter">
/// </param>
/// <returns>
/// </returns>
public IType ResolveTypeParameter(IType typeParameter, bool isByRef = false, bool isPinned = false)
{
IType resolved = null;
if (this.Map.TryGetValue(typeParameter, out resolved))
{
if (isByRef || isPinned)
{
return resolved.Clone(false, false, isByRef, isPinned);
}
return resolved;
}
return typeParameter;
}
/// <summary>
/// </summary>
/// <param name="type">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
private void Init(IType type, bool allowToUseDefinitionAsSpecialization = false)
{
if (type.IsGenericTypeDefinition)
{
this.TypeDefinition = type;
if (allowToUseDefinitionAsSpecialization)
{
this.TypeSpecialization = type;
}
}
if (type.IsGenericType)
{
this.TypeSpecialization = type;
if (this.TypeDefinition == null)
{
this.TypeDefinition = type.GetTypeDefinition();
}
}
}
/// <summary>
/// </summary>
/// <param name="method">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
private void Init(IMethod method, bool allowToUseDefinitionAsSpecialization = false)
{
if (method.IsGenericMethodDefinition)
{
this.MethodDefinition = method;
if (allowToUseDefinitionAsSpecialization)
{
this.MethodSpecialization = method;
}
}
if (method.IsGenericMethod)
{
this.MethodSpecialization = method;
if (this.MethodDefinition == null)
{
this.MethodDefinition = method.GetMethodDefinition();
}
}
}
}
}
|
gpl-3.0
|
flaminggenius/CSVAnalyzerPro
|
CSV Analyzer Pro/CSV Analyzer Pro/CheckUpdate.Designer.cs
|
3238
|
namespace CSV_Analyzer_Pro {
partial class CheckUpdate {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CheckUpdate));
this.label1 = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(142, 38);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(108, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Checking for updates";
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(145, 54);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(100, 23);
this.progressBar1.TabIndex = 1;
//
// button1
//
this.button1.Location = new System.Drawing.Point(157, 88);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 2;
this.button1.Text = "Ok";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// CheckUpdate
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(393, 123);
this.Controls.Add(this.button1);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.label1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "CheckUpdate";
this.Text = "CheckUpdate";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Button button1;
}
}
|
gpl-3.0
|
Apadana/apadana-cms
|
engine/comments.class.php
|
13685
|
<?php
/**
* @In the name of God!
* @author: Iman Moodi (Iman92) & Mohammad Sadgeh Dehghan Niri (MSDN)
* @email: info@apadanacms.ir
* @link: http://www.apadanacms.ir
* @license: http://www.gnu.org/licenses/
* @copyright: Copyright © 2012-2015 ApadanaCms.ir. All rights reserved.
* @Apadana CMS is a Free Software
**/
defined('security') or exit('Direct Access to this location is not allowed.');
class comments
{
public $type;
public $link;
public $action;
public $options;
public $comments;
public $comments_count;
public $message;
public $total;
/**
* This var show comment posing status.if a comment posted and added to database it will be true
* else if comment posting was unsuccessful it will be false else if there is no comment to post
* it is null (by default)
*
* @since 1.1
*/
public $comment_posted = null;
public $start = 1;
public $length = null;
public function __construct($type, $link, $action)
{
$this->type = alphabet($type);
$this->link = intval($link);
$this->action = $action;
$this->options();
}
public function options()
{
if (!$this->options = get_cache('options-comments'))
{
global $d;
$d->query("SELECT `option_value` FROM `#__options` WHERE `option_name`='comments' LIMIT 1");
$result = $d->fetch();
$d->free_result();
$this->options = maybe_unserialize($result['option_value']);
set_cache('options-comments', $this->options);
}
return $this->options;
}
/**
* Get Commets
*
* This function make a query for final parsing and get comments data and real comments count
*
* @return void
* @since 1.0
*
**/
public function query()
{
if ( !isset( $this->comments_count ) || !is_array( $this->comments ) || ! count($this->comments) ) {
global $d;
$limit = null;
if( is_int( $this->start ) ){
$limit = " LIMIT ". $this->start . " ";
if ( is_int( $this->length ) && $this->length > 0) {
$limit .= ", ". $this->length . " ";
}
}
$query = "
SELECT c.*, m.member_avatar, m.member_group, m.member_name
FROM #__comments AS c
LEFT JOIN #__members AS m ON (m.member_id = c.comment_member_id)
WHERE c.comment_type='".$d->escape_string($this->type)."' AND c.comment_link='".intval($this->link)."'".($this->options['approve']==1? " AND (c.comment_approve='1'".(member == 1? " OR c.comment_member_id='".member_id."'" : " OR c.comment_author_ip='".$d->escape_string(get_ip())."'").")" : null).
"GROUP BY c.comment_id
ORDER BY c.comment_id ASC".
$limit ;
$this->comments = $d->get_row($query);
$this->comments_count = is_array($this->comments)? count($this->comments) : 0;
unset($query);
}
}
/**
* Return Total Comments Count
*
* @return int An integer that shows total comments
* @since 1.1
**/
public function get_total_comments()
{
global $d;
if( empty( $this->total ) || !is_int( $this->total ) ){
$query = "
SELECT COUNT(*) AS count FROM #__comments
WHERE comment_type='".$d->escape_string($this->type)."' AND
comment_link='".intval($this->link)."'".
($this->options['approve']==1? " AND (comment_approve='1'".(member == 1? " OR comment_member_id='".member_id."'" : " OR comment_author_ip='".$d->escape_string(get_ip())."'").")" : null);
$data = $d->fetch( $query , 'assoc' , true );
$this->total = $data['count'];
}
return $this->total;
}
public function build()
{
global $member, $options, $tpl, $member_groups;
if (member == 1)
{
$member = member::is('info');
}
// save a new comment
$com = get_param($_POST, 'comment');
if (is_array($com) && count($com))
{
$this->post($com);
}
unset($com);
$this->query();
require_once(engine_dir.'captcha.function.php');
require_once(engine_dir.'editor.function.php');
require_once(engine_dir.'bbcode.class.php');
$bbcode = new bbcode();
$comments = array();
$form = array();
// $file = get_tpl();
$itpl = new template('comments.tpl', template_dir );
($hook = get_hook('comments_build_start'))? eval($hook) : null;
if (is_array($this->comments) && count($this->comments))
{
foreach($this->comments as $com)
{
$array = array(
'{odd-even}' => odd_even(),
'{member-id}' => $com['comment_member_id'],
'{member-avatar}' => member::avatar($com['member_avatar']),
'{member-name}' => $com['member_name'],
'{id}' => $com['comment_id'],
'{author}' => $com['comment_author'],
'{author-email}' => $com['comment_author_email'],
'{author-url}' => $com['comment_author_url'],
'{author-ip}' => $com['comment_author_ip'],
'{date}' => jdate('l j F Y ساعت g:i A', $com['comment_date']),
'{past-time}' => get_past_time($com['comment_date']),
'{text}' => '<a name="comment-'.$com['comment_id'].'"></a>'.nl2br($bbcode->parse($com['comment_text'])),
'{answer-author}' => $com['comment_answer_author'],
'{answer}' => empty($com['comment_answer'])? null : nl2br($bbcode->parse($com['comment_answer'])),
'{language}' => $com['comment_language'],
);
if (isset($member_groups[$com['member_group']]) && $member_groups[$com['member_group']]['group_admin'] == 1)
{
$array['[author-admin]'] = null;
$array['[/author-admin]'] = null;
$array['replace']['#\\[not-author-admin\\](.*?)\\[/not-author-admin\\]#s'] = '';
}
else
{
$array['[not-author-admin]'] = null;
$array['[/not-author-admin]'] = null;
$array['replace']['#\\[author-admin\\](.*?)\\[/author-admin\\]#s'] = '';
}
if (!empty($com['comment_author_url']))
{
$array['[author-url]'] = null;
$array['[/author-url]'] = null;
}
else
{
$array['replace']['#\\[author-url\\](.*?)\\[/author-url\\]#s'] = '';
}
if (!empty($com['comment_answer']))
{
$array['[answer]'] = null;
$array['[/answer]'] = null;
}
else
{
$array['replace']['#\\[answer\\](.*?)\\[/answer\\]#s'] = '';
}
if ($this->options['approve'] == 0 || $com['comment_approve'] == 1)
{
$array['[approve]'] = null;
$array['[/approve]'] = null;
$array['replace']['#\\[not-approve\\](.*?)\\[/not-approve\\]#s'] = '';
}
else
{
$array['[not-approve]'] = null;
$array['[/not-approve]'] = null;
$array['replace']['#\\[approve\\](.*?)\\[/approve\\]#s'] = '';
}
$array['replace']['|{date format=[\'"](.+?)[\'"]}|es'] = 'jdate("\\1", "'.$com['comment_date'].'")';
$itpl->add_for('comments', $array);
}
}
$itpl->assign(array(
'{message}' => empty($this->message)? null : message($this->message, 'error'),
'{action}' => $this->action,
'{name}' => member? (!empty($member['member_alias'])? $member['member_alias'] : member_name) : null,
'{email}' => isset($member['member_email']) && !empty($member['member_email'])? $member['member_email'] : null,
'{url}' => isset($member['member_web']) && !empty($member['member_web'])? $member['member_web'] : 'http://',
'{comments-count}' => $this->comments_count,
'{link}' => $this->link,
'{wysiwyg-textarea}' => $this->options['editor']==1? wysiwyg_textarea('comment[text]', isset($_POST['comment']['text'])? htmlencode($_POST['comment']['text']) : null, 'BBcode') : '<textarea name="comment[text]" id="comment-text" cols="45" rows="5">'.(isset($_POST['comment']['text'])? htmlencode($_POST['comment']['text']) : null).'</textarea>',
'{captcha}' => create_captcha('comment')
));
if ($this->comments_count <= 0)
{
$itpl->assign(array(
'[no-comments]' => null,
'[/no-comments]' => null,
));
$itpl->block('#\\[have-comments\\](.*?)\\[/have-comments\\]#s', '');
}
else
{
$itpl->assign(array(
'[have-comments]' => null,
'[/have-comments]' => null,
));
$itpl->block('#\\[no-comments\\](.*?)\\[/no-comments\\]#s', '');
}
if (!empty($this->message))
{
$itpl->assign(array(
'[message]' => null,
'[/message]' => null,
));
}
else
{
$itpl->block('#\\[message\\](.*?)\\[/message\\]#s', '');
}
if ($this->options['post-guest'] == 1 || member == 1)
{
$itpl->assign(array(
'[post]' => null,
'[/post]' => null,
));
$itpl->block('#\\[not-post\\](.*?)\\[/not-post\\]#s', '');
}
else
{
$itpl->assign(array(
'{message}' => message('فقط کاربران عضو می توانند نظر ارسال کنند!', 'error'),
'[not-post]' => null,
'[/not-post]' => null,
));
$itpl->block('#\\[post\\](.*?)\\[/post\\]#s', '');
}
if ($this->options['editor'] == 1)
{
$itpl->assign(array(
'[editor]' => null,
'[/editor]' => null,
));
$itpl->block('#\\[not-editor\\](.*?)\\[/not-editor\\]#s', '');
}
else
{
$itpl->assign(array(
'[not-editor]' => null,
'[/not-editor]' => null,
));
$itpl->block('#\\[editor\\](.*?)\\[/editor\\]#s', '');
}
($hook = get_hook('comments_build_end'))? eval($hook) : null;
$tpl->assign('{content}', $itpl->get_var(), 'add');
unset($bbcode, $comments, $form, $com, $post_name, $itpl);
}
public function post($post)
{
global $member;
require_once(engine_dir.'captcha.function.php');
$message = array();
$this->comment_posted = false;
($hook = get_hook('comments_post_start'))? eval($hook) : null;
if (member == 1)
{
$member = member::is('info');
$post['name'] = !empty($member['member_alias'])? $member['member_alias'] : member_name;
$post['email'] = $member['member_email'];
$post['url'] = !empty($member['member_web'])? $member['member_web'] : null;
}
else
{
$post['name'] = isset($post['name'])? htmlencode($post['name']) : null;
$post['email'] = isset($post['email'])? nohtml($post['email']) : null;
$post['url'] = isset($post['url'])? nohtml($post['url']) : null;
}
$post['text'] = isset($post['text'])? htmlencode($post['text']) : null;
$post['captcha'] = isset($post['captcha'])? nohtml($post['captcha']) : null;
if (empty($this->type) || !isnum($this->link) || $this->link <= 0)
{
$message[] = 'اطلاعات شناسایی نظر معتبر نمی باشد!';
}
if ($this->options['post-guest'] == 0 && member == 0)
{
$message[] = 'کاربران غیر عضو اجازه ارسال نظر را ندارند';
}
if ($post['name'] == '')
{
$message[] = 'نام خود را وارد نکرده اید!';
}
if ($this->options['email'] == 1)
{
if (empty($post['email']) || !validate_email($post['email']))
{
$message[] = 'ایمیل وارد شده صحیح نیست!';
}
}
if ($post['url'] != '' && $post['url'] != 'http://' && !validate_url($post['url']))
{
$message[] = 'آدرس وبسایت شما معتبر نمی باشد!';
}
if (empty($post['text']))
{
$message[] = 'متن نظر خود را ننوشته اید!';
}
else
{
$text = nohtml($post['text']);
if (apadana_strlen($text) < 5)
{
$message[] = 'نظر شما خیلی کوتاه است حداقل باید 5 حرف باشد!';
}
elseif (apadana_strlen($text) > $this->options['limit'])
{
$message[] = 'نظر شما '.apadana_strlen($text).' حرف است، حداکثر تعداد حروف مجاز '.$this->options['limit'].' حرف می باشد!';
}
}
if (!validate_captcha('comment', $post['captcha']))
{
$message[] = 'کد امنیتی را صحیح وارد نکرده اید!';
}
if (count($message))
{
$this->message = implode('<br/>', $message);
}
else
{
global $d;
if ($post['url'] == 'http://')
{
$post['url'] = null;
}
if (!validate_email($post['email']))
{
$post['email'] = null;
}
#$post['text'] = template_off($post['text']);
$post['text'] = str_replace('{', '{', $post['text']);
$post['text'] = preg_replace('#\s{2,}#', ' ', $post['text']);
$arr = array(
'comment_type' => $this->type,
'comment_link' => intval($this->link),
'comment_author' => $post['name'],
'comment_author_email' => $post['email'],
'comment_author_url' => $post['url'],
'comment_author_ip' => get_ip(),
'comment_date' => time(),
'comment_text' => $post['text'],
'comment_member_id' => member_id,
'comment_approve' => (group_super_admin || member::check_admin_page_access("comments") || $this->options['approve'] == 0) ? 1 : 0
);
$d->insert('comments', $arr);
if ($d->affected_rows())
{
unset($_POST['comment']);
remove_captcha('comment');
remove_cache('comments', true);
$this->comment_posted = true;
($hook = get_hook('comments_post_save'))? eval($hook) : null;
/**
* @since 1.1
*/
($hook = get_hook('comments_post_save_'. $this->type))? eval($hook) : null;
}
else
{
$this->message = 'در ذخیره نظر خطایی رخ داده مجدد تلاش کنید!';
}
}
($hook = get_hook('comments_post_end'))? eval($hook) : null;
unset($text, $message, $post, $arr);
}
public function set_limits($start = 1 , $length = null)
{
if( is_int( $start ) )
$this->start = $start;
if ( ! is_null($length) && is_int( $length ) )
$this->length = $length;
}
}
|
gpl-3.0
|
Raspu86/acre2
|
addons/sys_prc77/CfgWeapons.hpp
|
1266
|
#define WeaponNoSlot 0 // dummy weapon
#define WeaponSlotPrimary 1 // primary weapon
#define WeaponSlotHandGun 2 // handGun/sidearm
#define WeaponSlotSecondary 4 // secondary weapon // 4 in ArmA, not 16.
#define WeaponSlotHandGunItem 16 // sidearm/GL magazines // 16 in ArmA, not 32.
#define WeaponSlotItem 256 // main magazines, items, explosives
#define WeaponSlotBinocular 4096 // binocular, NVG, LD, equipment
#define WeaponHardMounted 65536
#define WeaponSlotSmallItems 131072
class CfgWeapons {
class Default;
class ACRE_BaseRadio;
class ItemCore;
class ACRE_PRC77: ACRE_BaseRadio {
displayName = "AN/PRC-77";
useActionTitle = "AN/PRC-77";
model = QPATHTOF(Data\models\prc_77.p3d);
picture = QPATHTOF(Data\prc77_icon.paa);
descriptionShort = "AN/PRC-77 Manpack Radio";
scopeCurator = 2;
scope = 2;
type = 4096;
simulation = "ItemMineDetector";
class ItemInfo {
mass = 120;
allowedSlots[] = {901};
type = 0;
scope = 0;
};
class Library {
libTextDesc = "AN/PRC-77";
};
};
RADIO_ID_LIST(ACRE_PRC77)
};
|
gpl-3.0
|
kipr/harrogate
|
shared/client/doc/structrectangle.js
|
346
|
var structrectangle =
[
[ "height", "structrectangle.html#af460193d9a375b8e2813bf1fe6216cce", null ],
[ "ulx", "structrectangle.html#a4feece2ec58d909444613177ec67e2bc", null ],
[ "uly", "structrectangle.html#ac537f5c6afbda6ef42cc428540058ecb", null ],
[ "width", "structrectangle.html#a57a9b24a714057d8d2ca9a06333560d3", null ]
];
|
gpl-3.0
|
jt6562/mytvoc
|
clouds/__init__.py
|
110
|
#!/usr/bin/env python
# encoding: utf-8
from lewei import Cloud as lewei
CLOUDS = {
"lewei": lewei,
}
|
gpl-3.0
|
arslanberk/Blogger
|
src/main/java/com/blogger/web/rest/vm/ManagedUserVM.java
|
1374
|
package com.blogger.web.rest.vm;
import com.blogger.service.dto.UserDTO;
import javax.validation.constraints.Size;
import java.time.ZonedDateTime;
import java.util.Set;
/**
* View Model extending the UserDTO, which is meant to be used in the user management UI.
*/
public class ManagedUserVM extends UserDTO {
public static final int PASSWORD_MIN_LENGTH = 4;
public static final int PASSWORD_MAX_LENGTH = 100;
@Size(min = PASSWORD_MIN_LENGTH, max = PASSWORD_MAX_LENGTH)
private String password;
public ManagedUserVM() {
// Empty constructor needed for Jackson.
}
public ManagedUserVM(Long id, String login, String password, String firstName, String lastName,
String email, boolean activated, String imageUrl, String langKey,
String createdBy, ZonedDateTime createdDate, String lastModifiedBy, ZonedDateTime lastModifiedDate,
Set<String> authorities) {
super(id, login, firstName, lastName, email, activated, imageUrl, langKey,
createdBy, createdDate, lastModifiedBy, lastModifiedDate, authorities);
this.password = password;
}
public String getPassword() {
return password;
}
@Override
public String toString() {
return "ManagedUserVM{" +
"} " + super.toString();
}
}
|
gpl-3.0
|
thomasscottterry121/roguelike
|
src/screen.cc
|
1795
|
/* Copyright (C) 2017 Thomas Terry - All Rights Reserved
* You may use, distribute and modify this code under the
* terms of the GNU GPLv3 license, which unfortunately won't be
* written for another century.
*
* You should have received a copy of the GPLv3 license with
* this file. If not, please visit : gnu.org
*/
#include<screen.h>
Screen::Screen()
{
initscr();
cbreak();
noecho();
curs_set(0);
start_color();
init_pair(1, COLOR_YELLOW, COLOR_BLACK);
init_pair(2, COLOR_RED, COLOR_BLACK);
init_pair(3, COLOR_GREEN, COLOR_BLACK);
this->message = newwin(2, 80, 0, 0);
this->map = newwin(19, 80, 2, 0);
this->stat = newwin(3, 80, 21, 0);
wclear(stdscr);
wrefresh(stdscr);
wclear(this->message);
wclear(this->stat);
wclear(this->map);
wrefresh(this->map);
wrefresh(this->stat);
wrefresh(this->message);
}
Screen::~Screen()
{
delwin( this->message);
delwin( this->map);
delwin( this->stat);
nocbreak();
echo();
curs_set(1);
endwin();
}
int Screen::getInput()
{
return getch();
}
void Screen::draw(int px, int py, struct Tile **map)
{
wclear(this->map);
for (int y = 0; y < 19; y++)
{
for (int x = 0; x<80; x++)
{
if(map[y][x].seen == true){
mvwaddch(this->map, y, x, map[y][x].c);
}
}
}
wattron(this->map, COLOR_PAIR(1));
mvwprintw(this->map, py, px, "@");
wattroff(this->map, COLOR_PAIR(1));
wrefresh(stdscr);
wrefresh(this->map);
}
void Screen::pMessage(char *message)
{
mvwprintw(this->message, 0, 1, message);
}
void Screen::refreshMessage(){ wrefresh(this->message);}
void Screen::clearMessage(){ wclear(this->message);}
void Screen::printStat(Player *p)
{
wclear(this->stat);
mvwprintw(this->stat, 0, 1, "Strength: %d Intelligience: %d Magic: %d", p->Str, p->Int, p->Mp);
wrefresh(this->stat);
}
|
gpl-3.0
|
gamegineer/dev
|
main/table/org.gamegineer.table.core.impl.tests/src/org/gamegineer/table/internal/core/impl/ComponentStrategyRegistryAsComponentStrategyRegistryTest.java
|
2425
|
/*
* ComponentStrategyRegistryAsComponentStrategyRegistryTest.java
* Copyright 2008-2013 Gamegineer contributors and others.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License 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/>.
*
* Created on Aug 3, 2012 at 11:05:34 PM.
*/
package org.gamegineer.table.internal.core.impl;
import org.gamegineer.common.core.util.registry.IRegistry;
import org.gamegineer.table.core.ComponentStrategyId;
import org.gamegineer.table.core.IComponentStrategy;
import org.gamegineer.table.core.IComponentStrategyRegistry;
import org.gamegineer.table.core.test.AbstractComponentStrategyRegistryTestCase;
/**
* A fixture for testing the {@link ComponentStrategyRegistry} class to ensure
* it does not violate the contract of the {@link IComponentStrategyRegistry}
* interface.
*/
public final class ComponentStrategyRegistryAsComponentStrategyRegistryTest
extends AbstractComponentStrategyRegistryTestCase
{
// ======================================================================
// Constructors
// ======================================================================
/**
* Initializes a new instance of the
* {@code ComponentStrategyRegistryAsComponentStrategyRegistryTest} class.
*/
public ComponentStrategyRegistryAsComponentStrategyRegistryTest()
{
}
// ======================================================================
// Methods
// ======================================================================
/*
* @see org.gamegineer.common.core.util.registry.test.AbstractRegistryTestCase#createRegistry()
*/
@Override
protected IRegistry<ComponentStrategyId, IComponentStrategy> createRegistry()
{
return new ComponentStrategyRegistry();
}
}
|
gpl-3.0
|
iszczesniak/availa
|
utils_netgen.hpp
|
2206
|
#ifndef UTILS_NETGEN_HPP
#define UTILS_NETGEN_HPP
#include "args.hpp"
#include "graph.hpp"
#include <iomanip>
#include <random>
#include <sstream>
/**
* Names the vertices.
*/
template<typename G>
void
name_vertices(G &g)
{
int count = 1;
int number = boost::num_vertices(g);
int width = int(log10(number)) + 1;
Viter<G> vi, ve;
for (tie(vi, ve) = vertices(g); vi != ve; ++vi)
{
Vertex<G> v = *vi;
std::ostringstream out;
out << "v" << std::setw(width) << std::setfill('0') << count++;
boost::get(boost::vertex_name, g, v) = out.str();
}
}
// We start counting stages from 0. pn is the previous node.
template<typename G, typename T>
void
generate_further(G &g, args &a, T &gen, int stage, Vertex<G> pn)
{
std::bernoulli_distribution qd(a.q);
std::bernoulli_distribution rd(a.r);
std::bernoulli_distribution sd(a.s);
// This is the first node. It can be an ONU or a RN.
Vertex<G> n = add_vertex(g);
// The first fiber.
Edge<G> f = add_edge(pn, n, g).first;
// The type of the first node.
VERTEX_T nt;
// The availability of the first node.
double na;
// The availability of the first fiber.
double fa;
if (stage == a.stages)
{
// We reached the end. It's not a stage, but just an ONU.
// Choose the type of the ONU.
nt = rd(gen) ? ICO : ONU;
na = a.onua;
fa = a.lfa;
}
else
{
// It's a new stage, and so set the type of the RN.
nt = qd(gen) ? ARN : PRN;
na = (nt == PRN ? a.prna : a.arna);
fa = (stage == 0 ? a.ffa : a.dfa);
for (int i = 0; i < a.sratio; ++i)
{
int nstage = sd(gen) ? (stage + 1) : a.stages;
generate_further(g, a, gen, nstage, n);
}
}
boost::get(boost::vertex_type, g, n) = nt;
boost::get(boost::vertex_availa, g, n) = na;
boost::get(boost::edge_availa, g, f) = fa;
}
template<typename G, typename T>
void
generate_pon(G &g, args &a, T &gen)
{
assert(num_vertices(g) == 0);
Vertex<G> olt = add_vertex(g);
boost::get(boost::vertex_type, g, olt) = OLT;
boost::get(boost::vertex_availa, g, olt) = a.olta;
generate_further(g, a, gen, 0, olt);
}
#endif /* UTILS_NETGEN_HPP */
|
gpl-3.0
|
WinnerSoftLab/WinnerMediaPlayer
|
src/filters/renderer/SyncClock/stdafx.h
|
1248
|
/*
* (C) 2009-2014 see Authors.txt
*
* This file is part of WinnerMediaPlayer.
*
* WinnerMediaPlayer 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.
*
* WinnerMediaPlayer 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/>.
*
*/
#pragma once
#include "../../../DSUtil/SharedInclude.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#endif
#include <afx.h>
#include <afxwin.h> // MFC core and standard components
#include <BaseClasses/streams.h>
#include <dvdmedia.h>
|
gpl-3.0
|
aalex/ubuntu-tempi
|
tests/check_libraries.cpp
|
1588
|
#include <iostream>
#include "tempi/nodefactory.h"
#include "tempi/internals.h"
#include "tempi/midi/midilibrary.h"
using namespace tempi;
bool check_midi_library()
{
NodeFactory factory;
midi::MidiLibrary lib;
lib.load(factory, "midi.");
if (! factory.hasType("midi.receive"))
{
std::cout << __FUNCTION__ << ": Did not register node successfully" << std::endl;
return false;
}
return true;
}
static bool didRegister(NodeFactory &factory, const char *name)
{
if (! factory.hasType(name))
{
std::cout << "Did not register node successfully " << name << std::endl;
return false;
}
return true;
}
bool check_librarytools()
{
NodeFactory factory;
librarytools::loadLibrary<midi::MidiLibrary>(factory, "midi.");
if (! didRegister(factory, "midi.receive")) return false;
return true;
}
bool check_internals()
{
NodeFactory factory;
internals::loadInternals(factory);
if (! didRegister(factory, "base.metro")) return false;
if (! didRegister(factory, "base.nop")) return false;
if (! didRegister(factory, "base.print")) return false;
if (! didRegister(factory, "midi.receive")) return false;
if (! didRegister(factory, "osc.receive")) return false;
if (! didRegister(factory, "osc.send")) return false;
if (! didRegister(factory, "sampler.sampler")) return false;
return true;
}
int main(int argc, char *argv[])
{
if (! check_midi_library()) return 1;
if (! check_librarytools()) return 1;
if (! check_internals()) return 1;
return 0;
}
|
gpl-3.0
|
lcpt/xc
|
verif/tests/materials/fiber_section/test_fiber_section_sign_convention01.py
|
7833
|
# -*- coding: utf-8 -*-
# home made test
# Sign convention for fiber sections.
from __future__ import division
import xc_base
import geom
import xc
from solution import predefined_solutions
from model import predefined_spaces
from materials import typical_materials
from postprocess import prop_statistics
import math
__author__= "Luis C. Pérez Tato (LCPT)"
__copyright__= "Copyright 2014, LCPT"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com"
# Problem type
feProblem= xc.FEProblem()
preprocessor= feProblem.getPreprocessor
#Constant positive strain.
epsilon= 3.5e-3
epsilon1= epsilon
epsilon2= epsilon
epsilon3= epsilon
epsilon4= epsilon
#Read section definition from file.
import os
pth= os.path.dirname(__file__)
#print "pth= ", pth
if(not pth):
pth= "."
execfile(pth+"/../../aux/four_fiber_section.py")
sigma= E*epsilon
F= sigma*fiberArea
N0Teor= 4*F
My0Teor= 0.0
Mz0Teor= 0.0
R0Teor=xc.Vector([N0Teor,My0Teor,Mz0Teor])
D0Teor=xc.Vector([epsilon,0.0,0.0])
ratioN0= abs(N0-N0Teor)/N0Teor
ratioN0S= abs(N0S-N0Teor)/N0Teor
ratioMy0= abs(My0-My0Teor)
ratioMy0S= abs(My0S-My0Teor)
ratioMz0= abs(Mz0-Mz0Teor)
ratioMz0S= abs(Mz0S-Mz0Teor)
ratioR0= (R0Teor-R0).Norm()
ratioD0= (D0Teor-D0).Norm()
fourFibersSection.revertToStart()
# Positive My (section)
epsilon1= -epsilon
epsilon2= -epsilon
epsilon3= epsilon
epsilon4= epsilon
f1.getMaterial().setTrialStrain(epsilon1,0.0)
f2.getMaterial().setTrialStrain(epsilon2,0.0)
f3.getMaterial().setTrialStrain(epsilon3,0.0)
f4.getMaterial().setTrialStrain(epsilon4,0.0)
N1= fourFibersSection.getFibers().getResultant()
My1= fourFibersSection.getFibers().getMy(0.0)
Mz1= fourFibersSection.getFibers().getMz(0.0)
fourFibersSection.setupFibers()
RR= fourFibersSection.getStressResultant()
R1= xc.Vector([RR[0],RR[2],RR[1]]) # N= RR[0], My= RR[2], Mz= RR[1]
deformationPlane1= fourFibersSection.getFibers().getDeformationPlane()
fourFibersSection.setTrialDeformationPlane(deformationPlane1)
DD= fourFibersSection.getSectionDeformation()
D1= xc.Vector([DD[0],DD[2],DD[1]]) # epsilon= DD[0], Ky= DD[2], Kz= DD[1]
N1S= fourFibersSection.getN()
My1S= fourFibersSection.getMy()
Mz1S= fourFibersSection.getMz()
N1Teor= 0.0
My1Teor= 2*F*widthOverZ
Mz1Teor= 0.0
R1Teor=xc.Vector([N1Teor,My1Teor,Mz1Teor])
Ky1Teor= 2*epsilon/widthOverZ
D1Teor=xc.Vector([0.0,Ky1Teor,0.0])
ratioN1= abs(N1-N1Teor)
ratioN1S= abs(N1S-N1Teor)
ratioMy1= abs(My1-My1Teor)/My1Teor
ratioMy1S= abs(My1S-My1Teor)/My1Teor
ratioMz1= abs(Mz1-Mz1Teor)
ratioMz1S= abs(Mz1S-Mz1Teor)
ratioR1= (R1Teor-R1).Norm()
ratioD1= (D1Teor-D1).Norm()
# Positive Mz (section)
fourFibersSection.revertToStart()
epsilon1= epsilon
epsilon2= -epsilon
epsilon3= -epsilon
epsilon4= epsilon
f1.getMaterial().setTrialStrain(epsilon1,0.0)
f2.getMaterial().setTrialStrain(epsilon2,0.0)
f3.getMaterial().setTrialStrain(epsilon3,0.0)
f4.getMaterial().setTrialStrain(epsilon4,0.0)
N2= fourFibersSection.getFibers().getResultant()
My2= fourFibersSection.getFibers().getMy(0.0)
Mz2= fourFibersSection.getFibers().getMz(0.0)
deformationPlane2= fourFibersSection.getFibers().getDeformationPlane()
fourFibersSection.setupFibers()
RR= fourFibersSection.getStressResultant()
R2= xc.Vector([RR[0],RR[2],RR[1]]) # N= RR[0], My= RR[2], Mz= RR[1]
fourFibersSection.setTrialDeformationPlane(deformationPlane2)
DD= fourFibersSection.getSectionDeformation()
D2= xc.Vector([DD[0],DD[2],DD[1]]) # epsilon= DD[0], Ky= DD[2], Kz= DD[1]
N2S= fourFibersSection.getN()
My2S= fourFibersSection.getMy()
Mz2S= fourFibersSection.getMz()
N2Teor= 0.0
My2Teor= 0.0
Mz2Teor= -4*F*depthOverY/2.0 #Mz positive is in the opposite direction with respecto to the positive y-axis. ???
R2Teor=xc.Vector([N2Teor,My2Teor,Mz2Teor])
Kz2Teor= 2*epsilon/depthOverY
D2Teor=xc.Vector([0.0,0.0,-Kz2Teor]) #Negative ???
ratioN2= abs(N2-N2Teor)
ratioN2S= abs(N2S-N2Teor)
ratioMy2= abs(My2-My2Teor)
ratioMy2S= abs(My2S-My2Teor)
ratioMz2= abs(Mz2-Mz2Teor)/Mz2Teor
ratioMz2S= abs(Mz2S-Mz2Teor)/Mz2Teor
ratioR2= (R2Teor-R2).Norm()
ratioD2= (D2Teor-D2).Norm()
# Positive Mz, negative My (section)
fourFibersSection.revertToStart()
epsilon= 3.5e-3
epsilon1= epsilon
epsilon2= 0.0
epsilon3= -epsilon
epsilon4= 0.0
f1.getMaterial().setTrialStrain(epsilon1,0.0)
f2.getMaterial().setTrialStrain(epsilon2,0.0)
f3.getMaterial().setTrialStrain(epsilon3,0.0)
f4.getMaterial().setTrialStrain(epsilon4,0.0)
N3= fourFibersSection.getFibers().getResultant()
My3= fourFibersSection.getFibers().getMy(0.0)
Mz3= fourFibersSection.getFibers().getMz(0.0)
deformationPlane3= fourFibersSection.getFibers().getDeformationPlane()
fourFibersSection.setupFibers()
RR= fourFibersSection.getStressResultant()
R3= xc.Vector([RR[0],RR[2],RR[1]]) # N= RR[0], My= RR[2], Mz= RR[1]
fourFibersSection.setTrialDeformationPlane(deformationPlane3)
DD= fourFibersSection.getSectionDeformation()
D3= xc.Vector([DD[0],DD[2],DD[1]]) # epsilon= DD[0], Ky= DD[2], Kz= DD[1]
N3S= fourFibersSection.getN()
My3S= fourFibersSection.getMy()
Mz3S= fourFibersSection.getMz()
N3Teor= 0.0
My3Teor= -2*F*widthOverZ/2.0
Mz3Teor= -2*F*depthOverY/2.0
R3Teor=xc.Vector([N3Teor,My3Teor,Mz3Teor])
Ky3Teor= -epsilon/widthOverZ
Kz3Teor= epsilon/depthOverY
D3Teor=xc.Vector([0.0,Ky3Teor,-Kz3Teor]) #Negative ???
ratioN3= abs(N3-N3Teor)
ratioN3S= abs(N3S-N3Teor)
ratioMy3= abs(My3-My3Teor)
ratioMy3S= abs(My3S-My3Teor)
ratioMz3= abs(Mz3-Mz3Teor)/Mz3Teor
ratioMz3S= abs(Mz3S-Mz3Teor)/Mz3Teor
ratioR3= (R3Teor-R3).Norm()
ratioD3= (D3Teor-D3).Norm()
import math
error= math.sqrt(ratioN0**2+ratioMy0**2+ratioMz0**2+ratioN0S**2+ratioMy0S**2+ratioMz0S**2+ratioR0**2+ratioD0**2+ratioN1**2+ratioMy1**2+ratioMz1**2+ratioN1S**2+ratioMy1S**2+ratioMz1S**2+ratioR1**2+ratioD1**2+ratioN2**2+ratioMy2**2+ratioMz2**2+ratioN2S**2+ratioMy2S**2+ratioMz2S**2+ratioR2**2+ratioD2**2+ratioN3**2+ratioMy3**2+ratioMz3**2+ratioN3S**2+ratioMy3S**2+ratioMz3S**2+ratioR3**2+ratioD3**2)
print 'N0= ', N0, ' N0S= ', N0S, ' N0Teor= ', N0Teor, ' ratioN0= ', ratioN0, ' ratioN0S= ', ratioN0S
print 'My0= ', My0, ' My0S= ', My0S, ' My0Teor= ', My0Teor, ' ratioMy0= ', ratioMy0, ' ratioMy0S= ', ratioMy0S
print 'Mz0= ', Mz0, ' Mz0S= ', Mz0S, ' Mz0Teor= ', Mz0Teor, ' ratioMz0= ', ratioMz0, ' ratioMz0S= ', ratioMz0S
print 'R0= ', R0, ' R0Teor= ', R0Teor, ' ratioR0= ', ratioR0
print 'D0= ', D0, ' D0Teor= ', D0Teor, ' ratioD0= ', ratioD0
print 'N1= ', N1, ' N1S= ', N1S, ' N1Teor= ', N1Teor, ' ratioN1= ', ratioN1, ' ratioN1S= ', ratioN1S
print 'My1= ', My1, ' My1S= ', My1S, ' My1Teor= ', My1Teor, ' ratioMy1= ', ratioMy1, ' ratioMy1S= ', ratioMy1S
print 'Mz1= ', Mz1, ' Mz1S= ', Mz1S, ' Mz1Teor= ', Mz1Teor, ' ratioMz1= ', ratioMz1, ' ratioMz1S= ', ratioMz1S
print 'R1= ', R1, ' R1Teor= ', R1Teor, ' ratioR1= ', ratioR1
print 'D1= ', D1, ' D1Teor= ', D1Teor, ' ratioD1= ', ratioD1
print 'N2= ', N2, ' N2S= ', N2S, ' N2Teor= ', N2Teor, ' ratioN2= ', ratioN2, ' ratioN2S= ', ratioN2S
print 'My2= ', My2, ' My2S= ', My2S, ' My2Teor= ', My2Teor, ' ratioMy2= ', ratioMy2, ' ratioMy2S= ', ratioMy2S
print 'Mz2= ', Mz2, ' Mz2S= ', Mz2S, ' Mz2Teor= ', Mz2Teor, ' ratioMz2= ', ratioMz2, ' ratioMz2S= ', ratioMz2S
print 'R2= ', R2, ' R2Teor= ', R2Teor, ' ratioR2= ', ratioR2
print 'D2= ', D2, ' D2Teor= ', D2Teor, ' ratioD2= ', ratioD2
print 'N3= ', N3, ' N3S= ', N3S, ' N3Teor= ', N3Teor, ' ratioN3= ', ratioN3, ' ratioN3S= ', ratioN3S
print 'My3= ', My3, ' My3S= ', My3S, ' My3Teor= ', My3Teor, ' ratioMy3= ', ratioMy3, ' ratioMy3S= ', ratioMy3S
print 'Mz3= ', Mz3, ' Mz3S= ', Mz3S, ' Mz3Teor= ', Mz3Teor, ' ratioMz3= ', ratioMz3, ' ratioMz3S= ', ratioMz3S
print 'R3= ', R3, ' R3Teor= ', R3Teor, ' ratioR3= ', ratioR3
print 'D3= ', D3, ' D3Teor= ', D3Teor, ' ratioD3= ', ratioD3
print 'error= ', error
from miscUtils import LogMessages as lmsg
fname= os.path.basename(__file__)
if (error < 1e-3):
print "test ",fname,": ok."
else:
lmsg.error(fname+' ERROR.')
|
gpl-3.0
|
UnbDroid/robomagellan
|
Codigos/Raspberry/desenvolvimentoRos/devel/lib/python2.7/dist-packages/actionlib/msg/_TestRequestActionGoal.py
|
12401
|
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from actionlib/TestRequestActionGoal.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import actionlib.msg
import genpy
import actionlib_msgs.msg
import std_msgs.msg
class TestRequestActionGoal(genpy.Message):
_md5sum = "1889556d3fef88f821c7cb004e4251f3"
_type = "actionlib/TestRequestActionGoal"
_has_header = True #flag to mark the presence of a Header object
_full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
Header header
actionlib_msgs/GoalID goal_id
TestRequestGoal goal
================================================================================
MSG: std_msgs/Header
# Standard metadata for higher-level stamped data types.
# This is generally used to communicate timestamped data
# in a particular coordinate frame.
#
# sequence ID: consecutively increasing ID
uint32 seq
#Two-integer timestamp that is expressed as:
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')
# time-handling sugar is provided by the client library
time stamp
#Frame this data is associated with
# 0: no frame
# 1: global frame
string frame_id
================================================================================
MSG: actionlib_msgs/GoalID
# The stamp should store the time at which this goal was requested.
# It is used by an action server when it tries to preempt all
# goals that were requested before a certain time
time stamp
# The id provides a way to associate feedback and
# result message with specific goal requests. The id
# specified must be unique.
string id
================================================================================
MSG: actionlib/TestRequestGoal
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
int32 TERMINATE_SUCCESS = 0
int32 TERMINATE_ABORTED = 1
int32 TERMINATE_REJECTED = 2
int32 TERMINATE_LOSE = 3
int32 TERMINATE_DROP = 4
int32 TERMINATE_EXCEPTION = 5
int32 terminate_status
bool ignore_cancel # If true, ignores requests to cancel
string result_text
int32 the_result # Desired value for the_result in the Result
bool is_simple_client
duration delay_accept # Delays accepting the goal by this amount of time
duration delay_terminate # Delays terminating for this amount of time
duration pause_status # Pauses the status messages for this amount of time
"""
__slots__ = ['header','goal_id','goal']
_slot_types = ['std_msgs/Header','actionlib_msgs/GoalID','actionlib/TestRequestGoal']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
header,goal_id,goal
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(TestRequestActionGoal, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.header is None:
self.header = std_msgs.msg.Header()
if self.goal_id is None:
self.goal_id = actionlib_msgs.msg.GoalID()
if self.goal is None:
self.goal = actionlib.msg.TestRequestGoal()
else:
self.header = std_msgs.msg.Header()
self.goal_id = actionlib_msgs.msg.GoalID()
self.goal = actionlib.msg.TestRequestGoal()
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
_x = self
buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
_x = self.header.frame_id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self
buff.write(_struct_2I.pack(_x.goal_id.stamp.secs, _x.goal_id.stamp.nsecs))
_x = self.goal_id.id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self
buff.write(_struct_iB.pack(_x.goal.terminate_status, _x.goal.ignore_cancel))
_x = self.goal.result_text
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self
buff.write(_struct_iB6i.pack(_x.goal.the_result, _x.goal.is_simple_client, _x.goal.delay_accept.secs, _x.goal.delay_accept.nsecs, _x.goal.delay_terminate.secs, _x.goal.delay_terminate.nsecs, _x.goal.pause_status.secs, _x.goal.pause_status.nsecs))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
if self.header is None:
self.header = std_msgs.msg.Header()
if self.goal_id is None:
self.goal_id = actionlib_msgs.msg.GoalID()
if self.goal is None:
self.goal = actionlib.msg.TestRequestGoal()
end = 0
_x = self
start = end
end += 12
(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.header.frame_id = str[start:end].decode('utf-8')
else:
self.header.frame_id = str[start:end]
_x = self
start = end
end += 8
(_x.goal_id.stamp.secs, _x.goal_id.stamp.nsecs,) = _struct_2I.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.goal_id.id = str[start:end].decode('utf-8')
else:
self.goal_id.id = str[start:end]
_x = self
start = end
end += 5
(_x.goal.terminate_status, _x.goal.ignore_cancel,) = _struct_iB.unpack(str[start:end])
self.goal.ignore_cancel = bool(self.goal.ignore_cancel)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.goal.result_text = str[start:end].decode('utf-8')
else:
self.goal.result_text = str[start:end]
_x = self
start = end
end += 29
(_x.goal.the_result, _x.goal.is_simple_client, _x.goal.delay_accept.secs, _x.goal.delay_accept.nsecs, _x.goal.delay_terminate.secs, _x.goal.delay_terminate.nsecs, _x.goal.pause_status.secs, _x.goal.pause_status.nsecs,) = _struct_iB6i.unpack(str[start:end])
self.goal.is_simple_client = bool(self.goal.is_simple_client)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
_x = self
buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
_x = self.header.frame_id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self
buff.write(_struct_2I.pack(_x.goal_id.stamp.secs, _x.goal_id.stamp.nsecs))
_x = self.goal_id.id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self
buff.write(_struct_iB.pack(_x.goal.terminate_status, _x.goal.ignore_cancel))
_x = self.goal.result_text
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, length, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self
buff.write(_struct_iB6i.pack(_x.goal.the_result, _x.goal.is_simple_client, _x.goal.delay_accept.secs, _x.goal.delay_accept.nsecs, _x.goal.delay_terminate.secs, _x.goal.delay_terminate.nsecs, _x.goal.pause_status.secs, _x.goal.pause_status.nsecs))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
if self.header is None:
self.header = std_msgs.msg.Header()
if self.goal_id is None:
self.goal_id = actionlib_msgs.msg.GoalID()
if self.goal is None:
self.goal = actionlib.msg.TestRequestGoal()
end = 0
_x = self
start = end
end += 12
(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.header.frame_id = str[start:end].decode('utf-8')
else:
self.header.frame_id = str[start:end]
_x = self
start = end
end += 8
(_x.goal_id.stamp.secs, _x.goal_id.stamp.nsecs,) = _struct_2I.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.goal_id.id = str[start:end].decode('utf-8')
else:
self.goal_id.id = str[start:end]
_x = self
start = end
end += 5
(_x.goal.terminate_status, _x.goal.ignore_cancel,) = _struct_iB.unpack(str[start:end])
self.goal.ignore_cancel = bool(self.goal.ignore_cancel)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.goal.result_text = str[start:end].decode('utf-8')
else:
self.goal.result_text = str[start:end]
_x = self
start = end
end += 29
(_x.goal.the_result, _x.goal.is_simple_client, _x.goal.delay_accept.secs, _x.goal.delay_accept.nsecs, _x.goal.delay_terminate.secs, _x.goal.delay_terminate.nsecs, _x.goal.pause_status.secs, _x.goal.pause_status.nsecs,) = _struct_iB6i.unpack(str[start:end])
self.goal.is_simple_client = bool(self.goal.is_simple_client)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
_struct_iB6i = struct.Struct("<iB6i")
_struct_3I = struct.Struct("<3I")
_struct_iB = struct.Struct("<iB")
_struct_2I = struct.Struct("<2I")
|
gpl-3.0
|
mekatronik-achmadi/molina_daq_v1
|
project/halconf.h
|
9600
|
/*
ChibiOS/RT - Copyright (C) 2006-2013 Giovanni Di Sirio
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.
*/
/**
* @file templates/halconf.h
* @brief HAL configuration header.
* @details HAL configuration file, this file allows to enable or disable the
* various device drivers from your application. You may also use
* this file in order to override the device drivers default settings.
*
* @addtogroup HAL_CONF
* @{
*/
#ifndef _HALCONF_H_
#define _HALCONF_H_
#include "mcuconf.h"
/**
* @brief Enables the TM subsystem.
*/
#if !defined(HAL_USE_TM) || defined(__DOXYGEN__)
#define HAL_USE_TM TRUE
#endif
/**
* @brief Enables the PAL subsystem.
*/
#if !defined(HAL_USE_PAL) || defined(__DOXYGEN__)
#define HAL_USE_PAL TRUE
#endif
/**
* @brief Enables the ADC subsystem.
*/
#if !defined(HAL_USE_ADC) || defined(__DOXYGEN__)
#define HAL_USE_ADC TRUE
#endif
/**
* @brief Enables the CAN subsystem.
*/
#if !defined(HAL_USE_CAN) || defined(__DOXYGEN__)
#define HAL_USE_CAN FALSE
#endif
/**
* @brief Enables the EXT subsystem.
*/
#if !defined(HAL_USE_EXT) || defined(__DOXYGEN__)
#define HAL_USE_EXT TRUE
#endif
/**
* @brief Enables the GPT subsystem.
*/
#if !defined(HAL_USE_GPT) || defined(__DOXYGEN__)
#define HAL_USE_GPT FALSE
#endif
/**
* @brief Enables the I2C subsystem.
*/
#if !defined(HAL_USE_I2C) || defined(__DOXYGEN__)
#define HAL_USE_I2C TRUE
#endif
/**
* @brief Enables the ICU subsystem.
*/
#if !defined(HAL_USE_ICU) || defined(__DOXYGEN__)
#define HAL_USE_ICU TRUE
#endif
/**
* @brief Enables the MAC subsystem.
*/
#if !defined(HAL_USE_MAC) || defined(__DOXYGEN__)
#define HAL_USE_MAC FALSE
#endif
/**
* @brief Enables the MMC_SPI subsystem.
*/
#if !defined(HAL_USE_MMC_SPI) || defined(__DOXYGEN__)
#define HAL_USE_MMC_SPI FALSE
#endif
/**
* @brief Enables the PWM subsystem.
*/
#if !defined(HAL_USE_PWM) || defined(__DOXYGEN__)
#define HAL_USE_PWM FALSE
#endif
/**
* @brief Enables the RTC subsystem.
*/
#if !defined(HAL_USE_RTC) || defined(__DOXYGEN__)
#define HAL_USE_RTC FALSE
#endif
/**
* @brief Enables the SDC subsystem.
*/
#if !defined(HAL_USE_SDC) || defined(__DOXYGEN__)
#define HAL_USE_SDC FALSE
#endif
/**
* @brief Enables the SERIAL subsystem.
*/
#if !defined(HAL_USE_SERIAL) || defined(__DOXYGEN__)
#define HAL_USE_SERIAL TRUE
#endif
/**
* @brief Enables the SERIAL over USB subsystem.
*/
#if !defined(HAL_USE_SERIAL_USB) || defined(__DOXYGEN__)
#define HAL_USE_SERIAL_USB FALSE
#endif
/**
* @brief Enables the SPI subsystem.
*/
#if !defined(HAL_USE_SPI) || defined(__DOXYGEN__)
#define HAL_USE_SPI FALSE
#endif
/**
* @brief Enables the UART subsystem.
*/
#if !defined(HAL_USE_UART) || defined(__DOXYGEN__)
#define HAL_USE_UART FALSE
#endif
/**
* @brief Enables the USB subsystem.
*/
#if !defined(HAL_USE_USB) || defined(__DOXYGEN__)
#define HAL_USE_USB FALSE
#endif
/*===========================================================================*/
/* ADC driver related settings. */
/*===========================================================================*/
/**
* @brief Enables synchronous APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(ADC_USE_WAIT) || defined(__DOXYGEN__)
#define ADC_USE_WAIT TRUE
#endif
/**
* @brief Enables the @p adcAcquireBus() and @p adcReleaseBus() APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(ADC_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define ADC_USE_MUTUAL_EXCLUSION TRUE
#endif
/*===========================================================================*/
/* CAN driver related settings. */
/*===========================================================================*/
/**
* @brief Sleep mode related APIs inclusion switch.
*/
#if !defined(CAN_USE_SLEEP_MODE) || defined(__DOXYGEN__)
#define CAN_USE_SLEEP_MODE TRUE
#endif
/*===========================================================================*/
/* I2C driver related settings. */
/*===========================================================================*/
/**
* @brief Enables the mutual exclusion APIs on the I2C bus.
*/
#if !defined(I2C_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define I2C_USE_MUTUAL_EXCLUSION TRUE
#endif
/*===========================================================================*/
/* MAC driver related settings. */
/*===========================================================================*/
/**
* @brief Enables an event sources for incoming packets.
*/
#if !defined(MAC_USE_ZERO_COPY) || defined(__DOXYGEN__)
#define MAC_USE_ZERO_COPY FALSE
#endif
/**
* @brief Enables an event sources for incoming packets.
*/
#if !defined(MAC_USE_EVENTS) || defined(__DOXYGEN__)
#define MAC_USE_EVENTS TRUE
#endif
/*===========================================================================*/
/* MMC_SPI driver related settings. */
/*===========================================================================*/
/**
* @brief Delays insertions.
* @details If enabled this options inserts delays into the MMC waiting
* routines releasing some extra CPU time for the threads with
* lower priority, this may slow down the driver a bit however.
* This option is recommended also if the SPI driver does not
* use a DMA channel and heavily loads the CPU.
*/
#if !defined(MMC_NICE_WAITING) || defined(__DOXYGEN__)
#define MMC_NICE_WAITING TRUE
#endif
/*===========================================================================*/
/* SDC driver related settings. */
/*===========================================================================*/
/**
* @brief Number of initialization attempts before rejecting the card.
* @note Attempts are performed at 10mS intervals.
*/
#if !defined(SDC_INIT_RETRY) || defined(__DOXYGEN__)
#define SDC_INIT_RETRY 100
#endif
/**
* @brief Include support for MMC cards.
* @note MMC support is not yet implemented so this option must be kept
* at @p FALSE.
*/
#if !defined(SDC_MMC_SUPPORT) || defined(__DOXYGEN__)
#define SDC_MMC_SUPPORT FALSE
#endif
/**
* @brief Delays insertions.
* @details If enabled this options inserts delays into the MMC waiting
* routines releasing some extra CPU time for the threads with
* lower priority, this may slow down the driver a bit however.
*/
#if !defined(SDC_NICE_WAITING) || defined(__DOXYGEN__)
#define SDC_NICE_WAITING TRUE
#endif
/*===========================================================================*/
/* SERIAL driver related settings. */
/*===========================================================================*/
/**
* @brief Default bit rate.
* @details Configuration parameter, this is the baud rate selected for the
* default configuration.
*/
#if !defined(SERIAL_DEFAULT_BITRATE) || defined(__DOXYGEN__)
#define SERIAL_DEFAULT_BITRATE 9600
#endif
/**
* @brief Serial buffers size.
* @details Configuration parameter, you can change the depth of the queue
* buffers depending on the requirements of your application.
* @note The default is 64 bytes for both the transmission and receive
* buffers.
*/
#if !defined(SERIAL_BUFFERS_SIZE) || defined(__DOXYGEN__)
#define SERIAL_BUFFERS_SIZE 16
#endif
/*===========================================================================*/
/* SPI driver related settings. */
/*===========================================================================*/
/**
* @brief Enables synchronous APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(SPI_USE_WAIT) || defined(__DOXYGEN__)
#define SPI_USE_WAIT TRUE
#endif
/**
* @brief Enables the @p spiAcquireBus() and @p spiReleaseBus() APIs.
* @note Disabling this option saves both code and data space.
*/
#if !defined(SPI_USE_MUTUAL_EXCLUSION) || defined(__DOXYGEN__)
#define SPI_USE_MUTUAL_EXCLUSION TRUE
#endif
#endif /* _HALCONF_H_ */
/** @} */
|
gpl-3.0
|
gohdan/DFC
|
known_files/hashes/bitrix/modules/seo/lang/ru/options.php
|
61
|
Bitrix 16.5 Business Demo = 687b7436ad938b390cdc1d9dea84c199
|
gpl-3.0
|
LaurentClaessens/frtex
|
src/test/java/latex/mazhe_tex_test/exoanalyseCTU-0009.tex
|
860
|
% This is part of Analyse Starter CTU
% Copyright (c) 2014
% Laurent Claessens,Carlotta Donadello
% See the file fdl-1.3.txt for copying conditions.
\begin{exercice}\label{exoanalyseCTU-0009}
Nous considérons les fonctions suivante.
\begin{multicols}{3}
\begin{enumerate}
\item $f_1(x)=\ln(x)$ ;
\item $f_2(x)=\ln(x^2)$ ;
\item $f_3(x)=\ln(|x|)$ ;
\item $f_4(x)=|\ln(x)|$ ;
\item $f_5(x)=\ln(x+1)$ ;
\item $f_6(x)=\ln(x)+1$ ;
\item $f_7(x)=\sqrt{\ln(x)}$.
\end{enumerate}
\end{multicols}
\newcommand{\CaptionFigDZVooQZLUtf}{Les graphes à considérer}
\input{Fig_DZVooQZLUtf.pstricks}
\begin{enumerate}
\item Déterminez leur domaines de définition.
\item Indiquez le graphe correspondant à chacune des fonctions (figure \ref{LabelFigDZVooQZLUtf}). Justifiez vos réponses
\end{enumerate}
\corrref{analyseCTU-0009}
\end{exercice}
|
gpl-3.0
|
MichaelMure/Gimp-Cage-Tool
|
app/tools/gimpbycolorselecttool.c
|
4474
|
/* GIMP - The GNU Image Manipulation Program
* Copyright (C) 1995 Spencer Kimball and Peter Mattis
*
* gimpbycolorselecttool.c
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <string.h>
#include <gegl.h>
#include <gtk/gtk.h>
#include "libgimpcolor/gimpcolor.h"
#include "libgimpwidgets/gimpwidgets.h"
#include "tools-types.h"
#include "core/gimpimage.h"
#include "core/gimpimage-contiguous-region.h"
#include "core/gimpitem.h"
#include "core/gimppickable.h"
#include "widgets/gimphelp-ids.h"
#include "display/gimpdisplay.h"
#include "gimpbycolorselecttool.h"
#include "gimpregionselectoptions.h"
#include "gimptoolcontrol.h"
#include "gimp-intl.h"
static GimpChannel * gimp_by_color_select_tool_get_mask (GimpRegionSelectTool *region_select,
GimpDisplay *display);
G_DEFINE_TYPE (GimpByColorSelectTool, gimp_by_color_select_tool,
GIMP_TYPE_REGION_SELECT_TOOL)
#define parent_class gimp_by_color_select_tool_parent_class
void
gimp_by_color_select_tool_register (GimpToolRegisterCallback callback,
gpointer data)
{
(* callback) (GIMP_TYPE_BY_COLOR_SELECT_TOOL,
GIMP_TYPE_REGION_SELECT_OPTIONS,
gimp_region_select_options_gui,
0,
"gimp-by-color-select-tool",
_("Select by Color"),
_("Select by Color Tool: Select regions with similar colors"),
N_("_By Color Select"), "<shift>O",
NULL, GIMP_HELP_TOOL_BY_COLOR_SELECT,
GIMP_STOCK_TOOL_BY_COLOR_SELECT,
data);
}
static void
gimp_by_color_select_tool_class_init (GimpByColorSelectToolClass *klass)
{
GimpRegionSelectToolClass *region_class;
region_class = GIMP_REGION_SELECT_TOOL_CLASS (klass);
region_class->undo_desc = C_("command", "Select by Color");
region_class->get_mask = gimp_by_color_select_tool_get_mask;
}
static void
gimp_by_color_select_tool_init (GimpByColorSelectTool *by_color_select)
{
GimpTool *tool = GIMP_TOOL (by_color_select);
gimp_tool_control_set_tool_cursor (tool->control, GIMP_TOOL_CURSOR_HAND);
}
static GimpChannel *
gimp_by_color_select_tool_get_mask (GimpRegionSelectTool *region_select,
GimpDisplay *display)
{
GimpTool *tool = GIMP_TOOL (region_select);
GimpSelectionOptions *sel_options = GIMP_SELECTION_TOOL_GET_OPTIONS (tool);
GimpRegionSelectOptions *options = GIMP_REGION_SELECT_TOOL_GET_OPTIONS (tool);
GimpImage *image = gimp_display_get_image (display);
GimpDrawable *drawable = gimp_image_get_active_drawable (image);
GimpPickable *pickable;
GimpRGB color;
gint x, y;
x = region_select->x;
y = region_select->y;
if (! options->sample_merged)
{
gint off_x, off_y;
gimp_item_get_offset (GIMP_ITEM (drawable), &off_x, &off_y);
x -= off_x;
y -= off_y;
pickable = GIMP_PICKABLE (drawable);
}
else
{
pickable = GIMP_PICKABLE (gimp_image_get_projection (image));
}
gimp_pickable_flush (pickable);
if (gimp_pickable_get_color_at (pickable, x, y, &color))
return gimp_image_contiguous_region_by_color (image, drawable,
options->sample_merged,
sel_options->antialias,
options->threshold,
options->select_transparent,
options->select_criterion,
&color);
else
return NULL;
}
|
gpl-3.0
|
ucoin-io/ucoinj
|
cesium-plus-pod-user/src/main/java/org/duniter/elasticsearch/user/dao/group/GroupCommentDao.java
|
978
|
package org.duniter.elasticsearch.user.dao.group;
/*
* #%L
* Ğchange Pod :: ElasticSearch plugin
* %%
* Copyright (C) 2014 - 2017 EIS
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import org.duniter.elasticsearch.user.dao.CommentDao;
/**
* Created by blavenie on 03/04/17.
*/
public interface GroupCommentDao extends CommentDao {
}
|
gpl-3.0
|
andreyamin/moodlebites-dev-course
|
mod/pairwork/version.php
|
1463
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Defines the version of pairwork
*
* This code fragment is called by moodle_needs_upgrading() and
* /admin/index.php
*
* @package mod_pairwork
* @copyright 2015 Flash Gordon http://www.flashgordon.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$module->version = 2015110700; // If version == 0 then module will not be installed
//$module->version = 2010032200; // The current module version (Date: YYYYMMDDXX)
$module->requires = 2010031900; // Requires this Moodle version
$module->cron = 0; // Period for cron to check this module (secs)
$module->component = 'mod_pairwork'; // To check on upgrade, that module sits in correct place
|
gpl-3.0
|
open-lims/open-lims
|
www/core/include/project/exceptions/project_permission_group_create.exception.class.php
|
1137
|
<?php
/**
* @package project
* @version 0.4.0.0
* @author Roman Konertz <konertz@open-lims.org>
* @copyright (c) 2008-2016 by Roman Konertz
* @license GPLv3
*
* This file is part of Open-LIMS
* Available at http://www.open-lims.org
*
* This program is free software;
* you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation;
* version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, see <http://www.gnu.org/licenses/>.
*/
/**
* Project Permission Group Create Exception
* @package project
*/
class ProjectPermissionGroupCreateException extends ProjectPermissionGroupException
{
function __construct($message = null)
{
parent::__construct($message);
}
}
?>
|
gpl-3.0
|
zeiss-microscopy/libCZI
|
Doc/html/classlib_c_z_i_1_1_i_czi_metadata-members.html
|
10436
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>libCZI: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script>
<script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">libCZI
</div>
<div id="projectbrief">Reading CZI documents made easy</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.1 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('classlib_c_z_i_1_1_i_czi_metadata.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">libCZI::ICziMetadata Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classlib_c_z_i_1_1_i_czi_metadata.html">libCZI::ICziMetadata</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#afe7294913f033998c7a0bb695d795c0f">EnumAttributes</a>(const std::function< bool(const std::wstring &attribName, const std::wstring &attribValue)> &enumFunc) const =0</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#a70385059cfda44a6f2d590a9a8d6ac3e">EnumChildren</a>(std::function< bool(std::shared_ptr< IXmlNodeRead >)> enumChildren)=0</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#a4e14de646b5624daf11b16ba42094c74">GetChildNodeReadonly</a>(const char *path)=0</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_czi_metadata.html#adf1a44d893d1f1aac6639bc39edda5af">GetDocumentInfo</a>()=0</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_czi_metadata.html">libCZI::ICziMetadata</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_czi_metadata.html#afd73a12ac5a04a725ad9f3d130f4e2de">GetXml</a>()=0</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_czi_metadata.html">libCZI::ICziMetadata</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_czi_metadata.html#aa0465981ea6ea4d2165c7dd20e4b6833">IsXmlValid</a>() const =0</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_czi_metadata.html">libCZI::ICziMetadata</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#a7a17744c795303a9c446b5ccf850a90c">Name</a>() const =0</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#a7cf31fe7e079358d5436289ee678e0df">TryGetAttribute</a>(const wchar_t *attributeName, std::wstring *attribValue) const =0</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#ab09530bf1a4633c499660da018bc0d89">TryGetValue</a>(std::wstring *value) const =0</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr>
<tr><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#a2d12c91c7ff8ef3b822d623f6c04b14f">TryGetValueAsBool</a>(bool *p)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#a3bb9226ebe823d70968e694407f90bc7">TryGetValueAsDouble</a>(double *p)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#af3070ab11416f7658e198d8cd89210c0">TryGetValueAsFloat</a>(float *p)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#ad03686b294d2271dfa1a44c88c0751bc">TryGetValueAsInt32</a>(std::int32_t *p)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#adbf74c7628e88a54791b315c12b176bf">TryGetValueAsInt64</a>(std::int64_t *p)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#a0cbe508500066393c05e5ebdfc3c7df7">TryGetValueAsUInt32</a>(std::uint32_t *p)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html#a6a250a2916f16985eff64b7a82ed2d99">TryGetValueAsUInt64</a>(std::uint64_t *p)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>~ICziMetadata</b>() (defined in <a class="el" href="classlib_c_z_i_1_1_i_czi_metadata.html">libCZI::ICziMetadata</a>)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_czi_metadata.html">libCZI::ICziMetadata</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>~IXmlNodeRead</b>() (defined in <a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a>)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_i_xml_node_read.html">libCZI::IXmlNodeRead</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.1 </li>
</ul>
</div>
</body>
</html>
|
gpl-3.0
|
clsid2/mpc-hc
|
src/mpc-hc/CMPCThemeStatic.h
|
476
|
#pragma once
#include <afxwin.h>
class CMPCThemeStatic :
public CStatic
{
DECLARE_DYNAMIC(CMPCThemeStatic)
public:
CMPCThemeStatic();
virtual ~CMPCThemeStatic();
void setFileDialogChild(bool set) { isFileDialogChild = set; };
DECLARE_MESSAGE_MAP()
afx_msg void OnPaint();
afx_msg void OnNcPaint();
afx_msg void OnEnable(BOOL bEnable);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
protected:
bool isFileDialogChild;
};
|
gpl-3.0
|
Physwf/physwf-x-lab
|
x0/Include/Algo/AllOf.h
|
962
|
#pragma once
#include "CoreTypes.h"
#include "Templates/Invoke.h"
namespace Algo
{
/**
* Checks if every element in the range is truthy.
*
* @param Range The range to check.
*
* @return true if all the elements are truthy, false otherwise.
*/
template <typename RangeType>
inline bool AllOf(const RangeType& Range)
{
for (const auto& Element : Range)
{
if (!Element)
{
return false;
}
}
return true;
}
/**
* Checks if every projection of the elements in the range is truthy.
*
* @param Range The range to check.
* @param Projection The projection to apply to each element.
*
* @return true if all the projections are truthy, false otherwise.
*/
template <typename RangeType, typename ProjectionType>
inline bool AllOf(const RangeType& Range, ProjectionType Projection)
{
for (const auto& Element : Range)
{
if (!Invoke(Projection, Element))
{
return false;
}
}
return true;
}
}
|
gpl-3.0
|
Forlini91/Empire-Earth---DB-Editor
|
doc/constants/ControlType.html
|
25034
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="it">
<head>
<!-- Generated by javadoc (1.8.0_51) on Sun Sep 11 12:16:02 CEST 2016 -->
<title>ControlType</title>
<meta name="date" content="2016-09-11">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ControlType";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":9,"i3":10,"i4":9,"i5":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ControlType.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../constants/AttributeCode.html" title="enum in constants"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../constants/EffectCode.html" title="enum in constants"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?constants/ControlType.html" target="_top">Frames</a></li>
<li><a href="ControlType.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum.constant.summary">Enum Constants</a> | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum.constant.detail">Enum Constants</a> | </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">constants</div>
<h2 title="Enum ControlType" class="title">Enum ControlType</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../constants/ControlType.html" title="enum in constants">ControlType</a>></li>
<li>
<ul class="inheritance">
<li>constants.ControlType</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../constants/EnumValue.html" title="interface in constants">EnumValue</a>, java.io.Serializable, java.lang.Comparable<<a href="../constants/ControlType.html" title="enum in constants">ControlType</a>></dd>
</dl>
<hr>
<br>
<pre>public enum <span class="typeNameLabel">ControlType</span>
extends java.lang.Enum<<a href="../constants/ControlType.html" title="enum in constants">ControlType</a>>
implements <a href="../constants/EnumValue.html" title="interface in constants">EnumValue</a></pre>
<div class="block">Controls codes used in an UI contro event entry.
They define the event condition of an UI element.</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>MarcoForlini</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum.constant.summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C0_Update_Controls">C0_Update_Controls</a></span></code>
<div class="block">Unknown event</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1000_Slider">C1000_Slider</a></span></code>
<div class="block">Move slider</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1001_Check">C1001_Check</a></span></code>
<div class="block">Check a checkbox</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1002_Uncheck">C1002_Uncheck</a></span></code>
<div class="block">Uncheck a checkbox</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1003_List_select">C1003_List_select</a></span></code>
<div class="block">Select an element in the list</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1004_Double_click">C1004_Double_click</a></span></code>
<div class="block">Double click an element</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1007_Password">C1007_Password</a></span></code>
<div class="block">Input password</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1008_Single_click">C1008_Single_click</a></span></code>
<div class="block">Click an element</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1009_Done_typing">C1009_Done_typing</a></span></code>
<div class="block">Stop typing in the field</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1010_Hovering">C1010_Hovering</a></span></code>
<div class="block">Move your mouse on the element</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1011_Not_hovering">C1011_Not_hovering</a></span></code>
<div class="block">Mouve your mouse away from the element</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#C1012_Chat">C1012_Chat</a></span></code>
<div class="block">Type in the chat box</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../constants/ControlType.html#NONE">NONE</a></span></code>
<div class="block">No condition</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../constants/ControlType.html#code">code</a></span></code>
<div class="block">Code used in the dat files</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../constants/ControlType.html#name">name</a></span></code>
<div class="block">Name to be shown in the UI</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../constants/ControlType.html#getCode--">getCode</a></span>()</code>
<div class="block">Gets the code used in the dat files</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../constants/ControlType.html#getName--">getName</a></span>()</code>
<div class="block">Gets the name to be shown in the UI</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>static <a href="../constants/ControlType.html" title="enum in constants">ControlType</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../constants/ControlType.html#parseValue-int-">parseValue</a></span>(int code)</code>
<div class="block">Parse the code and return the relative enum.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../constants/ControlType.html#toString--">toString</a></span>()</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>static <a href="../constants/ControlType.html" title="enum in constants">ControlType</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../constants/ControlType.html#valueOf-java.lang.String-">valueOf</a></span>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>static <a href="../constants/ControlType.html" title="enum in constants">ControlType</a>[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../constants/ControlType.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.constants.EnumValue">
<!-- -->
</a>
<h3>Methods inherited from interface constants.<a href="../constants/EnumValue.html" title="interface in constants">EnumValue</a></h3>
<code><a href="../constants/EnumValue.html#buildUIName--">buildUIName</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum.constant.detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="NONE">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>NONE</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> NONE</pre>
<div class="block">No condition</div>
</li>
</ul>
<a name="C0_Update_Controls">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C0_Update_Controls</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C0_Update_Controls</pre>
<div class="block">Unknown event</div>
</li>
</ul>
<a name="C1000_Slider">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1000_Slider</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1000_Slider</pre>
<div class="block">Move slider</div>
</li>
</ul>
<a name="C1001_Check">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1001_Check</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1001_Check</pre>
<div class="block">Check a checkbox</div>
</li>
</ul>
<a name="C1002_Uncheck">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1002_Uncheck</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1002_Uncheck</pre>
<div class="block">Uncheck a checkbox</div>
</li>
</ul>
<a name="C1003_List_select">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1003_List_select</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1003_List_select</pre>
<div class="block">Select an element in the list</div>
</li>
</ul>
<a name="C1004_Double_click">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1004_Double_click</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1004_Double_click</pre>
<div class="block">Double click an element</div>
</li>
</ul>
<a name="C1007_Password">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1007_Password</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1007_Password</pre>
<div class="block">Input password</div>
</li>
</ul>
<a name="C1008_Single_click">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1008_Single_click</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1008_Single_click</pre>
<div class="block">Click an element</div>
</li>
</ul>
<a name="C1009_Done_typing">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1009_Done_typing</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1009_Done_typing</pre>
<div class="block">Stop typing in the field</div>
</li>
</ul>
<a name="C1010_Hovering">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1010_Hovering</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1010_Hovering</pre>
<div class="block">Move your mouse on the element</div>
</li>
</ul>
<a name="C1011_Not_hovering">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>C1011_Not_hovering</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1011_Not_hovering</pre>
<div class="block">Mouve your mouse away from the element</div>
</li>
</ul>
<a name="C1012_Chat">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>C1012_Chat</h4>
<pre>public static final <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> C1012_Chat</pre>
<div class="block">Type in the chat box</div>
</li>
</ul>
</li>
</ul>
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="name">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>name</h4>
<pre>public final java.lang.String name</pre>
<div class="block">Name to be shown in the UI</div>
</li>
</ul>
<a name="code">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>code</h4>
<pre>public final int code</pre>
<div class="block">Code used in the dat files</div>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../constants/ControlType.html" title="enum in constants">ControlType</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (ControlType c : ControlType.values())
System.out.println(c);
</pre></div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>an array containing the constants of this enum type, in the order they are declared</dd>
</dl>
</li>
</ul>
<a name="valueOf-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>the enum constant with the specified name</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd>
</dl>
</li>
</ul>
<a name="getName--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getName</h4>
<pre>public java.lang.String getName()</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../constants/EnumValue.html#getName--">EnumValue</a></code></span></div>
<div class="block">Gets the name to be shown in the UI</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../constants/EnumValue.html#getName--">getName</a></code> in interface <code><a href="../constants/EnumValue.html" title="interface in constants">EnumValue</a></code></dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The UI name</dd>
</dl>
</li>
</ul>
<a name="getCode--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCode</h4>
<pre>public int getCode()</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../constants/EnumValue.html#getCode--">EnumValue</a></code></span></div>
<div class="block">Gets the code used in the dat files</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../constants/EnumValue.html#getCode--">getCode</a></code> in interface <code><a href="../constants/EnumValue.html" title="interface in constants">EnumValue</a></code></dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The dat code</dd>
</dl>
</li>
</ul>
<a name="parseValue-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>parseValue</h4>
<pre>public static <a href="../constants/ControlType.html" title="enum in constants">ControlType</a> parseValue(int code)</pre>
<div class="block">Parse the code and return the relative enum.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>code</code> - The code</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The relative enum</dd>
</dl>
</li>
</ul>
<a name="toString--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>toString</code> in class <code>java.lang.Enum<<a href="../constants/ControlType.html" title="enum in constants">ControlType</a>></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ControlType.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../constants/AttributeCode.html" title="enum in constants"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../constants/EffectCode.html" title="enum in constants"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?constants/ControlType.html" target="_top">Frames</a></li>
<li><a href="ControlType.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum.constant.summary">Enum Constants</a> | </li>
<li><a href="#field.summary">Field</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum.constant.detail">Enum Constants</a> | </li>
<li><a href="#field.detail">Field</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
gpl-3.0
|
murat-o/weddingdress
|
sw/code/mcu/src/lpcopen/uart_5411x.h
|
33708
|
/*
* @brief LPC5411X UART driver
*
* @note
* Copyright(C) NXP Semiconductors, 2015
* All rights reserved.
*
* @par
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* LPC products. This software is supplied "AS IS" without any warranties of
* any kind, and NXP Semiconductors and its licensor disclaim any and
* all warranties, express or implied, including all implied warranties of
* merchantability, fitness for a particular purpose and non-infringement of
* intellectual property rights. NXP Semiconductors assumes no responsibility
* or liability for the use of the software, conveys no license or rights under any
* patent, copyright, mask work right, or any other intellectual property rights in
* or to any products. NXP Semiconductors reserves the right to make changes
* in the software without notification. NXP Semiconductors also makes no
* representation or warranty that such application will be suitable for the
* specified use without further testing or modification.
*
* @par
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, under NXP Semiconductors' and its
* licensor's relevant copyrights in the software, without fee, provided that it
* is used in conjunction with NXP Semiconductors microcontrollers. This
* copyright, permission, and disclaimer notice must appear in all copies of
* this code.
*/
#ifndef __UART_5411X_H_
#define __UART_5411X_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "ring_buffer.h"
/** @defgroup UART_5411X CHIP: LPC5411X UART Driver
* @ingroup CHIP_5411X_DRIVERS
* @{
*/
/*******************
* EXPORTED MACROS *
********************/
#define ECHO_EN 1
#define ECHO_DIS 0
/** @brief UART Registers */
typedef struct { /* UART registers Structure */
__IO uint32_t CFG; /*!< Offset: 0x000 Configuration register */
__IO uint32_t CTL; /*!< Offset: 0x004 Control register */
__IO uint32_t STAT; /*!< Offset: 0x008 Status register */
__IO uint32_t INTENSET; /*!< Offset: 0x00C Interrupt Enable Read and Set register */
__O uint32_t INTENCLR; /*!< Offset: 0x010 Interrupt Enable Clear register @cond */
__I uint32_t RESERVED0A[3]; /*!< Offset: 0x014 Reserved register @endcond */
__IO uint32_t BRG; /*!< Offset: 0x020 Baud Rate Generator register */
__I uint32_t INTSTAT; /*!< Offset: 0x024 Interrupt Status register */
__IO uint32_t OSR; /*!< Offset: 0x028 Oversampling register */
__IO uint32_t ADDR; /*!< Offset: 0x02C Address register (for automatic address matching) @cond */
__I uint32_t RESERVED0[884]; /*!< Offset: 0x030 Reserved member */
/** UART FIFO Specific registers @endcond */
__IO uint32_t FIFOCFG; /*!< Offset: 0xE00 FIFO Configuration register */
__IO uint32_t FIFOSTAT; /*!< Offset: 0xE04 FIFO Status register */
__IO uint32_t FIFOTRIG; /*!< Offset: 0xE08 FIFO Trigger level register @cond */
__I uint32_t RESERVED1; /*!< Offset: 0xE0C Reserved register @endcond */
__IO uint32_t FIFOINTENSET; /*!< Offset: 0xE10 FIFO Interrupt enable SET register */
__IO uint32_t FIFOINTENCLR; /*!< Offset: 0xE14 FIFO Interrupt enable CLEAR register */
__IO uint32_t FIFOINTSTAT; /*!< Offset: 0xE18 FIFO Interrupt Status register @cond */
__I uint32_t RESERVED2; /*!< Offset: 0xE1C Reserved register @endcond */
__O uint32_t FIFOWR; /*!< Offset: 0xE20 FIFO Data write register @cond */
__I uint32_t RESERVED3[3]; /*!< Offset: 0xE24 Reserved register @endcond */
__I uint32_t FIFORD; /*!< Offset: 0xE30 FIFO Data read register @cond */
__I uint32_t RESERVED4[3]; /*!< Offset: 0xE24 Reserved register @endcond */
__I uint32_t FIFORDNOPOP; /*!< Offset: 0xE40 FIFO Data peek (read without popping out of queue) register @cond */
__I uint32_t RESERVED5[109]; /*!< Offset: 0xE44 Reserved register */
/** FLEXCOMM Interface registers @endcond */
__IO uint32_t PSELID; /*!< Offset: 0xFF8 Peripheral select/identification register */
__I uint32_t PID; /*!< Offset: 0xFFC Module identification register */
} LPC_USART_T;
/**
* @brief UART CFG register definitions
*/
#define UART_CFG_BITMASK (0x00fddbfd)
#define UART_CFG_ENABLE (0x01 << 0)
#define UART_CFG_DATALEN_7 (0x00 << 2) /*!< UART 7 bit length mode */
#define UART_CFG_DATALEN_8 (0x01 << 2) /*!< UART 8 bit length mode */
#define UART_CFG_DATALEN_9 (0x02 << 2) /*!< UART 9 bit length mode */
#define UART_CFG_PARITY_NONE (0x00 << 4) /*!< No parity */
#define UART_CFG_PARITY_EVEN (0x02 << 4) /*!< Even parity */
#define UART_CFG_PARITY_ODD (0x03 << 4) /*!< Odd parity */
#define UART_CFG_STOPLEN_1 (0x00 << 6) /*!< UART One Stop Bit Select */
#define UART_CFG_STOPLEN_2 (0x01 << 6) /*!< UART Two Stop Bits Select */
#define UART_CFG_MODE32K (0x01 << 7) /*!< UART 32K MODE */
#define UART_CFG_LINMODE (0x01 << 8) /*!< UART LIN MODE */
#define UART_CFG_CTSEN (0x01 << 9) /*!< CTS enable bit */
#define UART_CFG_SYNCEN (0x01 << 11) /*!< Synchronous mode enable bit */
#define UART_CFG_CLKPOL (0x01 << 12) /*!< Un_RXD rising edge sample enable bit */
#define UART_CFG_SYNCMST (0x01 << 14) /*!< Select master mode (synchronous mode) enable bit */
#define UART_CFG_LOOP (0x01 << 15) /*!< Loopback mode enable bit */
#define UART_CFG_IOMODE (0x01 << 16) /*!< enable bit standard UART / IrDA UART */
#define UART_CFG_OETA (0x01 << 18) /*!< Output Enable Turnaround time enable for RS-485 operation */
#define UART_CFG_AUTOADDR (0x01 << 19) /*!< Automatic Address matching enable */
#define UART_CFG_OESEL (0x01 << 20) /*!< Output Enable Select */
#define UART_CFG_OEPOL (0x01 << 21) /*!< Output Enable Polarity */
#define UART_CFG_RXPOL (0x01 << 22) /*!< Receive data polarity */
#define UART_CFG_TXPOL (0x01 << 23) /*!< Transmit data polarity */
/**
* @brief UART CTRL register definitions
*/
#define UART_CTRL_TXBRKEN (0x01 << 1) /*!< Continuous break enable bit */
#define UART_CTRL_ADDRDET (0x01 << 2) /*!< Address detect mode enable bit */
#define UART_CTRL_TXDIS (0x01 << 6) /*!< Transmit disable bit */
#define UART_CTRL_CC (0x01 << 8) /*!< Continuous Clock mode enable bit */
#define UART_CTRL_CLRCCONRX (0x01 << 9) /*!< Clear Continuous Clock bit */
#define UART_CTRL_AUTOBAUD (0x01 << 16) /*!< Auto baud bit */
/**
* @brief UART STAT register definitions
*/
#define UART_STAT_RXIDLE (0x01 << 1) /*!< Receiver idle */
#define UART_STAT_TXIDLE (0x01 << 3) /*!< Transmitter idle */
#define UART_STAT_CTS (0x01 << 4) /*!< Status of CTS signal */
#define UART_STAT_DELTACTS (0x01 << 5) /*!< Change in CTS state */
#define UART_STAT_TXDISINT (0x01 << 6) /*!< Transmitter disabled */
#define UART_STAT_RXBRK (0x01 << 10) /*!< Received break */
#define UART_STAT_DELTARXBRK (0x01 << 11) /*!< Change in receive break detection */
#define UART_STAT_START (0x01 << 12) /*!< Start detected */
#define UART_STAT_FRM_ERRINT (0x01 << 13) /*!< Framing Error interrupt flag */
#define UART_STAT_PAR_ERRINT (0x01 << 14) /*!< Parity Error interrupt flag */
#define UART_STAT_RXNOISEINT (0x01 << 15) /*!< Received Noise interrupt flag */
#define UART_STAT_ABERR (0x01 << 16) /*!< Auto baud error flag */
/**
* @brief UART INTENSET/INTENCLR/INTSTAT register definitions
*/
#define UART_INT_TXIDLE (0x01 << 3) /*!< Transmit idle interrupt */
#define UART_INT_DELTACTS (0x01 << 5) /*!< Change in CTS state interrupt */
#define UART_INT_TXDIS (0x01 << 6) /*!< Transmitter disable interrupt */
#define UART_INT_DELTARXBRK (0x01 << 11) /*!< Change in receiver break detection interrupt */
#define UART_INT_START (0x01 << 12) /*!< Start detect interrupt */
#define UART_INT_FRAMERR (0x01 << 13) /*!< Frame error interrupt */
#define UART_INT_PARITYERR (0x01 << 14) /*!< Parity error interrupt */
#define UART_INT_RXNOISE (0x01 << 15) /*!< Received noise interrupt */
#define UART_INT_ABERR (0x01 << 16) /*!< Auto-baud error interrupt */
/**
* @brief UART FIFO Configuration register bits
*/
#define UART_FIFOCFG_BITMASK (0x7F033) /*!< Register mask bit @endcond */
#define UART_FIFOCFG_ENABLETX (1 << 0) /*!< Enable TX FIFO */
#define UART_FIFOCFG_ENABLERX (1 << 1) /*!< Enable RX FIFO */
#define UART_FIFOCFG_DMATX (1 << 12) /*!< Enable DMA TX */
#define UART_FIFOCFG_DMARX (1 << 13) /*!< Enable DMA RX */
#define UART_FIFOCFG_WAKETX (1 << 14) /*!< Enable wakeup triggered by TX */
#define UART_FIFOCFG_WAKERX (1 << 15) /*!< Enable wakeup triggered by RX */
#define UART_FIFOCFG_EMPTYTX (1 << 16) /*!< Empty the TX FIFO */
#define UART_FIFOCFG_EMPTYRX (1 << 17) /*!< Empty the RX FIFO */
/**
* @brief UART FIFO Status register defines
*/
#define UART_FIFO_DEPTH (16) /** UART-FIFO How many entries are in the FIFO */
#define UART_FIFOSTAT_BITMASK (0x1F1FFB) /** UART-FIFO STAT Register BitMask */
#define UART_FIFOSTAT_TXERR (1 << 0) /*!< UART TX Error */
#define UART_FIFOSTAT_RXERR (1 << 1) /*!< UART RX Error */
#define UART_FIFOSTAT_PERIPH (1 << 3) /*!< Peripheral interrupt */
#define UART_FIFOSTAT_TXEMPTY (1 << 4) /*!< TXFIFO Empty */
#define UART_FIFOSTAT_TXNOTFULL (1 << 5) /*!< TXFIFO Not Full */
#define UART_FIFOSTAT_RXNOTEMPTY (1 << 6) /*!< RXFIFO Not empty */
#define UART_FIFOSTAT_RXFULL (1 << 7) /*!< RX FIFO Full */
#define UART_FIFOSTAT_TXLVL(lvl) (((lvl) >> 8) & 0x1F) /*!< Get TX Level from status */
#define UART_FIFOSTAT_RXLVL(lvl) (((lvl) >> 16) & 0x1F) /*!< Get TX Level from status */
/**
* @brief UART FIFO trigger settings register defines
*/
#define UART_FIFOTRIG_BITMASK (0x000f0f03) /** UART FIFO trigger settings Register BitMask */
#define UART_FIFOTRIG_TXLVLENA (1 << 0) /*!< TX level enable*/
#define UART_FIFOTRIG_RXLVLENA (1 << 1) /*!< RX level enable */
#define UART_FIFOTRIG_TXLVL(lvl) ((lvl & 0x0f) << 8) /*!< Set TX Level trigger */
#define UART_FIFOTRIG_RXLVL(lvl) ((lvl & 0x0f) << 16) /*!< Set RX Level trigger */
/**
* @brief UART FIFO Interrupt enable/disable/status [INTSET/INTCLR/INTSTAT and FIFOINTSET/FIFOINTCLR/FIFOINTSTAT registers]
*/
#define UART_FIFOINT_BITMASK (0x001F) /** FIFO interrupt Bit mask */
#define UART_FIFOINT_TXERR (1 << 0) /** TX error interrupt [BIT-0 of FIFOINTENSET/FIFOINTENCLR/FIFOINTSTAT register] */
#define UART_FIFOINT_RXERR (1 << 1) /** RX error interrupt [BIT-1 of FIFOINTENSET/FIFOINTENCLR/FIFOINTSTAT register] */
#define UART_FIFOINT_TXLVL (1 << 2) /** TX FIFO ready interrupt [BIT-2 of FIFOINTENSET/FIFOINTENCLR/FIFOINTSTAT register] */
#define UART_FIFOINT_RXLVL (1 << 3) /** RX Data ready interrupt [BIT-3 of FIFOINTENSET/FIFOINTENCLR/FIFOINTSTAT register] */
#define UART_FIFOINT_PERINT (1 << 4) /** UART peripheral interrupt [BIT-4 of FIFOINTSTAT register] */
/**
* @brief UART Baud rate calculation structure
* @note
* Use oversampling (@a ovr) value other than 16, only if the difference
* between the actual baud and desired baud has an unacceptable error percentage.
* Smaller @a ovr values can cause the sampling position within the data-bit
* less accurate an may potentially cause more noise errors or incorrect data
* set ovr to < 10 only when there is no other higher values suitable.
*/
typedef struct {
uint32_t clk; /*!< IN: Base clock to fractional divider; OUT: "Base clock rate for UART" */
uint32_t baud; /*!< IN: Required baud rate; OUT: Actual baud rate */
uint8_t ovr; /*!< IN: Number of desired over samples [0-auto detect or values 5 to 16]; OUT: Auto detected over samples [unchanged if IN is not 0] */
uint8_t mul; /*!< IN: 0 - calculate MUL, 1 - do't calculate (@a clk) has UART base clock; OUT: MUL value to be set in FRG register */
uint16_t div; /*!< OUT: Integer divider to divide the "Base clock rate for UART" */
} UART_BAUD_T;
/**
* @brief UART statistics structure
* @note
* Maintains current UART statistics.
*/
typedef struct {
uint32_t interrupts; /*!< count: interrupts */
uint32_t lvl_tx; /*!< count: transmit interrupts */
uint32_t lvl_rx; /*!< count: receive interrupts */
uint32_t fifo_err_tx; /*!< count: FIFO transmit errors */
uint32_t fifo_err_rx; /*!< count: FIFO receive errors */
uint32_t uart_cts; /*!< count: UART CTS */
uint32_t uart_break; /*!< count: UART break */
uint32_t uart_start; /*!< count: UART RX starts */
uint32_t uart_err_frame; /*!< count: UART frame errors */
uint32_t uart_err_parity; /*!< count: UART parity errors */
uint32_t uart_err_rx_noise; /*!< count: UART receive noise errors */
uint32_t uart_err_auto_baud; /*!< count: UART auto-baud errors */
} UART_STATISTICS_T;
/**
* @brief Enable the UART
* @param pUART : Pointer to selected UARTx peripheral
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_Enable(LPC_USART_T *pUART)
{
pUART->CFG |= UART_CFG_ENABLE;
}
/**
* @brief Disable the UART
* @param pUART : Pointer to selected UARTx peripheral
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_Disable(LPC_USART_T *pUART)
{
pUART->CFG &= ~UART_CFG_ENABLE;
}
/**
* @brief Enable transmission on UART TxD pin
* @param pUART : Pointer to selected pUART peripheral
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_TXEnable(LPC_USART_T *pUART)
{
pUART->CTL &= ~UART_CTRL_TXDIS;
}
/**
* @brief Disable transmission on UART TxD pin
* @param pUART : Pointer to selected pUART peripheral
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_TXDisable(LPC_USART_T *pUART)
{
pUART->CTL |= UART_CTRL_TXDIS;
}
/**
* @brief Set auto baud
* @param pUART : Pointer to selected pUART peripheral
* @return true if auto baud succeeds, false if fails
*/
__STATIC_INLINE uint32_t Chip_UART_AutoBaud(LPC_USART_T *pUART)
{
while ( (pUART->STAT & UART_STAT_RXIDLE) != UART_STAT_RXIDLE ) {}
pUART->CTL |= UART_CTRL_AUTOBAUD;
while ( pUART->CTL & UART_CTRL_AUTOBAUD ) {
if ( pUART->STAT & UART_STAT_ABERR ) {
pUART->STAT = UART_STAT_ABERR;
return false;
}
}
return true;
}
/**
* @brief Transmit a single data byte through the UART peripheral
* @param pUART : Pointer to selected UART peripheral
* @param data : Byte to transmit
* @return Nothing
* @note This function attempts to place a byte into the UART transmit
* holding register regard regardless of UART state.
*/
__STATIC_INLINE void Chip_UART_SendByte(LPC_USART_T *pUART, uint8_t data)
{
pUART->FIFOWR = (uint32_t)data;
}
/**
* @brief Read a single byte data from the UART peripheral
* @param pUART : Pointer to selected UART peripheral
* @return A single byte of data read
* @note This function reads a byte from the UART receive FIFO or
* receive hold register regard regardless of UART state.
*/
__STATIC_INLINE uint32_t Chip_UART_ReadByte(LPC_USART_T *pUART)
{
/* Strip off undefined reserved bits, keep 9 lower bits */
return (uint32_t) (pUART->FIFORD & 0x000001FF);
}
/**
* @brief Enable UART interrupts
* @param pUART : Pointer to selected UART peripheral
* @param intMask : OR'ed Interrupts to enable
* @return Nothing
* @note Use an OR'ed value of UART_INTEN_* definitions with this function
* to enable specific UART interrupts.
*/
__STATIC_INLINE void Chip_UART_IntEnable(LPC_USART_T *pUART, uint32_t intMask)
{
pUART->INTENSET = intMask;
}
/**
* @brief Disable UART interrupts
* @param pUART : Pointer to selected UART peripheral
* @param intMask : OR'ed Interrupts to disable
* @return Nothing
* @note Use an OR'ed value of UART_INTEN_* definitions with this function
* to disable specific UART interrupts.
*/
__STATIC_INLINE void Chip_UART_IntDisable(LPC_USART_T *pUART, uint32_t intMask)
{
pUART->INTENCLR = intMask;
}
/**
* @brief Returns UART interrupts that are enabled
* @param pUART : Pointer to selected UART peripheral
* @return Returns the enabled UART interrupts
* @note Use an OR'ed value of UART_INTEN_* definitions with this function
* to determine which interrupts are enabled. You can check
* for multiple enabled bits if needed.
*/
__STATIC_INLINE uint32_t Chip_UART_GetIntsEnabled(LPC_USART_T *pUART)
{
return pUART->INTENSET;
}
/**
* @brief Get UART interrupt status
* @param pUART : The base of UART peripheral on the chip
* @return The UART interrupt status register
* @note This register does not indicate UART pending interrupts.
* It indicates the enabled interrupts. To get pending interrupts,
* read the UART status register.
*/
__STATIC_INLINE uint32_t Chip_UART_GetIntStatus(LPC_USART_T *pUART)
{
return pUART->INTSTAT;
}
/**
* @brief Configure data width, parity and stop bits
* @param pUART : Pointer to selected pUART peripheral
* @param config : UART configuration, OR'ed values of select UART_CFG_* defines
* @return Nothing
* @note Select OR'ed config options for the UART from the UART_CFG_PARITY_*,
* UART_CFG_STOPLEN_*, and UART_CFG_DATALEN_* definitions. For example,
* a configuration of 8 data bits, 1 stop bit, and even (enabled) parity would be
* (UART_CFG_DATALEN_8 | UART_CFG_STOPLEN_1 | UART_CFG_PARITY_EVEN). Will not
* alter other bits in the CFG register.
*/
__STATIC_INLINE void Chip_UART_ConfigData(LPC_USART_T *pUART, uint32_t config)
{
pUART->CFG = (pUART->CFG & UART_CFG_BITMASK) | config;
}
/**
* @brief Get the UART status register
* @param pUART : Pointer to selected UARTx peripheral
* @return UART status register
* @note Multiple statuses may be pending. Mask the return value
* with one or more UART_STAT_* definitions to determine
* statuses.
*/
__STATIC_INLINE uint32_t Chip_UART_GetStatus(LPC_USART_T *pUART)
{
return pUART->STAT;
}
/**
* @brief Clear the UART status register
* @param pUART : Pointer to selected UARTx peripheral
* @param stsMask : OR'ed statuses to disable
* @return Nothing
* @note Multiple interrupts may be pending. Mask the return value
* with one or more UART_INTEN_* definitions to determine
* pending interrupts.
*/
__STATIC_INLINE void Chip_UART_ClearStatus(LPC_USART_T *pUART, uint32_t stsMask)
{
pUART->STAT = stsMask;
}
/**
* @brief Get the current status of UART controller FIFO
* @param pUART : The base of UART peripheral on the chip
* @return UART Status (Or-ed bit value of UART_FIFOSTAT_*)
* @note Mask the return value with a value of type UART_FIFOSTAT_* to determine
* if that status is active.
*/
__STATIC_INLINE uint32_t Chip_UART_GetFIFOStatus(LPC_USART_T *pUART)
{
return pUART->FIFOSTAT;
}
/**
* @brief Clear the FIFO status register
* @param pUART : The base of the UART peripheral on the chip
* @param mask : Mask of the status bits that needs to be cleared
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_ClearFIFOStatus(LPC_USART_T *pUART, uint32_t mask)
{
pUART->FIFOSTAT = mask;
}
/**
* @brief Setup the trigger level for UART FIFO
* @param pUART : The base of the UART peripheral on chip
* @param tx_lvl : TX Trigger level [Valid values 0 to 15]
* @param rx_lvl : RX Trigger level [Valid values 0 to 15]
* @return Nothing
* @note When @a tx_lvl = 0; trigger will happen when TX FIFO is empty
* if @a tx_lvl = 15; trigger will happen when TX FIFO has at least one free space<br>
* When @a rx_lvl = 0; trigger will happen when RX FIFO has at least one byte in it,
* if @a rx_lvl = 15; trigger will happen when RX FIFO is full and cannot receive anymore data
*/
__STATIC_INLINE void Chip_UART_SetFIFOTrigLevel(LPC_USART_T *pUART, uint8_t tx_lvl, uint8_t rx_lvl)
{
pUART->FIFOTRIG = (UART_FIFOTRIG_TXLVLENA|UART_FIFOTRIG_RXLVLENA) | UART_FIFOTRIG_TXLVL(tx_lvl) | UART_FIFOTRIG_RXLVL(rx_lvl);
}
/**
* @brief Enable a UART FIFO interrupt
* @param pUART : The base of UART peripheral on the chip
* @param intMask : Or'ed value of UART_FIFOINT_* values to enable
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_EnableFIFOInts(LPC_USART_T *pUART, uint32_t intMask)
{
pUART->FIFOINTENSET = intMask & UART_FIFOINT_BITMASK;
}
/**
* @brief Disable a UART FIFO interrupt
* @param pUART : The base of UART peripheral on the chip
* @param intMask : Or'ed value of UART_FIFOINT_* values to disable (See #UART_FIFOINT_BITMASK)
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_DisableFIFOInts(LPC_USART_T *pUART, uint32_t intMask)
{
pUART->FIFOINTENCLR = intMask & UART_FIFOINT_BITMASK;
}
/**
* @brief Return enabled UART FIFO interrupts
* @param pUART : The base of UART peripheral on the chip
* @return An Or'ed value of UART_FIFOINT_* values
*/
__STATIC_INLINE uint32_t Chip_UART_GetFIFOEnabledInts(LPC_USART_T *pUART)
{
return pUART->FIFOINTENSET & UART_FIFOINT_BITMASK;
}
/**
* @brief Return pending UART FIFO interrupts
* @param pUART : The base of UART peripheral on the chip
* @return An Or'ed value of UART_FIFOINT_* values
*/
__STATIC_INLINE uint32_t Chip_UART_GetFIFOPendingInts(LPC_USART_T *pUART)
{
return pUART->FIFOINTSTAT & UART_FIFOINT_BITMASK;
}
/**
* @brief Set FIFO Configuration register
* @param pUART : The base of UART peripheral on the chip
* @param cfg : Configuration value mask (OR'ed UART_FIFOCFG_* values like #UART_FIFOCFG_ENABLETX)
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_SetFIFOCfg(LPC_USART_T *pUART, uint32_t cfg)
{
pUART->FIFOCFG = (pUART->FIFOCFG & UART_FIFOCFG_BITMASK) | cfg;
}
/**
* @brief Clear FIFO Configuration register
* @param pUART : The base of UART peripheral on the chip
* @param cfg : Configuration value mask (OR'ed UART_FIFOCFG_* values like #UART_FIFOCFG_ENABLETX)
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_ClearFIFOCfg(LPC_USART_T *pUART, uint32_t cfg)
{
pUART->FIFOCFG = pUART->FIFOCFG & (UART_FIFOCFG_BITMASK & ~cfg);
}
/**
* @brief Flush FIFOs
* @param pUART : The base of UART peripheral on the chip
* @return Nothing
*/
__STATIC_INLINE void Chip_UART_FlushFIFOs(LPC_USART_T *pUART)
{
Chip_UART_SetFIFOCfg(pUART, UART_FIFOCFG_EMPTYTX | UART_FIFOCFG_EMPTYRX);
}
/**
* @brief Initialize the UART peripheral
* @param pUART : The base of UART peripheral on the chip
* @return 0 - On success; #ERR_FLEXCOMM_FUNCNOTSUPPORTED or #ERR_FLEXCOMM_NOTFREE on failure
*/
int Chip_UART_Init(LPC_USART_T *pUART);
/**
* @brief Deinitialize the UART peripheral
* @param pUART : The base of UART peripheral on the chip
* @return Nothing
*/
void Chip_UART_DeInit(LPC_USART_T *pUART);
/**
* @brief Configure UART for DMA
* @param pUART : The base of UART peripheral on the chip
* @return Nothing
*/
void Chip_UART_ConfigDMA(LPC_USART_T *pUART);
/**
* @brief Transmit a byte array through the UART peripheral (non-blocking)
* @param pUART : Pointer to selected UART peripheral
* @param data : Pointer to bytes to transmit
* @param numBytes : Number of bytes to transmit
* @return The actual number of bytes placed into the FIFO
* @note This function places data into the transmit FIFO until either
* all the data is in the FIFO or the FIFO is full. This function
* will not block in the FIFO is full. The actual number of bytes
* placed into the FIFO is returned. This function ignores errors.
*/
int Chip_UART_Send(LPC_USART_T *pUART, const void *data, int numBytes);
/**
* @brief Read data through the UART peripheral (non-blocking)
* @param pUART : Pointer to selected UART peripheral
* @param data : Pointer to bytes array to fill
* @param numBytes : Size of the passed data array
* @return The actual number of bytes read
* @note This function reads data from the receive FIFO until either
* all the data has been read or the passed buffer is completely full.
* This function will not block. This function ignores errors.
*/
int Chip_UART_Read(LPC_USART_T *pUART, void *data, int numBytes);
/**
* @brief Set baud rate for UART
* @param pUART : The base of UART peripheral on the chip
* @param baudrate: Baud rate to be set
* @return Actual baud rate set
* @note This function uses the FRG to generate the required
* clock, the FRG is shared by all the UARTs, hence calling this
* API for multiple UARTs can affect each other.
*/
uint32_t Chip_UART_SetBaud(LPC_USART_T *pUART, uint32_t baudrate);
/**
* @brief Transmit a byte array through the UART peripheral (blocking)
* @param pUART : Pointer to selected UART peripheral
* @param data : Pointer to data to transmit
* @param numBytes : Number of bytes to transmit
* @return The number of bytes transmitted
* @note This function will send or place all bytes into the transmit
* FIFO. This function will block until the last bytes are in the FIFO.
*/
int Chip_UART_SendBlocking(LPC_USART_T *pUART, const void *data, int numBytes);
/**
* @brief Read data through the UART peripheral (blocking)
* @param pUART : Pointer to selected UART peripheral
* @param data : Pointer to data array to fill
* @param numBytes : Size of the passed data array
* @return The size of the dat array
* @note This function reads data from the receive FIFO until the passed
* buffer is completely full. The function will block until full.
* This function ignores errors.
*/
int Chip_UART_ReadBlocking(LPC_USART_T *pUART, void *data, int numBytes);
/**
* @brief UART receive-only interrupt handler for ring buffers
* @param pUART : Pointer to selected UART peripheral
* @param pRB : Pointer to ring buffer structure to use
* @return Nothing
* @note If ring buffer support is desired for the receive side
* of data transfer, the UART interrupt should call this
* function for a receive based interrupt status.
*/
void Chip_UART_RXIntHandlerRB(LPC_USART_T *pUART, RINGBUFF_T *pRB);
/**
* @brief UART transmit-only interrupt handler for ring buffers
* @param pUART : Pointer to selected UART peripheral
* @param pRB : Pointer to ring buffer structure to use
* @return Nothing
* @note If ring buffer support is desired for the transmit side
* of data transfer, the UART interrupt should call this
* function for a transmit based interrupt status.
*/
void Chip_UART_TXIntHandlerRB(LPC_USART_T *pUART, RINGBUFF_T *pRB);
/**
* @brief Populate a transmit ring buffer and start UART transmit
* @param pUART : Pointer to selected UART peripheral
* @param pRB : Pointer to ring buffer structure to use
* @param data : Pointer to buffer to move to ring buffer
* @param count : Number of bytes to move
* @return The number of bytes placed into the ring buffer
* @note Will move the data into the TX ring buffer and start the
* transfer. If the number of bytes returned is less than the
* number of bytes to send, the ring buffer is considered full.
*/
uint32_t Chip_UART_SendRB(LPC_USART_T *pUART, RINGBUFF_T *pRB, const void *data, int count);
/**
* @brief Copy data from a receive ring buffer
* @param pUART : Pointer to selected UART peripheral
* @param pRB : Pointer to ring buffer structure to use
* @param data : Pointer to buffer to fill from ring buffer
* @param bytes : Size of the passed buffer in bytes
* @return The number of bytes placed into the ring buffer
* @note Will move the data from the RX ring buffer up to the
* the maximum passed buffer size. Returns 0 if there is
* no data in the ring buffer.
*/
int Chip_UART_ReadRB(LPC_USART_T *pUART, RINGBUFF_T *pRB, void *data, int bytes);
/**
* @brief UART receive/transmit interrupt handler for ring buffers
* @param pUART : Pointer to selected UART peripheral
* @param statistics : Pointer to statistics structure
* @param pRXRB : Pointer to transmit ring buffer
* @param pTXRB : Pointer to receive ring buffer
* @return Nothing
* @note This provides a basic implementation of the UART IRQ
* handler for support of a ring buffer implementation for
* transmit and receive.
*/
void Chip_UART_IRQHandlerRB(LPC_USART_T *pUART, UART_STATISTICS_T* statistics, RINGBUFF_T *pRXRB, RINGBUFF_T *pTXRB);
/**
* @brief UART receive/transmit interrupt handler for DMA
* @param pUART : Pointer to selected UART peripheral
* @param statistics : Pointer to statistics structure
* @return Nothing
* @note This interrupt service routine provides a basic implementation of the UART interrupt handler for DMA
*/
void Chip_UART_IRQHandlerDMA(LPC_USART_T *pUART, UART_STATISTICS_T* statistics);
#ifndef __DOXYGEN__
/* USART0 Defines */
#define LPC_USART0_BASE __APPEND3(LPC_FLEXCOMM,USART0_FLEXCOMM,_BASE)
#define LPC_USART0 ((LPC_USART_T *) LPC_USART0_BASE)
#define USART0_IRQHandler __APPEND3(FLEXCOMM,USART0_FLEXCOMM,_IRQHandler)
#define USART0_IRQn __APPEND3(FLEXCOMM,USART0_FLEXCOMM,_IRQn)
#define DMAREQ_USART0_RX __APPEND3(DMAREQ_FLEXCOMM,USART0_FLEXCOMM,_RX)
#define DMAREQ_USART0_TX __APPEND3(DMAREQ_FLEXCOMM,USART0_FLEXCOMM,_TX)
/* USART1 Defines */
#define LPC_USART1_BASE __APPEND3(LPC_FLEXCOMM,USART1_FLEXCOMM,_BASE)
#define LPC_USART1 ((LPC_USART_T *) LPC_USART1_BASE)
#define USART1_IRQHandler __APPEND3(FLEXCOMM,USART1_FLEXCOMM,_IRQHandler)
#define USART1_IRQn __APPEND3(FLEXCOMM,USART1_FLEXCOMM,_IRQn)
#define DMAREQ_USART1_RX __APPEND3(DMAREQ_FLEXCOMM,USART1_FLEXCOMM,_RX)
#define DMAREQ_USART1_TX __APPEND3(DMAREQ_FLEXCOMM,USART1_FLEXCOMM,_TX)
/* USART2 Defines */
#define LPC_USART2_BASE __APPEND3(LPC_FLEXCOMM,USART2_FLEXCOMM,_BASE)
#define LPC_USART2 ((LPC_USART_T *) LPC_USART2_BASE)
#define USART2_IRQHandler __APPEND3(FLEXCOMM,USART2_FLEXCOMM,_IRQHandler)
#define USART2_IRQn __APPEND3(FLEXCOMM,USART2_FLEXCOMM,_IRQn)
#define DMAREQ_USART2_RX __APPEND3(DMAREQ_FLEXCOMM,USART2_FLEXCOMM,_RX)
#define DMAREQ_USART2_TX __APPEND3(DMAREQ_FLEXCOMM,USART2_FLEXCOMM,_TX)
/* USART3 Defines */
#define LPC_USART3_BASE __APPEND3(LPC_FLEXCOMM,USART3_FLEXCOMM,_BASE)
#define LPC_USART3 ((LPC_USART_T *) LPC_USART3_BASE)
#define USART3_IRQHandler __APPEND3(FLEXCOMM,USART3_FLEXCOMM,_IRQHandler)
#define USART3_IRQn __APPEND3(FLEXCOMM,USART3_FLEXCOMM,_IRQn)
#define DMAREQ_USART3_RX __APPEND3(DMAREQ_FLEXCOMM,USART3_FLEXCOMM,_RX)
#define DMAREQ_USART3_TX __APPEND3(DMAREQ_FLEXCOMM,USART3_FLEXCOMM,_TX)
/* USART4 Defines */
#define LPC_USART4_BASE __APPEND3(LPC_FLEXCOMM,USART4_FLEXCOMM,_BASE)
#define LPC_USART4 ((LPC_USART_T *) LPC_USART4_BASE)
#define USART4_IRQHandler __APPEND3(FLEXCOMM,USART4_FLEXCOMM,_IRQHandler)
#define USART4_IRQn __APPEND3(FLEXCOMM,USART4_FLEXCOMM,_IRQn)
#define DMAREQ_USART4_RX __APPEND3(DMAREQ_FLEXCOMM,USART4_FLEXCOMM,_RX)
#define DMAREQ_USART4_TX __APPEND3(DMAREQ_FLEXCOMM,USART4_FLEXCOMM,_TX)
/* USART5 Defines */
#define LPC_USART5_BASE __APPEND3(LPC_FLEXCOMM,USART5_FLEXCOMM,_BASE)
#define LPC_USART5 ((LPC_USART_T *) LPC_USART5_BASE)
#define USART5_IRQHandler __APPEND3(FLEXCOMM,USART5_FLEXCOMM,_IRQHandler)
#define USART5_IRQn __APPEND3(FLEXCOMM,USART5_FLEXCOMM,_IRQn)
#define DMAREQ_USART5_RX __APPEND3(DMAREQ_FLEXCOMM,USART5_FLEXCOMM,_RX)
#define DMAREQ_USART5_TX __APPEND3(DMAREQ_FLEXCOMM,USART5_FLEXCOMM,_TX)
/* USART6 Defines */
#define LPC_USART6_BASE __APPEND3(LPC_FLEXCOMM,USART6_FLEXCOMM,_BASE)
#define LPC_USART6 ((LPC_USART_T *) LPC_USART6_BASE)
#define USART6_IRQHandler __APPEND3(FLEXCOMM,USART6_FLEXCOMM,_IRQHandler)
#define USART6_IRQn __APPEND3(FLEXCOMM,USART6_FLEXCOMM,_IRQn)
#define DMAREQ_USART6_RX __APPEND3(DMAREQ_FLEXCOMM,USART6_FLEXCOMM,_RX)
#define DMAREQ_USART6_TX __APPEND3(DMAREQ_FLEXCOMM,USART6_FLEXCOMM,_TX)
/* USART7 Defines */
#define LPC_USART7_BASE __APPEND3(LPC_FLEXCOMM,USART7_FLEXCOMM,_BASE)
#define LPC_USART7 ((LPC_USART_T *) LPC_USART7_BASE)
#define USART7_IRQHandler __APPEND3(FLEXCOMM,USART7_FLEXCOMM,_IRQHandler)
#define USART7_IRQn __APPEND3(FLEXCOMM,USART7_FLEXCOMM,_IRQn)
#define DMAREQ_USART7_RX __APPEND3(DMAREQ_FLEXCOMM,USART7_FLEXCOMM,_RX)
#define DMAREQ_USART7_TX __APPEND3(DMAREQ_FLEXCOMM,USART7_FLEXCOMM,_TX)
#endif
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __UART_5411X_H_ */
|
gpl-3.0
|
zeiss-microscopy/libCZI
|
Doc/html/classlib_c_z_i_1_1_lib_c_z_i_exception-members.html
|
4698
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.1"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>libCZI: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script>
<script type="text/javascript" async="async" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">libCZI
</div>
<div id="projectbrief">Reading CZI documents made easy</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.1 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('classlib_c_z_i_1_1_lib_c_z_i_exception.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">libCZI::LibCZIException Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classlib_c_z_i_1_1_lib_c_z_i_exception.html">libCZI::LibCZIException</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="classlib_c_z_i_1_1_lib_c_z_i_exception.html#ab6a09f2d1b399b1aa37f2ea75b80d6f8">LibCZIException</a>(const char *szErrMsg)</td><td class="entry"><a class="el" href="classlib_c_z_i_1_1_lib_c_z_i_exception.html">libCZI::LibCZIException</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">explicit</span></td></tr>
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by <a href="https://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.9.1 </li>
</ul>
</div>
</body>
</html>
|
gpl-3.0
|
cxcsds/ciao-contrib
|
ciao_contrib/downloadutils.py
|
22858
|
#
# Copyright (C) 2018, 2020
# Smithsonian Astrophysical Observatory
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
Support downloading data from URLs in CIAO.
A collection of routines related to data download used in CIAO.
retrieve_url
------------
CIAO 4.11 does not include any SSL support, instead relying on the OS.
This can cause problems on certain platforms. So try with Python and
then fall through to curl or wget. This can hopefully be removed for
CIAO 4.12 or later, but kept in just for now.
find_downloadable_files
-----------------------
Given a URL of a directory, return the files and sub-directories
available. This requires that the web server supports the Apache
mod_autoindex functionality, and is written for accessing the
Chandra Data Archive. Support for other web sites is not guaranteed.
find_all_downloadable_files
---------------------------
Similar to find_downloadble_files but recurses through all sub-directories.
ProgressBar
-----------
Display a "progress" bar, indicating the progress of a download.
This has very-limited functionality.
download_progress
-----------------
Download a URL to a file, supporting
- continuation of a previous partial download
- a rudimentary progress bar to display progress
Stability
---------
This is an internal module, and so the API it provides is not
considered stable (e.g. we may remove this module at any time). Use
at your own risk.
"""
import os
import sys
import ssl
import time
from io import BytesIO
from subprocess import check_output
import urllib.error
import urllib.request
import http.client
from html.parser import HTMLParser
import ciao_contrib.logger_wrapper as lw
logger = lw.initialize_module_logger("downloadutils")
v0 = logger.verbose0
v1 = logger.verbose1
v2 = logger.verbose1
v3 = logger.verbose3
v4 = logger.verbose4
__all__ = ('retrieve_url',
'find_downloadable_files',
'find_all_downloadable_files',
'ProgressBar',
'download_progress')
def manual_download(url):
"""Try curl then wget to query the URL.
Parameters
----------
url : str
The URL for the query; see construct_query
Returns
-------
ans : StringIO instance
The response
"""
v3("Fall back to curl or wget to download: {}".format(url))
# Should package this up nicely, but hardcode for the moment.
#
# It is not clear if this is sufficient to catch "no curl"
# while allowing errors like "no access to the internet"
# to not cause too much pointless work.
#
args = ['curl', '--silent', '-L', url]
v4("About to execute: {}".format(args))
try:
rsp = check_output(args)
except FileNotFoundError as exc1:
v3("Unable to call curl: {}".format(exc1))
args = ['wget', '--quiet', '-O-', url]
v4("About to execute: {}".format(args))
try:
rsp = check_output(args)
except FileNotFoundError as exc2:
v3("Unable to call wget: {}".format(exc2))
emsg = "Unable to access the URL {}.\n".format(url) + \
"Please install curl or wget (and if you " + \
"continue to see this message, contact the " + \
"CXC HelpDesk)."
raise RuntimeError(emsg)
return BytesIO(rsp)
def retrieve_url(url, timeout=None):
"""Handle possible problems retrieving the URL contents.
Using URLs with the https scheme causes problems for certain OS
set ups because CIAO 4.11 does not provide SSL support, but relies
on the system libraries to work. This is "supported" by falling
over from Python to external tools (curl or wget).
Parameters
----------
url : str
The URL to retrieve.
timeout : optional
The timeout parameter for the urlopen call; if not
None then the value is in seconds.
Returns
-------
response : HTTPResponse instance
The response
"""
try:
v3("Retrieving URL: {} timeout={}".format(url, timeout))
if timeout is None:
return urllib.request.urlopen(url)
return urllib.request.urlopen(url, timeout=timeout)
except urllib.error.URLError as ue:
v3("Error opening URL: {}".format(ue))
v3("error.reason = {}".format(ue.reason))
# Assume this is the error message indicating "no SSL support"
# There is a new (in CIAO 4.11) message
# "urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)"
#
# It appears that the reason attribute can be an object, so
# for now explicitly convert to a string:
reason = str(ue.reason)
if reason.find('unknown url type: https') != -1 or \
reason.find('CERTIFICATE_VERIFY_FAILED') != -1:
return manual_download(url)
# There used to be a check on the reason for the error,
# converting it into a "user-friendly" message, but this
# was error prone (the check itself was faulty) and
# potentially hid useful error information. So just
# re-raise the error here after logging it.
#
raise
class DirectoryContents(HTMLParser):
"""Extract the output of the mod_autoindex Apache directive.
Limited testing. It assumes that the files are given as links,
there's no other links on the page, and the parent directory is
listed as 'parent directory' (after removing the white space and
converting to lower case). There is special casing to remove links
where the text does not match the name of the link. This is to
handle query fragments, which are used to change the ordering of
the table display rather than be an actual link.
"""
def __init__(self, *args, **kwargs):
self.dirs = []
self.files = []
self.current = None
super().__init__(*args, **kwargs)
def add_link(self):
"""We've found a link, add it to the store"""
if self.current is None:
return
if self.current.endswith('/'):
store = self.dirs
else:
store = self.files
store.append(self.current)
self.current = None
def handle_starttag(self, tag, attrs):
if tag.upper() != 'A':
return
# In case we have a missing close tag
self.add_link()
attrs = dict(attrs)
try:
href = attrs['href']
except KeyError:
raise ValueError("Missing href attribute for a tag")
self.current = href
def handle_endtag(self, tag):
# do not expect end tags within <a> here, so we can
# treat it as the end of the a link if we find it
# (to support missing end tags).
#
if self.current is None:
return
self.add_link()
def handle_data(self, data):
if self.current is None:
return
# Skip the link to the parent directory, and skip any where
# the text is different to the href (e.g. to catch query-only
# links which are used to change the display rather than being
# a link).
#
data = data.strip()
if data.lower() == 'parent directory':
self.current = None
elif self.current != data:
v4(f"Dropping link={self.current} as test={data}")
self.current = None
def unpack_filelist_html(txt, baseurl):
"""Extract the contents of the page (assumed to be a directory listing).
Parameters
----------
txt : str
The HTML contents to parse.
baseurl : str
The URL of the page.
Returns
-------
urls : dict
The keys are directories and files, and the contents are
a list of absolute URLs (as strings).
"""
parser = DirectoryContents()
parser.feed(txt)
if not baseurl.endswith('/'):
baseurl += '/'
dirs = [baseurl + d for d in parser.dirs]
files = [baseurl + f for f in parser.files]
return {'directories': dirs, 'files': files}
def find_downloadable_files(urlname, headers):
"""Find the files and directories present in the given URL.
Report the files present at the given directory, for those
web servers which support an Apache-like mod_autoindex
function (i.e. return a HTML file listing the files and
sub-directories).
Parameters
----------
urlname : str
This must represent a directory.
headers : dict
The headers to add to the HTTP request (e.g. user-agent).
Returns
-------
urls : dict
The keys are directories and files, and the contents are
a list of absolute URLs (as strings).
See Also
--------
find_all_downloadable_files
Notes
-----
This is intended for use with the Chandra Data Archive, and
so there's no guarantee it will work for other web servers:
they may not return the necessary information, or use a
different markup.
Requests are made with *no* SSL validation (since there are
problems with CIAO 4.12 installed via ciao-install on a Ubuntu
machine).
There is no attempt to make a "nice" error message for a user
here, as that is better done in the calling code.
"""
no_context = ssl._create_unverified_context()
req = urllib.request.Request(urlname, headers=headers)
with urllib.request.urlopen(req, context=no_context) as rsp:
html_contents = rsp.read().decode('utf-8')
return unpack_filelist_html(html_contents, urlname)
def find_all_downloadable_files(urlname, headers):
"""Find the files present in the given URL, including sub-directories.
Report the files present at the given directory and
sub-directory, for those web servers which support an Apache-like
mod_autoindex function (i.e. return a HTML file listing the files
and sub-directories).
Parameters
----------
urlname : str
This must represent a directory.
headers : dict
The headers to add to the HTTP request (e.g. user-agent).
Returns
-------
urls : list of str
A list of absolute URLs.
See Also
--------
find_downloadable_files
Notes
-----
This is intended for use with the Chandra Data Archive, and
so there's no guarantee it will work for other web servers:
they may not return the necessary information, or use a
different markup.
Requests are made with *no* SSL validation (since there are
problems with CIAO 4.12 installed via ciao-install on a Ubuntu
machine).
"""
v3("Finding all files available at: {}".format(urlname))
base = find_downloadable_files(urlname, headers)
out = base['files']
todo = base['directories']
v4("Found sub-directories: {}".format(todo))
while True:
v4("Have {} sub-directories to process".format(len(todo)))
if todo == []:
break
durl = todo.pop()
v3("Recursing into {}".format(durl))
subdir = find_downloadable_files(durl, headers)
out += subdir['files']
v4("Adding sub-directories: {}".format(subdir['directories']))
todo += subdir['directories']
return out
class ProgressBar:
"""A very-simple progress "bar".
This just displays the hash marks for each segment of a
download to stdout. It is called from the code doing the
actual download. There is no logic to conditionally display
the output in this class - for instance based on the
current verbose setting - since this should be handled
by the code deciding to call this obejct or not.
Parameters
----------
size : int
The number of bytes to download.
nhash : int
The number of hashes representing the full download
(so each hash represents 100/nhash % of the file)
hashchar : char
The character to display when a chunk has been
downloaded.
Examples
--------
The bar is created with the total number of bytes to download,
then it starts (with an optional number of already-downloaded
bytes), and each chunk that is added is reported with the add
method. Once the download has finished the end method is called.
Note that the methods (start, add, and end) may cause output
to stdout.
>>> progress = ProgressBar(213948)
>>> progress.start()
...
>>> progress.add(8192)
...
>>> progress.add(8192)
...
>>> progress.end()
"""
def __init__(self, size, nhash=20, hashchar='#'):
if size < 0:
raise ValueError("size can not be negative")
if nhash < 1:
raise ValueError("must have at least one hash")
self.size = size
self.nhash = nhash
self.hashchar = hashchar
self.hashsize = size // nhash
self.hdl = sys.stdout
self.added = 0
self.hashes = 0
def start(self, nbytes=0):
"""Initialize the download.
Parameters
----------
nbytes : int, optional
The number of bytes of the file that has already been
downloaded. If not zero this may cause hash marks to be
displayed.
"""
self.added = nbytes
self.hashes = self.added // self.hashsize
if self.hashes == 0:
return
self.hdl.write(self.hashchar * self.hashes)
self.hdl.flush()
def add(self, nbytes):
"""Add the number of bytes for this segment.
This must only be called after start.
Parameters
----------
nbytes : int, optional
The number of bytes added to the file.
"""
if nbytes < 0:
raise ValueError("nbytes must be positive")
if nbytes == 0:
return
self.added += nbytes
hashes = self.added // self.hashsize
if hashes == self.hashes:
return
nadd = hashes - self.hashes
self.hdl.write(self.hashchar * nadd)
self.hdl.flush()
self.hashes = hashes
def end(self):
"""Finished the download.
This is mainly to allow for handling of rounding errors.
"""
nadd = self.nhash - self.hashes
if nadd <= 0:
return
# Don't bother trying to correct for any rounding errors
# if the file wasn't fully downloaded.
#
if self.added < self.size:
return
self.hdl.write(self.hashchar * nadd)
self.hdl.flush()
def myint(x):
"""Convert to an integer, my way."""
return int(x + 0.5)
def stringify_dt(dt):
"""Convert a time interval into a "human readable" string.
Parameters
----------
dt : number
The number of seconds.
Returns
-------
lbl : str
The "human readable" version of the time difference.
Examples
--------
>>> stringify_dt(0.2)
'< 1 s'
>>> stringify_dt(62.3)
'1 m 2 s'
>>> stringify_dt(2402.24)
'40 m 2 s'
"""
if dt < 1:
return "< 1 s"
d = myint(dt // (24 * 3600))
dt2 = dt % (24 * 3600)
h = myint(dt2 // 3600)
dt3 = dt % 3600
m = myint(dt3 // 60)
s = myint(dt3 % 60)
if d > 0:
lbl = "%d day" % d
if d > 1:
lbl += "s"
if h > 0:
lbl += " %d h" % h
elif h > 0:
lbl = "%d h" % h
if m > 0:
lbl += " %d m" % m
elif m > 0:
lbl = "%d m" % m
if s > 0:
lbl += " %d s" % s
else:
lbl = "%d s" % s
return lbl
def stringify_size(s):
"""Convert a file size to a text string.
Parameters
----------
size : int
File size, in bytes
Returns
-------
filesize : str
A "nice" representation of the size
Examples
--------
>>> stringify_size(1023)
'< 1 Kb'
>>> stringify_size(1024)
'1 Kb'
>>> stringify_size(1025)
'1 Kb'
>>> stringify_size(54232)
'53 Kb'
>>> stringify_size(4545833)
'4 Mb'
>>> stringify_size(45458330000)
'4.2 Gb'
"""
if s < 1024:
lbl = "< 1 Kb"
elif s < 1024 * 1024:
lbl = "%d Kb" % (myint(s / 1024.0))
elif s < 1024 * 1024 * 1024:
lbl = "%d Mb" % (myint(s / (1024 * 1024.0)))
else:
lbl = "%.1f Gb" % (s / (1024 * 1024 * 1024.0))
return lbl
def download_progress(url, size, outfile,
headers=None,
progress=None,
chunksize=8192,
verbose=True):
"""Download url and store in outfile, reporting progress.
The download will use chunks, logging the output to the
screen, and will not re-download partial data (e.g.
from a partially-completed earlier attempt). Information
on the state of the download will be displayed to stdout
unless verbose is False. This routine requires that
we already know the size of the file.
Parameters
----------
url : str
The URL to download; this must be http or https based.
size : int
The file size in bytes.
outfile : str
The output file (relative to the current working directory).
Any sub-directories must already exist.
headers : dict, optional
Any additions to the HTTP header in the request (e.g. to
set 'User-Agent'). If None, a user-agent string of
"ciao_contrib.downloadutils.download_progress" is
used).
progress : ProgressBar instance, optional
If not specified a default instance (20 '#' marks) is used.
chunksize : int, optional
The chunk size to use, in bytes.
verbose : bool, optional
Should progress information on the download be written to
stdout?
Notes
-----
This routine assumes that the HTTP server supports ranged
requests [1]_, and ignores SSL validation of the request.
The assumption is that the resource is static (i.e. it hasn't
been updated since content was downloaded). This means that it
is possible the output will be invalid, for instance if it
has increased in length since the last time it was fully
downloaded, or changed and there was a partial download.
References
----------
.. [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests
"""
# I used http.client rather than urllib because I read somewhere
# that urllib did not handle streaming requests (e.g. it would just
# read in everything in one go and then you read from the in-memory
# buffer).
#
# From https://stackoverflow.com/a/24900110 - is it still true?
#
purl = urllib.request.urlparse(url)
if purl.scheme == 'https':
no_context = ssl._create_unverified_context()
conn = http.client.HTTPSConnection(purl.netloc, context=no_context)
elif purl.scheme == 'http':
conn = http.client.HTTPConnection(purl.netloc)
else:
raise ValueError("Unsupported URL scheme: {}".format(url))
startfrom = 0
try:
fsize = os.path.getsize(outfile)
except OSError:
fsize = None
if fsize is not None:
equal_size = fsize == size
v3("Checking on-disk file size " +
"({}) against archive size ".format(fsize) +
"({}): {}".format(size, equal_size))
if equal_size:
if verbose:
# Ugly, since this is set up to match what is needed by
# ciao_contrib.cda.data.ObsIdFile.download rather than
# being generic. Need to look at how messages are
# displayed.
#
sys.stdout.write("{:>20s}\n".format("already downloaded"))
sys.stdout.flush()
return (0, 0)
if fsize > size:
v0("Archive size is less than disk size for " +
"{} - {} vs {} bytes.".format(outfile,
size,
fsize))
return (0, 0)
startfrom = fsize
try:
outfp = open(outfile, 'ab')
except IOError:
raise IOError("Unable to create '{}'".format(outfile))
# Is this seek needed?
if startfrom > 0 and outfp.tell() == 0:
outfp.seek(0, 2)
if progress is None:
progress = ProgressBar(size)
if headers is None:
headers = {'User-Agent':
'ciao_contrib.downloadutils.download_progress'}
else:
# Ensure we copy the header dictionary, since we are going
# to add to it. It is assumed that a shallow copy is
# enough.
#
headers = headers.copy()
# Could hide this if startfrom = 0 and size <= chunksize, but
# it doesn't seem worth it.
#
headers['Range'] = 'bytes={}-{}'.format(startfrom, size - 1)
time0 = time.time()
conn.request('GET', url, headers=headers)
with conn.getresponse() as rsp:
# Assume that rsp.status != 206 would cause some form
# of an error so we don't need to check for this here.
#
if verbose:
progress.start(startfrom)
# Note that the progress bar reflects the expected size, not
# the actual size; this may not be ideal (but don't expect the
# sizes to change so it doesn't really matter).
#
while True:
chunk = rsp.read(chunksize)
if not chunk:
break
outfp.write(chunk)
if verbose:
progress.add(len(chunk))
if verbose:
progress.end()
time1 = time.time()
nbytes = outfp.tell()
outfp.close()
dtime = time1 - time0
if verbose:
rate = (nbytes - startfrom) / (1024 * dtime)
tlabel = stringify_dt(dtime)
sys.stdout.write(" {:>13s} {:.1f} kb/s\n".format(tlabel, rate))
if size != nbytes:
v0("WARNING file sizes do not match: expected {} but downloaded {}".format(size, nbytes))
return (nbytes, dtime)
|
gpl-3.0
|
tim-taylor/evobee
|
docs/html/annotated_dup.js
|
2376
|
var annotated_dup =
[
[ "AbstractHive", "classAbstractHive.html", "classAbstractHive" ],
[ "Colour", "classColour.html", "classColour" ],
[ "Environment", "classEnvironment.html", "classEnvironment" ],
[ "EventManager", "classEventManager.html", "classEventManager" ],
[ "EvoBeeExperiment", "classEvoBeeExperiment.html", "classEvoBeeExperiment" ],
[ "EvoBeeModel", "classEvoBeeModel.html", "classEvoBeeModel" ],
[ "Flower", "classFlower.html", "classFlower" ],
[ "FloweringPlant", "classFloweringPlant.html", "classFloweringPlant" ],
[ "Hive", "classHive.html", "classHive" ],
[ "HiveConfig", "structHiveConfig.html", "structHiveConfig" ],
[ "HoneyBee", "classHoneyBee.html", "classHoneyBee" ],
[ "Hymenoptera", "classHymenoptera.html", "classHymenoptera" ],
[ "LocalDensityConstraint", "structLocalDensityConstraint.html", "structLocalDensityConstraint" ],
[ "Logger", "classLogger.html", "classLogger" ],
[ "ModelComponent", "classModelComponent.html", "classModelComponent" ],
[ "ModelParams", "classModelParams.html", null ],
[ "Patch", "classPatch.html", "classPatch" ],
[ "PlantTypeConfig", "structPlantTypeConfig.html", "structPlantTypeConfig" ],
[ "PlantTypeDistributionConfig", "structPlantTypeDistributionConfig.html", "structPlantTypeDistributionConfig" ],
[ "Pollen", "structPollen.html", "structPollen" ],
[ "Pollinator", "classPollinator.html", "classPollinator" ],
[ "PollinatorConfig", "structPollinatorConfig.html", "structPollinatorConfig" ],
[ "PollinatorLatestAction", "structPollinatorLatestAction.html", "structPollinatorLatestAction" ],
[ "PollinatorPerformanceInfo", "structPollinatorPerformanceInfo.html", "structPollinatorPerformanceInfo" ],
[ "Position", "classPosition.html", "classPosition" ],
[ "ReflectanceInfo", "classReflectanceInfo.html", "classReflectanceInfo" ],
[ "SDL2_gfxBresenhamIterator", "structSDL2__gfxBresenhamIterator.html", "structSDL2__gfxBresenhamIterator" ],
[ "SDL2_gfxMurphyIterator", "structSDL2__gfxMurphyIterator.html", "structSDL2__gfxMurphyIterator" ],
[ "Visualiser", "classVisualiser.html", "classVisualiser" ],
[ "VisualPreferenceInfo", "structVisualPreferenceInfo.html", "structVisualPreferenceInfo" ],
[ "VisualStimulusInfo", "structVisualStimulusInfo.html", "structVisualStimulusInfo" ]
];
|
gpl-3.0
|
donomii/svarmr
|
tcltk/share/doc/tcllib/tcllib/files/apps/nnslog.html
|
8043
|
<div class='fossil-doc' data-title='nnslog - Name service facility'>
<style>
HTML {
background: #FFFFFF;
color: black;
}
BODY {
background: #FFFFFF;
color: black;
}
DIV.doctools {
margin-left: 10%;
margin-right: 10%;
}
DIV.doctools H1,DIV.doctools H2 {
margin-left: -5%;
}
H1, H2, H3, H4 {
margin-top: 1em;
font-family: sans-serif;
font-size: large;
color: #005A9C;
background: transparent;
text-align: left;
}
H1.doctools_title {
text-align: center;
}
UL,OL {
margin-right: 0em;
margin-top: 3pt;
margin-bottom: 3pt;
}
UL LI {
list-style: disc;
}
OL LI {
list-style: decimal;
}
DT {
padding-top: 1ex;
}
UL.doctools_toc,UL.doctools_toc UL, UL.doctools_toc UL UL {
font: normal 12pt/14pt sans-serif;
list-style: none;
}
LI.doctools_section, LI.doctools_subsection {
list-style: none;
margin-left: 0em;
text-indent: 0em;
padding: 0em;
}
PRE {
display: block;
font-family: monospace;
white-space: pre;
margin: 0%;
padding-top: 0.5ex;
padding-bottom: 0.5ex;
padding-left: 1ex;
padding-right: 1ex;
width: 100%;
}
PRE.doctools_example {
color: black;
background: #f5dcb3;
border: 1px solid black;
}
UL.doctools_requirements LI, UL.doctools_syntax LI {
list-style: none;
margin-left: 0em;
text-indent: 0em;
padding: 0em;
}
DIV.doctools_synopsis {
color: black;
background: #80ffff;
border: 1px solid black;
font-family: serif;
margin-top: 1em;
margin-bottom: 1em;
}
UL.doctools_syntax {
margin-top: 1em;
border-top: 1px solid black;
}
UL.doctools_requirements {
margin-bottom: 1em;
border-bottom: 1px solid black;
}
</style>
<hr> [
<a href="../../../toc.html">Main Table Of Contents</a>
| <a href="../../toc.html">Table Of Contents</a>
| <a href="../../../index.html">Keyword Index</a>
| <a href="../../../toc0.html">Categories</a>
| <a href="../../../toc1.html">Modules</a>
| <a href="../../../toc2.html">Applications</a>
] <hr>
<div class="doctools">
<h1 class="doctools_title">nnslog(n) 1.0 tcllib "Name service facility"</h1>
<div id="name" class="doctools_section"><h2><a name="name">Name</a></h2>
<p>nnslog - Name service facility, Commandline Logging Client Application</p>
</div>
<div id="toc" class="doctools_section"><h2><a name="toc">Table Of Contents</a></h2>
<ul class="doctools_toc">
<li class="doctools_section"><a href="#toc">Table Of Contents</a></li>
<li class="doctools_section"><a href="#synopsis">Synopsis</a></li>
<li class="doctools_section"><a href="#section1">Description</a>
<ul>
<li class="doctools_subsection"><a href="#subsection1">USE CASES</a></li>
<li class="doctools_subsection"><a href="#subsection2">COMMAND LINE</a></li>
<li class="doctools_subsection"><a href="#subsection3">OPTIONS</a></li>
</ul>
</li>
<li class="doctools_section"><a href="#section2">Bugs, Ideas, Feedback</a></li>
<li class="doctools_section"><a href="#see-also">See Also</a></li>
<li class="doctools_section"><a href="#keywords">Keywords</a></li>
<li class="doctools_section"><a href="#category">Category</a></li>
<li class="doctools_section"><a href="#copyright">Copyright</a></li>
</ul>
</div>
<div id="synopsis" class="doctools_section"><h2><a name="synopsis">Synopsis</a></h2>
<div class="doctools_synopsis">
<ul class="doctools_syntax">
<li><a href="#1"><b class="cmd">nnslog</b> <span class="opt">?<b class="option">-host</b> <i class="arg">host</i>?</span> <span class="opt">?<b class="option">-port</b> <i class="arg">port</i>?</span></a></li>
</ul>
</div>
</div>
<div id="section1" class="doctools_section"><h2><a name="section1">Description</a></h2>
<p>Please read <i class="term"><a href="../modules/nns/nns_intro.html">Name service facility, introduction</a></i> first.</p>
<p>The application described by this document, <b class="syscmd">nnslog</b>, is a
simple command line client for the nano name service facility provided
by the Tcllib packages <b class="package"><a href="../modules/nns/nns_client.html">nameserv</a></b>, and <b class="package"><a href="../modules/nns/nns_server.html">nameserv::server</a></b>.</p>
<p>It essentially implements "<b class="syscmd"><a href="nns.html">nns</a></b> search -continuous *", but
uses a different output formatting. Instead of continuously showing
the current contents of the server in the terminal it simply logs all
received add/remove events to <b class="const">stdout</b>.</p>
<p>This name service facility has nothing to do with the Internet's
<i class="term">Domain Name System</i>, otherwise known as <i class="term"><a href="../../../index.html#key603">DNS</a></i>. If the
reader is looking for a package dealing with that please see either of
the packages <b class="package"><a href="../modules/dns/tcllib_dns.html">dns</a></b> and <b class="package">resolv</b>, both found in Tcllib
too.</p>
<div id="subsection1" class="doctools_subsection"><h3><a name="subsection1">USE CASES</a></h3>
<p><b class="syscmd">nnslog</b> was written with the following main use case in mind.</p>
<ol class="doctools_enumerated">
<li><p>Monitoring the name service for all changes and logging them in a text
terminal.</p></li>
</ol>
</div>
<div id="subsection2" class="doctools_subsection"><h3><a name="subsection2">COMMAND LINE</a></h3>
<dl class="doctools_definitions">
<dt><a name="1"><b class="cmd">nnslog</b> <span class="opt">?<b class="option">-host</b> <i class="arg">host</i>?</span> <span class="opt">?<b class="option">-port</b> <i class="arg">port</i>?</span></a></dt>
<dd><p>The command connects to the specified name service, sets up a search
for all changes and then prints all received events to stdout, with
each events on its own line. The command will not exit until it is
explicitly terminated by the user. It will especially survive the loss
of the connection to the name service and reestablish the search and
log when the connection is restored.</p>
<p>The options to specify the name service will be explained later, in
section <span class="sectref"><a href="#subsection3">OPTIONS</a></span>.</p></dd>
</dl>
</div>
<div id="subsection3" class="doctools_subsection"><h3><a name="subsection3">OPTIONS</a></h3>
<p>This section describes all the options available to the user of the
application</p>
<dl class="doctools_options">
<dt><b class="option">-host</b> name|ipaddress</dt>
<dd><p>If this option is not specified it defaults to <b class="const">localhost</b>. It
specifies the name or ip-address of the host the name service to talk
to is running on.</p></dd>
<dt><b class="option">-port</b> number</dt>
<dd><p>If this option is not specified it defaults to <b class="const">38573</b>. It
specifies the TCP port the name service to talk to is listening on for
requests.</p></dd>
</dl>
</div>
</div>
<div id="section2" class="doctools_section"><h2><a name="section2">Bugs, Ideas, Feedback</a></h2>
<p>This document, and the package it describes, will undoubtedly contain
bugs and other problems.
Please report such in the category <em>nameserv</em> of the
<a href="http://core.tcl.tk/tcllib/reportlist">Tcllib Trackers</a>.
Please also report any ideas for enhancements you may have for either
package and/or documentation.</p>
</div>
<div id="see-also" class="doctools_section"><h2><a name="see-also">See Also</a></h2>
<p><a href="../modules/nns/nns_client.html">nameserv(n)</a>, <a href="../modules/nns/nns_common.html">nameserv::common(n)</a></p>
</div>
<div id="keywords" class="doctools_section"><h2><a name="keywords">Keywords</a></h2>
<p><a href="../../../index.html#key28">application</a>, <a href="../../../index.html#key30">client</a>, <a href="../../../index.html#key29">name service</a></p>
</div>
<div id="category" class="doctools_section"><h2><a name="category">Category</a></h2>
<p>Networking</p>
</div>
<div id="copyright" class="doctools_section"><h2><a name="copyright">Copyright</a></h2>
<p>Copyright © 2008 Andreas Kupries <andreas_kupries@users.sourceforge.net></p>
</div>
</div>
|
gpl-3.0
|
madhukarbhat/scrappy
|
perl/multiply.pl
|
4350
|
#!/usr/local/bin/perl
# ----------------------------------------------------------------------
# Script Initialization
my $old_fh = select(STDOUT);
$| = 1;
select($old_fh);
my $EASY = 10;
my $NORMAL = 6;
my $CHALLENGING = 4;
my $ac = scalar @ARGV;
my $usage = <<"END_OF_USAGE";
Usage:
$0 <1|2|3|4> <easy|normal|challenging>
<1|2|3>: This is the round number. The round completes once all the
multiplication questions are asked.
- Round 1: In round 1, multiplication tables from 2 to 6 will be
asked in random sequence.
- Round 2: In round 2, multiplication tables from 6 to 9 will be
asked in random sequence.
- Round 3: In round 3, multiplication tables from 9 to 14 will be
asked in random sequence.
- Round 4: In round 4, multiplication tables from 14 to 19 will be
asked in random sequence.
<easy|normal|challenging>: This determines the time available for a
single question.
- easy : Question must be answered in roughly $EASY seconds.
- normal : Question must be answered in roughly $NORMAL seconds.
- challenging : Question must be answered in roughly $CHALLENGING seconds.
END_OF_USAGE
# Vaildate parameter
if ($ac != 2) {
print $usage;
exit;
}
my $round = shift;
my $qmode = shift;
chomp $round;
chomp $qmode;
# ----------------------------------------------------------------------
# Validate input
if (($round != 1) && ($round != 2) && ($round != 3) && ($round != 4)) {
print 'Round: ', $round, "\n";
print $usage;
exit;
}
if (($qmode !~ m/^easy$/) &&
($qmode !~ m/^normal$/) &&
($qmode !~ m/^challenging$/)){
print 'Round: ', $round, "\t", 'Mode: ', $qmode, "\n";
print $usage;
exit;
}
# ----------------------------------------------------------------------
# Alarm setup
# The default timeout value is 'normal' :-)
my $timeout = $NORMAL;
if ($qmode =~ m/challenging/i) {
$timeout = $CHALLENGING;
} elsif ($qmode =~ m/easy/i) {
$timeout = $EASY;
} else {
$timeout = $NORMAL;
}
# ----------------------------------------------------------------------
# Main code
my $question_table = initialize_question_table();
show_questions($question_table);
# ----------------------------------------------------------------------
# Subroutines
# Build the question table. This is a hash, with each key having a
# randomized sequence number and the corresponding value being the
# question.
sub initialize_question_table {
my $start_number = 0;
my $max_number = 0;
if ($round == 1) {
$start_number = 2;
$max_number = 6;
} elsif ($round == 2) {
$start_number = 6;
$max_number = 9;
} elsif ($round == 3) {
$start_number = 9;
$max_number = 14;
} elsif ($round == 4) {
$start_number = 14;
$max_number = 19;
} else {
$start_number = 2;
$max_number = 19;
}
my %table = ();
my $max_questions = ($max_number - $start_number + 1) * 10;
my @sequence = ();
for my $j (1..$max_questions) {
$sequence[$j] = $j;
}
for (my $a = $start_number; $a <= $max_number; ++$a) {
foreach my $i (1..10) {
my $key_index = int( rand( scalar @sequence ) );
my $key = $sequence[$key_index];
splice (@sequence, $key_index, 1);
my $question = $a." x ".$i;
my $answer = $a*$i;
my %value =
(
question => $question,
answer => $answer
);
$table{$key} = \%value;
}
}
return \%table;
}
# Displays the question and waits for timeout seconds for an
# answer. On timeout, it proceeds to the next question.
sub show_questions {
my $q_table = shift;
my $previous = select(STDIN);
$| = 1;
select($previous);
foreach my $ques_id (sort { $a <=> $b } keys %$q_table) {
eval {
local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
alarm $timeout;
print $ques_id, ". ", $q_table->{$ques_id}->{question}, ": ";
my $answer = <STDIN>;
chomp $answer;
my $correct_answer = $q_table->{$ques_id}->{answer};
if ($answer == $correct_answer) {
print "> Correct!";
} else {
print "> Wrong. answer is: $correct_answer";
}
alarm 0;
};
if ($@) {
die unless $@ eq "alarm\n"; # propagate unexpected errors
# timed out
print ' <late>', "\n";
} else {
# didn't
print ' ..', "\n";
}
}
return;
}
|
gpl-3.0
|
UberWaffe/OpenRA
|
OpenRA.Mods.RA/ServerTraits/MasterServerPinger.cs
|
3554
|
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using OpenRA.Server;
using S = OpenRA.Server.Server;
namespace OpenRA.Mods.RA.Server
{
public class MasterServerPinger : ServerTrait, ITick, INotifySyncLobbyInfo, IStartGame, IEndGame
{
const int MasterPingInterval = 60 * 3; // 3 minutes. server has a 5 minute TTL for games, so give ourselves a bit
// of leeway.
public int TickTimeout { get { return MasterPingInterval * 10000; } }
public void Tick(S server)
{
if ((Game.RunTime - lastPing > MasterPingInterval * 1000) || isInitialPing)
PingMasterServer(server);
else
lock (masterServerMessages)
while (masterServerMessages.Count > 0)
server.SendMessage(masterServerMessages.Dequeue());
}
public void LobbyInfoSynced(S server) { PingMasterServer(server); }
public void GameStarted(S server) { PingMasterServer(server); }
public void GameEnded(S server) { PingMasterServer(server); }
int lastPing = 0;
bool isInitialPing = true;
volatile bool isBusy;
Queue<string> masterServerMessages = new Queue<string>();
public void PingMasterServer(S server)
{
if (isBusy || !server.Settings.AdvertiseOnline) return;
lastPing = Game.RunTime;
isBusy = true;
var mod = server.ModData.Manifest.Mod;
// important to grab these on the main server thread, not in the worker we're about to spawn -- they may be modified
// by the main thread as clients join and leave.
var numPlayers = server.LobbyInfo.Clients.Where(c1 => c1.Bot == null && c1.Slot != null).Count();
var numBots = server.LobbyInfo.Clients.Where(c1 => c1.Bot != null).Count();
var numSpectators = server.LobbyInfo.Clients.Where(c1 => c1.Bot == null && c1.Slot == null).Count();
var passwordProtected = string.IsNullOrEmpty(server.Settings.Password) ? 0 : 1;
var clients = server.LobbyInfo.Clients.Where(c1 => c1.Bot == null).Select(c => Convert.ToBase64String(Encoding.UTF8.GetBytes(c.Name))).ToArray();
Action a = () =>
{
try
{
var url = "ping?port={0}&name={1}&state={2}&players={3}&bots={4}&mods={5}&map={6}&maxplayers={7}&spectators={8}&protected={9}&clients={10}";
if (isInitialPing) url += "&new=1";
using (var wc = new WebClient())
{
wc.Proxy = null;
wc.DownloadData(
server.Settings.MasterServer + url.F(
server.Settings.ExternalPort, Uri.EscapeUriString(server.Settings.Name),
(int)server.State,
numPlayers,
numBots,
"{0}@{1}".F(mod.Id, mod.Version),
server.LobbyInfo.GlobalSettings.Map,
server.Map.PlayerCount,
numSpectators,
passwordProtected,
string.Join(",", clients)));
if (isInitialPing)
{
isInitialPing = false;
lock (masterServerMessages)
masterServerMessages.Enqueue("Master server communication established.");
}
}
}
catch (Exception ex)
{
Log.Write("server", ex.ToString());
lock (masterServerMessages)
masterServerMessages.Enqueue("Master server communication failed.");
}
isBusy = false;
};
a.BeginInvoke(null, null);
}
}
}
|
gpl-3.0
|
thehyve/transmart-data
|
ddl/oracle/biomart/bio_data_disease.sql
|
1015
|
--
-- Type: TABLE; Owner: BIOMART; Name: BIO_DATA_DISEASE
--
CREATE TABLE "BIOMART"."BIO_DATA_DISEASE"
( "BIO_DATA_ID" NUMBER(18,0) NOT NULL ENABLE,
"BIO_DISEASE_ID" NUMBER(18,0) NOT NULL ENABLE,
"ETL_SOURCE" VARCHAR2(100 BYTE),
CONSTRAINT "BIO_DATA_DISEASE_PK" PRIMARY KEY ("BIO_DATA_ID", "BIO_DISEASE_ID")
USING INDEX
TABLESPACE "INDX" ENABLE
) SEGMENT CREATION IMMEDIATE
TABLESPACE "BIOMART" ;
--
-- Type: REF_CONSTRAINT; Owner: BIOMART; Name: BIO_DF_DISEASE_FK
--
ALTER TABLE "BIOMART"."BIO_DATA_DISEASE" ADD CONSTRAINT "BIO_DF_DISEASE_FK" FOREIGN KEY ("BIO_DISEASE_ID")
REFERENCES "BIOMART"."BIO_DISEASE" ("BIO_DISEASE_ID") ENABLE;
--
-- Type: INDEX; Owner: BIOMART; Name: BIO_DD_IDX2
--
CREATE INDEX "BIOMART"."BIO_DD_IDX2" ON "BIOMART"."BIO_DATA_DISEASE" ("BIO_DISEASE_ID")
TABLESPACE "INDX"
PARALLEL 4 ;
--
-- Type: INDEX; Owner: BIOMART; Name: BIO_DT_DIS_DID_IDX
--
CREATE INDEX "BIOMART"."BIO_DT_DIS_DID_IDX" ON "BIOMART"."BIO_DATA_DISEASE" ("BIO_DATA_ID")
TABLESPACE "INDX"
PARALLEL 4 ;
|
gpl-3.0
|
mgrzybek/ansible-ha-cluster
|
files/machine-slice-configuration.sh
|
521
|
#! /usr/bin/env bash
slice=/sys/fs/cgroup/cpuset/machine.slice
crm_cpus=$(/usr/sbin/crm node utilization $HOSTNAME show cpu|perl -ne '/value=(\d+)$/ && print $1')
server_cpus=$(grep -c ^proc /proc/cpuinfo)
server_cpus=$((server_cpus-1))
first_allowed_cpu=$(echo $server_cpus - $crm_cpus |bc)
/usr/bin/cluster_set_cpuset -p $slice -e -s "${first_allowed_cpu}-${server_cpus}"
if [ $? -eq 0 ] ; then
echo "Set cpu_cpus and cpu_exclusive... OK"
else
echo "Set cpu_cpus and cpu_exclusive... FAILED"
exit 1
fi
exit 0
|
gpl-3.0
|
nataniel/e4u-framework
|
src/E4u/Application/Controller/Redirect.php
|
455
|
<?php
namespace E4u\Application\Controller;
use E4u\Response\Response;
/**
* <code>
* $exception = new Controller\Redirect();
* throw $exception->setUrl('security/login');
* </code>
*/
class Redirect extends \Exception
{
protected $code = Response::STATUS_REDIRECT;
private $url;
public function setUrl($url) {
$this->url = $url;
return $this;
}
public function getUrl() {
return $this->url;
}
}
|
gpl-3.0
|
rvega/morphasynth
|
vendors/pd-extended-0.43.4/externals/Gem/src/Pixes/pix_backlight.cpp
|
16287
|
////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// tigital@mac.com
// ported from pete's_plugins
//
// Implementation file
//
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "GEM.LICENSE.TERMS" in this distribution.
//
/////////////////////////////////////////////////////////
#include "Utils/PixPete.h"
#include "pix_backlight.h"
CPPEXTERN_NEW(pix_backlight);
/////////////////////////////////////////////////////////
//
// pix_backlight
//
/////////////////////////////////////////////////////////
// Constructor
//
/////////////////////////////////////////////////////////
pix_backlight :: pix_backlight()
{
m_SpikeScale = 127.0f; // 0 to 255
m_SpikeFloor = 0.0f; // 0 to 255
m_SpikeCeiling = 255.0f; // 0 to 255
init =0;
inlet_new(this->x_obj, &this->x_obj->ob_pd, gensym("float"), gensym("scale"));
inlet_new(this->x_obj, &this->x_obj->ob_pd, gensym("float"), gensym("floor"));
inlet_new(this->x_obj, &this->x_obj->ob_pd, gensym("float"), gensym("ceiling"));
}
/////////////////////////////////////////////////////////
// Destructor
//
/////////////////////////////////////////////////////////
pix_backlight :: ~pix_backlight()
{
//if(init) Pete_BackLight_DeInit();
}
/////////////////////////////////////////////////////////
// processImage
//
/////////////////////////////////////////////////////////
void pix_backlight :: processRGBAImage(imageStruct &image)
{
nWidth = image.xsize;
nHeight = image.ysize;
if (!init) {
//Pete_BackLight_Init();
init = 1;
}
pSource = (U32*)image.data;
myImage.xsize = image.xsize;
myImage.ysize = image.ysize;
myImage.setCsizeByFormat(image.format);
myImage.reallocate();
pOutput = (U32*)myImage.data;
const int nFixedShift=8;
// const int nFixedMult=(1<<nFixedShift);
const int nHalfWidth=(nWidth/2);
const int nHalfHeight=(nHeight/2);
const int nNumPixels = nWidth*nHeight;
U32* pCurrentSource=pSource;
U32* pCurrentOutput=pOutput;
const U32* pSourceEnd=(pSource+nNumPixels);
// const U32* pOutputEnd=(pOutput+nNumPixels);
Pete_ZeroMemory(pOutput,sizeof(U32)*nNumPixels);
const int nSpikeScale=static_cast<int>(m_SpikeScale);
const int nSpikeFloor=static_cast<int>(m_SpikeFloor);
const int nSpikeCeiling=static_cast<int>(m_SpikeCeiling);
int nY=0;
while (pCurrentSource!=pSourceEnd) {
// const U32* pSourceLineStart=pCurrentSource;
const U32* pSourceLineEnd=pCurrentSource+nWidth;
int nX=0;
while (pCurrentSource!=pSourceLineEnd) {
U32 SourceColour=*pCurrentSource;
int nRed=(SourceColour&(0xff<<SHIFT_RED))>>SHIFT_RED;
int nGreen=(SourceColour&(0xff<<SHIFT_GREEN))>>SHIFT_GREEN;
int nBlue=(SourceColour&(0xff<<SHIFT_BLUE))>>SHIFT_BLUE;
int nLuminance =
((90 * nRed)+
(115 * nGreen)+
(51 * nBlue));
nLuminance>>=8;
// SourceColour|=(nLuminance<<24);
nLuminance=clampFunc(nLuminance,nSpikeFloor,nSpikeCeiling);
nLuminance-=nSpikeFloor;
const int nLength=((nLuminance*nSpikeScale)>>nFixedShift);
int nDeltaX=((nX-nHalfWidth)*nLength)>>8;
int nDeltaY=((nY-nHalfHeight)*nLength)>>8;
int nEndX=nX+nDeltaX;
if (nEndX>nWidth) {
nEndX=nWidth;
} else if (nEndX<0) {
nEndX=0;
}
int nEndY=nY+nDeltaY;
if (nEndY>nHeight) {
nEndY=nHeight;
} else if (nEndY<0) {
nEndY=0;
}
int nXInc;
if (nDeltaX<0) {
nXInc=-1;
} else {
nXInc=1;
}
int nYInc;
if (nDeltaY<0) {
nYInc=-1;
} else {
nYInc=1;
}
nDeltaX*=nXInc;
nDeltaY*=nYInc;
int nCurrentX=nX;
int nCurrentY=nY;
if ((nDeltaX==0)&&(nDeltaY==0)) {
nDeltaX=1;
nEndX+=1;
nEndY+=1;
} else if (nDeltaX==0) {
nEndX+=1;
} else if (nDeltaY==0) {
nEndY+=1;
}
U32* pDest=(pOutput+(nCurrentY*nWidth)+nCurrentX);
const int nDestYInc=(nWidth*nYInc);
const int nDestXInc=nXInc;
if (nDeltaX>nDeltaY) {
int nCounter=nDeltaY;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaX) {
nCounter-=nDeltaX;
nCurrentY+=nYInc;
pDest+=nDestYInc;
}
nCurrentX+=nXInc;
pDest+=nDestXInc;
nCounter+=nDeltaY;
}
} else {
int nCounter=nDeltaX;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaY) {
nCounter-=nDeltaY;
nCurrentX+=nXInc;
pDest+=nDestXInc;
}
nCurrentY+=nYInc;
pDest+=nDestYInc;
nCounter+=nDeltaX;
};
}
pCurrentSource+=1;
pCurrentOutput+=1;
nX+=1;
}
nY+=1;
}
image.data = myImage.data;
}
/////////////////////////////////////////////////////////
// do the YUV processing here
//
/////////////////////////////////////////////////////////
void pix_backlight :: processYUVImage(imageStruct &image)
{
nWidth = image.xsize/2;
nHeight = image.ysize;
if (!init) {
//Pete_BackLight_Init();
init = 1;
}
pSource = (U32*)image.data;
myImage.xsize = image.xsize;
myImage.ysize = image.ysize;
myImage.setCsizeByFormat(image.format);
myImage.reallocate();
pOutput = (U32*)myImage.data;
const int nFixedShift=8;
// const int nFixedMult=(1<<nFixedShift);
const int nHalfWidth=(nWidth/2);
const int nHalfHeight=(nHeight/2);
const int nNumPixels = nWidth*nHeight;
U32* pCurrentSource=pSource;
U32* pCurrentOutput=pOutput;
const U32* pSourceEnd=(pSource+nNumPixels);
// const U32* pOutputEnd=(pOutput+nNumPixels);
//Pete_ZeroMemory(pOutput,sizeof(U32)*nNumPixels);
unsigned char *zero;
zero = (unsigned char*)pOutput;
int temp = nNumPixels;
while(--temp>>1){
*zero++ = 128; *zero++ =0;
*zero++ = 128; *zero++ = 0;
}
union {
unsigned char c[4];
unsigned int i;
}bu;
bu.c[0] = 128;
bu.c[1] = 0;
bu.c[2] = 128;
bu.c[3] = 0;
unsigned int black;
black = bu.i;
const int nSpikeScale=static_cast<int>(m_SpikeScale);
const int nSpikeFloor=static_cast<int>(m_SpikeFloor);
const int nSpikeCeiling=static_cast<int>(m_SpikeCeiling);
int nY=0;
while (pCurrentSource!=pSourceEnd) {
// const U32* pSourceLineStart=pCurrentSource;
const U32* pSourceLineEnd=pCurrentSource+nWidth;
int nX=0;
while (pCurrentSource!=pSourceLineEnd) {
U32 SourceColour=*pCurrentSource;
int nLuminance=(SourceColour&(0xff<<SHIFT_Y1))>>SHIFT_Y1;
nLuminance=clampFunc(nLuminance,nSpikeFloor,nSpikeCeiling);
nLuminance-=nSpikeFloor;
const int nLength=((nLuminance*nSpikeScale)>>nFixedShift);
int nDeltaX=((nX-nHalfWidth)*nLength)>>8;
int nDeltaY=((nY-nHalfHeight)*nLength)>>8;
int nEndX=nX+nDeltaX;
if (nEndX>nWidth) {
nEndX=nWidth;
} else if (nEndX<0) {
nEndX=0;
}
int nEndY=nY+nDeltaY;
if (nEndY>nHeight) {
nEndY=nHeight;
} else if (nEndY<0) {
nEndY=0;
}
int nXInc;
if (nDeltaX<0) {
nXInc=-1;
} else {
nXInc=1;
}
int nYInc;
if (nDeltaY<0) {
nYInc=-1;
} else {
nYInc=1;
}
nDeltaX*=nXInc;
nDeltaY*=nYInc;
int nCurrentX=nX;
int nCurrentY=nY;
if ((nDeltaX==0)&&(nDeltaY==0)) {
nDeltaX=1;
nEndX+=1;
nEndY+=1;
} else if (nDeltaX==0) {
nEndX+=1;
} else if (nDeltaY==0) {
nEndY+=1;
}
U32* pDest=(pOutput+(nCurrentY*nWidth)+nCurrentX);
const int nDestYInc=(nWidth*nYInc);
const int nDestXInc=nXInc;
if (nDeltaX>nDeltaY) {
int nCounter=nDeltaY;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour || DestColour == black) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaX) {
nCounter-=nDeltaX;
nCurrentY+=nYInc;
pDest+=nDestYInc;
}
nCurrentX+=nXInc;
pDest+=nDestXInc;
nCounter+=nDeltaY;
}
} else {
int nCounter=nDeltaX;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
// if (DestColour<SourceColour) {
if (DestColour<SourceColour || DestColour == black) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaY) {
nCounter-=nDeltaY;
nCurrentX+=nXInc;
pDest+=nDestXInc;
}
nCurrentY+=nYInc;
pDest+=nDestYInc;
nCounter+=nDeltaX;
};
}
pCurrentSource+=1;
pCurrentOutput+=1;
nX+=1;
}
nY+=1;
}
image.data = myImage.data;
}
/////////////////////////////////////////////////////////
// do the Gray processing here
//
/////////////////////////////////////////////////////////
/*
void pix_backlight :: processGrayImage(imageStruct &image)
{
nWidth = image.xsize;
nHeight = image.ysize;
if (!init) {
//Pete_BackLight_Init();
init = 1;
}
unsigned char* pSource = image.data;
if ( myImage.xsize*myImage.ysize*myImage.csize != image.xsize*image.ysize*image.csize ){
int dataSize = image.xsize * image.ysize * image.csize;
myImage.clear();
myImage.allocate(dataSize);
}
myImage.xsize = image.xsize;
myImage.ysize = image.ysize;
myImage.csize = image.csize;
myImage.type = image.type;
unsigned char* pOutput = myImage.data;
const int nFixedShift=8;
// const int nFixedMult=(1<<nFixedShift);
const int nHalfWidth=(nWidth/2);
const int nHalfHeight=(nHeight/2);
const int nNumPixels = nWidth*nHeight;
U32* pCurrentSource=pSource;
U32* pCurrentOutput=pOutput;
const U32* pSourceEnd=(pSource+nNumPixels);
// const U32* pOutputEnd=(pOutput+nNumPixels);
Pete_ZeroMemory(pOutput,sizeof(U32)*nNumPixels);
const int nSpikeScale=static_cast<int>(m_SpikeScale);
const int nSpikeFloor=static_cast<int>(m_SpikeFloor);
const int nSpikeCeiling=static_cast<int>(m_SpikeCeiling);
int nY=0;
while (pCurrentSource!=pSourceEnd) {
// const U32* pSourceLineStart=pCurrentSource;
const U32* pSourceLineEnd=pCurrentSource+nWidth;
int nX=0;
while (pCurrentSource!=pSourceLineEnd) {
U32 SourceColour=*pCurrentSource;
int nRed=(SourceColour&(0xff<<SHIFT_RED))>>SHIFT_RED;
int nGreen=(SourceColour&(0xff<<SHIFT_GREEN))>>SHIFT_GREEN;
int nBlue=(SourceColour&(0xff<<SHIFT_BLUE))>>SHIFT_BLUE;
int nLuminance =
((90 * nRed)+
(115 * nGreen)+
(51 * nBlue));
nLuminance>>=8;
// SourceColour|=(nLuminance<<24);
nLuminance=clampFunc(nLuminance,nSpikeFloor,nSpikeCeiling);
nLuminance-=nSpikeFloor;
const int nLength=((nLuminance*nSpikeScale)>>nFixedShift);
int nDeltaX=((nX-nHalfWidth)*nLength)>>8;
int nDeltaY=((nY-nHalfHeight)*nLength)>>8;
int nEndX=nX+nDeltaX;
if (nEndX>nWidth) {
nEndX=nWidth;
} else if (nEndX<0) {
nEndX=0;
}
int nEndY=nY+nDeltaY;
if (nEndY>nHeight) {
nEndY=nHeight;
} else if (nEndY<0) {
nEndY=0;
}
int nXInc;
if (nDeltaX<0) {
nXInc=-1;
} else {
nXInc=1;
}
int nYInc;
if (nDeltaY<0) {
nYInc=-1;
} else {
nYInc=1;
}
nDeltaX*=nXInc;
nDeltaY*=nYInc;
int nCurrentX=nX;
int nCurrentY=nY;
if ((nDeltaX==0)&&(nDeltaY==0)) {
nDeltaX=1;
nEndX+=1;
nEndY+=1;
} else if (nDeltaX==0) {
nEndX+=1;
} else if (nDeltaY==0) {
nEndY+=1;
}
U32* pDest=(pOutput+(nCurrentY*nWidth)+nCurrentX);
const int nDestYInc=(nWidth*nYInc);
const int nDestXInc=nXInc;
if (nDeltaX>nDeltaY) {
int nCounter=nDeltaY;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaX) {
nCounter-=nDeltaX;
nCurrentY+=nYInc;
pDest+=nDestYInc;
}
nCurrentX+=nXInc;
pDest+=nDestXInc;
nCounter+=nDeltaY;
}
} else {
int nCounter=nDeltaX;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaY) {
nCounter-=nDeltaY;
nCurrentX+=nXInc;
pDest+=nDestXInc;
}
nCurrentY+=nYInc;
pDest+=nDestYInc;
nCounter+=nDeltaX;
};
}
pCurrentSource+=1;
pCurrentOutput+=1;
nX+=1;
}
nY+=1;
}
image.data = myImage.data;
}
*/
/////////////////////////////////////////////////////////
// static member function
//
/////////////////////////////////////////////////////////
void pix_backlight :: obj_setupCallback(t_class *classPtr)
{
class_addmethod(classPtr, reinterpret_cast<t_method>(&pix_backlight::scaleCallback),
gensym("scale"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&pix_backlight::floorCallback),
gensym("floor"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&pix_backlight::ceilingCallback),
gensym("ceiling"), A_DEFFLOAT, A_NULL);
}
void pix_backlight :: scaleCallback(void *data, t_floatarg m_SpikeScale)
{
m_SpikeScale*=255.0;
// if(m_SpikeScale<0.f)m_SpikeScale=0.f;else if(m_SpikeScale>255.f)m_SpikeScale=255.f;
GetMyClass(data)->m_SpikeScale=(m_SpikeScale);
GetMyClass(data)->setPixModified();
}
void pix_backlight :: floorCallback(void *data, t_floatarg m_SpikeFloor)
{
m_SpikeFloor*=255.0;
if(m_SpikeFloor<0.f)m_SpikeFloor=0.f;else if(m_SpikeFloor>255.f)m_SpikeFloor=255.f;
GetMyClass(data)->m_SpikeFloor=(m_SpikeFloor);
GetMyClass(data)->setPixModified();
}
void pix_backlight :: ceilingCallback(void *data, t_floatarg m_SpikeCeiling)
{
m_SpikeCeiling*=255.0;
if(m_SpikeCeiling<0.f)m_SpikeCeiling=0.f;else if(m_SpikeCeiling>255.f)m_SpikeCeiling=255.f;
GetMyClass(data)->m_SpikeCeiling=(m_SpikeCeiling);
GetMyClass(data)->setPixModified();
}
|
gpl-3.0
|
Tabinol/WorldGuard2Secuboid
|
src/main/java/me/tabinol/worldguard2secuboid/ParType.java
|
820
|
/*
WorldGuard2Secuboid: Convert from WorldGuard regions to Secuboid lands
Copyright (C) 2015 Tabinol
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 me.tabinol.worldguard2secuboid;
public enum ParType {
PERMISSION,
FLAG
}
|
gpl-3.0
|
driusan/Loris
|
modules/dashboard/test/TestPlan.md
|
272
|
1. Log in. Note the time. Log out and log back in after 2 minutes. Check that welcome panel info is correct.
[Automate Test on Travis_CI]
2. Check performance on the raisin bread dataset: make sure the dashboard page displays within 5 seconds or less.
[Manual Test]
|
gpl-3.0
|
brianray/citar
|
src/tagger/hmm/ModelPrivate.hh
|
2739
|
#ifndef CITAR_MODEL_PRIVATE_HH
#define CITAR_MODEL_PRIVATE_HH
#include <iostream>
#include <map>
#include <string>
#include <memory>
#include <unordered_map>
#include <citar/util/NonCopyable.hh>
#include <citar/tagger/hmm/BiGram.hh>
#include <citar/tagger/hmm/TriGram.hh>
#include <citar/tagger/hmm/UniGram.hh>
namespace citar {
namespace tagger {
typedef std::unordered_map<std::string, std::map<size_t, size_t> >
WordTagFreqs;
/**
* Instances of this class contain a model for a trigram HMM tagger. It
* consists of the language model (uni/bi/trigram statistics) and a lexicon.
*/
class ModelPrivate
{
public:
BiGramFreqs const &biGrams() const;
WordTagFreqs const &lexicon() const;
std::unordered_map<size_t, std::string> const &numberTags() const;
/**
* Read the model from input streams. An input stream for the lexicon, and
* an input stream for n-gram statistics should be provided. The lexicon
* should list one word per line, followed by pairs of a tag and its
* frequency, for instance:
*
* <pre>
* uncommunicative JJ 1
* dormant JJ 3
* paranormal JJ 1
* plan NN 138 VB 27
* accolades NNS 1
* </pre>
*
* The ngram stream should list one ngram per line with its frequency. For
* instance:
*
* <pre>
* BED ABX 5
* OD , 82
* AP DO 1
* BEN ABN 1
* WPO VBD 5
* </pre>
*/
static ModelPrivate *readModel(std::istream &lexiconStream,
std::istream &nGramStream);
std::unordered_map<std::string, size_t> const &tagNumbers() const;
TriGramFreqs const &triGrams() const;
UniGramFreqs const &uniGrams() const;
private:
ModelPrivate(std::shared_ptr<WordTagFreqs> lexicon,
std::shared_ptr<NGrams> nGrams) :
d_lexicon(lexicon), d_nGrams(nGrams) {}
ModelPrivate(ModelPrivate const &other);
ModelPrivate &operator=(ModelPrivate const &other);
static std::shared_ptr<WordTagFreqs>
readLexicon(std::istream &lexiconStream,
std::unordered_map<std::string, size_t> const &tagNumbers);
static std::shared_ptr<NGrams> readNGrams(std::istream &lexiconStream);
std::shared_ptr<WordTagFreqs> d_lexicon;
std::shared_ptr<NGrams> d_nGrams;
};
inline BiGramFreqs const &ModelPrivate::biGrams() const
{
return d_nGrams->biGrams;
}
inline WordTagFreqs const &ModelPrivate::lexicon() const
{
return *d_lexicon;
}
inline std::unordered_map<size_t, std::string> const &ModelPrivate::numberTags() const
{
return d_nGrams->numberTags;
}
inline std::unordered_map<std::string, size_t> const &ModelPrivate::tagNumbers() const
{
return d_nGrams->tagNumbers;
}
inline TriGramFreqs const &ModelPrivate::triGrams() const
{
return d_nGrams->triGrams;
}
inline UniGramFreqs const &ModelPrivate::uniGrams() const
{
return d_nGrams->uniGrams;
}
}
}
#endif // CITAR_MODEL_HH
|
gpl-3.0
|
UnigramDev/Unigram
|
Unigram/Unigram/Common/TLNavigationService.cs
|
12617
|
using LinqToVisualTree;
using System;
using System.Collections.Generic;
using System.Linq;
using Telegram.Td.Api;
using Unigram.Controls;
using Unigram.Navigation;
using Unigram.Navigation.Services;
using Unigram.Services;
using Unigram.Services.ViewService;
using Unigram.ViewModels;
using Unigram.ViewModels.Settings;
using Unigram.Views;
using Unigram.Views.Payments;
using Unigram.Views.Settings;
using Unigram.Views.Settings.Popups;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.WindowManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Unigram.Common
{
public class TLNavigationService : NavigationService
{
private readonly IProtoService _protoService;
private readonly IPasscodeService _passcodeService;
private readonly IViewService _viewService;
private readonly Dictionary<string, AppWindow> _instantWindows = new Dictionary<string, AppWindow>();
public TLNavigationService(IProtoService protoService, IViewService viewService, Frame frame, int session, string id)
: base(frame, session, id)
{
_protoService = protoService;
_passcodeService = TLContainer.Current.Passcode;
_viewService = viewService;
}
public int SessionId => _protoService.SessionId;
public IProtoService ProtoService => _protoService;
public async void NavigateToInstant(string url)
{
//if (ApiInformation.IsTypePresent("Windows.UI.WindowManagement.AppWindow"))
//{
// _instantWindows.TryGetValue(url, out AppWindow window);
// if (window == null)
// {
// var nav = BootStrapper.Current.NavigationServiceFactory(BootStrapper.BackButton.Ignore, BootStrapper.ExistingContent.Exclude, 0, "0", false);
// var frame = BootStrapper.Current.CreateRootElement(nav);
// nav.Navigate(typeof(InstantPage), url);
// window = await AppWindow.TryCreateAsync();
// window.PersistedStateId = "InstantView";
// window.TitleBar.ExtendsContentIntoTitleBar = true;
// window.Closed += (s, args) =>
// {
// _instantWindows.Remove(url);
// frame = null;
// window = null;
// };
// _instantWindows[url] = window;
// ElementCompositionPreview.SetAppWindowContent(window, frame);
// }
// await window.TryShowAsync();
// window.RequestMoveAdjacentToCurrentView();
//}
//else
{
Navigate(typeof(InstantPage), url);
}
}
public async void NavigateToInvoice(MessageViewModel message)
{
var parameters = new ViewServiceParams
{
Title = message.Content is MessageInvoice invoice && invoice.ReceiptMessageId == 0 ? Strings.Resources.PaymentCheckout : Strings.Resources.PaymentReceipt,
Width = 380,
Height = 580,
PersistentId = "Payments",
Content = control =>
{
var nav = BootStrapper.Current.NavigationServiceFactory(BootStrapper.BackButton.Ignore, BootStrapper.ExistingContent.Exclude, SessionId, "Payments" + Guid.NewGuid(), false);
nav.Navigate(typeof(PaymentFormPage), state: Navigation.Services.NavigationState.GetInvoice(message.ChatId, message.Id));
return BootStrapper.Current.CreateRootElement(nav);
}
};
await _viewService.OpenAsync(parameters);
}
public async void NavigateToSender(MessageSender sender)
{
if (sender is MessageSenderUser user)
{
var response = await ProtoService.SendAsync(new CreatePrivateChat(user.UserId, false));
if (response is Chat chat)
{
Navigate(typeof(ProfilePage), chat.Id);
}
}
else if (sender is MessageSenderChat chat)
{
Navigate(typeof(ProfilePage), chat.ChatId);
}
}
public async void NavigateToChat(Chat chat, long? message = null, long? thread = null, string accessToken = null, NavigationState state = null, bool scheduled = false, bool force = true, bool createNewWindow = false)
{
if (chat == null)
{
return;
}
if (chat.Type is ChatTypePrivate privata)
{
var user = _protoService.GetUser(privata.UserId);
if (user == null)
{
return;
}
if (user.RestrictionReason.Length > 0)
{
await MessagePopup.ShowAsync(user.RestrictionReason, Strings.Resources.AppName, Strings.Resources.OK);
return;
}
}
else if (chat.Type is ChatTypeSupergroup super)
{
var supergroup = _protoService.GetSupergroup(super.SupergroupId);
if (supergroup == null)
{
return;
}
if (supergroup.Status is ChatMemberStatusLeft && string.IsNullOrEmpty(supergroup.Username) && !supergroup.HasLocation && !supergroup.HasLinkedChat && !_protoService.IsChatAccessible(chat))
{
await MessagePopup.ShowAsync(Strings.Resources.ChannelCantOpenPrivate, Strings.Resources.AppName, Strings.Resources.OK);
return;
}
if (supergroup.RestrictionReason.Length > 0)
{
await MessagePopup.ShowAsync(supergroup.RestrictionReason, Strings.Resources.AppName, Strings.Resources.OK);
return;
}
}
if (Frame.Content is ChatPage page && chat.Id.Equals((long)CurrentPageParam) && thread == null && !scheduled && !createNewWindow)
{
if (message != null)
{
await page.ViewModel.LoadMessageSliceAsync(null, message.Value);
}
else
{
await page.ViewModel.LoadMessageSliceAsync(null, chat.LastMessage?.Id ?? long.MaxValue, VerticalAlignment.Bottom);
}
if (accessToken != null && ProtoService.TryGetUser(chat, out User user) && ProtoService.TryGetUserFull(chat, out UserFullInfo userFull))
{
page.ViewModel.AccessToken = accessToken;
page.View.UpdateUserFullInfo(chat, user, userFull, false, true);
}
page.ViewModel.TextField?.Focus(FocusState.Programmatic);
if (App.DataPackages.TryRemove(chat.Id, out DataPackageView package))
{
await page.ViewModel.HandlePackageAsync(package);
}
}
else
{
//NavigatedEventHandler handler = null;
//handler = async (s, args) =>
//{
// Frame.Navigated -= handler;
// if (args.Content is DialogPage page1 /*&& chat.Id.Equals((long)args.Parameter)*/)
// {
// if (message.HasValue)
// {
// await page1.ViewModel.LoadMessageSliceAsync(null, message.Value);
// }
// }
//};
//Frame.Navigated += handler;
state ??= new NavigationState();
if (message != null)
{
state["message_id"] = message.Value;
}
if (accessToken != null)
{
state["access_token"] = accessToken;
}
if (createNewWindow)
{
Type target;
object parameter;
if (thread != null)
{
target = typeof(ChatThreadPage);
parameter = $"{chat.Id};{thread}";
}
else if (scheduled)
{
target = typeof(ChatScheduledPage);
parameter = chat.Id;
}
else
{
target = typeof(ChatPage);
parameter = chat.Id;
}
// This is horrible here but I don't want to bloat this method with dozens of parameters.
var masterDetailPanel = Window.Current.Content.Descendants<MasterDetailPanel>().FirstOrDefault();
if (masterDetailPanel != null)
{
await OpenAsync(target, parameter, size: new Windows.Foundation.Size(masterDetailPanel.ActualDetailWidth, masterDetailPanel.ActualHeight));
}
else
{
await OpenAsync(target, parameter);
}
}
else
{
if (Frame.Content is ChatPage chatPage && thread == null && !scheduled && !force)
{
chatPage.ViewModel.OnNavigatingFrom(null);
chatPage.Dispose();
chatPage.Activate(SessionId);
chatPage.ViewModel.NavigationService = this;
chatPage.ViewModel.Dispatcher = Dispatcher;
await chatPage.ViewModel.OnNavigatedToAsync(chat.Id, Windows.UI.Xaml.Navigation.NavigationMode.New, state);
FrameFacade.RaiseNavigated(chat.Id);
}
else
{
Type target;
object parameter;
if (thread != null)
{
target = typeof(ChatThreadPage);
parameter = $"{chat.Id};{thread}";
}
else if (scheduled)
{
target = typeof(ChatScheduledPage);
parameter = chat.Id;
}
else
{
target = typeof(ChatPage);
parameter = chat.Id;
}
Navigate(target, parameter, state);
}
}
}
}
public async void NavigateToChat(long chatId, long? message = null, long? thread = null, string accessToken = null, NavigationState state = null, bool scheduled = false, bool force = true, bool createNewWindow = false)
{
var chat = _protoService.GetChat(chatId);
if (chat == null)
{
chat = await _protoService.SendAsync(new GetChat(chatId)) as Chat;
}
if (chat == null)
{
return;
}
NavigateToChat(chat, message, thread, accessToken, state, scheduled, force, createNewWindow);
}
public async void NavigateToPasscode()
{
if (_passcodeService.IsEnabled)
{
var dialog = new SettingsPasscodeConfirmPopup();
var confirm = await dialog.ShowQueuedAsync();
if (confirm == ContentDialogResult.Primary)
{
Navigate(typeof(SettingsPasscodePage));
}
}
else
{
var popup = new SettingsPasscodePopup();
var confirm = await popup.ShowQueuedAsync();
if (confirm == ContentDialogResult.Primary)
{
var viewModel = TLContainer.Current.Resolve<SettingsPasscodeViewModel>(SessionId);
if (viewModel != null)
{
viewModel.ToggleCommand.Execute();
}
}
}
}
}
}
|
gpl-3.0
|
EITIorg/eiti
|
public_html/sites/all/libraries/awssdk2/Aws/CloudTrail/LogRecordIterator.php
|
5581
|
<?php
namespace AwsSdk2\Aws\CloudTrail;
use AwsSdk2\Aws\S3\S3Client;
use AwsSdk2\Guzzle\Common\Collection;
/**
* The `AwsSdk2\Aws\CloudTrail\LogRecordIterator` provides an easy way to iterate over log records from log files generated by
* AWS CloudTrail. CloudTrail log files contain data about your AWS API calls and are stored in Amazon S3 at a
* predictable path based on a bucket name, a key prefix, an account ID, a region, and date information. The files are
* gzipped and contain structured data in JSON format. This class allows you to specify options via its factory methods,
* including a date range, and emits each log record from any log files that match the provided options.
*
* @yields Collection A log record containing data about an AWS API call is yielded for each iteration on this object
*/
class LogRecordIterator implements \OuterIterator
{
/**
* @var LogFileReader
*/
private $logFileReader;
/**
* @var \Iterator
*/
private $logFileIterator;
/**
* @var array
*/
private $records;
/**
* @var int
*/
private $recordIndex;
/**
* @param S3Client $s3Client
* @param CloudTrailClient $cloudTrailClient
* @param array $options
*
* @return LogRecordIterator
*/
public static function forTrail(S3Client $s3Client, CloudTrailClient $cloudTrailClient, array $options = array())
{
$logFileReader = new LogFileReader($s3Client);
$logFileIterator = LogFileIterator::forTrail($s3Client, $cloudTrailClient, $options);
return new self($logFileReader, $logFileIterator);
}
/**
* @param S3Client $s3Client
* @param string $s3BucketName
* @param array $options
*
* @return LogRecordIterator
*/
public static function forBucket(S3Client $s3Client, $s3BucketName, array $options = array())
{
$logFileReader = new LogFileReader($s3Client);
$logFileIterator = new LogFileIterator($s3Client, $s3BucketName, $options);
return new self($logFileReader, $logFileIterator);
}
/**
* @param S3Client $s3Client
* @param string $s3BucketName
* @param string $s3ObjectKey
*
* @return LogRecordIterator
*/
public static function forFile(S3Client $s3Client, $s3BucketName, $s3ObjectKey)
{
$logFileReader = new LogFileReader($s3Client);
$logFileIterator = new \ArrayIterator(array(array(
'Bucket' => $s3BucketName,
'Key' => $s3ObjectKey,
)));
return new self($logFileReader, $logFileIterator);
}
/**
* @param LogFileReader $logFileReader
* @param \Iterator $logFileIterator
*/
public function __construct(LogFileReader $logFileReader, \Iterator $logFileIterator)
{
$this->logFileReader = $logFileReader;
$this->logFileIterator = $logFileIterator;
$this->records = array();
$this->recordIndex = 0;
}
/**
* Returns the current log record as a Guzzle Collection object. This object behaves like an associative array
* except that it returns `null` on non-existent keys instead of causing an error. See the linked resources for the
* schema of the log record data and how to work with Guzzle Collections.
*
* @return Collection
* @link http://docs.aws.amazon.com/awscloudtrail/latest/userguide/eventreference.html
* @link http://api.guzzlephp.org/class-Guzzle.Common.Collection.html
*/
public function current()
{
if ($this->valid()) {
return new Collection($this->records[$this->recordIndex]);
} else {
return false;
}
}
public function next()
{
$this->recordIndex++;
// If all the records have been exhausted, get more records from the next log file
while (!$this->valid()) {
$this->logFileIterator->next();
$success = $this->loadRecordsFromCurrentLogFile();
if (!$success) {
// The objects iterator is exhausted as well, so stop trying
break;
}
}
}
public function key()
{
if ($logFile = $this->logFileIterator->current()) {
return $logFile['Key'] . '.' . $this->recordIndex;
} else {
return null;
}
}
public function valid()
{
return isset($this->records[$this->recordIndex]);
}
public function rewind()
{
$this->logFileIterator->rewind();
$this->loadRecordsFromCurrentLogFile();
}
public function getInnerIterator()
{
return $this->logFileIterator;
}
/**
* Examines the current file in the `logFileIterator` and attempts to read it and load log records from it using
* the `logFileReader`. This method expects that items pulled from the iterator will take the form:
*
* array(
* 'Bucket' => '...',
* 'Key' => '...',
* )
*
* @return bool Returns `true` if records were loaded and `false` if no records were found
*/
private function loadRecordsFromCurrentLogFile()
{
$this->recordIndex = 0;
$this->records = array();
$logFile = $this->logFileIterator->current();
if ($logFile && isset($logFile['Bucket']) && isset($logFile['Key'])) {
$this->records = $this->logFileReader->read($logFile['Bucket'], $logFile['Key']);
}
return (bool) $logFile;
}
}
|
gpl-3.0
|
FBrand/MobileComputing2017
|
AppDBConnection/DBHelper.java
|
7405
|
package com.example.lars.connector;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by lars on 09.03.17.
*/
public class DBHelper extends SQLiteOpenHelper {
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE IF NOT EXISTS " + DBInfo.EXERCISE_TABLE_NAME + " (" +
DBInfo.EXERCISE_COLUMN_NAME_ID + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_AGE + " STRING,"+
DBInfo.EXERCISE_COLUMN_NAME_AUTORMAIL + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_AUTORNAME + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_DESCRIPTION + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_DURATION + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_GRAPHIC + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_GROUPSIZE + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_IDLOCAL + " INTEGER PRIMARY KEY AUTOINCREMENT," +
DBInfo.EXERCISE_COLUMN_NAME_KEYWORDS + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_LASTCHANGE +" DATE," +
DBInfo.EXERCISE_COLUMN_NAME_MATIRIAL + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_NAME + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_PHYSIS + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_RATING + " DOUBLE," +
DBInfo.EXERCISE_COLUMN_NAME_SPORT + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_TACTIC + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_TECHNIC + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_VIDEOLINK + " STRING);" +
"CREATE TABLE IF NOT EXISTS "+ DBInfo.TRAININGSUNIT_TABLE_NAME + " (" +
DBInfo.TRAININGSUNIT_COLUMN_NAME_AGE + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_AUTORMAIL + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_AUTORNAME + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_DESCRIPTION + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_DURATION + " INTEGER," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_EXERCISE + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_ID + " INTEGER," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_IDLOCAL + "INTEGER PRIMARY KEY AUTOINCREMENT," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_KEYWORDS + " STRINGS," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_LASTCHANGE + " DATE," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_NAME + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_RATING + " DOUBLE);";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + DBInfo.EXERCISE_TABLE_NAME + "; " +
"DROP TABLE IF EXISTS " + DBInfo.TRAININGSUNIT_TABLE_NAME;
public DBHelper(Context context){
super(context, DBInfo.DATABASE_NAME, null, DBInfo.DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
insertTestdata(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
/**
* Method for getting a database connection.
* @param context Contains context.
* @return A connection to the localdatabase ist returned.
*/
public static DBConnection getConnection (Context context){
DBHelper db = new DBHelper(context);
return new LocalDBConnection(db.getReadableDatabase());
}
public static void insertTestdata(SQLiteDatabase db){
LocalDBConnection con = new LocalDBConnection(db);
ContentValues row = new ContentValues();
row.put(DBInfo.EXERCISE_COLUMN_NAME_ID, 1);
row.put(DBInfo.EXERCISE_COLUMN_NAME_AGE, "A B C");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORMAIL, "mustermax@mail.com");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORNAME, "mustermax");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DESCRIPTION, "Dies ist eine Übung für Flanken von außen.");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DURATION, 30);
row.put(DBInfo.EXERCISE_COLUMN_NAME_GRAPHIC, "HFASFJK");
row.put(DBInfo.EXERCISE_COLUMN_NAME_GROUPSIZE, 5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_KEYWORDS, "Passen");
row.put(DBInfo.EXERCISE_COLUMN_NAME_MATIRIAL, "Ball, Tor");
row.put(DBInfo.EXERCISE_COLUMN_NAME_NAME, "Flanken");
row.put(DBInfo.EXERCISE_COLUMN_NAME_PHYSIS, 1);
row.put(DBInfo.EXERCISE_COLUMN_NAME_RATING, 3.5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_SPORT, "Fußball");
row.put(DBInfo.EXERCISE_COLUMN_NAME_TACTIC,2);
row.put(DBInfo.EXERCISE_COLUMN_NAME_TECHNIC,4);
row.put(DBInfo.EXERCISE_COLUMN_NAME_VIDEOLINK, "https://www.youtube.com/watch?v=C8oi-Q8oWCE");
con.insert(DBInfo.EXERCISE_TABLE_NAME, row);
row.clear();
row.put(DBInfo.EXERCISE_COLUMN_NAME_ID, 2);
row.put(DBInfo.EXERCISE_COLUMN_NAME_AGE, "A B");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORMAIL, "mustermax@mail.com");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORNAME, "mustermax");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DESCRIPTION, "Dies ist eine Übung für Schießen aus der Distanz.");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DURATION, 25);
row.put(DBInfo.EXERCISE_COLUMN_NAME_GRAPHIC, "HFadASFJK");
row.put(DBInfo.EXERCISE_COLUMN_NAME_GROUPSIZE, 4);
row.put(DBInfo.EXERCISE_COLUMN_NAME_KEYWORDS, "Schuss");
row.put(DBInfo.EXERCISE_COLUMN_NAME_MATIRIAL, "Ball, Tor");
row.put(DBInfo.EXERCISE_COLUMN_NAME_NAME, "Topspin");
row.put(DBInfo.EXERCISE_COLUMN_NAME_PHYSIS, 1);
row.put(DBInfo.EXERCISE_COLUMN_NAME_RATING, 4.5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_SPORT, "Fußball");
row.put(DBInfo.EXERCISE_COLUMN_NAME_TACTIC,1);
row.put(DBInfo.EXERCISE_COLUMN_NAME_TECHNIC,5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_VIDEOLINK, "https://www.youtube.com/watch?v=USVxAreHDow");
con.insert(DBInfo.EXERCISE_TABLE_NAME, row);
row.clear();
row.put(DBInfo.EXERCISE_COLUMN_NAME_ID, 3);
row.put(DBInfo.EXERCISE_COLUMN_NAME_AGE, "A B C D");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORMAIL, "mustermax@mail.com");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORNAME, "mustermax");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DESCRIPTION, "Dies ist eine Übung 1 gegen 1.");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DURATION, 15);
row.put(DBInfo.EXERCISE_COLUMN_NAME_GRAPHIC, "HFdadsadASFJK");
row.put(DBInfo.EXERCISE_COLUMN_NAME_GROUPSIZE, 6);
row.put(DBInfo.EXERCISE_COLUMN_NAME_KEYWORDS, "Zweikampf");
row.put(DBInfo.EXERCISE_COLUMN_NAME_MATIRIAL, "3 Ball");
row.put(DBInfo.EXERCISE_COLUMN_NAME_NAME, "Körpertäuschung");
row.put(DBInfo.EXERCISE_COLUMN_NAME_PHYSIS, 3);
row.put(DBInfo.EXERCISE_COLUMN_NAME_RATING, 1.5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_SPORT, "Fußball");
row.put(DBInfo.EXERCISE_COLUMN_NAME_TACTIC,3);
row.put(DBInfo.EXERCISE_COLUMN_NAME_TECHNIC,3);
row.put(DBInfo.EXERCISE_COLUMN_NAME_VIDEOLINK, "https://www.youtube.com/watch?v=HnHatjXLBY8");
System.out.println("TESTDATAINSERT " + con.insert(DBInfo.EXERCISE_TABLE_NAME, row));
row.clear();
}
}
|
gpl-3.0
|
SpecLad/Octetoscope
|
core/src/main/scala/ru/corrigendum/octetoscope/core/MoleculeBuilder.scala
|
2108
|
/*
This file is part of Octetoscope.
Copyright (C) 2013-2015 Octetoscope contributors (see /AUTHORS.txt)
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 ru.corrigendum.octetoscope.core
class MoleculeBuilder() {
private[this] val childrenBuilder = Seq.newBuilder[SubPiece]
private[this] var repr: Either[Option[String], () => Option[String]] = Left(None)
private[this] var autoSize: InfoSize = InfoSize()
private[this] var fixedSize: Option[InfoSize] = None
private[this] val notes = Seq.newBuilder[Note]
private[this] var hasChildren_ = false
def setRepr(repr: String): Unit = { this.repr = Left(Some(repr)) }
def setReprLazyO(reprOption: => Option[String]): Unit = {
this.repr = Right(() => reprOption)
}
def setReprLazy(repr: => String): Unit = {
setReprLazyO(Some(repr))
}
def addChild(name: String, offset: InfoSize, piece: PlainPiece): Unit = {
childrenBuilder += SubPiece(name, offset, piece)
autoSize = List(autoSize, offset + piece.size).max
hasChildren_ = true
}
def addNote(severity: NoteSeverity.Value, text: String): Unit = { notes += Note(severity, text) }
def build[V](v: V): MoleculeC[V] = {
val contents = repr.fold(new EagerContents(v, _), r => new Contents(v) {
override def reprO: Option[String] = r()
})
Molecule(fixedSize.getOrElse(autoSize), contents, childrenBuilder.result(), notes.result())
}
def hasChildren: Boolean = hasChildren_
def fixSize(size: InfoSize): Unit = { fixedSize = Some(size) }
}
|
gpl-3.0
|
divyanshgaba/Competitive-Coding
|
Random Pair/main.cpp
|
1044
|
/************************************
* AUTHOR: Divyansh Gaba *
* INSTITUTION: ASET, BIJWASAN *
************************************/
#include<bits/stdc++.h>
#define fast ios_base::sync_with_stdio(0); cin.tie(0);
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define REP(i,a,b) for (int i = a; i <= b; i++)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
int main()
{
fast;
int test=1;
cin>>test;
while(test--)
{
int n;
cin>>n;
vector<int> v,k;
for(int i = 0;i<n;i++)
{
int a;
cin>>a;
v.PB(a);
k.PB(a);
}
sort(k.begin(),k.end());
int val = k[n-1] + k[n-2];
double ans = 0;
for(int i = 0;i<n-1;i++)
{
for(int j = i+1;j<n;j++)
{
if(val == v[i]+v[j])
ans += 1;
}
}
cout<<fixed<<setprecision(10)<<(ans/double(double(n*(n-1))/2))<<endl;
}
return 0;
}
|
gpl-3.0
|
115ek/androidclient
|
app/src/main/java/org/kontalk/service/msgcenter/event/VersionRequest.java
|
1049
|
/*
* Kontalk Android client
* Copyright (C) 2018 Kontalk Devteam <devteam@kontalk.org>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kontalk.service.msgcenter.event;
import org.jxmpp.jid.Jid;
/**
* Version request event.
* @author Daniele Ricci
*/
public class VersionRequest extends RequestEvent {
public final Jid jid;
public VersionRequest(String id, Jid jid) {
super(id);
this.jid = jid;
}
}
|
gpl-3.0
|
Ignigena/bethel-dashboard
|
core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/Entity/EntityTestRev.php
|
1893
|
<?php
/**
* @file
* Definition of Drupal\entity_test\Entity\EntityTestRev.
*/
namespace Drupal\entity_test\Entity;
use Drupal\Core\Field\FieldDefinition;
use Drupal\entity_test\Entity\EntityTest;
/**
* Defines the test entity class.
*
* @EntityType(
* id = "entity_test_rev",
* label = @Translation("Test entity - revisions"),
* controllers = {
* "storage" = "Drupal\Core\Entity\FieldableDatabaseStorageController",
* "access" = "Drupal\entity_test\EntityTestAccessController",
* "form" = {
* "default" = "Drupal\entity_test\EntityTestFormController"
* },
* "translation" = "Drupal\content_translation\ContentTranslationController"
* },
* base_table = "entity_test_rev",
* revision_table = "entity_test_rev_revision",
* fieldable = TRUE,
* entity_keys = {
* "id" = "id",
* "uuid" = "uuid",
* "revision" = "revision_id",
* "bundle" = "type"
* },
* links = {
* "canonical" = "entity_test.edit_entity_test_rev",
* "edit-form" = "entity_test.edit_entity_test_rev"
* }
* )
*/
class EntityTestRev extends EntityTest {
/**
* The entity revision id.
*
* @var \Drupal\Core\Field\FieldItemListInterface
*/
public $revision_id;
/**
* {@inheritdoc}
*/
public function init() {
parent::init();
unset($this->revision_id);
}
/**
* Implements Drupal\Core\Entity\EntityInterface::getRevisionId().
*/
public function getRevisionId() {
return $this->get('revision_id')->value;
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions($entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields['revision_id'] = FieldDefinition::create('integer')
->setLabel(t('Revision ID'))
->setDescription(t('The version id of the test entity.'))
->setReadOnly(TRUE);
return $fields;
}
}
|
gpl-3.0
|
tanakamura/meadow
|
src/w32heap.h
|
3440
|
/* Heap management routines (including unexec) for GNU Emacs on Windows NT.
Copyright (C) 1994, 2001, 2002, 2003, 2004, 2005,
2006, 2007, 2008 Free Software Foundation, Inc.
This file is part of GNU Emacs.
GNU Emacs 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, or (at your option)
any later version.
GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
Geoff Voelker (voelker@cs.washington.edu) 7-29-94
*/
#ifndef NTHEAP_H_
#define NTHEAP_H_
#include <windows.h>
#define ROUND_UP(p, align) (((DWORD)(p) + (align)-1) & ~((align)-1))
#define ROUND_DOWN(p, align) ((DWORD)(p) & ~((align)-1))
/*
* Heap related stuff.
*/
#define get_reserved_heap_size() reserved_heap_size
#define get_committed_heap_size() (get_data_end () - get_data_start ())
#define get_heap_start() get_data_start ()
#define get_heap_end() get_data_end ()
#define get_page_size() sysinfo_cache.dwPageSize
#define get_allocation_unit() sysinfo_cache.dwAllocationGranularity
#define get_processor_type() sysinfo_cache.dwProcessorType
#define get_w32_major_version() w32_major_version
#define get_w32_minor_version() w32_minor_version
extern unsigned char *get_data_start();
extern unsigned char *get_data_end();
extern unsigned long reserved_heap_size;
extern SYSTEM_INFO sysinfo_cache;
extern OSVERSIONINFO osinfo_cache;
extern BOOL using_dynamic_heap;
extern int w32_major_version;
extern int w32_minor_version;
extern int w32_build_number;
enum {
OS_WIN95 = 1,
OS_NT
};
extern int os_subtype;
/* Emulation of Unix sbrk(). */
extern void *sbrk (unsigned long size);
/* Initialize heap structures for sbrk on startup. */
extern void init_heap ();
/* Round the heap to this size. */
extern void round_heap (unsigned long size);
/* Cache system info, e.g., the NT page size. */
extern void cache_system_info (void);
/* ----------------------------------------------------------------- */
/* Useful routines for manipulating memory-mapped files. */
typedef struct file_data {
char *name;
unsigned long size;
HANDLE file;
HANDLE file_mapping;
unsigned char *file_base;
} file_data;
int open_input_file (file_data *p_file, char *name);
int open_output_file (file_data *p_file, char *name, unsigned long size);
void close_file_data (file_data *p_file);
/* Return pointer to section header for named section. */
IMAGE_SECTION_HEADER * find_section (char * name, IMAGE_NT_HEADERS * nt_header);
/* Return pointer to section header for section containing the given
relative virtual address. */
IMAGE_SECTION_HEADER * rva_to_section (DWORD rva, IMAGE_NT_HEADERS * nt_header);
#endif /* NTHEAP_H_ */
/* arch-tag: 3ba4cbe1-8a09-4a41-8f37-fd31f7426b3c
(do not change this comment) */
|
gpl-3.0
|
AAlvz/aalvz.github.io
|
_pages/cool_code/random.md
|
298
|
---
resource: true
categories: [Cool-Code]
title: Renaming enumerating
description: For a bunch of files, this code renames the file adding a number to the beginning of the filename.
---
```
c=1; for file in `ls -Utp | grep -v / | awk '{ print $9 }' `; do mv "$file" "$[c++]"-"$file"; done
```
|
gpl-3.0
|
ManifoldScholar/manifold
|
client/src/global/components/Annotation/Annotation/UserContent/Meta.js
|
3870
|
import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { withTranslation } from "react-i18next";
import FormattedDate from "global/components/FormattedDate";
import classNames from "classnames";
import Authorize from "hoc/Authorize";
import Avatar from "global/components/avatar/index";
import lh from "helpers/linkHandler";
import { Link } from "react-router-dom";
class AnnotationMeta extends PureComponent {
static displayName = "Annotation.Meta";
static propTypes = {
annotation: PropTypes.object.isRequired,
subject: PropTypes.string,
includeMarkers: PropTypes.bool,
t: PropTypes.func
};
static defaultProps = {
includeMarkers: true
};
get subtitle() {
if (!this.props.subject) return this.dateSubtitle;
return this.subjectSubtitle;
}
get name() {
const {
t,
annotation: {
attributes: { currentUserIsCreator, creatorName }
}
} = this.props;
if (currentUserIsCreator) return t("common.me");
return creatorName;
}
get subjectSubtitle() {
const { subject } = this.props;
return (
<div className="annotation-meta__subtitle">
{subject} {this.dateSubtitle}
</div>
);
}
get dateSubtitle() {
const { annotation, t } = this.props;
return (
<span className="annotation-meta__datetime">
<FormattedDate
format="distanceInWords"
date={annotation.attributes.createdAt}
/>{" "}
{t("dates.ago")}
</span>
);
}
get avatarUrl() {
const {
annotation: {
attributes: { creatorAvatarStyles }
}
} = this.props;
return creatorAvatarStyles.smallSquare;
}
get avatarClassNames() {
return classNames({
"annotation-meta__avatar": true,
"annotation-meta__avatar-placeholder-container": !this.avatarUrl,
"annotation-meta__avatar-image-container": this.avatarUrl
});
}
renderMarkers(annotation) {
const t = this.props.t;
return (
<div className="annotation-tag annotation-tag--group">
{annotation.attributes.authorCreated && (
<div className="annotation-tag__inner">
{t("glossary.author_one")}
</div>
)}
{annotation.attributes.private && (
<div className="annotation-tag__inner annotation-tag--secondary">
{t("common.private")}
</div>
)}
{annotation.attributes.flagsCount > 0 && (
<Authorize kind="admin">
<div className="annotation-tag__inner annotation-tag--secondary">
{t("counts.flag", { count: annotation.attributes.flagsCount })}
</div>
</Authorize>
)}
{annotation.attributes.readingGroupId && (
<Link
to={lh.link(
"frontendReadingGroupDetail",
annotation.attributes.readingGroupId,
{
text: annotation.attributes.textId
}
)}
className="annotation-tag__inner"
>
<div className="annotation-tag__text">
{annotation.attributes.readingGroupName}
</div>
</Link>
)}
</div>
);
}
render() {
const { annotation, includeMarkers } = this.props;
if (!annotation) return null;
return (
<section className="annotation-meta">
{/* NB: Empty div required for flex-positioning of private/author marker */}
<div>
<div className={this.avatarClassNames}>
<Avatar url={this.avatarUrl} />
</div>
<h4 className="annotation-meta__author-name">{this.name}</h4>
{this.subtitle}
</div>
{includeMarkers && this.renderMarkers(annotation)}
</section>
);
}
}
export default withTranslation()(AnnotationMeta);
|
gpl-3.0
|
OmniEvo/android_frameworks_base
|
services/core/java/com/android/server/power/Notifier.java
|
27822
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.power;
import android.app.ActivityManagerInternal;
import android.app.AppOpsManager;
import com.android.internal.app.IAppOpsService;
import com.android.internal.app.IBatteryStats;
import com.android.server.EventLogTags;
import com.android.server.LocalServices;
import android.app.ActivityManagerNative;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManagerInternal;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.BatteryStats;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManagerInternal;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.UserHandle;
import android.os.WorkSource;
import android.provider.Settings;
import android.util.EventLog;
import android.util.Slog;
import android.view.WindowManagerPolicy;
import android.view.inputmethod.InputMethodManagerInternal;
/**
* Sends broadcasts about important power state changes.
* <p>
* This methods of this class may be called by the power manager service while
* its lock is being held. Internally it takes care of sending broadcasts to
* notify other components of the system or applications asynchronously.
* </p><p>
* The notifier is designed to collapse unnecessary broadcasts when it is not
* possible for the system to have observed an intermediate state.
* </p><p>
* For example, if the device wakes up, goes to sleep, wakes up again and goes to
* sleep again before the wake up notification is sent, then the system will
* be told about only one wake up and sleep. However, we always notify the
* fact that at least one transition occurred. It is especially important to
* tell the system when we go to sleep so that it can lock the keyguard if needed.
* </p>
*/
final class Notifier {
private static final String TAG = "PowerManagerNotifier";
private static final boolean DEBUG = false;
private static final int INTERACTIVE_STATE_UNKNOWN = 0;
private static final int INTERACTIVE_STATE_AWAKE = 1;
private static final int INTERACTIVE_STATE_ASLEEP = 2;
private static final int MSG_USER_ACTIVITY = 1;
private static final int MSG_BROADCAST = 2;
private static final int MSG_WIRELESS_CHARGING_STARTED = 3;
private static final int MSG_SCREEN_BRIGHTNESS_BOOST_CHANGED = 4;
private static final int MSG_WIRED_CHARGING_STARTED = 5;
private final Object mLock = new Object();
private final Context mContext;
private final IBatteryStats mBatteryStats;
private final IAppOpsService mAppOps;
private final SuspendBlocker mSuspendBlocker;
private final WindowManagerPolicy mPolicy;
private final ActivityManagerInternal mActivityManagerInternal;
private final InputManagerInternal mInputManagerInternal;
private final InputMethodManagerInternal mInputMethodManagerInternal;
private final NotifierHandler mHandler;
private final Intent mScreenOnIntent;
private final Intent mScreenOffIntent;
private final Intent mScreenBrightnessBoostIntent;
// True if the device should suspend when the screen is off due to proximity.
private final boolean mSuspendWhenScreenOffDueToProximityConfig;
// The current interactive state. This is set as soon as an interactive state
// transition begins so as to capture the reason that it happened. At some point
// this state will propagate to the pending state then eventually to the
// broadcasted state over the course of reporting the transition asynchronously.
private boolean mInteractive = true;
private int mInteractiveChangeReason;
private boolean mInteractiveChanging;
// The pending interactive state that we will eventually want to broadcast.
// This is designed so that we can collapse redundant sequences of awake/sleep
// transition pairs while still guaranteeing that at least one transition is observed
// whenever this happens.
private int mPendingInteractiveState;
private boolean mPendingWakeUpBroadcast;
private boolean mPendingGoToSleepBroadcast;
// The currently broadcasted interactive state. This reflects what other parts of the
// system have observed.
private int mBroadcastedInteractiveState;
private boolean mBroadcastInProgress;
private long mBroadcastStartTime;
// True if a user activity message should be sent.
private boolean mUserActivityPending;
public Notifier(Looper looper, Context context, IBatteryStats batteryStats,
IAppOpsService appOps, SuspendBlocker suspendBlocker,
WindowManagerPolicy policy) {
mContext = context;
mBatteryStats = batteryStats;
mAppOps = appOps;
mSuspendBlocker = suspendBlocker;
mPolicy = policy;
mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
mInputMethodManagerInternal = LocalServices.getService(InputMethodManagerInternal.class);
mHandler = new NotifierHandler(looper);
mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
mScreenOnIntent.addFlags(
Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
mScreenOffIntent.addFlags(
Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
mScreenBrightnessBoostIntent =
new Intent(PowerManager.ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED);
mScreenBrightnessBoostIntent.addFlags(
Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
mSuspendWhenScreenOffDueToProximityConfig = context.getResources().getBoolean(
com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
// Initialize interactive state for battery stats.
try {
mBatteryStats.noteInteractive(true);
} catch (RemoteException ex) { }
}
/**
* Called when a wake lock is acquired.
*/
public void onWakeLockAcquired(int flags, String tag, String packageName,
int ownerUid, int ownerPid, WorkSource workSource, String historyTag) {
if (DEBUG) {
Slog.d(TAG, "onWakeLockAcquired: flags=" + flags + ", tag=\"" + tag
+ "\", packageName=" + packageName
+ ", ownerUid=" + ownerUid + ", ownerPid=" + ownerPid
+ ", workSource=" + workSource);
}
final int monitorType = getBatteryStatsWakeLockMonitorType(flags);
if (monitorType >= 0) {
try {
final boolean unimportantForLogging = ownerUid == Process.SYSTEM_UID
&& (flags & PowerManager.UNIMPORTANT_FOR_LOGGING) != 0;
if (workSource != null) {
mBatteryStats.noteStartWakelockFromSource(workSource, ownerPid, tag,
historyTag, monitorType, unimportantForLogging);
} else {
mBatteryStats.noteStartWakelock(ownerUid, ownerPid, tag, historyTag,
monitorType, unimportantForLogging);
// XXX need to deal with disabled operations.
mAppOps.startOperation(AppOpsManager.getToken(mAppOps),
AppOpsManager.OP_WAKE_LOCK, ownerUid, packageName);
}
} catch (RemoteException ex) {
// Ignore
}
}
}
/**
* Called when a wake lock is changing.
*/
public void onWakeLockChanging(int flags, String tag, String packageName,
int ownerUid, int ownerPid, WorkSource workSource, String historyTag,
int newFlags, String newTag, String newPackageName, int newOwnerUid,
int newOwnerPid, WorkSource newWorkSource, String newHistoryTag) {
final int monitorType = getBatteryStatsWakeLockMonitorType(flags);
final int newMonitorType = getBatteryStatsWakeLockMonitorType(newFlags);
if (workSource != null && newWorkSource != null
&& monitorType >= 0 && newMonitorType >= 0) {
if (DEBUG) {
Slog.d(TAG, "onWakeLockChanging: flags=" + newFlags + ", tag=\"" + newTag
+ "\", packageName=" + newPackageName
+ ", ownerUid=" + newOwnerUid + ", ownerPid=" + newOwnerPid
+ ", workSource=" + newWorkSource);
}
final boolean unimportantForLogging = newOwnerUid == Process.SYSTEM_UID
&& (newFlags & PowerManager.UNIMPORTANT_FOR_LOGGING) != 0;
try {
mBatteryStats.noteChangeWakelockFromSource(workSource, ownerPid, tag, historyTag,
monitorType, newWorkSource, newOwnerPid, newTag, newHistoryTag,
newMonitorType, unimportantForLogging);
} catch (RemoteException ex) {
// Ignore
}
} else {
onWakeLockReleased(flags, tag, packageName, ownerUid, ownerPid, workSource, historyTag);
onWakeLockAcquired(newFlags, newTag, newPackageName, newOwnerUid, newOwnerPid,
newWorkSource, newHistoryTag);
}
}
/**
* Called when a wake lock is released.
*/
public void onWakeLockReleased(int flags, String tag, String packageName,
int ownerUid, int ownerPid, WorkSource workSource, String historyTag) {
if (DEBUG) {
Slog.d(TAG, "onWakeLockReleased: flags=" + flags + ", tag=\"" + tag
+ "\", packageName=" + packageName
+ ", ownerUid=" + ownerUid + ", ownerPid=" + ownerPid
+ ", workSource=" + workSource);
}
final int monitorType = getBatteryStatsWakeLockMonitorType(flags);
if (monitorType >= 0) {
try {
if (workSource != null) {
mBatteryStats.noteStopWakelockFromSource(workSource, ownerPid, tag,
historyTag, monitorType);
} else {
mBatteryStats.noteStopWakelock(ownerUid, ownerPid, tag,
historyTag, monitorType);
mAppOps.finishOperation(AppOpsManager.getToken(mAppOps),
AppOpsManager.OP_WAKE_LOCK, ownerUid, packageName);
}
} catch (RemoteException ex) {
// Ignore
}
}
}
private int getBatteryStatsWakeLockMonitorType(int flags) {
switch (flags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
case PowerManager.PARTIAL_WAKE_LOCK:
return BatteryStats.WAKE_TYPE_PARTIAL;
case PowerManager.SCREEN_DIM_WAKE_LOCK:
case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
return BatteryStats.WAKE_TYPE_FULL;
case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
if (mSuspendWhenScreenOffDueToProximityConfig) {
return -1;
}
return BatteryStats.WAKE_TYPE_PARTIAL;
case PowerManager.DRAW_WAKE_LOCK:
return BatteryStats.WAKE_TYPE_DRAW;
case PowerManager.DOZE_WAKE_LOCK:
// Doze wake locks are an internal implementation detail of the
// communication between dream manager service and power manager
// service. They have no additive battery impact.
return -1;
default:
return -1;
}
}
/**
* Notifies that the device is changing wakefulness.
* This function may be called even if the previous change hasn't finished in
* which case it will assume that the state did not fully converge before the
* next transition began and will recover accordingly.
*/
public void onWakefulnessChangeStarted(final int wakefulness, int reason) {
final boolean interactive = PowerManagerInternal.isInteractive(wakefulness);
if (DEBUG) {
Slog.d(TAG, "onWakefulnessChangeStarted: wakefulness=" + wakefulness
+ ", reason=" + reason + ", interactive=" + interactive);
}
// Tell the activity manager about changes in wakefulness, not just interactivity.
// It needs more granularity than other components.
mHandler.post(new Runnable() {
@Override
public void run() {
mActivityManagerInternal.onWakefulnessChanged(wakefulness);
}
});
// Handle any early interactive state changes.
// Finish pending incomplete ones from a previous cycle.
if (mInteractive != interactive) {
// Finish up late behaviors if needed.
if (mInteractiveChanging) {
handleLateInteractiveChange();
}
// Start input as soon as we start waking up or going to sleep.
mInputManagerInternal.setInteractive(interactive);
mInputMethodManagerInternal.setInteractive(interactive);
// Notify battery stats.
try {
mBatteryStats.noteInteractive(interactive);
} catch (RemoteException ex) { }
// Handle early behaviors.
mInteractive = interactive;
mInteractiveChangeReason = reason;
mInteractiveChanging = true;
handleEarlyInteractiveChange();
}
}
/**
* Notifies that the device has finished changing wakefulness.
*/
public void onWakefulnessChangeFinished() {
if (DEBUG) {
Slog.d(TAG, "onWakefulnessChangeFinished");
}
if (mInteractiveChanging) {
mInteractiveChanging = false;
handleLateInteractiveChange();
}
}
/**
* Handle early interactive state changes such as getting applications or the lock
* screen running and ready for the user to see (such as when turning on the screen).
*/
private void handleEarlyInteractiveChange() {
synchronized (mLock) {
if (mInteractive) {
// Waking up...
mHandler.post(new Runnable() {
@Override
public void run() {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, 0, 0, 0);
mPolicy.startedWakingUp();
}
});
// Send interactive broadcast.
mPendingInteractiveState = INTERACTIVE_STATE_AWAKE;
mPendingWakeUpBroadcast = true;
updatePendingBroadcastLocked();
} else {
// Going to sleep...
// Tell the policy that we started going to sleep.
final int why = translateOffReason(mInteractiveChangeReason);
mHandler.post(new Runnable() {
@Override
public void run() {
mPolicy.startedGoingToSleep(why);
}
});
}
}
}
/**
* Handle late interactive state changes once they are finished so that the system can
* finish pending transitions (such as turning the screen off) before causing
* applications to change state visibly.
*/
private void handleLateInteractiveChange() {
synchronized (mLock) {
if (mInteractive) {
// Finished waking up...
mHandler.post(new Runnable() {
@Override
public void run() {
mPolicy.finishedWakingUp();
}
});
} else {
// Finished going to sleep...
// This is a good time to make transitions that we don't want the user to see,
// such as bringing the key guard to focus. There's no guarantee for this
// however because the user could turn the device on again at any time.
// Some things may need to be protected by other mechanisms that defer screen on.
// Cancel pending user activity.
if (mUserActivityPending) {
mUserActivityPending = false;
mHandler.removeMessages(MSG_USER_ACTIVITY);
}
// Tell the policy we finished going to sleep.
final int why = translateOffReason(mInteractiveChangeReason);
mHandler.post(new Runnable() {
@Override
public void run() {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, why, 0, 0);
mPolicy.finishedGoingToSleep(why);
}
});
// Send non-interactive broadcast.
mPendingInteractiveState = INTERACTIVE_STATE_ASLEEP;
mPendingGoToSleepBroadcast = true;
updatePendingBroadcastLocked();
}
}
}
private static int translateOffReason(int reason) {
switch (reason) {
case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
return WindowManagerPolicy.OFF_BECAUSE_OF_ADMIN;
case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
return WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
default:
return WindowManagerPolicy.OFF_BECAUSE_OF_USER;
}
}
/**
* Called when screen brightness boost begins or ends.
*/
public void onScreenBrightnessBoostChanged() {
if (DEBUG) {
Slog.d(TAG, "onScreenBrightnessBoostChanged");
}
mSuspendBlocker.acquire();
Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_CHANGED);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
/**
* Called when there has been user activity.
*/
public void onUserActivity(int event, int uid) {
if (DEBUG) {
Slog.d(TAG, "onUserActivity: event=" + event + ", uid=" + uid);
}
try {
mBatteryStats.noteUserActivity(uid, event);
} catch (RemoteException ex) {
// Ignore
}
synchronized (mLock) {
if (!mUserActivityPending) {
mUserActivityPending = true;
Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
}
}
/**
* Called when the screen has turned on.
*/
public void onWakeUp(String reason, int reasonUid, String opPackageName, int opUid) {
if (DEBUG) {
Slog.d(TAG, "onWakeUp: event=" + reason + ", reasonUid=" + reasonUid
+ " opPackageName=" + opPackageName + " opUid=" + opUid);
}
try {
mBatteryStats.noteWakeUp(reason, reasonUid);
if (opPackageName != null) {
mAppOps.noteOperation(AppOpsManager.OP_TURN_SCREEN_ON, opUid, opPackageName);
}
} catch (RemoteException ex) {
// Ignore
}
}
/**
* Called when wireless charging has started so as to provide user feedback.
*/
public void onWirelessChargingStarted() {
if (DEBUG) {
Slog.d(TAG, "onWirelessChargingStarted");
}
mSuspendBlocker.acquire();
Message msg = mHandler.obtainMessage(MSG_WIRELESS_CHARGING_STARTED);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
/**
* Called when wireless charging has started so as to provide user feedback.
*/
public void onWiredChargingStarted() {
if (DEBUG) {
Slog.d(TAG, "onWiredChargingStarted");
}
mSuspendBlocker.acquire();
Message msg = mHandler.obtainMessage(MSG_WIRED_CHARGING_STARTED);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
private void updatePendingBroadcastLocked() {
if (!mBroadcastInProgress
&& mPendingInteractiveState != INTERACTIVE_STATE_UNKNOWN
&& (mPendingWakeUpBroadcast || mPendingGoToSleepBroadcast
|| mPendingInteractiveState != mBroadcastedInteractiveState)) {
mBroadcastInProgress = true;
mSuspendBlocker.acquire();
Message msg = mHandler.obtainMessage(MSG_BROADCAST);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
}
private void finishPendingBroadcastLocked() {
mBroadcastInProgress = false;
mSuspendBlocker.release();
}
private void sendUserActivity() {
synchronized (mLock) {
if (!mUserActivityPending) {
return;
}
mUserActivityPending = false;
}
mPolicy.userActivity();
}
private void sendNextBroadcast() {
final int powerState;
synchronized (mLock) {
if (mBroadcastedInteractiveState == INTERACTIVE_STATE_UNKNOWN) {
// Broadcasted power state is unknown. Send wake up.
mPendingWakeUpBroadcast = false;
mBroadcastedInteractiveState = INTERACTIVE_STATE_AWAKE;
} else if (mBroadcastedInteractiveState == INTERACTIVE_STATE_AWAKE) {
// Broadcasted power state is awake. Send asleep if needed.
if (mPendingWakeUpBroadcast || mPendingGoToSleepBroadcast
|| mPendingInteractiveState == INTERACTIVE_STATE_ASLEEP) {
mPendingGoToSleepBroadcast = false;
mBroadcastedInteractiveState = INTERACTIVE_STATE_ASLEEP;
} else {
finishPendingBroadcastLocked();
return;
}
} else {
// Broadcasted power state is asleep. Send awake if needed.
if (mPendingWakeUpBroadcast || mPendingGoToSleepBroadcast
|| mPendingInteractiveState == INTERACTIVE_STATE_AWAKE) {
mPendingWakeUpBroadcast = false;
mBroadcastedInteractiveState = INTERACTIVE_STATE_AWAKE;
} else {
finishPendingBroadcastLocked();
return;
}
}
mBroadcastStartTime = SystemClock.uptimeMillis();
powerState = mBroadcastedInteractiveState;
}
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, 1);
if (powerState == INTERACTIVE_STATE_AWAKE) {
sendWakeUpBroadcast();
} else {
sendGoToSleepBroadcast();
}
}
private void sendBrightnessBoostChangedBroadcast() {
if (DEBUG) {
Slog.d(TAG, "Sending brightness boost changed broadcast.");
}
mContext.sendOrderedBroadcastAsUser(mScreenBrightnessBoostIntent, UserHandle.ALL, null,
mScreeBrightnessBoostChangedDone, mHandler, 0, null, null);
}
private final BroadcastReceiver mScreeBrightnessBoostChangedDone = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mSuspendBlocker.release();
}
};
private void sendWakeUpBroadcast() {
if (DEBUG) {
Slog.d(TAG, "Sending wake up broadcast.");
}
if (ActivityManagerNative.isSystemReady()) {
mContext.sendOrderedBroadcastAsUser(mScreenOnIntent, UserHandle.ALL, null,
mWakeUpBroadcastDone, mHandler, 0, null, null);
} else {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2, 1);
sendNextBroadcast();
}
}
private final BroadcastReceiver mWakeUpBroadcastDone = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
SystemClock.uptimeMillis() - mBroadcastStartTime, 1);
sendNextBroadcast();
}
};
private void sendGoToSleepBroadcast() {
if (DEBUG) {
Slog.d(TAG, "Sending go to sleep broadcast.");
}
if (ActivityManagerNative.isSystemReady()) {
mContext.sendOrderedBroadcastAsUser(mScreenOffIntent, UserHandle.ALL, null,
mGoToSleepBroadcastDone, mHandler, 0, null, null);
} else {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3, 1);
sendNextBroadcast();
}
}
private final BroadcastReceiver mGoToSleepBroadcastDone = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
SystemClock.uptimeMillis() - mBroadcastStartTime, 1);
sendNextBroadcast();
}
};
private void playWirelessChargingStartedSound() {
final boolean enabled = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.CHARGING_SOUNDS_ENABLED, 1) != 0;
final String soundPath = Settings.Global.getString(mContext.getContentResolver(),
Settings.Global.WIRELESS_CHARGING_STARTED_SOUND);
if (enabled && soundPath != null) {
final Uri soundUri = Uri.parse("file://" + soundPath);
if (soundUri != null) {
final Ringtone sfx = RingtoneManager.getRingtone(mContext, soundUri);
if (sfx != null) {
sfx.setStreamType(AudioManager.STREAM_SYSTEM);
sfx.play();
}
}
}
mSuspendBlocker.release();
}
private final class NotifierHandler extends Handler {
public NotifierHandler(Looper looper) {
super(looper, null, true /*async*/);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_USER_ACTIVITY:
sendUserActivity();
break;
case MSG_BROADCAST:
sendNextBroadcast();
break;
case MSG_WIRELESS_CHARGING_STARTED:
case MSG_WIRED_CHARGING_STARTED:
playWirelessChargingStartedSound();
break;
case MSG_SCREEN_BRIGHTNESS_BOOST_CHANGED:
sendBrightnessBoostChangedBroadcast();
break;
}
}
}
}
|
gpl-3.0
|
jadijadi/snowcrash
|
theme/bookstrap/static/css/style.css
|
1000
|
/*@import url(//fonts.googleapis.com/earlyaccess/droidarabicnaskh.css);
*/
@font-face {
font-family: 'Sahel';
src: url('../font/Sahel.eot');
src: url('../font/Sahel.eot?#iefix') format('embedded-opentype'), url('../font/Sahel.woff') format('woff'), url('../font/Sahel.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
ul {
margin-right: 28pt;
font-family: 'Sahel', "Droid Arabic Naskh";
font-size: 1.1em;
line-height: normal;
}
h1 {
margin-bottom: 32pt;
}
body {
padding-top: 60px;
padding-bottom: 40px;
font-family: 'Sahel', 'Droid Arabic Naskh', sans-serif !important;
}
.sidebar-nav {
padding: 9px 0;
}
.tag-1 {
font-size: 1.2em;
}
.tag-2 {
font-size: 10p1emt;
}
.tag-2 {
font-size: 0.9em;
}
.tag-4 {
font-size: 0.8em;
}
p {
font-family: 'Sahel', "Droid Arabic Naskh";
font-size: 1.2em;
line-height: normal;
}
.container-fluid {
direction: rtl;
}
pre {
font-size: 1.4em;
}
address {
text-align: center;
line-height: 14px;
margin-bottom: 6px;
}
|
gpl-3.0
|
gpospelov/BornAgain
|
gui2/model/applicationmodels.cpp
|
4964
|
// ************************************************************************************************
//
// BornAgain: simulate and fit reflection and scattering
//
//! @file gui2/model/applicationmodels.cpp
//! @brief Implements class CLASS?
//!
//! @homepage http://www.bornagainproject.org
//! @license GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2020
//! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
// ************************************************************************************************
#include "gui2/model/applicationmodels.h"
#include "gui2/model/experimentaldatacontroller.h"
#include "gui2/model/experimentaldatamodel.h"
#include "gui2/model/instrumentmodel.h"
#include "gui2/model/jobmodel.h"
#include "gui2/model/materialmodel.h"
#include "gui2/model/materialpropertycontroller.h"
#include "gui2/model/sampleitems.h"
#include "gui2/model/samplemodel.h"
#include "gui2/sldeditor/sldelementmodel.h"
#include "mvvm/model/externalproperty.h"
#include "mvvm/model/itempool.h"
#include "mvvm/model/modelutils.h"
#include "mvvm/model/sessionitem.h"
namespace gui2 {
using namespace ModelView;
struct ApplicationModels::ApplicationModelsImpl {
std::unique_ptr<MaterialModel> m_material_model;
std::unique_ptr<SampleModel> m_sample_model;
std::unique_ptr<SLDElementModel> m_sld_view_model;
std::unique_ptr<JobModel> m_job_model;
std::unique_ptr<ExperimentalDataModel> m_experimental_model;
std::unique_ptr<InstrumentModel> m_instrument_model;
std::unique_ptr<MaterialPropertyController> m_material_controller;
std::unique_ptr<ExperimentalDataController> m_data_controller;
std::shared_ptr<ItemPool> item_pool;
ApplicationModelsImpl()
{
item_pool = std::make_shared<ItemPool>();
m_material_model = std::make_unique<MaterialModel>(item_pool);
m_sample_model = std::make_unique<SampleModel>(item_pool);
m_sld_view_model = std::make_unique<SLDElementModel>();
m_job_model = std::make_unique<JobModel>(item_pool);
m_experimental_model = std::make_unique<ExperimentalDataModel>(item_pool);
m_instrument_model = std::make_unique<InstrumentModel>(item_pool);
m_material_controller = std::make_unique<MaterialPropertyController>(m_material_model.get(),
m_sample_model.get());
m_data_controller = std::make_unique<ExperimentalDataController>(m_experimental_model.get(),
m_instrument_model.get());
m_sample_model->create_default_multilayer();
update_material_properties();
}
//! Runs through all layers and assign materials.
//! Expecting 3 materials existing by default (air, default, Si) to assign to our 3 layers.
void update_material_properties()
{
auto multilayer = Utils::TopItem<MultiLayerItem>(m_sample_model.get());
auto layers = multilayer->items<LayerItem>(MultiLayerItem::T_LAYERS);
size_t index(0);
for (const auto& material_property : m_material_model->material_data()) {
if (index < layers.size())
layers[index]->setProperty(LayerItem::P_MATERIAL, material_property);
++index;
}
}
//! Models intended for saving.
std::vector<SessionModel*> persistent_models() const
{
return {m_material_model.get(), m_sample_model.get(), m_instrument_model.get(),
m_experimental_model.get()};
}
//! All application models.
std::vector<SessionModel*> application_models() const
{
return {m_material_model.get(), m_sample_model.get(), m_instrument_model.get(),
m_sld_view_model.get(), m_job_model.get(), m_experimental_model.get()};
}
};
ApplicationModels::ApplicationModels() : p_impl(std::make_unique<ApplicationModelsImpl>()) {}
ApplicationModels::~ApplicationModels() = default;
MaterialModel* ApplicationModels::materialModel()
{
return p_impl->m_material_model.get();
}
SampleModel* ApplicationModels::sampleModel()
{
return p_impl->m_sample_model.get();
}
SLDElementModel* ApplicationModels::sldViewModel()
{
return p_impl->m_sld_view_model.get();
}
JobModel* ApplicationModels::jobModel()
{
return p_impl->m_job_model.get();
}
ExperimentalDataModel* ApplicationModels::experimentalDataModel()
{
return p_impl->m_experimental_model.get();
}
InstrumentModel* ApplicationModels::instrumentModel()
{
return p_impl->m_instrument_model.get();
}
std::vector<SessionModel*> ApplicationModels::persistent_models() const
{
return p_impl->persistent_models();
}
//! Return vector of all models of our application.
std::vector<SessionModel*> ApplicationModels::application_models() const
{
return p_impl->application_models();
}
} // namespace gui2
|
gpl-3.0
|
neooblaster/Template
|
tests/data-validation2.php
|
468
|
<?php
$vars = Array(
// Simple
// Block
"A" => Array(
Array(
"B" => Array(
Array(
"ALLOWED" => "TRUE"
),
Array(
"ALLOWED" => "FALSE"
),
Array(
"ALLOWED" => "TRUE"
)
)
),
Array(
"B" => Array(
Array(
"ALLOWED" => "FALSE"
),
Array(
"ALLOWED" => "TRUE"
),
Array(
"ALLOWED" => "FALSE"
)
)
)
)
);
?>
|
gpl-3.0
|