code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
cask "cantata" do
version "2.3.2"
sha256 "c9eb8a1102d0a68cafc93f22df73445b8f69706f3322285f9a2f623a28df0176"
url "https://github.com/CDrummond/cantata/releases/download/v#{version}/Cantata-#{version}.dmg"
appcast "https://github.com/CDrummond/cantata/releases.atom"
name "Cantata"
homepage "https://github.com/cdrummond/cantata"
depends_on macos: ">= :sierra"
app "Cantata.app"
end
| haha1903/homebrew-cask | Casks/cantata.rb | Ruby | bsd-2-clause | 400 |
package org.dstadler.commoncrawl.index;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.logging.Logger;
import org.dstadler.commons.logging.jdk.LoggerFactory;
/**
* Sample to read from locally stored cdx-00000.gz files
*
* @author dstadler
*
*/
public class DownloadURLIndexFromFile {
private static final Logger log = LoggerFactory.make();
private static final int START_INDEX = 0;
private static final int END_INDEX = 1;
public static void main(String[] args) throws Exception {
LoggerFactory.initLogging();
for(int i = START_INDEX;i <= END_INDEX;i++) {
File file = new File(String.format("cdx-%05d.gz", i));
log.info("Loading data from " + file + " which has " + file.length() + " bytes");
try (InputStream stream = new FileInputStream(file)) {
DownloadURLIndex.handleInputStream(file.getAbsolutePath(), stream, i, file.length());
}
}
}
}
| centic9/CommonCrawlDocumentDownload | src/main/java/org/dstadler/commoncrawl/index/DownloadURLIndexFromFile.java | Java | bsd-2-clause | 956 |
// Copyright (C) 2015 Mike Pennisi. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-array.prototype-@@unscopables
description: >
Initial value of `Symbol.unscopables` property
info: |
22.1.3.32 Array.prototype [ @@unscopables ]
1. Let unscopableList be ObjectCreate(null).
2. Perform CreateDataProperty(unscopableList, "copyWithin", true).
3. Perform CreateDataProperty(unscopableList, "entries", true).
4. Perform CreateDataProperty(unscopableList, "fill", true).
5. Perform CreateDataProperty(unscopableList, "find", true).
6. Perform CreateDataProperty(unscopableList, "findIndex", true).
7. Perform CreateDataProperty(unscopableList, "includes", true).
8. Perform CreateDataProperty(unscopableList, "keys", true).
9. Perform CreateDataProperty(unscopableList, "values", true).
10. Assert: Each of the above calls will return true.
11. Return unscopableList.
includes: [propertyHelper.js]
features: [Symbol.unscopables]
---*/
var unscopables = Array.prototype[Symbol.unscopables];
assert.sameValue(Object.getPrototypeOf(unscopables), null);
assert.sameValue(unscopables.copyWithin, true, '`copyWithin` property value');
verifyEnumerable(unscopables, 'copyWithin');
verifyWritable(unscopables, 'copyWithin');
verifyConfigurable(unscopables, 'copyWithin');
assert.sameValue(unscopables.entries, true, '`entries` property value');
verifyEnumerable(unscopables, 'entries');
verifyWritable(unscopables, 'entries');
verifyConfigurable(unscopables, 'entries');
assert.sameValue(unscopables.fill, true, '`fill` property value');
verifyEnumerable(unscopables, 'fill');
verifyWritable(unscopables, 'fill');
verifyConfigurable(unscopables, 'fill');
assert.sameValue(unscopables.find, true, '`find` property value');
verifyEnumerable(unscopables, 'find');
verifyWritable(unscopables, 'find');
verifyConfigurable(unscopables, 'find');
assert.sameValue(unscopables.findIndex, true, '`findIndex` property value');
verifyEnumerable(unscopables, 'findIndex');
verifyWritable(unscopables, 'findIndex');
verifyConfigurable(unscopables, 'findIndex');
assert.sameValue(unscopables.includes, true, '`includes` property value');
verifyEnumerable(unscopables, 'includes');
verifyWritable(unscopables, 'includes');
verifyConfigurable(unscopables, 'includes');
assert.sameValue(unscopables.keys, true, '`keys` property value');
verifyEnumerable(unscopables, 'keys');
verifyWritable(unscopables, 'keys');
verifyConfigurable(unscopables, 'keys');
assert.sameValue(unscopables.values, true, '`values` property value');
verifyEnumerable(unscopables, 'values');
verifyWritable(unscopables, 'values');
verifyConfigurable(unscopables, 'values');
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/Array/prototype/Symbol.unscopables/value.js | JavaScript | bsd-2-clause | 2,739 |
class NSColor
def self.systemControlColor
NSColor.colorForControlTint(NSColor.currentControlTint)
end
def self.blueControlColor
NSColor.colorForControlTint(NSBlueControlTint)
end
def self.graphiteControlColor
NSColor.colorForControlTint(NSGraphiteControlTint)
end
def nscolor(alpha=nil)
if alpha
if named_color_space?
self.colorUsingColorSpace(NSColorSpace.genericRGBColorSpace).colorWithAlphaComponent(alpha.to_f)
else
self.colorWithAlphaComponent(alpha.to_f)
end
else
if named_color_space?
self.colorUsingColorSpace(NSColorSpace.genericRGBColorSpace)
else
self
end
end
end
def self.rgba(r, g, b, a)
if NSColor.respond_to?('colorWithRed:green:blue:alpha:')
NSColor.colorWithRed(r, green: g, blue: b, alpha: a)
else
NSColor.colorWithCalibratedRed(r, green: g, blue: b, alpha: a)
end
end
def named_color_space?
colorSpaceName == "NSNamedColorSpace"
end
def cgcolor(alpha=nil)
nscolor(alpha).CGColor
end
def skcolor(alpha=nil)
nscolor(alpha)
end
# blends two colors by averaging the RGB and alpha components.
# @example
# :white.nscolor + :black.nscolor == :gray.nscolor
def +(color)
mix_with(color.nscolor, 0.5)
end
# blends two colors by adding the colors, with an upper maximum of 255.
# Adding white to any color will create white, adding black will do nothing.
# Also takes transparency into account; adding a transparent color has no
# effect, adding an opaque color has the most effect.
# @example
# :red.nscolor << :blue.nscolor == '#ff00ff'.nscolor (:magenta)
# :red.nscolor << :blue.nscolor(0.5) == '#ff0080'.nscolor (pinkish)
def <<(color)
r = [1.0, color.red * color.alpha + self.red].min
g = [1.0, color.green * color.alpha + self.green].min
b = [1.0, color.blue * color.alpha + self.blue].min
a = self.alpha
NSColor.rgba(r, g, b, a)
end
# a more generic color mixing method. mixes two colors, but a second
# parameter determines how much of each. 0.5 means equal parts, 0.0 means use
# all of the first, and 1.0 means use all of the second
def mix_with(color, amount)
color = color.nscolor
# make amount between 0 and 1
amount = [[0, amount].max, 1].min
# start with precise amounts: 0, 0.5, and 1.
if amount == 0 && self.alpha == color.alpha
self
elsif amount == 1 && self.alpha == color.alpha
color
elsif amount == 0.5 && self.alpha == color.alpha
r = (self.red + color.red) / 2
g = (self.green + color.green) / 2
b = (self.blue + color.blue) / 2
a = self.alpha
NSColor.rgba(r, g, b, a)
else
a = (color.alpha - self.alpha) * amount + self.alpha
return NSColor.clearColor if a == 0
color_red = color.red * color.alpha + self.red * (1 - color.alpha)
self_red = self.red * self.alpha + color.red * (1 - self.alpha)
color_green = color.green * color.alpha + self.green * (1 - color.alpha)
self_green = self.green * self.alpha + color.green * (1 - self.alpha)
color_blue = color.blue * color.alpha + self.blue * (1 - color.alpha)
self_blue = self.blue * self.alpha + color.blue * (1 - self.alpha)
r = (color_red - self_red) * amount + self_red
g = (color_green - self_green) * amount + self_green
b = (color_blue - self_blue) * amount + self_blue
NSColor.rgba(r, g, b, a)
end
end
# inverts the RGB channel. keeps the alpha channel unchanged
# @example
# :white.nscolor.invert == :black.nscolor
def invert
r = 1.0 - self.red
g = 1.0 - self.green
b = 1.0 - self.blue
a = self.alpha
NSColor.rgba(r, g, b, a)
end
# Cannot define method `hue' because no Objective-C stub was pre-compiled for
# types `d@:'. Make sure you properly link with the framework or library that
# defines this message.
### def hue
### hueComponent
### rescue Exception
### nil
### end
# Cannot define method `saturation' because no Objective-C stub was
# pre-compiled for types `d@:'. Make sure you properly link with the framework
# or library that defines this message.
### def saturation
### saturationComponent
### rescue Exception
### nil
### end
# Cannot define method `brightness' because no Objective-C stub was
# pre-compiled for types `d@:'. Make sure you properly link with the framework
# or library that defines this message.
### def brightness
### brightnessComponent
### rescue Exception
### nil
### end
def red
redComponent
rescue NSInvalidArgumentException
whiteComponent
rescue Exception
nil
end
def green
greenComponent
rescue NSInvalidArgumentException
whiteComponent
rescue Exception
nil
end
def blue
blueComponent
rescue NSInvalidArgumentException
whiteComponent
rescue Exception
nil
end
def alpha
alphaComponent
rescue Exception
nil
end
# returns the components OR'd together, as 32 bit RGB integer. alpha channel
# is dropped
def to_i
if self.red && self.green && self.blue
red = (self.red * 255).round << 16
green = (self.green * 255).round << 8
blue = (self.blue * 255).round
return red + green + blue
else
return nil
end
end
# returns the components as an array of 32 bit RGB values. alpha channel is
# dropped
def to_a
if self.red && self.green && self.blue
red = (self.red * 255).round
green = (self.green * 255).round
blue = (self.blue * 255).round
return [red, green, blue]
else
return nil
end
end
def hex
my_color = self.to_i
if my_color
return '#' + my_color.to_s(16).rjust(6, '0')
else
nil
end
end
# returns the closest css name
def css_name
my_color = self.to_i
css_name = nil
Symbol.css_colors.each do |color, hex|
if hex == my_color
css_name = color
break
end
end
return css_name
end
def system_name
system_color = nil
Symbol.nscolors.each do |color_name, method|
color = NSColor.send(method)
without_alpha = self.nscolor(color.alpha)
if color == self || color == without_alpha
system_color = method
break
end
end
return system_color
end
end
| Watson1978/sugarcube | lib/osx/sugarcube-color/nscolor.rb | Ruby | bsd-2-clause | 6,386 |
# -*- coding: utf-8 -*-
"""
Builds epub book out of Paul Graham's essays: http://paulgraham.com/articles.html
Author: Ola Sitarska <ola@sitarska.com>
Copyright: Licensed under the GPL-3 (http://www.gnu.org/licenses/gpl-3.0.html)
This script requires python-epub-library: http://code.google.com/p/python-epub-builder/
"""
import re, ez_epub, urllib2, genshi
#from BeautifulSoup import BeautifulSoup
from bs4 import BeautifulSoup
def addSection(link, title):
if not 'http' in link:
page = urllib2.urlopen('http://www.paulgraham.com/'+link).read()
soup = BeautifulSoup(page)
soup.prettify()
else:
page = urllib2.urlopen(link).read()
section = ez_epub.Section()
try:
section.title = title
print section.title
if not 'http' in link:
font = str(soup.findAll('table', {'width':'435'})[0].findAll('font')[0])
if not 'Get funded by' in font and not 'Watch how this essay was' in font and not 'Like to build things?' in font and not len(font)<100:
content = font
else:
content = ''
for par in soup.findAll('table', {'width':'435'})[0].findAll('p'):
content += str(par)
for p in content.split("<br /><br />"):
section.text.append(genshi.core.Markup(p))
#exception for Subject: Airbnb
for pre in soup.findAll('pre'):
section.text.append(genshi.core.Markup(pre))
else:
for p in str(page).replace("\n","<br />").split("<br /><br />"):
section.text.append(genshi.core.Markup(p))
except:
pass
return section
book = ez_epub.Book()
book.title = "Paul Graham's Essays"
book.authors = ['Paul Graham']
page = urllib2.urlopen('http://www.paulgraham.com/articles.html').read()
soup = BeautifulSoup(page)
soup.prettify()
links = soup.findAll('table', {'width': '435'})[1].findAll('a')
sections = []
for link in links:
sections.append(addSection(link['href'], link.text))
book.sections = sections
book.make(book.title)
| norayr/pgessays | pgessays.py | Python | bsd-2-clause | 2,125 |
package com.jayantkrish.jklol.lisp.inc;
import java.util.Collection;
import java.util.List;
import com.google.common.base.Preconditions;
import com.jayantkrish.jklol.inference.MarginalCalculator.ZeroProbabilityError;
import com.jayantkrish.jklol.models.parametric.SufficientStatistics;
import com.jayantkrish.jklol.training.GradientOracle;
import com.jayantkrish.jklol.training.LogFunction;
public class IncEvalLoglikelihoodOracle implements
GradientOracle<IncEval, IncEvalExample> {
private final ParametricIncEval family;
private final int beamSize;
public IncEvalLoglikelihoodOracle(ParametricIncEval family, int beamSize) {
this.family = Preconditions.checkNotNull(family);
this.beamSize = beamSize;
}
@Override
public SufficientStatistics initializeGradient() {
return family.getNewSufficientStatistics();
}
@Override
public IncEval instantiateModel(SufficientStatistics parameters) {
return family.getModelFromParameters(parameters);
}
@Override
public double accumulateGradient(SufficientStatistics gradient, SufficientStatistics currentParameters,
IncEval model, IncEvalExample example, LogFunction log) {
// Get a distribution over unconditional executions.
log.startTimer("update_gradient/input_marginal");
IncEvalCost marginCost = example.getMarginCost();
List<IncEvalState> unconditionalStates = model.evaluateBeam(example.getLogicalForm(),
example.getDiagram(), marginCost, model.getEnvironment(), log, beamSize);
if (unconditionalStates.size() == 0) {
System.out.println("unconditional search failure");
throw new ZeroProbabilityError();
}
log.stopTimer("update_gradient/input_marginal");
// Get a distribution on executions conditioned on the label of the example.
log.startTimer("update_gradient/output_marginal");
IncEvalCost labelCost = example.getLabelCost();
List<IncEvalState> conditionalStates = model.evaluateBeam(example.getLogicalForm(),
example.getDiagram(), labelCost, model.getEnvironment(), log, beamSize);
if (conditionalStates.size() == 0) {
System.out.println("conditional search failure");
System.out.println(" " + example.getLogicalForm());
System.out.println(" " + example.getDiagram());
System.out.println(" " + example);
throw new ZeroProbabilityError();
}
log.stopTimer("update_gradient/output_marginal");
log.startTimer("update_gradient/increment_gradient");
double unconditionalPartitionFunction = getPartitionFunction(unconditionalStates);
for (IncEvalState state : unconditionalStates) {
family.incrementSufficientStatistics(gradient, currentParameters, example.getLogicalForm(),
state, -1.0 * state.getProb() / unconditionalPartitionFunction);
}
double conditionalPartitionFunction = getPartitionFunction(conditionalStates);
for (IncEvalState state : conditionalStates) {
family.incrementSufficientStatistics(gradient, currentParameters, example.getLogicalForm(),
state, state.getProb() / conditionalPartitionFunction);
}
log.stopTimer("update_gradient/increment_gradient");
// Note that the returned loglikelihood is an approximation because
// inference is approximate.
return Math.log(conditionalPartitionFunction) - Math.log(unconditionalPartitionFunction);
}
public double getPartitionFunction(Collection<IncEvalState> states) {
double partitionFunction = 0.0;
for (IncEvalState state : states) {
partitionFunction += state.getProb();
}
return partitionFunction;
}
}
| jayantk/jklol | src/com/jayantkrish/jklol/lisp/inc/IncEvalLoglikelihoodOracle.java | Java | bsd-2-clause | 3,627 |
#from shoutrequest import ShoutRequest
from djangorequest import DjangoRequest
import json
from twisted.internet import task
from twisted.internet import reactor
mb = {"requestid":"AAAAA1", "requesttype":"get", "requesttimeout":10, "requestbody":{"selects": [{"name":"sweetspot.models.Locations", "label":"L", "cols":["boroughCode", "locationCode"]}, {"name":"sweetspot.models.Signs", "label":"S", "cols":["FtFromCurb", "locationCode"]}], "joins":[{"L.locationCode":"P-004958", "op":"eq"}, {"S.FtFromCurb":"9", "op":"eq"}, {"L.boroughCode":["M","B"], "op":"in"}]}}
def runEvery5Seconds():
print shoutRequest.getResults()
decoder = json.JSONEncoder()
requestid = mb["requestid"]
requesttimeout = mb["requesttimeout"]
requestbody = mb["requestbody"]
shoutRequest = DjangoRequest(format = "JSON", requestObj = requestbody, requesttimeout = requesttimeout, requestid = requestid)
if shoutRequest.isValidRequest():
print "request is valid"
gms = shoutRequest.createGenericModels()
else:
print mb, " is not a valid request"
#l = task.LoopingCall(runEvery5Seconds)
#l.start(2)
#reactor.run()
| psiCode/shoutserver | mysite/djangorequest_test.py | Python | bsd-2-clause | 1,094 |
package milter
import (
"errors"
)
// pre-defined errors
var (
errCloseSession = errors.New("Stop current milter processing")
errMacroNoData = errors.New("Macro definition with no data")
)
| phalaaxx/milter | errors.go | GO | bsd-2-clause | 195 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
ScheduledDance = orm['stepping_out.ScheduledDance']
Venue = orm['stepping_out.Venue']
for sd in ScheduledDance.objects.all():
v = Venue.objects.create(
name=sd.name,
banner=sd.banner,
description=sd.description,
website=sd.website,
weekday=sd.weekday,
weeks=sd.weeks,
dance_template=sd.dance_template
)
sd.dances.update(venue=v)
def backwards(self, orm):
"Write your backwards methods here."
ScheduledDance = orm['stepping_out.ScheduledDance']
Venue = orm['stepping_out.Venue']
for v in Venue.objects.all():
sd = ScheduledDance.objects.create(
name=v.name,
banner=v.banner,
description=v.description,
website=v.website,
weekday=v.weekday,
weeks=v.weeks,
dance_template=v.dance_template
)
v.dances.update(venue=sd)
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'stepping_out.dance': {
'Meta': {'ordering': "('start', 'end')", 'object_name': 'Dance'},
'banner': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'custom_price': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'djs': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'dj_for'", 'blank': 'True', 'through': u"orm['stepping_out.DanceDJ']", 'to': u"orm['stepping_out.Person']"}),
'end': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'hosts': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'host_for'", 'blank': 'True', 'to': u"orm['stepping_out.Person']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_canceled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'live_acts': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['stepping_out.LiveAct']", 'symmetrical': 'False', 'through': u"orm['stepping_out.DanceLiveAct']", 'blank': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.Location']", 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'price': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
'scheduled_dance': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'dances'", 'null': 'True', 'to': u"orm['stepping_out.ScheduledDance']"}),
'sites': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['sites.Site']", 'symmetrical': 'False', 'blank': 'True'}),
'start': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'student_price': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'tagline': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'venue': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'dances'", 'null': 'True', 'to': u"orm['stepping_out.Venue']"})
},
u'stepping_out.dancedj': {
'Meta': {'ordering': "('order', 'start', 'end')", 'object_name': 'DanceDJ'},
'dance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.Dance']"}),
'end': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'order': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'person': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.Person']"}),
'start': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
u'stepping_out.danceliveact': {
'Meta': {'ordering': "('order', 'start', 'end')", 'object_name': 'DanceLiveAct'},
'dance': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.Dance']"}),
'end': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'live_act': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.LiveAct']"}),
'order': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'start': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
u'stepping_out.dancetemplate': {
'Meta': {'object_name': 'DanceTemplate'},
'banner': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'custom_price': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'end_time': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.Location']", 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'price': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
'sites': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['sites.Site']", 'symmetrical': 'False', 'blank': 'True'}),
'start_time': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}),
'student_price': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'tagline': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'})
},
u'stepping_out.lesson': {
'Meta': {'ordering': "('start', 'end')", 'object_name': 'Lesson'},
'custom_price': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'dance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'lessons'", 'to': u"orm['stepping_out.Dance']"}),
'dance_included': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'end': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.Location']", 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'price': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
'start': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'student_price': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'teachers': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['stepping_out.Person']", 'symmetrical': 'False', 'blank': 'True'})
},
u'stepping_out.lessontemplate': {
'Meta': {'object_name': 'LessonTemplate'},
'custom_price': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'dance_included': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'dance_template': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'lesson_templates'", 'null': 'True', 'to': u"orm['stepping_out.DanceTemplate']"}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'end_time': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.Location']", 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'price': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
'start_time': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}),
'student_price': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'})
},
u'stepping_out.liveact': {
'Meta': {'object_name': 'LiveAct'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'stepping_out.location': {
'Meta': {'object_name': 'Location'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '150'}),
'banner': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'default': "'Seattle'", 'max_length': '100'}),
'custom_map_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'custom_map_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latitude': ('django.db.models.fields.FloatField', [], {}),
'longitude': ('django.db.models.fields.FloatField', [], {}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'neighborhood': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'state': ('django_localflavor_us.models.USStateField', [], {'default': "'WA'", 'max_length': '2'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'})
},
u'stepping_out.person': {
'Meta': {'object_name': 'Person'},
'bio': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True', 'null': 'True', 'blank': 'True'})
},
u'stepping_out.scheduleddance': {
'Meta': {'object_name': 'ScheduledDance'},
'banner': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'dance_template': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.DanceTemplate']", 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'weekday': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
'weeks': ('django.db.models.fields.CommaSeparatedIntegerField', [], {'default': "'1,2,3,4,5'", 'max_length': '9'})
},
u'stepping_out.venue': {
'Meta': {'object_name': 'Venue'},
'banner': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'dance_template': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['stepping_out.DanceTemplate']", 'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'weekday': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
'weeks': ('django.db.models.fields.CommaSeparatedIntegerField', [], {'default': "'1,2,3,4,5'", 'max_length': '9'})
}
}
complete_apps = ['stepping_out']
symmetrical = True
| melinath/django-stepping-out | stepping_out/migrations/0016_scheduled_dance_to_venue.py | Python | bsd-2-clause | 17,560 |
#include "Jitter_CodeGen_x86_32.h"
#include <algorithm>
using namespace Jitter;
CX86Assembler::REGISTER CCodeGen_x86_32::g_registers[MAX_REGISTERS] =
{
CX86Assembler::rBX,
CX86Assembler::rSI,
CX86Assembler::rDI,
};
CX86Assembler::XMMREGISTER CCodeGen_x86_32::g_mdRegisters[MAX_MDREGISTERS] =
{
CX86Assembler::xMM4,
CX86Assembler::xMM5,
CX86Assembler::xMM6,
CX86Assembler::xMM7
};
CCodeGen_x86_32::CONSTMATCHER CCodeGen_x86_32::g_constMatchers[] =
{
{ OP_PARAM, MATCH_NIL, MATCH_CONTEXT, MATCH_NIL, &CCodeGen_x86_32::Emit_Param_Ctx },
{ OP_PARAM, MATCH_NIL, MATCH_MEMORY, MATCH_NIL, &CCodeGen_x86_32::Emit_Param_Mem },
{ OP_PARAM, MATCH_NIL, MATCH_CONSTANT, MATCH_NIL, &CCodeGen_x86_32::Emit_Param_Cst },
{ OP_PARAM, MATCH_NIL, MATCH_REGISTER, MATCH_NIL, &CCodeGen_x86_32::Emit_Param_Reg },
{ OP_PARAM, MATCH_NIL, MATCH_MEMORY64, MATCH_NIL, &CCodeGen_x86_32::Emit_Param_Mem64 },
{ OP_PARAM, MATCH_NIL, MATCH_CONSTANT64, MATCH_NIL, &CCodeGen_x86_32::Emit_Param_Cst64 },
{ OP_PARAM, MATCH_NIL, MATCH_REGISTER128, MATCH_NIL, &CCodeGen_x86_32::Emit_Param_Reg128 },
{ OP_PARAM, MATCH_NIL, MATCH_MEMORY128, MATCH_NIL, &CCodeGen_x86_32::Emit_Param_Mem128 },
{ OP_PARAM_RET, MATCH_NIL, MATCH_MEMORY128, MATCH_NIL, &CCodeGen_x86_32::Emit_ParamRet_Mem128 },
{ OP_CALL, MATCH_NIL, MATCH_CONSTANTPTR, MATCH_CONSTANT, &CCodeGen_x86_32::Emit_Call },
{ OP_RETVAL, MATCH_TEMPORARY, MATCH_NIL, MATCH_NIL, &CCodeGen_x86_32::Emit_RetVal_Tmp },
{ OP_RETVAL, MATCH_REGISTER, MATCH_NIL, MATCH_NIL, &CCodeGen_x86_32::Emit_RetVal_Reg },
{ OP_RETVAL, MATCH_MEMORY64, MATCH_NIL, MATCH_NIL, &CCodeGen_x86_32::Emit_RetVal_Mem64 },
{ OP_MOV, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_NIL, &CCodeGen_x86_32::Emit_Mov_Mem64Mem64 },
{ OP_MOV, MATCH_RELATIVE64, MATCH_CONSTANT64, MATCH_NIL, &CCodeGen_x86_32::Emit_Mov_Rel64Cst64 },
{ OP_ADD64, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_MEMORY64, &CCodeGen_x86_32::Emit_Add64_MemMemMem },
{ OP_ADD64, MATCH_RELATIVE64, MATCH_RELATIVE64, MATCH_CONSTANT64, &CCodeGen_x86_32::Emit_Add64_RelRelCst },
{ OP_SUB64, MATCH_RELATIVE64, MATCH_RELATIVE64, MATCH_RELATIVE64, &CCodeGen_x86_32::Emit_Sub64_RelRelRel },
{ OP_SUB64, MATCH_RELATIVE64, MATCH_CONSTANT64, MATCH_RELATIVE64, &CCodeGen_x86_32::Emit_Sub64_RelCstRel },
{ OP_AND64, MATCH_RELATIVE64, MATCH_RELATIVE64, MATCH_RELATIVE64, &CCodeGen_x86_32::Emit_And64_RelRelRel },
{ OP_SRL64, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_REGISTER, &CCodeGen_x86_32::Emit_Srl64_MemMemReg },
{ OP_SRL64, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_MEMORY, &CCodeGen_x86_32::Emit_Srl64_MemMemMem },
{ OP_SRL64, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_CONSTANT, &CCodeGen_x86_32::Emit_Srl64_MemMemCst },
{ OP_SRA64, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_REGISTER, &CCodeGen_x86_32::Emit_Sra64_MemMemReg },
{ OP_SRA64, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_MEMORY, &CCodeGen_x86_32::Emit_Sra64_MemMemMem },
{ OP_SRA64, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_CONSTANT, &CCodeGen_x86_32::Emit_Sra64_MemMemCst },
{ OP_SLL64, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_REGISTER, &CCodeGen_x86_32::Emit_Sll64_MemMemReg },
{ OP_SLL64, MATCH_MEMORY64, MATCH_MEMORY64, MATCH_MEMORY, &CCodeGen_x86_32::Emit_Sll64_MemMemMem },
{ OP_SLL64, MATCH_RELATIVE64, MATCH_RELATIVE64, MATCH_CONSTANT, &CCodeGen_x86_32::Emit_Sll64_RelRelCst },
{ OP_CMP64, MATCH_REGISTER, MATCH_RELATIVE64, MATCH_RELATIVE64, &CCodeGen_x86_32::Emit_Cmp64_RegRelRel },
{ OP_CMP64, MATCH_RELATIVE, MATCH_RELATIVE64, MATCH_RELATIVE64, &CCodeGen_x86_32::Emit_Cmp64_RelRelRel },
{ OP_CMP64, MATCH_REGISTER, MATCH_RELATIVE64, MATCH_CONSTANT64, &CCodeGen_x86_32::Emit_Cmp64_RegRelCst },
{ OP_CMP64, MATCH_RELATIVE, MATCH_RELATIVE64, MATCH_CONSTANT64, &CCodeGen_x86_32::Emit_Cmp64_RelRelCst },
{ OP_CMP64, MATCH_TEMPORARY, MATCH_RELATIVE64, MATCH_RELATIVE64, &CCodeGen_x86_32::Emit_Cmp64_TmpRelRoc },
{ OP_CMP64, MATCH_TEMPORARY, MATCH_RELATIVE64, MATCH_CONSTANT64, &CCodeGen_x86_32::Emit_Cmp64_TmpRelRoc },
{ OP_RELTOREF, MATCH_TMP_REF, MATCH_CONSTANT, MATCH_NIL, &CCodeGen_x86_32::Emit_RelToRef_TmpCst },
{ OP_ADDREF, MATCH_MEM_REF, MATCH_MEM_REF, MATCH_REGISTER, &CCodeGen_x86_32::Emit_AddRef_MemMemReg },
{ OP_ADDREF, MATCH_MEM_REF, MATCH_MEM_REF, MATCH_MEMORY, &CCodeGen_x86_32::Emit_AddRef_MemMemMem },
{ OP_ADDREF, MATCH_MEM_REF, MATCH_MEM_REF, MATCH_CONSTANT, &CCodeGen_x86_32::Emit_AddRef_MemMemCst },
{ OP_LOADFROMREF, MATCH_REGISTER, MATCH_TMP_REF, MATCH_NIL, &CCodeGen_x86_32::Emit_LoadFromRef_RegTmp },
{ OP_LOADFROMREF, MATCH_MEMORY, MATCH_TMP_REF, MATCH_NIL, &CCodeGen_x86_32::Emit_LoadFromRef_MemTmp },
{ OP_LOADFROMREF, MATCH_REGISTER128, MATCH_MEM_REF, MATCH_NIL, &CCodeGen_x86_32::Emit_LoadFromRef_Md_RegMem },
{ OP_LOADFROMREF, MATCH_MEMORY128, MATCH_MEM_REF, MATCH_NIL, &CCodeGen_x86_32::Emit_LoadFromRef_Md_MemMem },
{ OP_STOREATREF, MATCH_NIL, MATCH_TMP_REF, MATCH_REGISTER, &CCodeGen_x86_32::Emit_StoreAtRef_TmpReg },
{ OP_STOREATREF, MATCH_NIL, MATCH_TMP_REF, MATCH_MEMORY, &CCodeGen_x86_32::Emit_StoreAtRef_TmpMem },
{ OP_STOREATREF, MATCH_NIL, MATCH_TMP_REF, MATCH_CONSTANT, &CCodeGen_x86_32::Emit_StoreAtRef_TmpCst },
{ OP_STOREATREF, MATCH_NIL, MATCH_MEM_REF, MATCH_REGISTER128, &CCodeGen_x86_32::Emit_StoreAtRef_Md_MemReg },
{ OP_STOREATREF, MATCH_NIL, MATCH_MEM_REF, MATCH_MEMORY128, &CCodeGen_x86_32::Emit_StoreAtRef_Md_MemMem },
{ OP_MOV, MATCH_NIL, MATCH_NIL, MATCH_NIL, NULL },
};
CCodeGen_x86_32::CCodeGen_x86_32()
{
CCodeGen_x86::m_registers = g_registers;
CCodeGen_x86::m_mdRegisters = g_mdRegisters;
for(CONSTMATCHER* constMatcher = g_constMatchers; constMatcher->emitter != NULL; constMatcher++)
{
MATCHER matcher;
matcher.op = constMatcher->op;
matcher.dstType = constMatcher->dstType;
matcher.src1Type = constMatcher->src1Type;
matcher.src2Type = constMatcher->src2Type;
matcher.emitter = std::bind(constMatcher->emitter, this, std::placeholders::_1);
m_matchers.insert(MatcherMapType::value_type(matcher.op, matcher));
}
}
CCodeGen_x86_32::~CCodeGen_x86_32()
{
}
void CCodeGen_x86_32::Emit_Prolog(const StatementList& statements, unsigned int stackSize, uint32 registerUsage)
{
//Compute the size needed to store all function call parameters
uint32 maxParamSize = 0;
uint32 maxParamSpillSize = 0;
{
uint32 currParamSize = 0;
uint32 currParamSpillSize = 0;
for(const auto& statement : statements)
{
switch(statement.op)
{
case OP_PARAM:
case OP_PARAM_RET:
{
CSymbol* src1 = statement.src1->GetSymbol().get();
switch(src1->m_type)
{
case SYM_CONTEXT:
case SYM_REGISTER:
case SYM_RELATIVE:
case SYM_CONSTANT:
case SYM_TEMPORARY:
case SYM_RELATIVE128:
case SYM_TEMPORARY128:
currParamSize += 4;
break;
case SYM_REGISTER128:
currParamSize += 4;
currParamSpillSize += 16;
break;
case SYM_CONSTANT64:
case SYM_TEMPORARY64:
case SYM_RELATIVE64:
currParamSize += 8;
break;
default:
assert(0);
break;
}
}
break;
case OP_CALL:
maxParamSize = std::max<uint32>(currParamSize, maxParamSize);
maxParamSpillSize = std::max<uint32>(currParamSpillSize, maxParamSpillSize);
currParamSize = 0;
currParamSpillSize = 0;
break;
}
}
}
assert((stackSize & 0x0F) == 0);
assert((maxParamSpillSize & 0x0F) == 0);
maxParamSize = ((maxParamSize + 0xF) & ~0xF);
//Fetch parameter
m_assembler.Push(CX86Assembler::rBP);
m_assembler.MovEd(CX86Assembler::rBP, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, 8));
//Save registers
for(unsigned int i = 0; i < MAX_REGISTERS; i++)
{
if(registerUsage & (1 << i))
{
m_assembler.Push(m_registers[i]);
}
}
//Align stack
m_assembler.MovEd(CX86Assembler::rAX, CX86Assembler::MakeRegisterAddress(CX86Assembler::rSP));
m_assembler.AndId(CX86Assembler::MakeRegisterAddress(CX86Assembler::rSP), ~0x0F);
m_assembler.SubId(CX86Assembler::MakeRegisterAddress(CX86Assembler::rSP), 0x0C);
m_assembler.Push(CX86Assembler::rAX);
//Allocate stack space for temps
m_totalStackAlloc = stackSize + maxParamSize + maxParamSpillSize;
m_paramSpillBase = stackSize + maxParamSize;
m_stackLevel = maxParamSize;
//Allocate stack space
if(m_totalStackAlloc != 0)
{
m_assembler.SubId(CX86Assembler::MakeRegisterAddress(CX86Assembler::rSP), m_totalStackAlloc);
}
//-------------------------------
//Stack Frame
//-------------------------------
//(High address)
//------------------
//Saved registers + alignment adjustment
//------------------
//Saved rSP
//------------------ <----- aligned on 0x10
//Params spill space
//------------------ <----- rSP + m_paramSpillBase
//Temporary symbols (stackSize) + alignment adjustment
//------------------ <----- rSP + m_stackLevel
//Param space for callee
//------------------ <----- rSP
//(Low address)
}
void CCodeGen_x86_32::Emit_Epilog(unsigned int stackSize, uint32 registerUsage)
{
if(m_totalStackAlloc != 0)
{
m_assembler.AddId(CX86Assembler::MakeRegisterAddress(CX86Assembler::rSP), m_totalStackAlloc);
}
m_assembler.Pop(CX86Assembler::rSP);
for(int i = MAX_REGISTERS - 1; i >= 0; i--)
{
if(registerUsage & (1 << i))
{
m_assembler.Pop(m_registers[i]);
}
}
m_assembler.Pop(CX86Assembler::rBP);
m_assembler.Ret();
}
unsigned int CCodeGen_x86_32::GetAvailableRegisterCount() const
{
return MAX_REGISTERS;
}
unsigned int CCodeGen_x86_32::GetAvailableMdRegisterCount() const
{
return MAX_MDREGISTERS;
}
bool CCodeGen_x86_32::CanHold128BitsReturnValueInRegisters() const
{
return false;
}
void CCodeGen_x86_32::Emit_Param_Ctx(const STATEMENT& statement)
{
m_params.push_back(
[this] (CALL_STATE& state)
{
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset), CX86Assembler::rBP);
state.paramOffset += 4;
}
);
}
void CCodeGen_x86_32::Emit_Param_Reg(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
m_params.push_back(
[this, src1] (CALL_STATE& state)
{
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset), m_registers[src1->m_valueLow]);
state.paramOffset += 4;
}
);
}
void CCodeGen_x86_32::Emit_Param_Mem(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
m_params.push_back(
[this, src1] (CALL_STATE& state)
{
m_assembler.MovEd(CX86Assembler::rAX, MakeMemorySymbolAddress(src1));
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset), CX86Assembler::rAX);
state.paramOffset += 4;
}
);
}
void CCodeGen_x86_32::Emit_Param_Cst(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
m_params.push_back(
[this, src1] (CALL_STATE& state)
{
m_assembler.MovId(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset), src1->m_valueLow);
state.paramOffset += 4;
}
);
}
void CCodeGen_x86_32::Emit_Param_Mem64(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
m_params.push_back(
[this, src1] (CALL_STATE& state)
{
m_assembler.MovEd(CX86Assembler::rAX, MakeMemory64SymbolLoAddress(src1));
m_assembler.MovEd(CX86Assembler::rDX, MakeMemory64SymbolHiAddress(src1));
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset + 0), CX86Assembler::rAX);
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset + 4), CX86Assembler::rDX);
state.paramOffset += 8;
}
);
}
void CCodeGen_x86_32::Emit_Param_Cst64(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
m_params.push_back(
[this, src1] (CALL_STATE& state)
{
m_assembler.MovId(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset + 0), src1->m_valueLow);
m_assembler.MovId(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset + 4), src1->m_valueHigh);
state.paramOffset += 8;
}
);
}
void CCodeGen_x86_32::Emit_Param_Reg128(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
m_params.push_back(
[this, src1] (CALL_STATE& state)
{
auto paramTempAddr = CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, m_paramSpillBase + state.paramSpillOffset);
m_assembler.MovapsVo(paramTempAddr, m_mdRegisters[src1->m_valueLow]);
m_assembler.LeaGd(CX86Assembler::rAX, paramTempAddr);
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset), CX86Assembler::rAX);
state.paramOffset += 4;
state.paramSpillOffset += 0x10;
}
);
}
void CCodeGen_x86_32::Emit_Param_Mem128(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
m_params.push_back(
[this, src1] (CALL_STATE& state)
{
m_assembler.LeaGd(CX86Assembler::rAX, MakeMemory128SymbolAddress(src1));
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rSP, state.paramOffset), CX86Assembler::rAX);
state.paramOffset += 4;
}
);
}
void CCodeGen_x86_32::Emit_ParamRet_Mem128(const STATEMENT& statement)
{
//Basically the same as Param_Mem128, but special care must be taken
//as System V ABI automatically cleans up that extra parameter that's
//used as return value
Emit_Param_Mem128(statement);
assert(!m_hasImplicitRetValueParam);
m_hasImplicitRetValueParam = true;
}
void CCodeGen_x86_32::Emit_Call(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
auto src2 = statement.src2->GetSymbol().get();
uint32 paramCount = src2->m_valueLow;
CALL_STATE callState;
for(unsigned int i = 0; i < paramCount; i++)
{
auto emitter(m_params.back());
m_params.pop_back();
emitter(callState);
}
m_assembler.MovId(CX86Assembler::rAX, src1->m_valueLow);
auto symbolRefLabel = m_assembler.CreateLabel();
m_assembler.MarkLabel(symbolRefLabel, -4);
m_symbolReferenceLabels.push_back(std::make_pair(src1->GetConstantPtr(), symbolRefLabel));
m_assembler.CallEd(CX86Assembler::MakeRegisterAddress(CX86Assembler::rAX));
#if defined(__APPLE__) || defined(__ANDROID__)
if(m_hasImplicitRetValueParam)
{
//Allocated stack space for the extra parameter is cleaned up by the callee.
//So adjust the amount of stack space we free up after the call
m_assembler.SubId(CX86Assembler::MakeRegisterAddress(CX86Assembler::rSP), 4);
}
#endif
m_hasImplicitRetValueParam = false;
}
void CCodeGen_x86_32::Emit_RetVal_Tmp(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
m_assembler.MovGd(MakeTemporarySymbolAddress(dst), CX86Assembler::rAX);
}
void CCodeGen_x86_32::Emit_RetVal_Reg(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
assert(dst->m_type == SYM_REGISTER);
m_assembler.MovGd(CX86Assembler::MakeRegisterAddress(m_registers[dst->m_valueLow]), CX86Assembler::rAX);
}
void CCodeGen_x86_32::Emit_RetVal_Mem64(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
m_assembler.MovGd(MakeMemory64SymbolLoAddress(dst), CX86Assembler::rAX);
m_assembler.MovGd(MakeMemory64SymbolHiAddress(dst), CX86Assembler::rDX);
}
void CCodeGen_x86_32::Emit_Mov_Mem64Mem64(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
m_assembler.MovEd(CX86Assembler::rAX, MakeMemory64SymbolLoAddress(src1));
m_assembler.MovEd(CX86Assembler::rDX, MakeMemory64SymbolHiAddress(src1));
m_assembler.MovGd(MakeMemory64SymbolLoAddress(dst), CX86Assembler::rAX);
m_assembler.MovGd(MakeMemory64SymbolHiAddress(dst), CX86Assembler::rDX);
}
void CCodeGen_x86_32::Emit_Mov_Rel64Cst64(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
assert(dst->m_type == SYM_RELATIVE64);
assert(src1->m_type == SYM_CONSTANT64);
m_assembler.MovId(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 0), src1->m_valueLow);
m_assembler.MovId(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 4), src1->m_valueHigh);
}
void CCodeGen_x86_32::Emit_Add64_MemMemMem(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
m_assembler.MovEd(CX86Assembler::rAX, MakeMemory64SymbolLoAddress(src1));
m_assembler.MovEd(CX86Assembler::rDX, MakeMemory64SymbolHiAddress(src1));
m_assembler.AddEd(CX86Assembler::rAX, MakeMemory64SymbolLoAddress(src2));
m_assembler.AdcEd(CX86Assembler::rDX, MakeMemory64SymbolHiAddress(src2));
m_assembler.MovGd(MakeMemory64SymbolLoAddress(dst), CX86Assembler::rAX);
m_assembler.MovGd(MakeMemory64SymbolHiAddress(dst), CX86Assembler::rDX);
}
void CCodeGen_x86_32::Emit_Add64_RelRelCst(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(dst->m_type == SYM_RELATIVE64);
assert(src1->m_type == SYM_RELATIVE64);
assert(src2->m_type == SYM_CONSTANT64);
m_assembler.MovEd(CX86Assembler::rAX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 0));
m_assembler.MovEd(CX86Assembler::rDX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 4));
m_assembler.AddId(CX86Assembler::MakeRegisterAddress(CX86Assembler::rAX), src2->m_valueLow);
m_assembler.AdcId(CX86Assembler::MakeRegisterAddress(CX86Assembler::rDX), src2->m_valueHigh);
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 0), CX86Assembler::rAX);
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 4), CX86Assembler::rDX);
}
void CCodeGen_x86_32::Emit_Sub64_RelRelRel(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(dst->m_type == SYM_RELATIVE64);
assert(src1->m_type == SYM_RELATIVE64);
assert(src2->m_type == SYM_RELATIVE64);
m_assembler.MovEd(CX86Assembler::rAX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 0));
m_assembler.MovEd(CX86Assembler::rDX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 4));
m_assembler.SubEd(CX86Assembler::rAX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src2->m_valueLow + 0));
m_assembler.SbbEd(CX86Assembler::rDX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src2->m_valueLow + 4));
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 0), CX86Assembler::rAX);
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 4), CX86Assembler::rDX);
}
void CCodeGen_x86_32::Emit_Sub64_RelCstRel(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(dst->m_type == SYM_RELATIVE64);
assert(src1->m_type == SYM_CONSTANT64);
assert(src2->m_type == SYM_RELATIVE64);
m_assembler.MovId(CX86Assembler::rAX, src1->m_valueLow);
m_assembler.MovId(CX86Assembler::rDX, src1->m_valueHigh);
m_assembler.SubEd(CX86Assembler::rAX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src2->m_valueLow + 0));
m_assembler.SbbEd(CX86Assembler::rDX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src2->m_valueLow + 4));
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 0), CX86Assembler::rAX);
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 4), CX86Assembler::rDX);
}
void CCodeGen_x86_32::Emit_And64_RelRelRel(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(dst->m_type == SYM_RELATIVE64);
assert(src1->m_type == SYM_RELATIVE64);
assert(src2->m_type == SYM_RELATIVE64);
m_assembler.MovEd(CX86Assembler::rAX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 0));
m_assembler.MovEd(CX86Assembler::rDX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 4));
m_assembler.AndEd(CX86Assembler::rAX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src2->m_valueLow + 0));
m_assembler.AndEd(CX86Assembler::rDX, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src2->m_valueLow + 4));
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 0), CX86Assembler::rAX);
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 4), CX86Assembler::rDX);
}
//---------------------------------------------------------------------------------
//SR64
//---------------------------------------------------------------------------------
void CCodeGen_x86_32::Emit_Sr64Var_MemMem(CSymbol* dst, CSymbol* src1, CX86Assembler::REGISTER shiftRegister, SHIFTRIGHT_TYPE shiftType)
{
auto regLo = CX86Assembler::rAX;
auto regHi = CX86Assembler::rDX;
auto regSa = CX86Assembler::rCX;
auto lessThan32Label = m_assembler.CreateLabel();
auto endLabel = m_assembler.CreateLabel();
if(shiftRegister != regSa)
{
m_assembler.MovEd(regSa, CX86Assembler::MakeRegisterAddress(shiftRegister));
}
m_assembler.AndId(CX86Assembler::MakeRegisterAddress(regSa), 0x3F);
m_assembler.CmpId(CX86Assembler::MakeRegisterAddress(regSa), 32);
m_assembler.JbJx(lessThan32Label);
//greaterOrEqual:
//---------------------------------------------
m_assembler.MovEd(regLo, MakeMemory64SymbolHiAddress(src1));
m_assembler.AndId(CX86Assembler::MakeRegisterAddress(regSa), 0x1F);
if(shiftType == SHIFTRIGHT_LOGICAL)
{
m_assembler.ShrEd(CX86Assembler::MakeRegisterAddress(regLo));
m_assembler.XorEd(regHi, CX86Assembler::MakeRegisterAddress(regHi));
}
else if(shiftType == SHIFTRIGHT_ARITHMETIC)
{
m_assembler.MovEd(regHi, CX86Assembler::MakeRegisterAddress(regLo));
m_assembler.SarEd(CX86Assembler::MakeRegisterAddress(regHi), 31);
m_assembler.SarEd(CX86Assembler::MakeRegisterAddress(regLo));
}
else
{
assert(false);
}
m_assembler.JmpJx(endLabel);
//lessThan:
//---------------------------------------------
m_assembler.MarkLabel(lessThan32Label);
m_assembler.MovEd(regLo, MakeMemory64SymbolLoAddress(src1));
m_assembler.MovEd(regHi, MakeMemory64SymbolHiAddress(src1));
m_assembler.ShrdEd(CX86Assembler::MakeRegisterAddress(regLo), regHi);
if(shiftType == SHIFTRIGHT_LOGICAL)
{
m_assembler.ShrEd(CX86Assembler::MakeRegisterAddress(regHi));
}
else if(shiftType == SHIFTRIGHT_ARITHMETIC)
{
m_assembler.SarEd(CX86Assembler::MakeRegisterAddress(regHi));
}
else
{
assert(false);
}
//end:
//---------------------------------------------
m_assembler.MarkLabel(endLabel);
m_assembler.MovGd(MakeMemory64SymbolLoAddress(dst), regLo);
m_assembler.MovGd(MakeMemory64SymbolHiAddress(dst), regHi);
}
void CCodeGen_x86_32::Emit_Sr64Cst_MemMem(CSymbol* dst, CSymbol* src1, uint32 shiftAmount, SHIFTRIGHT_TYPE shiftType)
{
assert(dst->m_type == SYM_RELATIVE64);
assert(src1->m_type == SYM_RELATIVE64);
shiftAmount = shiftAmount & 0x3F;
auto regLo = CX86Assembler::rAX;
auto regHi = CX86Assembler::rDX;
if(shiftAmount >= 32)
{
m_assembler.MovEd(regLo, MakeMemory64SymbolHiAddress(src1));
if(shiftType == SHIFTRIGHT_LOGICAL)
{
if(shiftAmount != 32)
{
//shr reg, amount
m_assembler.ShrEd(CX86Assembler::MakeRegisterAddress(regLo), shiftAmount & 0x1F);
}
m_assembler.XorEd(regHi, CX86Assembler::MakeRegisterAddress(regHi));
}
else if(shiftType == SHIFTRIGHT_ARITHMETIC)
{
if(shiftAmount != 32)
{
//sar reg, amount
m_assembler.SarEd(CX86Assembler::MakeRegisterAddress(regLo), shiftAmount & 0x1F);
}
m_assembler.MovEd(regHi, CX86Assembler::MakeRegisterAddress(regLo));
m_assembler.SarEd(CX86Assembler::MakeRegisterAddress(regHi), 31);
}
else
{
assert(false);
}
}
else //Amount < 32
{
m_assembler.MovEd(regLo, MakeMemory64SymbolLoAddress(src1));
m_assembler.MovEd(regHi, MakeMemory64SymbolHiAddress(src1));
if(shiftAmount != 0)
{
//shrd nReg1, nReg2, nAmount
m_assembler.ShrdEd(CX86Assembler::MakeRegisterAddress(regLo), regHi, shiftAmount);
if(shiftType == SHIFTRIGHT_LOGICAL)
{
//shr nReg2, nAmount
m_assembler.ShrEd(CX86Assembler::MakeRegisterAddress(regHi), shiftAmount);
}
else if(shiftType == SHIFTRIGHT_ARITHMETIC)
{
//sar nReg2, nAmount
m_assembler.SarEd(CX86Assembler::MakeRegisterAddress(regHi), shiftAmount);
}
else
{
assert(false);
}
}
}
m_assembler.MovGd(MakeMemory64SymbolLoAddress(dst), regLo);
m_assembler.MovGd(MakeMemory64SymbolHiAddress(dst), regHi);
}
//---------------------------------------------------------------------------------
//SRL64
//---------------------------------------------------------------------------------
void CCodeGen_x86_32::Emit_Srl64_MemMemReg(const STATEMENT& statement)
{
auto dst = statement.dst->GetSymbol().get();
auto src1 = statement.src1->GetSymbol().get();
auto src2 = statement.src2->GetSymbol().get();
assert(src2->m_type == SYM_REGISTER);
Emit_Sr64Var_MemMem(dst, src1, g_registers[src2->m_valueLow], SHIFTRIGHT_LOGICAL);
}
void CCodeGen_x86_32::Emit_Srl64_MemMemMem(const STATEMENT& statement)
{
auto dst = statement.dst->GetSymbol().get();
auto src1 = statement.src1->GetSymbol().get();
auto src2 = statement.src2->GetSymbol().get();
auto shiftAmount = CX86Assembler::rCX;
m_assembler.MovEd(shiftAmount, MakeMemorySymbolAddress(src2));
Emit_Sr64Var_MemMem(dst, src1, shiftAmount, SHIFTRIGHT_LOGICAL);
}
void CCodeGen_x86_32::Emit_Srl64_MemMemCst(const STATEMENT& statement)
{
auto dst = statement.dst->GetSymbol().get();
auto src1 = statement.src1->GetSymbol().get();
auto src2 = statement.src2->GetSymbol().get();
Emit_Sr64Cst_MemMem(dst, src1, src2->m_valueLow, SHIFTRIGHT_LOGICAL);
}
//---------------------------------------------------------------------------------
//SRA64
//---------------------------------------------------------------------------------
void CCodeGen_x86_32::Emit_Sra64_MemMemReg(const STATEMENT& statement)
{
auto dst = statement.dst->GetSymbol().get();
auto src1 = statement.src1->GetSymbol().get();
auto src2 = statement.src2->GetSymbol().get();
assert(src2->m_type == SYM_REGISTER);
Emit_Sr64Var_MemMem(dst, src1, g_registers[src2->m_valueLow], SHIFTRIGHT_ARITHMETIC);
}
void CCodeGen_x86_32::Emit_Sra64_MemMemMem(const STATEMENT& statement)
{
auto dst = statement.dst->GetSymbol().get();
auto src1 = statement.src1->GetSymbol().get();
auto src2 = statement.src2->GetSymbol().get();
auto shiftAmount = CX86Assembler::rCX;
m_assembler.MovEd(shiftAmount, MakeMemorySymbolAddress(src2));
Emit_Sr64Var_MemMem(dst, src1, shiftAmount, SHIFTRIGHT_ARITHMETIC);
}
void CCodeGen_x86_32::Emit_Sra64_MemMemCst(const STATEMENT& statement)
{
auto dst = statement.dst->GetSymbol().get();
auto src1 = statement.src1->GetSymbol().get();
auto src2 = statement.src2->GetSymbol().get();
Emit_Sr64Cst_MemMem(dst, src1, src2->m_valueLow, SHIFTRIGHT_ARITHMETIC);
}
//---------------------------------------------------------------------------------
//SLL64
//---------------------------------------------------------------------------------
void CCodeGen_x86_32::Emit_Sll64_MemMemVar(const STATEMENT& statement, CX86Assembler::REGISTER shiftRegister)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CX86Assembler::LABEL doneLabel = m_assembler.CreateLabel();
CX86Assembler::LABEL more32Label = m_assembler.CreateLabel();
CX86Assembler::REGISTER amountReg = CX86Assembler::rCX;
CX86Assembler::REGISTER resultLow = CX86Assembler::rAX;
CX86Assembler::REGISTER resultHigh = CX86Assembler::rDX;
if(shiftRegister != amountReg)
{
m_assembler.MovEd(amountReg, CX86Assembler::MakeRegisterAddress(shiftRegister));
}
m_assembler.MovEd(resultLow, MakeMemory64SymbolLoAddress(src1));
m_assembler.MovEd(resultHigh, MakeMemory64SymbolHiAddress(src1));
m_assembler.AndIb(CX86Assembler::MakeByteRegisterAddress(amountReg), 0x3F);
m_assembler.TestEb(amountReg, CX86Assembler::MakeByteRegisterAddress(amountReg));
m_assembler.JzJx(doneLabel);
m_assembler.CmpIb(CX86Assembler::MakeByteRegisterAddress(amountReg), 0x20);
m_assembler.JnbJx(more32Label);
m_assembler.ShldEd(CX86Assembler::MakeRegisterAddress(resultHigh), resultLow);
m_assembler.ShlEd(CX86Assembler::MakeRegisterAddress(resultLow));
m_assembler.JmpJx(doneLabel);
//$more32
m_assembler.MarkLabel(more32Label);
m_assembler.MovEd(resultHigh, CX86Assembler::MakeRegisterAddress(resultLow));
m_assembler.XorEd(resultLow, CX86Assembler::MakeRegisterAddress(resultLow));
m_assembler.AndIb(CX86Assembler::MakeByteRegisterAddress(amountReg), 0x1F);
m_assembler.ShlEd(CX86Assembler::MakeRegisterAddress(resultHigh));
//$done
m_assembler.MarkLabel(doneLabel);
m_assembler.MovGd(MakeMemory64SymbolLoAddress(dst), resultLow);
m_assembler.MovGd(MakeMemory64SymbolHiAddress(dst), resultHigh);
}
void CCodeGen_x86_32::Emit_Sll64_MemMemReg(const STATEMENT& statement)
{
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(src2->m_type == SYM_REGISTER);
Emit_Sll64_MemMemVar(statement, g_registers[src2->m_valueLow]);
}
void CCodeGen_x86_32::Emit_Sll64_MemMemMem(const STATEMENT& statement)
{
CSymbol* src2 = statement.src2->GetSymbol().get();
CX86Assembler::REGISTER shiftAmount = CX86Assembler::rCX;
m_assembler.MovEd(shiftAmount, MakeMemorySymbolAddress(src2));
Emit_Sll64_MemMemVar(statement, shiftAmount);
}
void CCodeGen_x86_32::Emit_Sll64_RelRelCst(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(dst->m_type == SYM_RELATIVE64);
assert(src1->m_type == SYM_RELATIVE64);
assert(src2->m_type == SYM_CONSTANT);
uint8 shiftAmount = static_cast<uint8>(src2->m_valueLow & 0x3F);
CX86Assembler::REGISTER regLo = CX86Assembler::rAX;
CX86Assembler::REGISTER regHi = CX86Assembler::rDX;
if(shiftAmount >= 32)
{
m_assembler.MovEd(regHi, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 0));
if(shiftAmount != 0)
{
//shl reg, amount
m_assembler.ShlEd(CX86Assembler::MakeRegisterAddress(regHi), shiftAmount & 0x1F);
}
m_assembler.XorEd(regLo, CX86Assembler::MakeRegisterAddress(regLo));
}
else //Amount < 32
{
m_assembler.MovEd(regLo, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 0));
m_assembler.MovEd(regHi, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 4));
//shld nReg2, nReg1, nAmount
m_assembler.ShldEd(CX86Assembler::MakeRegisterAddress(regHi), regLo, shiftAmount);
//shl nReg1, nAmount
m_assembler.ShlEd(CX86Assembler::MakeRegisterAddress(regLo), shiftAmount);
}
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 0), regLo);
m_assembler.MovGd(CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, dst->m_valueLow + 4), regHi);
}
//---------------------------------------------------------------------------------
//CMP64
//---------------------------------------------------------------------------------
void CCodeGen_x86_32::Cmp64_Equal(const STATEMENT& statement)
{
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
struct CmpLo
{
void operator()(CX86Assembler& assembler, CX86Assembler::REGISTER registerId, CSymbol* symbol)
{
switch(symbol->m_type)
{
case SYM_RELATIVE64:
assembler.CmpEd(registerId, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, symbol->m_valueLow + 0));
break;
case SYM_CONSTANT64:
if(symbol->m_valueLow == 0)
{
assembler.TestEd(registerId, CX86Assembler::MakeRegisterAddress(registerId));
}
else
{
assembler.CmpId(CX86Assembler::MakeRegisterAddress(registerId), symbol->m_valueLow);
}
break;
default:
assert(0);
break;
}
}
};
struct CmpHi
{
void operator()(CX86Assembler& assembler, CX86Assembler::REGISTER registerId, CSymbol* symbol)
{
switch(symbol->m_type)
{
case SYM_RELATIVE64:
assembler.CmpEd(registerId, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, symbol->m_valueLow + 4));
break;
case SYM_CONSTANT64:
if(symbol->m_valueHigh == 0)
{
assembler.TestEd(registerId, CX86Assembler::MakeRegisterAddress(registerId));
}
else
{
assembler.CmpId(CX86Assembler::MakeRegisterAddress(registerId), symbol->m_valueHigh);
}
break;
default:
assert(0);
break;
}
}
};
assert(src1->m_type == SYM_RELATIVE64);
bool isEqual = (statement.jmpCondition == CONDITION_EQ);
CX86Assembler::REGISTER valReg = CX86Assembler::rDX;
CX86Assembler::REGISTER res1Reg = CX86Assembler::rAX;
CX86Assembler::REGISTER res2Reg = CX86Assembler::rCX;
m_assembler.MovEd(valReg, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 0));
CmpLo()(m_assembler, valReg, src2);
if(isEqual)
{
m_assembler.SeteEb(CX86Assembler::MakeRegisterAddress(res1Reg));
}
else
{
m_assembler.SetneEb(CX86Assembler::MakeRegisterAddress(res1Reg));
}
m_assembler.MovEd(valReg, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 4));
CmpHi()(m_assembler, valReg, src2);
if(isEqual)
{
m_assembler.SeteEb(CX86Assembler::MakeRegisterAddress(res2Reg));
}
else
{
m_assembler.SetneEb(CX86Assembler::MakeRegisterAddress(res2Reg));
}
if(isEqual)
{
m_assembler.AndEd(res1Reg, CX86Assembler::MakeRegisterAddress(res2Reg));
}
else
{
m_assembler.OrEd(res1Reg, CX86Assembler::MakeRegisterAddress(res2Reg));
}
m_assembler.MovzxEb(res1Reg, CX86Assembler::MakeRegisterAddress(res1Reg));
}
struct CompareOrder64Less
{
typedef void (CX86Assembler::*OrderCheckFunction)(const CX86Assembler::CAddress&);
static bool IsSigned(Jitter::CONDITION condition)
{
return (condition == CONDITION_LE) || (condition == CONDITION_LT);
}
static bool OrEqual(Jitter::CONDITION condition)
{
return (condition == CONDITION_LE) || (condition == CONDITION_BE);
}
static OrderCheckFunction CheckOrderSigned()
{
return &CX86Assembler::SetlEb;
}
static OrderCheckFunction CheckOrderUnsigned()
{
return &CX86Assembler::SetbEb;
}
static OrderCheckFunction CheckOrderOrEqualUnsigned()
{
return &CX86Assembler::SetbeEb;
}
};
struct CompareOrder64Greater
{
typedef void (CX86Assembler::*OrderCheckFunction)(const CX86Assembler::CAddress&);
static bool IsSigned(Jitter::CONDITION condition)
{
return (condition == CONDITION_GE) || (condition == CONDITION_GT);
}
static bool OrEqual(Jitter::CONDITION condition)
{
return (condition == CONDITION_GE) || (condition == CONDITION_AE);
}
static OrderCheckFunction CheckOrderSigned()
{
return &CX86Assembler::SetgEb;
}
static OrderCheckFunction CheckOrderUnsigned()
{
return &CX86Assembler::SetaEb;
}
static OrderCheckFunction CheckOrderOrEqualUnsigned()
{
return &CX86Assembler::SetaeEb;
}
};
template <typename CompareTraits>
void CCodeGen_x86_32::Cmp64_Order(const STATEMENT& statement)
{
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
CompareTraits compareTraits;
(void)compareTraits;
struct CmpLo
{
void operator()(CX86Assembler& assembler, CX86Assembler::REGISTER registerId, CSymbol* symbol)
{
switch(symbol->m_type)
{
case SYM_RELATIVE64:
assembler.CmpEd(registerId, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, symbol->m_valueLow + 0));
break;
case SYM_CONSTANT64:
assembler.CmpId(CX86Assembler::MakeRegisterAddress(registerId), symbol->m_valueLow);
break;
default:
assert(0);
break;
}
}
};
struct CmpHi
{
void operator()(CX86Assembler& assembler, CX86Assembler::REGISTER registerId, CSymbol* symbol)
{
switch(symbol->m_type)
{
case SYM_RELATIVE64:
assembler.CmpEd(registerId, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, symbol->m_valueLow + 4));
break;
case SYM_CONSTANT64:
assembler.CmpId(CX86Assembler::MakeRegisterAddress(registerId), symbol->m_valueHigh);
break;
default:
assert(0);
break;
}
}
};
assert(src1->m_type == SYM_RELATIVE64);
CX86Assembler::REGISTER regLo = CX86Assembler::rAX;
CX86Assembler::REGISTER regHi = CX86Assembler::rDX;
bool isSigned = compareTraits.IsSigned(statement.jmpCondition);
bool orEqual = compareTraits.OrEqual(statement.jmpCondition);
CX86Assembler::LABEL highOrderEqualLabel = m_assembler.CreateLabel();
CX86Assembler::LABEL doneLabel = m_assembler.CreateLabel();
/////////////////////////////////////////
//Check high order word if equal
m_assembler.MovEd(regHi, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 4));
CmpHi()(m_assembler, regHi, src2);
//je highOrderEqual
m_assembler.JzJx(highOrderEqualLabel);
///////////////////////////////////////////////////////////
//If they aren't equal, this comparaison decides of result
//setb/l reg[l]
if(isSigned)
{
((m_assembler).*(compareTraits.CheckOrderSigned()))(CX86Assembler::MakeByteRegisterAddress(regLo));
}
else
{
((m_assembler).*(compareTraits.CheckOrderUnsigned()))(CX86Assembler::MakeByteRegisterAddress(regLo));
}
//movzx reg, reg[l]
m_assembler.MovzxEb(regLo, CX86Assembler::MakeByteRegisterAddress(regLo));
//jmp done
m_assembler.JmpJx(doneLabel);
//highOrderEqual: /////////////////////////////////////
m_assembler.MarkLabel(highOrderEqualLabel);
//If they are equal, next comparaison decides of result
m_assembler.MovEd(regLo, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow + 0));
CmpLo()(m_assembler, regLo, src2);
//setb/be reg[l]
if(orEqual)
{
((m_assembler).*(compareTraits.CheckOrderOrEqualUnsigned()))(CX86Assembler::MakeByteRegisterAddress(regLo));
}
else
{
((m_assembler).*(compareTraits.CheckOrderUnsigned()))(CX86Assembler::MakeByteRegisterAddress(regLo));
}
//movzx reg, reg[l]
m_assembler.MovzxEb(regLo, CX86Assembler::MakeByteRegisterAddress(regLo));
//done: ///////////////////////////////////////////////
m_assembler.MarkLabel(doneLabel);
}
void CCodeGen_x86_32::Cmp64_GenericRel(const STATEMENT& statement)
{
switch(statement.jmpCondition)
{
case CONDITION_BL:
case CONDITION_LT:
case CONDITION_LE:
Cmp64_Order<CompareOrder64Less>(statement);
break;
case CONDITION_AB:
case CONDITION_GT:
case CONDITION_GE:
Cmp64_Order<CompareOrder64Greater>(statement);
break;
case CONDITION_NE:
case CONDITION_EQ:
Cmp64_Equal(statement);
break;
default:
assert(0);
break;
}
}
void CCodeGen_x86_32::Emit_Cmp64_RegRelRel(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
assert(dst->m_type == SYM_REGISTER);
Cmp64_GenericRel(statement);
m_assembler.MovGd(CX86Assembler::MakeRegisterAddress(m_registers[dst->m_valueLow]), CX86Assembler::rAX);
}
void CCodeGen_x86_32::Emit_Cmp64_RelRelRel(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
assert(dst->m_type == SYM_RELATIVE);
Cmp64_GenericRel(statement);
m_assembler.MovGd(MakeRelativeSymbolAddress(dst), CX86Assembler::rAX);
}
void CCodeGen_x86_32::Emit_Cmp64_RegRelCst(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
assert(dst->m_type == SYM_REGISTER);
Cmp64_GenericRel(statement);
m_assembler.MovGd(CX86Assembler::MakeRegisterAddress(m_registers[dst->m_valueLow]), CX86Assembler::rAX);
}
void CCodeGen_x86_32::Emit_Cmp64_RelRelCst(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
assert(dst->m_type == SYM_RELATIVE);
Cmp64_GenericRel(statement);
m_assembler.MovGd(MakeRelativeSymbolAddress(dst), CX86Assembler::rAX);
}
void CCodeGen_x86_32::Emit_Cmp64_TmpRelRoc(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
assert(dst->m_type == SYM_TEMPORARY);
Cmp64_GenericRel(statement);
m_assembler.MovGd(MakeTemporarySymbolAddress(dst), CX86Assembler::rAX);
}
void CCodeGen_x86_32::Emit_RelToRef_TmpCst(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
assert(dst->m_type == SYM_TMP_REFERENCE);
assert(src1->m_type == SYM_CONSTANT);
CX86Assembler::REGISTER tmpReg = CX86Assembler::rAX;
m_assembler.LeaGd(tmpReg, CX86Assembler::MakeIndRegOffAddress(CX86Assembler::rBP, src1->m_valueLow));
m_assembler.MovGd(MakeTemporaryReferenceSymbolAddress(dst), tmpReg);
}
void CCodeGen_x86_32::Emit_AddRef_MemMemReg(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(src2->m_type == SYM_REGISTER);
CX86Assembler::REGISTER tmpReg = CX86Assembler::rAX;
m_assembler.MovEd(tmpReg, MakeMemoryReferenceSymbolAddress(src1));
m_assembler.AddEd(tmpReg, CX86Assembler::MakeRegisterAddress(m_registers[src2->m_valueLow]));
m_assembler.MovGd(MakeMemoryReferenceSymbolAddress(dst), tmpReg);
}
void CCodeGen_x86_32::Emit_AddRef_MemMemMem(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
auto tmpReg = CX86Assembler::rAX;
m_assembler.MovEd(tmpReg, MakeMemoryReferenceSymbolAddress(src1));
m_assembler.AddEd(tmpReg, MakeMemorySymbolAddress(src2));
m_assembler.MovGd(MakeMemoryReferenceSymbolAddress(dst), tmpReg);
}
void CCodeGen_x86_32::Emit_AddRef_MemMemCst(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(src2->m_type == SYM_CONSTANT);
CX86Assembler::REGISTER tmpReg = CX86Assembler::rAX;
m_assembler.MovEd(tmpReg, MakeMemoryReferenceSymbolAddress(src1));
m_assembler.AddId(CX86Assembler::MakeRegisterAddress(tmpReg), src2->m_valueLow);
m_assembler.MovGd(MakeMemoryReferenceSymbolAddress(dst), tmpReg);
}
void CCodeGen_x86_32::Emit_LoadFromRef_RegTmp(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
assert(dst->m_type == SYM_REGISTER);
assert(src1->m_type == SYM_TMP_REFERENCE);
CX86Assembler::REGISTER tmpReg = CX86Assembler::rAX;
m_assembler.MovEd(tmpReg, MakeTemporaryReferenceSymbolAddress(src1));
m_assembler.MovEd(m_registers[dst->m_valueLow], CX86Assembler::MakeIndRegAddress(tmpReg));
}
void CCodeGen_x86_32::Emit_LoadFromRef_MemTmp(const STATEMENT& statement)
{
CSymbol* dst = statement.dst->GetSymbol().get();
CSymbol* src1 = statement.src1->GetSymbol().get();
assert(src1->m_type == SYM_TMP_REFERENCE);
CX86Assembler::REGISTER addressReg = CX86Assembler::rAX;
CX86Assembler::REGISTER valueReg = CX86Assembler::rDX;
m_assembler.MovEd(addressReg, MakeTemporaryReferenceSymbolAddress(src1));
m_assembler.MovEd(valueReg, CX86Assembler::MakeIndRegAddress(addressReg));
m_assembler.MovGd(MakeMemorySymbolAddress(dst), valueReg);
}
void CCodeGen_x86_32::Emit_LoadFromRef_Md_RegMem(const STATEMENT& statement)
{
auto dst = statement.dst->GetSymbol().get();
auto src1 = statement.src1->GetSymbol().get();
auto addressReg = CX86Assembler::rAX;
m_assembler.MovEd(addressReg, MakeMemoryReferenceSymbolAddress(src1));
m_assembler.MovapsVo(g_mdRegisters[dst->m_valueLow], CX86Assembler::MakeIndRegAddress(addressReg));
}
void CCodeGen_x86_32::Emit_LoadFromRef_Md_MemMem(const STATEMENT& statement)
{
auto dst = statement.dst->GetSymbol().get();
auto src1 = statement.src1->GetSymbol().get();
auto addressReg = CX86Assembler::rAX;
auto valueReg = CX86Assembler::xMM0;
m_assembler.MovEd(addressReg, MakeMemoryReferenceSymbolAddress(src1));
m_assembler.MovapsVo(valueReg, CX86Assembler::MakeIndRegAddress(addressReg));
m_assembler.MovapsVo(MakeMemory128SymbolAddress(dst), valueReg);
}
void CCodeGen_x86_32::Emit_StoreAtRef_TmpReg(const STATEMENT& statement)
{
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(src1->m_type == SYM_TMP_REFERENCE);
assert(src2->m_type == SYM_REGISTER);
CX86Assembler::REGISTER addressReg = CX86Assembler::rAX;
m_assembler.MovEd(addressReg, MakeTemporaryReferenceSymbolAddress(src1));
m_assembler.MovGd(CX86Assembler::MakeIndRegAddress(addressReg), m_registers[src2->m_valueLow]);
}
void CCodeGen_x86_32::Emit_StoreAtRef_TmpMem(const STATEMENT& statement)
{
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(src1->m_type == SYM_TMP_REFERENCE);
CX86Assembler::REGISTER addressReg = CX86Assembler::rAX;
CX86Assembler::REGISTER valueReg = CX86Assembler::rDX;
m_assembler.MovEd(addressReg, MakeTemporaryReferenceSymbolAddress(src1));
m_assembler.MovEd(valueReg, MakeMemorySymbolAddress(src2));
m_assembler.MovGd(CX86Assembler::MakeIndRegAddress(addressReg), valueReg);
}
void CCodeGen_x86_32::Emit_StoreAtRef_TmpCst(const STATEMENT& statement)
{
CSymbol* src1 = statement.src1->GetSymbol().get();
CSymbol* src2 = statement.src2->GetSymbol().get();
assert(src1->m_type == SYM_TMP_REFERENCE);
assert(src2->m_type == SYM_CONSTANT);
CX86Assembler::REGISTER tmpReg = CX86Assembler::rAX;
m_assembler.MovEd(tmpReg, MakeTemporaryReferenceSymbolAddress(src1));
m_assembler.MovId(CX86Assembler::MakeIndRegAddress(tmpReg), src2->m_valueLow);
}
void CCodeGen_x86_32::Emit_StoreAtRef_Md_MemReg(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
auto src2 = statement.src2->GetSymbol().get();
auto addressReg = CX86Assembler::rAX;
m_assembler.MovEd(addressReg, MakeMemoryReferenceSymbolAddress(src1));
m_assembler.MovapsVo(CX86Assembler::MakeIndRegAddress(addressReg), g_mdRegisters[src2->m_valueLow]);
}
void CCodeGen_x86_32::Emit_StoreAtRef_Md_MemMem(const STATEMENT& statement)
{
auto src1 = statement.src1->GetSymbol().get();
auto src2 = statement.src2->GetSymbol().get();
auto addressReg = CX86Assembler::rAX;
auto valueReg = CX86Assembler::xMM0;
m_assembler.MovEd(addressReg, MakeMemoryReferenceSymbolAddress(src1));
m_assembler.MovapsVo(valueReg, MakeMemory128SymbolAddress(src2));
m_assembler.MovapsVo(CX86Assembler::MakeIndRegAddress(addressReg), valueReg);
}
| Alloyed/Play--CodeGen | src/Jitter_CodeGen_x86_32.cpp | C++ | bsd-2-clause | 48,543 |
require 'test_helper'
class LampControllerTest < ActionController::TestCase
test "should get lamp" do
get :lamp
assert_response :success
end
end
| thelukemccarthy/Wakeup-Lamp | website/test/functional/lamp_controller_test.rb | Ruby | bsd-2-clause | 159 |
// Code generated by include_assets.go. DO NOT EDIT.
package assets
var (
Analyticsjs = `!function(e){function t(t){t.holmesId=e.localStorage.getItem("_holmesId");for(var n=0;n<o.length;n++)o[n](t);var a="__HOLMES_BASE_URL__/track?u="+(new Date).getTime()+"&t="+encodeURIComponent(JSON.stringify(t)),r=new XMLHttpRequest;r.open("GET",a),r.send()}var n,o=[];null===e.localStorage.getItem("_holmesId")&&e.localStorage.setItem("_holmesId",function(){for(var e=[],t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);var n=4294967296*Math.random()>>>0,o=4294967296*Math.random()>>>0,a=4294967296*Math.random()>>>0,r=4294967296*Math.random()>>>0;return e[255&n]+e[n>>8&255]+e[n>>16&255]+e[n>>24&255]+"-"+e[255&o]+e[o>>8&255]+"-"+e[o>>16&15|64]+e[o>>24&255]+"-"+e[63&a|128]+e[a>>8&255]+"-"+e[a>>16&255]+e[a>>24&255]+e[255&r]+e[r>>8&255]+e[r>>16&255]+e[r>>24&255]}()),e.Holmes={pageView:function(e){e.type="PAGE_VIEW",t(e)},addTrackingEnricher:function(e){o.push(e)},track:t},(n=document.createEvent("Event")).initEvent("holmesloaded",!1,!1),e.dispatchEvent(n)}(window);`
Bannertxt = `
,_
,' ` + "`" + `\,_ ██╗ ██╗ ██████╗ ██╗ ███╗ ███╗███████╗███████╗
|_,-'_) ██║ ██║██╔═══██╗██║ ████╗ ████║██╔════╝██╔════╝
/##c '\ ( ███████║██║ ██║██║ ██╔████╔██║█████╗ ███████╗
' |' -{. ) ██╔══██║██║ ██║██║ ██║╚██╔╝██║██╔══╝ ╚════██║
/\__-' \[] ██║ ██║╚██████╔╝███████╗██║ ╚═╝ ██║███████╗███████║
/` + "`" + `-_` + "`" + `\ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝
' \
`
)
| justsocialapps/holmes | assets/assets.go | GO | bsd-2-clause | 2,093 |
#!/usr/bin/env node
function main() {
if (process.env.SUPPRESS_SUPPORT || process.env.OPENCOLLECTIVE_HIDE) {
return;
}
try {
const Configstore = require('configstore');
const pkg = require(__dirname + '/../package.json');
const now = Date.now();
var week = 1000 * 60 * 60 * 24 * 7;
// create a Configstore instance with an unique ID e.g.
// Package name and optionally some default values
const conf = new Configstore(pkg.name);
const last = conf.get('lastCheck');
if (!last || now - week > last) {
console.log('\u001b[32mLove nodemon? You can now support the project via the open collective:\u001b[22m\u001b[39m\n > \u001b[96m\u001b[1mhttps://opencollective.com/nodemon/donate\u001b[0m\n');
conf.set('lastCheck', now);
}
} catch (e) {
console.log('\u001b[32mLove nodemon? You can now support the project via the open collective:\u001b[22m\u001b[39m\n > \u001b[96m\u001b[1mhttps://opencollective.com/nodemon/donate\u001b[0m\n');
}
}
main();
| nihospr01/OpenSpeechPlatform-UCSD | Sources/ewsnodejs-server/node_modules/nodemon/bin/postinstall.js | JavaScript | bsd-2-clause | 1,017 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Converted from VPC_With_VPN_Connection.template located at:
# http://aws.amazon.com/cloudformation/aws-cloudformation-templates
from troposphere import Base64, FindInMap, GetAtt, Join, Output
from troposphere import Parameter, Ref, Tags, Template
from troposphere.autoscaling import Metadata
from troposphere.ec2 import PortRange, NetworkAcl, Route, \
VPCGatewayAttachment, SubnetRouteTableAssociation, Subnet, RouteTable, \
VPC, NetworkInterfaceProperty, NetworkAclEntry, \
SubnetNetworkAclAssociation, EIP, Instance, InternetGateway, \
SecurityGroupRule, SecurityGroup
from troposphere.policies import CreationPolicy, ResourceSignal
from troposphere.cloudformation import Init, InitFile, InitFiles, \
InitConfig, InitService, InitServices
t = Template()
t.add_version('2010-09-09')
t.set_description("""\
AWS CloudFormation Sample Template VPC_Single_Instance_In_Subnet: Sample \
template showing how to create a VPC and add an EC2 instance with an Elastic \
IP address and a security group. \
**WARNING** This template creates an Amazon EC2 instance. You will be billed \
for the AWS resources used if you create a stack from this template.""")
keyname_param = t.add_parameter(
Parameter(
'KeyName',
ConstraintDescription='must be the name of an existing EC2 KeyPair.',
Description='Name of an existing EC2 KeyPair to enable SSH access to \
the instance',
Type='AWS::EC2::KeyPair::KeyName',
))
sshlocation_param = t.add_parameter(
Parameter(
'SSHLocation',
Description=' The IP address range that can be used to SSH to the EC2 \
instances',
Type='String',
MinLength='9',
MaxLength='18',
Default='0.0.0.0/0',
AllowedPattern=r"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})",
ConstraintDescription=(
"must be a valid IP CIDR range of the form x.x.x.x/x."),
))
instanceType_param = t.add_parameter(Parameter(
'InstanceType',
Type='String',
Description='WebServer EC2 instance type',
Default='m1.small',
AllowedValues=[
't1.micro',
't2.micro', 't2.small', 't2.medium',
'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge',
'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge',
'm3.medium', 'm3.large', 'm3.xlarge', 'm3.2xlarge',
'c1.medium', 'c1.xlarge',
'c3.large', 'c3.xlarge', 'c3.2xlarge', 'c3.4xlarge', 'c3.8xlarge',
'g2.2xlarge',
'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge', 'r3.8xlarge',
'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge', 'i2.8xlarge',
'hi1.4xlarge',
'hs1.8xlarge',
'cr1.8xlarge',
'cc2.8xlarge',
'cg1.4xlarge',
],
ConstraintDescription='must be a valid EC2 instance type.',
))
t.add_mapping('AWSInstanceType2Arch', {
't1.micro': {'Arch': 'PV64'},
't2.micro': {'Arch': 'HVM64'},
't2.small': {'Arch': 'HVM64'},
't2.medium': {'Arch': 'HVM64'},
'm1.small': {'Arch': 'PV64'},
'm1.medium': {'Arch': 'PV64'},
'm1.large': {'Arch': 'PV64'},
'm1.xlarge': {'Arch': 'PV64'},
'm2.xlarge': {'Arch': 'PV64'},
'm2.2xlarge': {'Arch': 'PV64'},
'm2.4xlarge': {'Arch': 'PV64'},
'm3.medium': {'Arch': 'HVM64'},
'm3.large': {'Arch': 'HVM64'},
'm3.xlarge': {'Arch': 'HVM64'},
'm3.2xlarge': {'Arch': 'HVM64'},
'c1.medium': {'Arch': 'PV64'},
'c1.xlarge': {'Arch': 'PV64'},
'c3.large': {'Arch': 'HVM64'},
'c3.xlarge': {'Arch': 'HVM64'},
'c3.2xlarge': {'Arch': 'HVM64'},
'c3.4xlarge': {'Arch': 'HVM64'},
'c3.8xlarge': {'Arch': 'HVM64'},
'g2.2xlarge': {'Arch': 'HVMG2'},
'r3.large': {'Arch': 'HVM64'},
'r3.xlarge': {'Arch': 'HVM64'},
'r3.2xlarge': {'Arch': 'HVM64'},
'r3.4xlarge': {'Arch': 'HVM64'},
'r3.8xlarge': {'Arch': 'HVM64'},
'i2.xlarge': {'Arch': 'HVM64'},
'i2.2xlarge': {'Arch': 'HVM64'},
'i2.4xlarge': {'Arch': 'HVM64'},
'i2.8xlarge': {'Arch': 'HVM64'},
'hi1.4xlarge': {'Arch': 'HVM64'},
'hs1.8xlarge': {'Arch': 'HVM64'},
'cr1.8xlarge': {'Arch': 'HVM64'},
'cc2.8xlarge': {'Arch': 'HVM64'},
})
t.add_mapping('AWSRegionArch2AMI', {
'us-east-1': {'PV64': 'ami-50842d38', 'HVM64': 'ami-08842d60',
'HVMG2': 'ami-3a329952'},
'us-west-2': {'PV64': 'ami-af86c69f', 'HVM64': 'ami-8786c6b7',
'HVMG2': 'ami-47296a77'},
'us-west-1': {'PV64': 'ami-c7a8a182', 'HVM64': 'ami-cfa8a18a',
'HVMG2': 'ami-331b1376'},
'eu-west-1': {'PV64': 'ami-aa8f28dd', 'HVM64': 'ami-748e2903',
'HVMG2': 'ami-00913777'},
'ap-southeast-1': {'PV64': 'ami-20e1c572', 'HVM64': 'ami-d6e1c584',
'HVMG2': 'ami-fabe9aa8'},
'ap-northeast-1': {'PV64': 'ami-21072820', 'HVM64': 'ami-35072834',
'HVMG2': 'ami-5dd1ff5c'},
'ap-southeast-2': {'PV64': 'ami-8b4724b1', 'HVM64': 'ami-fd4724c7',
'HVMG2': 'ami-e98ae9d3'},
'sa-east-1': {'PV64': 'ami-9d6cc680', 'HVM64': 'ami-956cc688',
'HVMG2': 'NOT_SUPPORTED'},
'cn-north-1': {'PV64': 'ami-a857c591', 'HVM64': 'ami-ac57c595',
'HVMG2': 'NOT_SUPPORTED'},
'eu-central-1': {'PV64': 'ami-a03503bd', 'HVM64': 'ami-b43503a9',
'HVMG2': 'ami-b03503ad'},
})
ref_stack_id = Ref('AWS::StackId')
ref_region = Ref('AWS::Region')
ref_stack_name = Ref('AWS::StackName')
VPC = t.add_resource(
VPC(
'VPC',
CidrBlock='10.0.0.0/16',
Tags=Tags(
Application=ref_stack_id)))
subnet = t.add_resource(
Subnet(
'Subnet',
CidrBlock='10.0.0.0/24',
VpcId=Ref(VPC),
Tags=Tags(
Application=ref_stack_id)))
internetGateway = t.add_resource(
InternetGateway(
'InternetGateway',
Tags=Tags(
Application=ref_stack_id)))
gatewayAttachment = t.add_resource(
VPCGatewayAttachment(
'AttachGateway',
VpcId=Ref(VPC),
InternetGatewayId=Ref(internetGateway)))
routeTable = t.add_resource(
RouteTable(
'RouteTable',
VpcId=Ref(VPC),
Tags=Tags(
Application=ref_stack_id)))
route = t.add_resource(
Route(
'Route',
DependsOn='AttachGateway',
GatewayId=Ref('InternetGateway'),
DestinationCidrBlock='0.0.0.0/0',
RouteTableId=Ref(routeTable),
))
subnetRouteTableAssociation = t.add_resource(
SubnetRouteTableAssociation(
'SubnetRouteTableAssociation',
SubnetId=Ref(subnet),
RouteTableId=Ref(routeTable),
))
networkAcl = t.add_resource(
NetworkAcl(
'NetworkAcl',
VpcId=Ref(VPC),
Tags=Tags(
Application=ref_stack_id),
))
inBoundPrivateNetworkAclEntry = t.add_resource(
NetworkAclEntry(
'InboundHTTPNetworkAclEntry',
NetworkAclId=Ref(networkAcl),
RuleNumber='100',
Protocol='6',
PortRange=PortRange(To='80', From='80'),
Egress='false',
RuleAction='allow',
CidrBlock='0.0.0.0/0',
))
inboundSSHNetworkAclEntry = t.add_resource(
NetworkAclEntry(
'InboundSSHNetworkAclEntry',
NetworkAclId=Ref(networkAcl),
RuleNumber='101',
Protocol='6',
PortRange=PortRange(To='22', From='22'),
Egress='false',
RuleAction='allow',
CidrBlock='0.0.0.0/0',
))
inboundResponsePortsNetworkAclEntry = t.add_resource(
NetworkAclEntry(
'InboundResponsePortsNetworkAclEntry',
NetworkAclId=Ref(networkAcl),
RuleNumber='102',
Protocol='6',
PortRange=PortRange(To='65535', From='1024'),
Egress='false',
RuleAction='allow',
CidrBlock='0.0.0.0/0',
))
outBoundHTTPNetworkAclEntry = t.add_resource(
NetworkAclEntry(
'OutBoundHTTPNetworkAclEntry',
NetworkAclId=Ref(networkAcl),
RuleNumber='100',
Protocol='6',
PortRange=PortRange(To='80', From='80'),
Egress='true',
RuleAction='allow',
CidrBlock='0.0.0.0/0',
))
outBoundHTTPSNetworkAclEntry = t.add_resource(
NetworkAclEntry(
'OutBoundHTTPSNetworkAclEntry',
NetworkAclId=Ref(networkAcl),
RuleNumber='101',
Protocol='6',
PortRange=PortRange(To='443', From='443'),
Egress='true',
RuleAction='allow',
CidrBlock='0.0.0.0/0',
))
outBoundResponsePortsNetworkAclEntry = t.add_resource(
NetworkAclEntry(
'OutBoundResponsePortsNetworkAclEntry',
NetworkAclId=Ref(networkAcl),
RuleNumber='102',
Protocol='6',
PortRange=PortRange(To='65535', From='1024'),
Egress='true',
RuleAction='allow',
CidrBlock='0.0.0.0/0',
))
subnetNetworkAclAssociation = t.add_resource(
SubnetNetworkAclAssociation(
'SubnetNetworkAclAssociation',
SubnetId=Ref(subnet),
NetworkAclId=Ref(networkAcl),
))
instanceSecurityGroup = t.add_resource(
SecurityGroup(
'InstanceSecurityGroup',
GroupDescription='Enable SSH access via port 22',
SecurityGroupIngress=[
SecurityGroupRule(
IpProtocol='tcp',
FromPort='22',
ToPort='22',
CidrIp=Ref(sshlocation_param)),
SecurityGroupRule(
IpProtocol='tcp',
FromPort='80',
ToPort='80',
CidrIp='0.0.0.0/0')],
VpcId=Ref(VPC),
))
instance_metadata = Metadata(
Init({
'config': InitConfig(
packages={'yum': {'httpd': []}},
files=InitFiles({
'/var/www/html/index.html': InitFile(content=Join('\n',
[
'<img \
src="https://s3.amazonaws.com/cloudformation-examples/\
cloudformation_graphic.png" alt="AWS CloudFormation Logo"/>',
'<h1>\
Congratulations, you have successfully launched the AWS CloudFormation sample.\
</h1>']),
mode='000644',
owner='root',
group='root'),
'/etc/cfn/cfn-hup.conf': InitFile(content=Join('',
['[main]\n',
'stack=',
ref_stack_id,
'\n',
'region=',
ref_region,
'\n',
]),
mode='000400',
owner='root',
group='root'),
'/etc/cfn/hooks.d/cfn-auto-reloader.conf': InitFile(
content=Join('',
['[cfn-auto-reloader-hook]\n',
'triggers=post.update\n',
'path=Resources.WebServerInstance.\
Metadata.AWS::CloudFormation::Init\n',
'action=/opt/aws/bin/cfn-init -v ',
' --stack ',
ref_stack_name,
' --resource WebServerInstance ',
' --region ',
ref_region,
'\n',
'runas=root\n',
]))}),
services={
'sysvinit': InitServices({
'httpd': InitService(
enabled=True,
ensureRunning=True),
'cfn-hup': InitService(
enabled=True,
ensureRunning=True,
files=[
'/etc/cfn/cfn-hup.conf',
'/etc/cfn/hooks.d/cfn-auto-reloader.conf'
])})})}))
instance = t.add_resource(
Instance(
'WebServerInstance',
Metadata=instance_metadata,
ImageId=FindInMap(
'AWSRegionArch2AMI',
Ref('AWS::Region'),
FindInMap(
'AWSInstanceType2Arch',
Ref(instanceType_param),
'Arch')),
InstanceType=Ref(instanceType_param),
KeyName=Ref(keyname_param),
NetworkInterfaces=[
NetworkInterfaceProperty(
GroupSet=[
Ref(instanceSecurityGroup)],
AssociatePublicIpAddress='true',
DeviceIndex='0',
DeleteOnTermination='true',
SubnetId=Ref(subnet))],
UserData=Base64(
Join(
'',
[
'#!/bin/bash -xe\n',
'yum update -y aws-cfn-bootstrap\n',
'/opt/aws/bin/cfn-init -v ',
' --stack ',
Ref('AWS::StackName'),
' --resource WebServerInstance ',
' --region ',
Ref('AWS::Region'),
'\n',
'/opt/aws/bin/cfn-signal -e $? ',
' --stack ',
Ref('AWS::StackName'),
' --resource WebServerInstance ',
' --region ',
Ref('AWS::Region'),
'\n',
])),
CreationPolicy=CreationPolicy(
ResourceSignal=ResourceSignal(
Timeout='PT15M')),
Tags=Tags(
Application=ref_stack_id),
))
ipAddress = t.add_resource(
EIP('IPAddress',
DependsOn='AttachGateway',
Domain='vpc',
InstanceId=Ref(instance)
))
t.add_output(
[Output('URL',
Description='Newly created application URL',
Value=Join('',
['http://',
GetAtt('WebServerInstance',
'PublicIp')]))])
print(t.to_json())
| ikben/troposphere | examples/VPC_single_instance_in_subnet.py | Python | bsd-2-clause | 14,764 |
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, Anima Istanbul
#
# This module is part of anima-tools and is released under the BSD 2
# License: http://www.opensource.org/licenses/BSD-2-Clause
import tempfile
import unittest
import pymel.core as pm
from stalker import (db, User, Repository, Status, FilenameTemplate, Structure,
StatusList, ImageFormat, Project, Task, Sequence, Shot,
Type, Version)
from anima.env.mayaEnv import previs, Maya
class ShotSplitterTestCase(unittest.TestCase):
"""tests the anima.env.maya.previs.ShotSplitter class
"""
def setUp(self):
"""create test data
"""
database_url = 'sqlite:///:memory:'
db.setup({'sqlalchemy.url': database_url})
db.init()
self.temp_repo_path = tempfile.mkdtemp()
self.user1 = User(
name='User 1',
login='User 1',
email='user1@users.com',
password='12345'
)
self.repo1 = Repository(
name='Test Project Repository',
linux_path=self.temp_repo_path,
windows_path=self.temp_repo_path,
osx_path=self.temp_repo_path
)
self.status_new = Status.query.filter_by(code='NEW').first()
self.status_wip = Status.query.filter_by(code='WIP').first()
self.status_comp = Status.query.filter_by(code='CMPL').first()
self.task_template = FilenameTemplate(
name='Task Template',
target_entity_type='Task',
path='{{project.code}}/'
'{%- for parent_task in parent_tasks -%}'
'{{parent_task.nice_name}}/'
'{%- endfor -%}',
filename='{{version.nice_name}}'
'_v{{"%03d"|format(version.version_number)}}',
)
self.asset_template = FilenameTemplate(
name='Asset Template',
target_entity_type='Asset',
path='{{project.code}}/'
'{%- for parent_task in parent_tasks -%}'
'{{parent_task.nice_name}}/'
'{%- endfor -%}',
filename='{{version.nice_name}}'
'_v{{"%03d"|format(version.version_number)}}',
)
self.shot_template = FilenameTemplate(
name='Shot Template',
target_entity_type='Shot',
path='{{project.code}}/'
'{%- for parent_task in parent_tasks -%}'
'{{parent_task.nice_name}}/'
'{%- endfor -%}',
filename='{{version.nice_name}}'
'_v{{"%03d"|format(version.version_number)}}',
)
self.sequence_template = FilenameTemplate(
name='Sequence Template',
target_entity_type='Sequence',
path='{{project.code}}/'
'{%- for parent_task in parent_tasks -%}'
'{{parent_task.nice_name}}/'
'{%- endfor -%}',
filename='{{version.nice_name}}'
'_v{{"%03d"|format(version.version_number)}}',
)
self.structure = Structure(
name='Project Struture',
templates=[self.task_template, self.asset_template,
self.shot_template, self.sequence_template]
)
self.project_status_list = StatusList(
name='Project Statuses',
target_entity_type='Project',
statuses=[self.status_new, self.status_wip, self.status_comp]
)
self.image_format = ImageFormat(
name='HD 1080',
width=1920,
height=1080,
pixel_aspect=1.0
)
# create a test project
self.project = Project(
name='Test Project',
code='TP',
repository=self.repo1,
status_list=self.project_status_list,
structure=self.structure,
image_format=self.image_format
)
# create task hierarchy
#
# ASSETS
#
self.assets = Task(
name='Assets',
project=self.project,
responsible=[self.user1]
)
#
# SEQUENCES
#
self.sequences = Task(
name='Sequences',
project=self.project,
responsible=[self.user1]
)
self.seq001 = Sequence(
name='Seq001',
code='Seq001',
parent=self.sequences
)
self.scene_task = Task(
name='001_IST',
parent=self.seq001
)
self.scene_previs_type = Type(
name='Scene Previs',
code='Scene Previs',
target_entity_type='Task'
)
self.scene_previs = Task(
name='Scene Previs',
parent=self.scene_task,
type=self.scene_previs_type
)
self.shots = Task(
name='Shots',
parent=self.scene_task
)
self.shot1 = Shot(
name='Seq001_001_IST_0010',
code='Seq001_001_IST_0010',
parent=self.shots
)
# create shot tasks
self.previs = Task(
name='Previs',
parent=self.shot1
)
self.camera = Task(
name='Camera',
parent=self.shot1
)
self.animation = Task(
name='Animation',
parent=self.shot1
)
self.scene_assembly = Task(
name='SceneAssembly',
parent=self.shot1
)
self.lighting = Task(
name='Lighting',
parent=self.shot1
)
self.comp = Task(
name='Comp',
parent=self.shot1
)
# create maya files
self.maya_env = Maya()
pm.newFile(force=True)
sm = pm.PyNode('sequenceManager1')
seq1 = sm.create_sequence('001_IST')
# create 3 shots
shot1 = seq1.create_shot('shot1')
shot2 = seq1.create_shot('shot2')
shot3 = seq1.create_shot('shot3')
# set shot ranges
shot1.startFrame.set(1)
shot1.endFrame.set(100)
shot2.startFrame.set(101)
shot2.endFrame.set(200)
shot2.sequenceStartFrame.set(101)
shot3.startFrame.set(201)
shot3.endFrame.set(300)
shot3.sequenceStartFrame.set(201)
# save the file under scene previs
v = Version(task=self.scene_previs)
self.maya_env.save_as(v)
pm.newFile(force=1)
print(v.absolute_full_path)
def test_test_setup(self):
"""to test test setup
"""
pass
| sergeneren/anima | tests/env/maya/test_previs.py | Python | bsd-2-clause | 6,717 |
import isLength from './isLength';
import toObject from './toObject';
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
var length = collection ? collection.length : 0;
if (!isLength(length)) {
return eachFunc(collection, iteratee);
}
var index = fromRight ? length : -1,
iterable = toObject(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
export default createBaseEach;
| wushuyi/remoteMultiSketchpad | frontend/assets/libs/lodash-3.6.0-es/internal/createBaseEach.js | JavaScript | bsd-2-clause | 861 |
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2004
*
* Bugfixes provided by:
* Olof Sivertsson <olsi0767@student.uu.se>
*
* Last modified:
* $Date: 2014-09-22 01:35:47 +0200 (må, 22 sep 2014) $ by $Author: mears $
* $Revision: 14223 $
*
* This file is part of Gecode, the generic constraint
* development environment:
* http://www.gecode.org
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <gecode/driver.hh>
#include <gecode/int.hh>
using namespace Gecode;
/**
* \brief %Options for %BIBD problems
*
*/
class BIBDOptions : public Options {
public:
int v, k, lambda; ///< Parameters to be given on command line
int b, r; ///< Derived parameters
/// Derive additional parameters
void derive(void) {
b = (v*(v-1)*lambda)/(k*(k-1));
r = (lambda*(v-1)) / (k-1);
}
/// Initialize options for example with name \a s
BIBDOptions(const char* s,
int v0, int k0, int lambda0)
: Options(s), v(v0), k(k0), lambda(lambda0) {
derive();
}
/// Parse options from arguments \a argv (number is \a argc)
void parse(int& argc, char* argv[]) {
Options::parse(argc,argv);
if (argc < 4)
return;
v = atoi(argv[1]);
k = atoi(argv[2]);
lambda = atoi(argv[3]);
derive();
}
/// Print help message
virtual void help(void) {
Options::help();
std::cerr << "\t(unsigned int) default: " << v << std::endl
<< "\t\tparameter v" << std::endl
<< "\t(unsigned int) default: " << k << std::endl
<< "\t\tparameter k" << std::endl
<< "\t(unsigned int) default: " << lambda << std::endl
<< "\t\tparameter lambda" << std::endl;
}
};
/**
* \brief %Example: Balanced incomplete block design (%BIBD)
*
* See problem 28 at http://www.csplib.org/.
*
* \ingroup Example
*
*/
class BIBD : public Script {
protected:
/// Options providing access to parameters
const BIBDOptions& opt;
/// Matrix of Boolean variables
BoolVarArray _p;
public:
/// Symmetry breaking variants
enum {
SYMMETRY_NONE, ///< No symmetry breaking
SYMMETRY_LEX, ///< Lex-constraints on rows/columns
SYMMETRY_LDSB ///< LDSB on rows/columns
};
/// Actual model
BIBD(const BIBDOptions& o)
: opt(o), _p(*this,opt.v*opt.b,0,1) {
Matrix<BoolVarArray> p(_p,opt.b,opt.v);
// r ones per row
for (int i=0; i<opt.v; i++)
linear(*this, p.row(i), IRT_EQ, opt.r);
// k ones per column
for (int j=0; j<opt.b; j++)
linear(*this, p.col(j), IRT_EQ, opt.k);
// Exactly lambda ones in scalar product between two different rows
for (int i1=0; i1<opt.v; i1++)
for (int i2=i1+1; i2<opt.v; i2++) {
BoolVarArgs row(opt.b);
for (int j=0; j<opt.b; j++)
row[j] = expr(*this, p(j,i1) && p(j,i2));
linear(*this, row, IRT_EQ, opt.lambda);
}
if (opt.symmetry() == SYMMETRY_LDSB) {
Symmetries s;
s << rows_interchange(p);
s << columns_interchange(p);
branch(*this, _p, INT_VAR_NONE(), INT_VAL_MIN(), s);
} else {
if (opt.symmetry() == SYMMETRY_LEX) {
for (int i=1; i<opt.v; i++)
rel(*this, p.row(i-1), IRT_GQ, p.row(i));
for (int j=1; j<opt.b; j++)
rel(*this, p.col(j-1), IRT_GQ, p.col(j));
}
branch(*this, _p, INT_VAR_NONE(), INT_VAL_MIN());
}
}
/// Print solution
virtual void
print(std::ostream& os) const {
os << "\tBIBD("
<< opt.v << "," << opt.k << ","
<< opt.lambda << ")" << std::endl;
Matrix<BoolVarArray> p(_p,opt.b,opt.v);
for (int i = 0; i<opt.v; i++) {
os << "\t\t";
for (int j = 0; j<opt.b; j++)
os << p(j,i) << " ";
os << std::endl;
}
os << std::endl;
}
/// Constructor for cloning \a s
BIBD(bool share, BIBD& s)
: Script(share,s), opt(s.opt) {
_p.update(*this,share,s._p);
}
/// Copy during cloning
virtual Space*
copy(bool share) {
return new BIBD(share,*this);
}
};
/** \brief Main-function
* \relates BIBD
*/
int
main(int argc, char* argv[]) {
BIBDOptions opt("BIBD",7,3,60);
opt.symmetry(BIBD::SYMMETRY_LEX);
opt.symmetry(BIBD::SYMMETRY_NONE,"none");
opt.symmetry(BIBD::SYMMETRY_LEX,"lex");
opt.symmetry(BIBD::SYMMETRY_LDSB,"ldsb");
opt.parse(argc,argv);
/*
* Other interesting instances:
* BIBD(7,3,1), BIBD(6,3,2), BIBD(7,3,20), ...
*/
Script::run<BIBD,DFS,BIBDOptions>(opt);
return 0;
}
// STATISTICS: example-any
| PetterS/easy-IP | third-party/gecode/examples/bibd.cpp | C++ | bsd-2-clause | 5,709 |
package uk.co.marmablue.gunboat.gui;
import uk.co.marmablue.gunboat.gui.GLDisplay;
/** Game window for Gunboat.
* @author Ian Renton
*/
public class Game {
/** Main method.
* @param args command line arguments.
*/
public static void main(String[] args) {
GLDisplay gameGLDisplay = null;
boolean windowed = false;
for (int i=0; i<args.length; i++) {
if (args[i].equals("-windowed")) {
windowed = true;
}
}
if (windowed) {
gameGLDisplay = GLDisplay.createGLDisplay("Gunboat");
} else {
gameGLDisplay = GLDisplay.createFullScreenGLDisplay("Gunboat");
}
GameRenderer renderer = new GameRenderer();
KeyboardHandler keyboardHandler = new KeyboardHandler(renderer, gameGLDisplay);
MouseHandler mouseHandler = new MouseHandler(renderer, gameGLDisplay);
gameGLDisplay.addGLEventListener(renderer);
gameGLDisplay.addKeyListener(keyboardHandler);
gameGLDisplay.addMouseMotionListener(mouseHandler);
gameGLDisplay.addMouseListener(mouseHandler);
gameGLDisplay.start();
}
}
| ianrenton/Gunboat | src/uk/co/marmablue/gunboat/gui/Game.java | Java | bsd-2-clause | 1,174 |
package pub
import (
"fmt"
)
type RtmpTransferCmd struct {
FromLiveAddr string
ToRtmpPublishAddr string
}
func (c *RtmpTransferCmd) CmdString() string {
return fmt.Sprintf("rtmp_transfer %s %s", c.FromLiveAddr, c.ToRtmpPublishAddr)
}
type HlsTransferCmd struct {
FromHlsAddr string
ToRtmpPublishAddr string
}
func (c *HlsTransferCmd) CmdString() string {
return fmt.Sprintf("hls_pub %s %s", c.FromHlsAddr, c.ToRtmpPublishAddr)
}
type FlvTransferCmd struct {
FromFlvAddr string
ToRtmpPublishAddr string
}
func (c *FlvTransferCmd) CmdString() string {
return fmt.Sprintf("flv_pub %s %s", c.FromFlvAddr, c.ToRtmpPublishAddr)
}
| jemygraw/go-pub-sdk | pub/cmd.go | GO | bsd-2-clause | 658 |
# MusicPlayer, https://github.com/albertz/music-player
# Copyright (c) 2012, Albert Zeyer, www.az2000.de
# All rights reserved.
# This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
def queueMain():
from Player import PlayerEventCallbacks
from Queue import queue
from State import state
queue.fillUpTo() # add some right away if empty...
for ev, args, kwargs in state.updates.read():
if ev is PlayerEventCallbacks.onSongChange:
queue.fillUpTo()
| albertz/music-player | src/modules/mod_queue.py | Python | bsd-2-clause | 505 |
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include <thread>
#include <vector>
#include <iostream>
#include <mutex>
#include <set>
#include "catch.hpp"
#include "elimination_array.hpp"
#include <functional>
#include <chrono>
#include <thread>
using namespace std;
TEST_CASE( "elimination_array size 1", "[elimination_array]" ) {
constexpr size_t elim_size = 1;
elimination_array<int, elim_size> elim;
long timeout_us = 10000;
elim.set_timeout( timeout_us );
function<void(bool*,int*)> f = [&](bool* b, int * a){
*b = elim.visit( *a, elim_size-1 );
};
int n= 100;
vector<int> vals(n);
int count = 0;
for( auto & i : vals ){
i = count;
++count;
}
bool * rets = new bool[n];
vector<thread> ts(n);
for(size_t i = 0; i < n; ++i ){
bool * b = &rets[i];
int * a = &vals[i];
ts[i] = std::thread( f, b, a );
}
for(size_t i = 0; i < n; ++i ){
ts[i].join();
}
std::cout << "threads joined." << std::endl;
vector<int> expected_vals(n);
count = 0;
for( auto & i : expected_vals ){
i = count;
++count;
}
//check each value has changed
int count_eliminated = 0;
for( size_t i = 0; i < n; ++i ){
if( rets[i] ){
++count_eliminated;
}
}
std::cout << "num thread: " << n << ", size elimnation array: " << elim_size << ", percent eliminated: " << (double)count_eliminated / n * 100.0 << std::endl;
//check appearance of each unique value
sort(vals.begin(), vals.end());
bool vals_unique = expected_vals == vals;
CHECK( vals_unique );
delete [] rets;
}
TEST_CASE( "elimination_array visit range exceed size", "[elimination_array]" ) {
constexpr size_t elim_size = 1;
elimination_array<int, elim_size> elim;
long timeout_us = 10000;
elim.set_timeout( timeout_us );
function<void(bool*,int*)> f = [&](bool* b, int * a){
*b = elim.visit( *a, 5 );
};
int n= 10;
vector<int> vals(n);
int count = 0;
for( auto & i : vals ){
i = count;
++count;
}
bool * rets = new bool[n];
vector<thread> ts(n);
for(size_t i = 0; i < n; ++i ){
bool * b = &rets[i];
int * a = &vals[i];
ts[i] = std::thread( f, b, a );
}
for(size_t i = 0; i < n; ++i ){
ts[i].join();
}
std::cout << "threads joined." << std::endl;
vector<int> expected_vals(n);
count = 0;
for( auto & i : expected_vals ){
i = count;
++count;
}
//check each value has changed
int count_eliminated = 0;
for( size_t i = 0; i < n; ++i ){
if( rets[i] ){
++count_eliminated;
}
}
std::cout << "num thread: " << n << ", size elimnation array: " << elim_size << ", percent eliminated: " << (double)count_eliminated / n * 100.0 << std::endl;
//check appearance of each unique value
sort(vals.begin(), vals.end());
bool vals_unique = expected_vals == vals;
CHECK( vals_unique );
delete [] rets;
}
| bilbil/enhance | test/concurrent/test_elimination_array.cpp | C++ | bsd-2-clause | 3,032 |
package net.imagej.ops.math.divide;
import net.imagej.ops.Contingent;
import net.imagej.ops.Ops;
import net.imagej.ops.map.MapBinaryInplace1s;
import net.imagej.ops.special.inplace.AbstractBinaryInplace1Op;
import net.imagej.ops.special.inplace.BinaryInplace1Op;
import net.imagej.ops.special.inplace.Inplaces;
import net.imglib2.IterableInterval;
import net.imglib2.type.numeric.RealType;
import org.scijava.Priority;
import org.scijava.plugin.Plugin;
@Plugin(type = Ops.Math.Divide.class, priority = Priority.NORMAL_PRIORITY)
public class DivideHandleZeroMap1<I extends RealType<I>, O extends RealType<O>>
extends AbstractBinaryInplace1Op<IterableInterval<O>, IterableInterval<I>>
implements Ops.Math.Divide, Contingent
{
private BinaryInplace1Op<O, I, O> divide;
private BinaryInplace1Op<IterableInterval<O>, IterableInterval<I>, IterableInterval<O>> map;
@Override
@SuppressWarnings("unchecked")
public void initialize() {
super.initialize();
divide = (BinaryInplace1Op) Inplaces.binary1(ops(),
DivideHandleZeroOp1.class, RealType.class, RealType.class);
map = (BinaryInplace1Op) Inplaces.binary1(ops(),
MapBinaryInplace1s.IIAndII.class, IterableInterval.class,
IterableInterval.class, divide);
}
@Override
public boolean conforms() {
return true;
/* if (!Intervals.equalDimensions(in1(), in2())) return false;
if (!in1().iterationOrder().equals(in2().iterationOrder())) return false;
if (out() == null) return true;
return Intervals.equalDimensions(in1(), out()) && in1().iterationOrder()
.equals(out().iterationOrder());*/
}
@Override
public void mutate1(final IterableInterval<O> outin,
final IterableInterval<I> input2)
{
map.mutate1(outin, input2);
}
}
| stelfrich/imagej-ops | src/main/java/net/imagej/ops/math/divide/DivideHandleZeroMap1.java | Java | bsd-2-clause | 1,726 |
package io.pivotal.node_gemfire;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.execute.FunctionAdapter;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.RegionFunctionContext;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Put extends FunctionAdapter {
public void execute(FunctionContext fc) {
RegionFunctionContext regionFunctionContext = (RegionFunctionContext) fc;
Region<Object, Object> region = regionFunctionContext.getDataSet();
List arguments = (List) regionFunctionContext.getArguments();
region.put(arguments.get(0), arguments.get(1));
fc.getResultSender().lastResult(true);
}
public String getId() {
return getClass().getName();
}
}
| gemfire/node-gemfire | spec/support/java/function/src/main/java/io/pivotal/node_gemfire/Put.java | Java | bsd-2-clause | 814 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import time
import getpass
import schedule
import configparser
import subprocess
import syslog
import json
import datetime
import dateutil.parser
from time import gmtime, strftime
from pytz import timezone
import pytz
from datetime import timedelta
# Configuration
restic_args = ''
restic_password = ''
# Load Configuration
config = configparser.ConfigParser()
config.read("pyresticd.cfg")
restic_args = "snapshots --json"
backup_interval_allowed = timedelta(days=int(config['cleanup']['interval_days']),
hours=int(config['cleanup']['interval_hours']),
minutes=int(config['cleanup']['interval_minutes']),
seconds=int(config['cleanup']['interval_seconds']))
def snapshots_to_delete(password):
last_removed = False
removelist = [] # list of snapshots to be removed!
# run restic
args = [config['restic']['binary']] + restic_args.split()
ps = subprocess.Popen(args, env={
'RESTIC_PASSWORD': password,
'RESTIC_REPOSITORY': config['pyresticd']['repo'],
'PATH': os.environ['PATH'],
},
stdout=subprocess.PIPE,
)
#ps.wait()
json_input = ps.stdout.read()
json_parsed = json.loads(json_input)
last_backup = datetime.datetime(1, 1, 1, tzinfo=timezone('Europe/Berlin'))
for data in json_parsed:
data_datum = dateutil.parser.parse(data['time'])
data_id = data['id'][:8]
print("--------------")
#print(data_datum.strftime('%d.%m.%Y %H:%M:%S'))
print(data_id + " || " + data['time'])
backup_interval_current = data_datum - last_backup
print(backup_interval_current)
if backup_interval_current < backup_interval_allowed and not last_removed:
last_removed = True
print("REMOVE")
removelist.append(data_id)
else:
last_removed = False
# save backup date for the next step
last_backup = data_datum
print("\nSummary for interval " + str(backup_interval_allowed) + "\n==========\n\nI found " + str(len(removelist)) + " of " + str(len(json_parsed)) + " snapshots to delete:\n")
remove_string = ""
for i in removelist:
print(i+" ", end='')
remove_string = remove_string + i + " "
print()
remove_command = config['restic']['binary'] + " -r " + config['pyresticd']['repo'] + " forget " + remove_string
print("Suggested command: \n")
print(remove_command)
if not restic_password and 'RESTIC_PASSWORD' in os.environ:
restic_password = os.environ['RESTIC_PASSWORD']
if not restic_password:
restic_password = getpass.getpass(
prompt='Please enter the restic encryption password: ')
print("Password entered.")
snapshots_to_delete(restic_password)
| Mebus/pyresticd | cleanup.py | Python | bsd-2-clause | 2,933 |
package com.multiwork.andres;
import java.io.InputStream;
import java.io.OutputStream;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.bluetoothutils.andres.BluetoothHelper;
import com.bluetoothutils.andres.OnBluetoothConnected;
import com.frecuencimeter.andres.FrecView;
import com.protocolanalyzer.andres.LogicAnalyzerActivity;
import com.roboticarm.andres.BrazoRobot;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainMenu extends SherlockListActivity implements OnBluetoothConnected{
private static final boolean DEBUG = true;
private static final Class<?>[] className = {LCView.class, FrecView.class,
LogicAnalyzerActivity.class, BrazoRobot.class};
private static String[] MenuNames = new String[className.length];
private static ApplicationContext myApp;
private static SharedPreferences mPrefs;
private static String bluetoothName = "linvor";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(DEBUG) Log.i("MainMenu", "onCreate() -> MainMenu");
myApp = (ApplicationContext)getApplication();
// Nombres de los Menu
MenuNames[0] = getString(R.string.LCMeterMenu);
MenuNames[1] = getString(R.string.FrecMenu);
MenuNames[2] = getString(R.string.LogicAnalyzerMenu);
MenuNames[3] = getString(R.string.BrazoMenu);
// Menu
setListAdapter(new ArrayAdapter<String>(MainMenu.this, android.R.layout.simple_list_item_1, MenuNames));
// Obtengo el nombre del dispositivo bluetooth al cual conectarme
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
bluetoothName = mPrefs.getString("btName", "linvor");
// Solo creo el diálogo si ya no lo cree antes
if(myApp.mBluetoothHelper == null){
final Context ctx = this;
// Pregunto si deseo entrar en modo offline primero
final AlertDialog.Builder mDialog = new AlertDialog.Builder(this);
mDialog.setTitle(getString(R.string.BTOfflineTitle));
mDialog.setMessage(getString(R.string.BTOfflineSummary));
mDialog.setPositiveButton(getString(R.string.Yes), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(DEBUG) Log.i("MainMenu", "Offline mode enabled");
// Offline
myApp.mBluetoothHelper = new BluetoothHelper(ctx, bluetoothName, true, (OnBluetoothConnected)ctx);
}
});
mDialog.setNegativeButton(getString(R.string.No), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(DEBUG) Log.i("MainMenu", "Offline mode disabled");
// Online
myApp.mBluetoothHelper = new BluetoothHelper(ctx, bluetoothName, false, (OnBluetoothConnected)ctx);
myApp.mBluetoothHelper.setConnectionDialog(true);
myApp.mBluetoothHelper.turnOnBluetooth();
myApp.mBluetoothHelper.setBTRequestTitleString(R.string.BTRequestTitle)
.setBTRequestSummaryString(R.string.BTRequestSummary)
.setPleaseWaitString(R.string.PleaseWait)
.setConnectingString(R.string.BTConnecting)
.setScanString(R.string.button_scan)
.setScanningString(R.string.scanning)
.setSelectDeviceString(R.string.select_device)
.setNoDeviceString(R.string.none_found);
myApp.mBluetoothHelper.connect();
}
});
mDialog.setCancelable(false);
mDialog.show();
}
}
@Override
protected void onDestroy() {
if(myApp.mBluetoothHelper != null){
myApp.mBluetoothHelper.turnOffBluetooth();
myApp.mBluetoothHelper.disconnect();
}
myApp.mBluetoothHelper = null;
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
}
// Click en algun elemento de la lista
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(DEBUG) Log.i("MainMenu", "onListItemClick() - Position: " + position);
Intent mIntent = new Intent(MainMenu.this, className[position]);
startActivity(mIntent);
}
// Creo el ActionBar con los iconos
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(DEBUG) Log.i("MainMenu", "onCreateOptionsMenu() -> MainMenu");
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.actionbarmain, menu);
return true;
}
// Al presionar los iconos del ActionBar
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(DEBUG) Log.i("MainMenu", "onOptionsItemSelected() -> MainMenu - Item: " + item.getTitle());
switch(item.getItemId()){
case R.id.exitMain:
finish();
break;
case R.id.settingsMain:
startActivity(new Intent(this, MainPrefs.class));
}
return true;
}
@Override
public void onBluetoothConnected(InputStream mInputStream, OutputStream mOutputStream) {
myApp.mInputStream = mInputStream;
myApp.mOutputStream = mOutputStream;
}
} | dragondgold/MultiWork | MultiWork/src/main/java/com/multiwork/andres/MainMenu.java | Java | bsd-2-clause | 5,809 |
#include <ffmpeg/avcodec.h>
#include <ffmpeg/avformat.h>
#include <stdio.h>
#include <stdlib.h>
#define IS_INTERLACED(a) ((a)&MB_TYPE_INTERLACED)
#define IS_16X16(a) ((a)&MB_TYPE_16x16)
#define IS_16X8(a) ((a)&MB_TYPE_16x8)
#define IS_8X16(a) ((a)&MB_TYPE_8x16)
#define IS_8X8(a) ((a)&MB_TYPE_8x8)
#define USES_LIST(a, list) ((a) & ((MB_TYPE_P0L0|MB_TYPE_P1L0)<<(2*(list))))
bool GetNextFrame(AVFormatContext *pFormatCtx, AVCodecContext *pCodecCtx,
int videoStream, AVFrame *pFrame)
{
static AVPacket packet;
static int bytesRemaining = 0;
static uint8_t *rawData;
static bool fFirstTime = true;
int bytesDecoded;
int frameFinished;
// First time we're called, set packet.data to NULL to indicate it
// doesn't have to be freed
if (fFirstTime) {
fFirstTime = false;
packet.data = NULL;
}
// Decode packets until we have decoded a complete frame
while (true) {
// Work on the current packet until we have decoded all of it
while (bytesRemaining > 0) {
// Decode the next chunk of data
bytesDecoded = avcodec_decode_video(pCodecCtx, pFrame,
&frameFinished, rawData, bytesRemaining);
// Was there an error?
if (bytesDecoded < 0) {
fprintf(stderr, "Error while decoding frame\n");
return false;
}
bytesRemaining -= bytesDecoded;
rawData += bytesDecoded;
// Did we finish the current frame? Then we can return
if (frameFinished)
return true;
}
// Read the next packet, skipping all packets that aren't for this
// stream
do {
// Free old packet
if (packet.data != NULL)
av_free_packet(&packet);
// Read new packet
if (av_read_packet(pFormatCtx, &packet) < 0)
goto loop_exit;
} while (packet.stream_index != videoStream);
bytesRemaining = packet.size;
rawData = packet.data;
}
loop_exit:
// Decode the rest of the last frame
bytesDecoded = avcodec_decode_video(pCodecCtx, pFrame, &frameFinished,
rawData, bytesRemaining);
// Free last packet
if (packet.data != NULL)
av_free_packet(&packet);
fprintf(stderr, "finished: %d\n", frameFinished);
return frameFinished != 0;
}
void print_vector(int x, int y, int dx, int dy)
{
printf("%d %d ; %d %d\n", x, y, dx, dy);
}
/* Print motion vector for each macroblock in this frame. If there is
* no motion vector in some macroblock, it prints a magic number NO_MV. */
void printMVMatrix(int index, AVFrame *pict, AVCodecContext *ctx)
{
const int mb_width = (ctx->width + 15) / 16;
const int mb_height = (ctx->height + 15) / 16;
const int mb_stride = mb_width + 1;
const int mv_sample_log2 = 4 - pict->motion_subsample_log2;
const int mv_stride = (mb_width << mv_sample_log2) + (ctx->codec_id == CODEC_ID_H264 ? 0 : 1);
const int quarter_sample = (ctx->flags & CODEC_FLAG_QPEL) != 0;
const int shift = 1 + quarter_sample;
printf("frame %d, %d x %d\n", index, mb_height, mb_width);
for (int mb_y = 0; mb_y < mb_height; mb_y++) {
for (int mb_x = 0; mb_x < mb_width; mb_x++) {
const int mb_index = mb_x + mb_y * mb_stride;
if (pict->motion_val) {
for (int type = 0; type < 3; type++) {
int direction = 0;
switch (type) {
case 0:
if (pict->pict_type != FF_P_TYPE)
continue;
direction = 0;
break;
case 1:
if (pict->pict_type != FF_B_TYPE)
continue;
direction = 0;
break;
case 2:
if (pict->pict_type != FF_B_TYPE)
continue;
direction = 1;
break;
}
if (!USES_LIST(pict->mb_type[mb_index], direction)) {
#define NO_MV 10000
if (IS_8X8(pict->mb_type[mb_index])) {
print_vector(mb_x, mb_y, NO_MV, NO_MV);
print_vector(mb_x, mb_y, NO_MV, NO_MV);
print_vector(mb_x, mb_y, NO_MV, NO_MV);
print_vector(mb_x, mb_y, NO_MV, NO_MV);
} else if (IS_16X8(pict->mb_type[mb_index])) {
print_vector(mb_x, mb_y, NO_MV, NO_MV);
print_vector(mb_x, mb_y, NO_MV, NO_MV);
} else if (IS_8X16(pict->mb_type[mb_index])) {
print_vector(mb_x, mb_y, NO_MV, NO_MV);
print_vector(mb_x, mb_y, NO_MV, NO_MV);
} else {
print_vector(mb_x, mb_y, NO_MV, NO_MV);
}
#undef NO_MV
continue;
}
if (IS_8X8(pict->mb_type[mb_index])) {
for (int i = 0; i < 4; i++) {
int xy = (mb_x*2 + (i&1) + (mb_y*2 + (i>>1))*mv_stride) << (mv_sample_log2-1);
int dx = (pict->motion_val[direction][xy][0]>>shift);
int dy = (pict->motion_val[direction][xy][1]>>shift);
print_vector(mb_x, mb_y, dx, dy);
}
} else if (IS_16X8(pict->mb_type[mb_index])) {
for (int i = 0; i < 2; i++) {
int xy = (mb_x*2 + (mb_y*2 + i)*mv_stride) << (mv_sample_log2-1);
int dx = (pict->motion_val[direction][xy][0]>>shift);
int dy = (pict->motion_val[direction][xy][1]>>shift);
if (IS_INTERLACED(pict->mb_type[mb_index]))
dy *= 2;
print_vector(mb_x, mb_y, dx, dy);
}
} else if (IS_8X16(pict->mb_type[mb_index])) {
for (int i = 0; i < 2; i++) {
int xy = (mb_x*2 + i + mb_y*2*mv_stride) << (mv_sample_log2-1);
int dx = (pict->motion_val[direction][xy][0]>>shift);
int dy = (pict->motion_val[direction][xy][1]>>shift);
if (IS_INTERLACED(pict->mb_type[mb_index]))
dy *= 2;
print_vector(mb_x, mb_y, dx, dy);
}
} else {
int xy = (mb_x + mb_y*mv_stride) << mv_sample_log2;
int dx = (pict->motion_val[direction][xy][0]>>shift);
int dy = (pict->motion_val[direction][xy][1]>>shift);
print_vector(mb_x, mb_y, dx, dy);
}
}
}
printf("--\n");
}
printf("====\n");
}
}
int main(int argc, char *argv[])
{
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
AVFrame *pFrame;
int videoStream;
// Register all formats and codecs
av_register_all();
// Open video file
if (av_open_input_file(&pFormatCtx, argv[1], NULL, 0, NULL) != 0)
return -1; // Couldn't open file
// Retrieve stream information
if (av_find_stream_info(pFormatCtx) < 0)
return -1; // Couldn't find stream information
// Dump information about file onto standard error
// dump_format(pFormatCtx, 0, argv[1], false);
// Find the first video stream
videoStream = -1;
for (int i = 0; i < pFormatCtx->nb_streams; i++) {
AVCodecContext *cc = pFormatCtx->streams[i]->codec;
if (cc->codec_type==CODEC_TYPE_VIDEO) {
// don't care FF_DEBUG_VIS_MV_B_BACK
cc->debug_mv = FF_DEBUG_VIS_MV_P_FOR | FF_DEBUG_VIS_MV_B_FOR;
videoStream = i;
break;
}
}
if (videoStream == -1)
return -1; // Didn't find a video stream
// Get a pointer to the codec context for the video stream
pCodecCtx = pFormatCtx->streams[videoStream]->codec;
// Find the decoder for the video stream
pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL)
return -1; // Codec not found
// Inform the codec that we can handle truncated bitstreams -- i.e.,
// bitstreams where frame boundaries can fall in the middle of packets
if (pCodec->capabilities & CODEC_CAP_TRUNCATED)
pCodecCtx->flags |= CODEC_FLAG_TRUNCATED;
// Open codec
if (avcodec_open(pCodecCtx, pCodec)<0)
return -1; // Could not open codec
// Hack to correct wrong frame rates that seem to be generated by some
// codecs
// if (pCodecCtx->frame_rate>1000 && pCodecCtx->frame_rate_base==1)
// pCodecCtx->frame_rate_base=1000;
// Allocate video frame
pFrame = avcodec_alloc_frame();
int f = 1;
while (GetNextFrame(pFormatCtx, pCodecCtx, videoStream, pFrame)) {
// Ignore I-Frame
if (pFrame->pict_type != FF_I_TYPE)
printMVMatrix(f, pFrame, pCodecCtx);
++f;
}
av_free(pFrame);
avcodec_close(pCodecCtx);
av_close_input_file(pFormatCtx);
return 0;
}
| victorhsieh/motion-vector | motion_vector.cpp | C++ | bsd-2-clause | 8,277 |
# -*- coding: utf-8 -*-
"""
The Logging component of the Server.
"""
import logging.handlers
################################################################################
class Logging:
"""
This class handles the console and file logging.
"""
def __init__(self, filename):
self._logger = logging.getLogger(filename)
self._logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.ERROR)
file_handler = logging.handlers.RotatingFileHandler(
'logs/' + filename + '.log',
encoding = 'utf8',
maxBytes = 1048576, # 1 MB
backupCount = 2)
file_handler.setLevel(logging.DEBUG)
console_formatter = logging.Formatter(
"%(asctime)s - %(levelname)-7s - %(name)-21s - %(message)s",
"%Y-%m-%d %H:%M:%S")
file_formatter = logging.Formatter(
"%(asctime)s - %(levelname)-7s - %(message)s",
"%Y-%m-%d %H:%M:%S")
console_handler.setFormatter(console_formatter)
file_handler.setFormatter(file_formatter)
self._logger.addHandler(console_handler)
self._logger.addHandler(file_handler)
############################################################################
def get_logger(self):
"""
Method to return the logger.
@return: the logger
"""
return self._logger
| andreas-kowasch/DomainSearch | DomainSearchServer/additional/Logging.py | Python | bsd-2-clause | 1,463 |
class Groff < Formula
desc "GNU troff text-formatting system"
homepage "https://www.gnu.org/software/groff/"
url "https://ftp.gnu.org/gnu/groff/groff-1.22.4.tar.gz"
mirror "https://ftpmirror.gnu.org/groff/groff-1.22.4.tar.gz"
sha256 "e78e7b4cb7dec310849004fa88847c44701e8d133b5d4c13057d876c1bad0293"
license "GPL-3.0"
bottle do
sha256 "a7c425eec2e56f10e06978b393c0cf53269d27f20e801856fd6d2ba91df81136" => :catalina
sha256 "1ee2ce419f4d59f098f0804e1dea42524ef72a88b69ce891c42f13d5f19be5f9" => :mojave
sha256 "24fac4b672946970b70c6e308311e87a6686fed50d4d0909228afb252531065d" => :high_sierra
sha256 "2966f4b562c30eb6679d6940b43f4b99b2b625433e6a218489f160eb76c7c360" => :sierra
sha256 "d31274339f07f31fa1a710f04120927f11c8ad03d780ddd3e39363ca3a5d5fe3" => :x86_64_linux
end
depends_on "texinfo" => :build
def install
system "./configure", "--prefix=#{prefix}", "--without-x"
system "make" # Separate steps required
system "make", "install"
end
test do
assert_match "homebrew\n",
pipe_output("#{bin}/groff -a", "homebrew\n")
end
end
| rwhogg/homebrew-core | Formula/groff.rb | Ruby | bsd-2-clause | 1,100 |
package com.study.mli.dobe.activity.tools;
import java.io.Serializable;
/**
* Created by crown on 2016/9/30.
*/
public class ImageViewInfo implements Serializable {
public float mOriginX;
public float mOriginY;
public float mOriginWidth;
public float mOriginHeight;
public String mThumbnail;
public String mUrl;
public String mTitle;
public ImageViewInfo(float x, float y, float width , float height, String thumbnail, String url, String title) {
this.mOriginX = x;
this.mOriginY = y;
this.mOriginWidth = width;
this.mOriginHeight = height;
this.mThumbnail = thumbnail;
this.mUrl = url;
this.mTitle = title;
}
}
| mianli/Dobelity | dobe/src/main/java/com/study/mli/dobe/activity/tools/ImageViewInfo.java | Java | bsd-2-clause | 643 |
#*******************************************************************************
# U n s u p e r v i s e d D e c o m p o s i t i o n B a s e *
#*******************************************************************************
class UnsupervisedDecompositionBase(object):
#human readable information
name = "Base Unsupervised Decomposition"
description = "virtual base class"
author = "HCI, University of Heidelberg"
homepage = "http://hci.iwr.uni-heidelberg.de"
def __init__(self):
pass
def decompose(self, features):
pass
def checkNumComponents(self, numChannels, numComponents):
if(numChannels < numComponents):
print "WARNING: The data set comprises", numChannels, "channels. Decomposition into more components (", numComponents, ") is not possible. Using", numChannels, "components instead."
return numChannels
if(numComponents < 1):
print "WARNING: Decomposition into less than one component is not possible. Using one component instead."
return 1
return numComponents
# it is probably NOT a good idea to define this a class level (more than one PLSA
# instance with different numbers of components might exist), but in the current
# ilastik architecture this method is called before the instance is even created,
# so it HAS to be a class method for now
# workaround: set self.numComponents in init function
@classmethod
def setNumberOfComponents(cls, numComponents):
cls.numComponents = numComponents
| ilastik/ilastik-0.5 | ilastik/modules/unsupervised_decomposition/core/algorithms/unsupervisedDecompositionBase.py | Python | bsd-2-clause | 1,598 |
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
if Rails.version.start_with? '4.2'
config.serve_static_files = true
else
config.serve_static_assets = true
end
config.static_cache_control = "public, max-age=3600"
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Randomize the order test cases are executed
config.active_support.test_order = :random
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end
| diowa/twbs_less_rails | test/dummy/config/environments/test.rb | Ruby | bsd-2-clause | 1,741 |
/*-
* #%L
* PropertiesFramework :: Core
* %%
* Copyright (C) 2017 LeanFrameworks
* %%
* 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package com.github.leanframeworks.propertiesframework.api.common;
/**
* Interface to be implemented by entities that would require an explicit disposal for complete disconnection from other
* entities and to allow garbage collection.
* <p>
* For example, if the disposable entity registers some listeners to other objects, disposing this entity should remove
* those listeners.
* <p>
* Note that after disposing an object, it cannot be re-used for other purposes. Also, calling methods on previously
* disposed objects has unspecified behavior.
*/
@FunctionalInterface
public interface Disposable {
/**
* Disposes the entity by disconnecting any listener and any reference that would prevent garbage collection.
* <p>
* Note that calling this method a second time should have no effect (and certainly not generate an exception).
*/
void dispose();
}
| LeanFrameworks/PropertiesFramework | propertiesframework-core/src/main/java/com/github/leanframeworks/propertiesframework/api/common/Disposable.java | Java | bsd-2-clause | 2,297 |
<?php
use common\models\User;
use yii\db\Schema;
use yii\db\Migration;
class M170205110000Install extends Migration
{
/**
*
*/
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%poll_question}}', [
'id' => $this->primaryKey(),
'question_text' => $this->string(128),
'answer_options' => $this->text()->notNull(),
'created_at' => $this->integer(11)->notNull(),
'updated_at' => $this->integer(11),
'deleted_at' => $this->integer(11)
], $tableOptions);
$this->createTable('{{%poll_response}}', [
'user_id' => $this->primaryKey(11),
'question_text' => $this->string(128),
'answers' => $this->text(),
'value' => $this->integer(11),
'created_at' => $this->integer(11)->notNull(),
'updated_at' => $this->integer(11),
'deleted_at' => $this->integer(11)
], $tableOptions);
$this->createTable('{{%poll_user}}', [
'id' => $this->primaryKey(11),
'poll_id' => $this->integer(11),
'user_id' => $this->integer(11)
], $tableOptions);
}
/**
*
*/
public function safeDown()
{
$this->dropTable('{{%poll_question}}');
$this->dropTable('{{%poll_response}}');
$this->dropTable('{{%poll_user}}');
}
}
| davidjeddy/yii2-poll | migrations/M170205110000Install.php | PHP | bsd-2-clause | 1,634 |
class Cryptopp < Formula
desc "Free C++ class library of cryptographic schemes"
homepage "https://www.cryptopp.com/"
url "https://downloads.sourceforge.net/project/cryptopp/cryptopp/5.6.3/cryptopp563.zip"
mirror "https://www.cryptopp.com/cryptopp563.zip"
version "5.6.3"
sha256 "9390670a14170dd0f48a6b6b06f74269ef4b056d4718a1a329f6f6069dc957c9"
revision 1
# https://cryptopp.com/wiki/Config.h#Options_and_Defines
bottle :disable, "Library and clients must be built on the same microarchitecture"
option :cxx11
patch do
# fix failing test
# https://github.com/Homebrew/homebrew-core/issues/2783
# http://comments.gmane.org/gmane.comp.encryption.cryptopp/8028
url "https://github.com/weidai11/cryptopp/commit/0059f48.diff"
sha256 "f75d6cf87f00dfa98839a89a3c0c57dc26c1739916d6d5c0abbd9228b0a01829"
end
def install
ENV.cxx11 if build.cxx11?
system "make", "shared", "all", "CXX=#{ENV.cxx}"
system "./cryptest.exe", "v"
system "make", "install", "PREFIX=#{prefix}"
end
test do
(testpath/"test.cpp").write <<-EOS.undent
#include <cryptopp/sha.h>
#include <string>
using namespace CryptoPP;
using namespace std;
int main()
{
byte digest[SHA::DIGESTSIZE];
string data = "Hello World!";
SHA().CalculateDigest(digest, (byte*) data.c_str(), data.length());
return 0;
}
EOS
ENV.cxx11 if build.cxx11?
system ENV.cxx, "test.cpp", "-L#{lib}", "-lcryptopp", "-o", "test"
system "./test"
end
end
| ShivaHuang/homebrew-core | Formula/cryptopp.rb | Ruby | bsd-2-clause | 1,547 |
/*
* Copyright (c) 2014, tibbitts
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.puyallupfamilyhistorycenter.service.cache;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import org.puyallupfamilyhistorycenter.service.models.Fact;
import org.puyallupfamilyhistorycenter.service.models.Person;
import org.puyallupfamilyhistorycenter.service.models.PersonReference;
/**
*
* @author tibbitts
*/
public class PersonDaoTest {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private final PersonDao dao;
private final List<Person> family;
private final List<Person> ancestors;
private final List<Person> descendants;
public PersonDaoTest() {
MockPersonSource source = new MockPersonSource();
dao = new PersonDao(source);
family = Arrays.asList(source.get("KWCB-HZV", ""), source.get("KWCB-HZ2", ""), source.get("KWC6-X7D", ""), source.get("KWJJ-4XH", ""));
ancestors = Arrays.asList(source.get("KWCB-HZV", ""), source.get("KWZP-8K5", ""), source.get("KWZP-8KG", ""));
descendants = Arrays.asList(source.get("KWCB-HZV", ""), source.get("KWC6-X7D", ""), source.get("KWJJ-4XH", ""), source.get("KJWD-Z94", ""));
}
/**
* Test of getPerson method, of class PersonCache.
*/
@Test
@Ignore
public void testGetPerson() {
Person person = dao.getPerson("KWCB-HZV", "");
assertEquals("KWCB-HZV", person.id);
assertEquals("Willis Aaron Dial", person.name);
assertFalse(person.living);
assertArrayEquals("Facts don't match expected: " + Arrays.deepToString(person.facts),
new Fact[] {
new Fact("birth", "23 December 1897", null, 1897, "Hooper, Weber, Utah, United States"),
new Fact("death", "19 January 1985", null, 1985, "Logan, Cache, Utah, United States") },
person.facts);
assertArrayEquals("Parents don't match expected: " + Arrays.deepToString(person.parents),
new PersonReference[] {
new PersonReference("KWZP-8K5", "William Burris Dial", "father"),
new PersonReference("KWZP-8KG", "Temperance Lavina Moore", "mother")
},
person.parents);
assertArrayEquals("Spouses don't match expected: " + Arrays.deepToString(person.spouses),
new PersonReference[] {
new PersonReference("KWCB-HZ2", "Ida Lovisa Beckstrand", "wife")
},
person.spouses);
assertArrayEquals("Children don't match expected: " + Arrays.deepToString(person.children),
new PersonReference[] {
new PersonReference("KWC6-X7D", "Glen \"B\" Dial", "son"),
new PersonReference("KWJJ-4XH", "Merlin \"B\" Dial", "son")
},
person.children);
}
@Test
public void testTraverseFamily() {
System.out.println("testTraverseFamily");
List<Person> people = dao.listImmediateFamily("KWCB-HZV", "");
assertIdsEqual(family, people);
}
/**
* Test of traverseAncestors method, of class PersonCache.
*/
@Test
@Ignore
public void testTraverseAncestors() {
System.out.println("testTraverseAncestors");
List<Person> people = dao.listAncestors("KWCB-HZV", 10, "", false);
assertIdsEqual(ancestors, people);
}
/**
* Test of traverseDescendants method, of class PersonCache.
*/
@Test
public void testTraverseDescendants() {
System.out.println("testTraverseDescendants");
List<Person> people = dao.listDescendants("KWCB-HZV", 10, "");
assertIdsEqual(descendants, people);
}
private void assertIdsEqual(List<Person> expected, List<Person> actual) {
List<String> expectedIds = new ArrayList<>(expected.size());
List<String> actualIds = new ArrayList<>(actual.size());
for (Person person : expected) {
expectedIds.add(person.id);
}
for (Person person : actual) {
actualIds.add(person.id);
}
assertEquals(expectedIds, actualIds);
}
}
| PuyallupStakeFamilyHistoryCenter/familyhistoryservice | src/test/java/org/puyallupfamilyhistorycenter/service/cache/PersonDaoTest.java | Java | bsd-2-clause | 5,730 |
class Sonobuoy < Formula
desc "Kubernetes component that generates reports on cluster conformance"
homepage "https://github.com/vmware-tanzu/sonobuoy"
url "https://github.com/vmware-tanzu/sonobuoy/archive/v0.18.1.tar.gz"
sha256 "2443b098de78c457776ce6d13803547d33ffd563984a269be6d449886652592c"
bottle do
cellar :any_skip_relocation
sha256 "83840094cad8029b8d704a2eed6f8dba54af0451dde44f4f76067e1f6d8e6c8d" => :catalina
sha256 "6574af5655839764c65615964d7fae9717c9549cbc2c91aa780c2e62a0ec61ee" => :mojave
sha256 "a574b687bfaf73ca026fdf3875d8e0910d243663f51ab9723b13fbaada23622c" => :high_sierra
end
depends_on "go" => :build
resource "sonobuoyresults" do
url "https://raw.githubusercontent.com/heptio/sonobuoy/master/pkg/client/results/testdata/results-0.10.tar.gz"
sha256 "a945ba4d475e33820310a6138e3744f301a442ba01977d38f2b635d2e6f24684"
end
def install
system "go", "build", "-ldflags",
"-s -w -X github.com/vmware-tanzu/sonobuoy/pkg/buildinfo.Version=v#{version}",
*std_go_args
prefix.install_metafiles
end
test do
resources.each { |r| r.verify_download_integrity(r.fetch) }
assert_match "Sonobuoy is an introspective kubernetes component that generates reports on cluster conformance",
shell_output("#{bin}/sonobuoy 2>&1")
assert_match version.to_s,
shell_output("#{bin}/sonobuoy version 2>&1")
assert_match "name: sonobuoy",
shell_output("#{bin}/sonobuoy gen --kube-conformance-image-version=v1.14 2>&1")
assert_match "all tests",
shell_output("#{bin}/sonobuoy e2e --show=all " + resource("sonobuoyresults").cached_download + " 2>&1")
end
end
| uyjulian/homebrew-core | Formula/sonobuoy.rb | Ruby | bsd-2-clause | 1,694 |
////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Daniel Kollmann
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list of conditions
// and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// - Neither the name of Daniel Kollmann nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
using Brainiac.Design.Attributes;
using Brainiac.Design.Nodes;
using System.Reflection;
using Brainiac.Design.Properties;
namespace Brainiac.Design.FileManagers
{
/// <summary>
/// This is the default file manager which saves and loads XML files.
/// </summary>
public class FileManagerXML : FileManager
{
protected XmlDocument _xmlfile= new XmlDocument();
/// <summary>
/// Creates a new XML file manager to load and save behaviours.
/// </summary>
/// <param name="filename">The file we want to load from or save to.</param>
/// <param name="node">The node we want to save. When loading, use null.</param>
public FileManagerXML(string filename, BehaviorNode node) : base(filename, node)
{
}
/// <summary>
/// Retrieves an attribute from a XML node. If the attribute does not exist an exception is thrown.
/// </summary>
/// <param name="node">The XML node we want to get the attribute from.</param>
/// <param name="att">The name of the attribute we want.</param>
/// <returns>Returns the attributes value. Is always valid.</returns>
protected string GetAttribute(XmlNode node, string att)
{
XmlNode value= node.Attributes.GetNamedItem(att);
// maintain compatibility to version 1
if(value ==null)
value= node.Attributes.GetNamedItem(att.ToLowerInvariant());
if(value !=null && value.NodeType ==XmlNodeType.Attribute)
return value.Value;
throw new Exception( string.Format(Resources.ExceptionFileManagerXMLMissingAttribute, att) );
}
/// <summary>
/// Retrieves an attribute from a XML node. Attribute does not need to exist.
/// </summary>
/// <param name="node">The XML node we want to get the attribute from.</param>
/// <param name="att">The name of the attribute we want.</param>
/// <param name="result">The value of the attribute found. Is string.Empty if the attribute does not exist.</param>
/// <returns>Returns true if the attribute exists.</returns>
protected bool GetAttribute(XmlNode node, string att, out string result)
{
XmlNode value= node.Attributes.GetNamedItem(att);
if(value !=null && value.NodeType ==XmlNodeType.Attribute)
{
result= value.Value;
return true;
}
result= string.Empty;
return false;
}
/// <summary>
/// Initialises a property on a given node.
/// </summary>
/// <param name="xml">The XML element containing the attribute we want to get.</param>
/// <param name="node">The node whose property we want to set.</param>
/// <param name="property">The property on the node we want to set.</param>
protected void InitProperty(XmlNode xml, Node node, DesignerPropertyInfo property)
{
string value;
if(GetAttribute(xml, property.Property.Name, out value))
property.SetValueFromString(node, value);
}
/// <summary>
/// Initialises a property on a given event.
/// </summary>
/// <param name="xml">The XML element containing the attribute we want to get.</param>
/// <param name="node">The event whose property we want to set.</param>
/// <param name="property">The property on the event we want to set.</param>
protected void InitProperty(XmlNode xml, Events.Event evnt, DesignerPropertyInfo property)
{
string value;
if(GetAttribute(xml, property.Property.Name, out value))
property.SetValueFromString(evnt, value);
}
/// <summary>
/// Loads an event which is attached to a node.
/// </summary>
/// <param name="node">The node the event is created for.</param>
/// <param name="xml">The XML node the event retrieves its name and attributes from.</param>
/// <returns>Returns the created SubItems.Event.</returns>
protected Events.Event CreateEvent(Node node, XmlNode xml)
{
// get the type of the event and create it
// maintain compatibility with version 1
//string clss= GetAttribute(xml, "Class");
string clss;
if(!GetAttribute(xml, "Class", out clss))
{
string find= ".Events."+ GetAttribute(xml, "name");
Type found= Plugin.FindType(find);
if(found !=null)
clss= found.FullName;
}
Type t= Plugin.GetType(clss);
if(t ==null)
throw new Exception( string.Format(Resources.ExceptionUnknownEventType, clss) );
Events.Event evnt= Events.Event.Create(t, node);
// initialise the events properties
IList<DesignerPropertyInfo> properties= evnt.GetDesignerProperties();
for(int p= 0; p <properties.Count; ++p)
{
if(properties[p].Attribute.HasFlags(DesignerProperty.DesignerFlags.NoSave))
continue;
InitProperty(xml, evnt, properties[p]);
}
// update event with attributes
evnt.OnPropertyValueChanged(false);
return evnt;
}
/// <summary>
/// Loads a node from a given XML node.
/// </summary>
/// <param name="xml">The XML node we want to create the node from.</param>
/// <returns>Returns the created node.</returns>
protected Node CreateNode(XmlNode xml)
{
// get the type of the node and create it
string clss= GetAttribute(xml, "Class");
Type t= Plugin.GetType(clss);
if(t ==null)
throw new Exception( string.Format(Resources.ExceptionUnknownNodeType, clss) );
Node node= Nodes.Node.Create(t);
// update the loaded behaviour member
if(node is BehaviorNode && _loadedBehavior ==null)
_loadedBehavior= (BehaviorNode)node;
// initialise the properties
IList<DesignerPropertyInfo> properties= node.GetDesignerProperties();
foreach(DesignerPropertyInfo property in properties)
{
if(property.Attribute.HasFlags(DesignerProperty.DesignerFlags.NoSave))
continue;
InitProperty(xml, node, property);
node.PostPropertyInit(property);
}
// maintain compatibility with version 1
if(node is ReferencedBehaviorNode)
{
ReferencedBehaviorNode refbehavior= (ReferencedBehaviorNode)node;
if(refbehavior.ReferenceFilename ==null)
refbehavior.ReferenceFilename= GetAttribute(xml, "Reference");
}
// update node with properties
node.OnPropertyValueChanged(false);
// load child objects
foreach(XmlNode xnode in xml.ChildNodes)
{
if(xnode.NodeType ==XmlNodeType.Element)
{
switch(xnode.Name.ToLowerInvariant())
{
// maintain compatibility with version 1
case("node"):
node.AddChild(node.DefaultConnector, CreateNode(xnode));
break;
case("event"):
node.AddSubItem( new Node.SubItemEvent( CreateEvent(node, xnode) ) );
break;
case("comment"):
// create a comment object
node.CommentText= "temp";
// initialise the attributes
properties= node.CommentObject.GetDesignerProperties();
foreach(DesignerPropertyInfo property in properties)
{
if(property.Attribute.HasFlags(DesignerProperty.DesignerFlags.NoSave))
continue;
string value;
if(GetAttribute(xnode, property.Property.Name, out value))
property.SetValueFromString(node.CommentObject, value);
}
break;
case("connector"):
string identifier= GetAttribute(xnode, "Identifier");
Nodes.Node.Connector connector= node.GetConnector(identifier);
foreach(XmlNode connected in xnode.ChildNodes)
{
if( connected.NodeType ==XmlNodeType.Element &&
connected.Name.ToLowerInvariant() =="node" )
{
node.AddChildNotModified(connector, CreateNode(connected));
}
}
break;
}
}
}
// update events with attributes
if(node.SubItems.Count >0)
{
foreach(Nodes.Node.SubItem sub in node.SubItems)
{
node.SelectedSubItem= sub;
node.OnSubItemPropertyValueChanged(false);
}
node.SelectedSubItem= null;
}
return node;
}
/// <summary>
/// This method allows nodes to process the loaded attributes.
/// </summary>
/// <param name="node">The node which is processed.</param>
protected void DoPostLoad(Node node)
{
node.PostLoad(_node);
foreach(Node child in node.Children)
DoPostLoad(child);
}
/// <summary>
/// Loads a behaviour from the given filename
/// </summary>
public override void Load()
{
try
{
_xmlfile.Load(_filename);
XmlNode root= _xmlfile.ChildNodes[1].ChildNodes[0];
_node= (BehaviorNode) CreateNode(root);
_node.FileManager= this;
DoPostLoad((Node)_node);
}
catch
{
_xmlfile.RemoveAll();
throw;
}
}
/// <summary>
/// Saves a node to the XML file.
/// </summary>
/// <param name="root">The XML node we want to attach the node to.</param>
/// <param name="node">The node we want to save.</param>
protected void SaveNode(XmlElement root, Node node)
{
// allow the node to process its attributes in preparation of the save
node.PreSave(_node);
// store the class we have to create when loading
XmlElement elem= _xmlfile.CreateElement("Node");
elem.SetAttribute("Class", node.GetType().FullName);
// save attributes
IList<DesignerPropertyInfo> properties= node.GetDesignerProperties();
for(int p= 0; p <properties.Count; ++p)
{
if(!properties[p].Attribute.HasFlags(DesignerProperty.DesignerFlags.NoSave))
elem.SetAttribute(properties[p].Property.Name, properties[p].GetStringValue(node));
}
// append node to root
root.AppendChild(elem);
// save comment
if(node.CommentObject !=null)
{
XmlElement comment= _xmlfile.CreateElement("Comment");
properties= node.CommentObject.GetDesignerProperties();
for(int p= 0; p <properties.Count; ++p)
{
if(!properties[p].Attribute.HasFlags(DesignerProperty.DesignerFlags.NoSave))
comment.SetAttribute(properties[p].Property.Name, properties[p].GetStringValue(node.CommentObject));
}
elem.AppendChild(comment);
}
// save events
foreach(Nodes.Node.SubItem sub in node.SubItems)
{
if(sub is Nodes.Node.SubItemEvent)
{
Events.Event ne= ((Nodes.Node.SubItemEvent)sub).Event;
XmlElement evnt= _xmlfile.CreateElement("Event");
evnt.SetAttribute("Class", ne.GetType().FullName);
// save attributes
properties= ne.GetDesignerProperties();
for(int p= 0; p <properties.Count; ++p)
{
if(!properties[p].Attribute.HasFlags(DesignerProperty.DesignerFlags.NoSave))
elem.SetAttribute(properties[p].Property.Name, properties[p].GetStringValue(ne));
}
elem.AppendChild(evnt);
}
}
// save children if allowed. Disallowed for referenced behaviours.
if(node.SaveChildren)
{
// save connectors
foreach(Nodes.Node.Connector connector in node.Connectors)
{
// if we have no children to store we can skip the connector
if(connector.ChildCount <1)
continue;
XmlElement conn= _xmlfile.CreateElement("Connector");
conn.SetAttribute("Identifier", connector.Identifier);
elem.AppendChild(conn);
// save their children
for(int i= 0; i <connector.ChildCount; ++i)
SaveNode(conn, connector.GetChild(i));
}
}
}
/// <summary>
/// Save the given behaviour to the given file.
/// </summary>
public override void Save()
{
_xmlfile.RemoveAll();
XmlDeclaration declaration= _xmlfile.CreateXmlDeclaration("1.0", "utf-8", null);
_xmlfile.AppendChild(declaration);
XmlElement root= _xmlfile.CreateElement("Behavior");
_xmlfile.AppendChild(root);
SaveNode(root, (Node)_node);
try
{
MakeWritable();
_xmlfile.Save(_filename);
}
catch
{
_xmlfile.RemoveAll();
throw;
}
}
}
}
| learno/Brainiac-Designer | Brainiac Designer Base/FileManagers/FileManagerXML.cs | C# | bsd-3-clause | 13,808 |
<?php
/**
* @package SimplePortal
*
* @author SimplePortal Team
* @copyright 2020 SimplePortal Team
* @license BSD 3-clause
*
* @version 2.3.8
*/
if (!defined('SMF'))
die('Hacking attempt...');
/*
void sportal_articles()
// !!!
array sportal_articles_callback()
// !!!
void sportal_add_article()
// !!!
void sportal_remove_article()
// !!!
*/
function sportal_articles()
{
global $smcFunc, $context, $modSettings, $article_request;
loadLanguage('Stats');
loadTemplate('PortalArticles');
$context['sub_template'] = 'articles';
if (empty($modSettings['articleactive']))
return;
$request = $smcFunc['db_query']('','
SELECT COUNT(*)
FROM {db_prefix}sp_articles as a
INNER JOIN {db_prefix}sp_categories AS c ON (c.id_category = a.id_category)
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_message)
INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
WHERE {query_see_board}
AND a.approved = {int:approved}
AND publish = {int:publish}',
array(
'approved' => 1,
'publish' => 1,
)
);
list ($totalArticles) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
$modSettings['articleperpage'] = isset($modSettings['articleperpage']) ? (int) $modSettings['articleperpage'] : 5;
$context['start'] = !empty($_REQUEST['articles']) ? (int) $_REQUEST['articles'] : 0;
if (!empty($modSettings['articleperpage']) && $totalArticles > 0)
$context['page_index'] = constructPageIndex($context['portal_url'] . '?articles=%1$d', $context['start'], $totalArticles, $modSettings['articleperpage'], true);
if (empty($modSettings['sp_disableColor']))
{
$members_request = $smcFunc['db_query']('','
SELECT m.id_member
FROM {db_prefix}sp_articles AS a
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_message)
INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
INNER JOIN {db_prefix}sp_categories AS c ON (c.id_category = a.id_category)
WHERE {query_see_board}
AND a.approved = {int:approved}
AND publish = {int:publish}
AND m.id_member != {int:guest}
ORDER BY a.id_message DESC' . (empty($modSettings['articleperpage']) ? '' : '
LIMIT {int:start}, {int:end}'),
array(
'approved' => 1,
'publish' => 1,
'start' => $context['start'],
'end' => $modSettings['articleperpage'],
'guest' => 0,
)
);
$colorids = array();
while($row = $smcFunc['db_fetch_assoc']($members_request))
$colorids[] = $row['id_member'];
$smcFunc['db_free_result']($members_request);
if (!empty($colorids))
sp_loadColors($colorids);
}
$article_request = $smcFunc['db_query']('','
SELECT
a.id_article, a.id_category, a.id_message, a.approved, c.name as cname, c.picture, m.id_member,
IFNULL(mem.real_name, m.poster_name) AS poster_name, m.icon, m.subject, m.body, m.poster_time,
m.smileys_enabled, t.id_topic, t.num_replies, t.num_views, t.locked, b.id_board, b.name as bname,
mem.avatar, at.id_attach, at.attachment_type, at.filename
FROM {db_prefix}sp_articles AS a
INNER JOIN {db_prefix}sp_categories AS c ON (c.id_category = a.id_category)
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_message)
INNER JOIN {db_prefix}topics AS t ON (t.id_first_msg = a.id_message)
INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
LEFT JOIN {db_prefix}attachments AS at ON (at.id_member = mem.id_member)
WHERE {query_see_board}
AND a.approved = {int:approved}
AND publish = {int:publish}
ORDER BY a.id_message DESC' . (empty($modSettings['articleperpage']) ? '' : '
LIMIT {int:start}, {int:end}'),
array(
'approved' => 1,
'publish' => 1,
'start' => $context['start'],
'end' => $modSettings['articleperpage'],
)
);
$context['get_articles'] = 'sportal_articles_callback';
}
function sportal_articles_callback($reset = false)
{
global $smcFunc, $scripturl, $modSettings, $settings, $txt, $color_profile, $article_request, $current;
if ($article_request == false)
return false;
if (!($row = $smcFunc['db_fetch_assoc']($article_request)))
return false;
if (!empty($current) && $current == $row['id_message'])
return;
$current = $row['id_message'];
$stable_icons = array('xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'moved', 'recycled', 'wireless');
$icon_sources = array();
foreach ($stable_icons as $icon)
$icon_sources[$icon] = 'images_url';
$limited = false;
if (($cutoff = $smcFunc['strpos']($row['body'], '[cutoff]')) !== false)
{
$row['body'] = $smcFunc['substr']($row['body'], 0, $cutoff);
$limited = true;
}
elseif (!empty($modSettings['articlelength']) && $smcFunc['strlen']($row['body']) > $modSettings['articlelength'])
{
$row['body'] = $smcFunc['substr']($row['body'], 0, $modSettings['articlelength']);
$limited = true;
}
$row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_message']);
// Only place an ellipsis if the body has been shortened.
if ($limited)
$row['body'] .= '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0" title="' . $row['subject'] . '">...</a>';
if ($modSettings['avatar_action_too_large'] == 'option_html_resize' || $modSettings['avatar_action_too_large'] == 'option_js_resize')
{
$avatar_width = !empty($modSettings['avatar_max_width_external']) ? ' width="' . $modSettings['avatar_max_width_external'] . '"' : '';
$avatar_height = !empty($modSettings['avatar_max_height_external']) ? ' height="' . $modSettings['avatar_max_height_external'] . '"' : '';
}
else
{
$avatar_width = '';
$avatar_height = '';
}
if (empty($modSettings['messageIconChecks_disable']) && !isset($icon_sources[$row['icon']]))
$icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.gif') ? 'images_url' : 'default_images_url';
censorText($row['subject']);
censorText($row['body']);
if ($modSettings['sp_resize_images'])
$row['body'] = preg_replace('~class="bbc_img~i', 'class="bbc_img sp_article', $row['body']);
$output = array(
'article' => array(
'id' => $row['id_article'],
'comment_href' => !empty($row['locked']) ? '' : $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . ';num_replies=' . $row['num_replies'],
'comment_link' => !empty($row['locked']) ? '' : '| <a href="' . $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . ';num_replies=' . $row['num_replies'] . '">' . $txt['ssi_write_comment'] . '</a>',
'new_comment' => !empty($row['locked']) ? '' : '| <a href="' . $scripturl . '?action=post;topic=' . $row['id_topic'] . '.' . $row['num_replies'] . '">' . $txt['ssi_write_comment'] . '</a>',
'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $txt['sp-read_more'] . '</a>',
'approved' => $row['approved'],
),
'category' => array(
'id' => $row['id_category'],
'name' => $row['cname'],
'picture' => array (
'href' => $row['picture'],
'image' => '<img src="' . $row['picture'] . '" alt="' . $row['cname'] . '" width="75" />',
),
),
'message' => array(
'id' => $row['id_message'],
'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.gif" align="middle" alt="' . $row['icon'] . '" border="0" />',
'subject' => $row['subject'],
'body' => $row['body'],
'time' => timeformat($row['poster_time']),
),
'poster' => array(
'id' => $row['id_member'],
'name' => $row['poster_name'],
'href' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '',
'link' => !empty($row['id_member']) ? (!empty($color_profile[$row['id_member']]['link']) ? $color_profile[$row['id_member']]['link'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>') : $row['poster_name'],
'avatar' => array(
'name' => $row['avatar'],
'image' => $row['avatar'] == '' ? ($row['id_attach'] > 0 ? '<img src="' . (empty($row['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $row['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $row['filename']) . '" alt="" class="avatar" border="0" />' : '') : (stristr($row['avatar'], 'http://') ? '<img src="' . $row['avatar'] . '"' . $avatar_width . $avatar_height . ' alt="" class="avatar" border="0" />' : '<img src="' . $modSettings['avatar_url'] . '/' . htmlspecialchars($row['avatar']) . '" alt="" class="avatar" border="0" />'),
'href' => $row['avatar'] == '' ? ($row['id_attach'] > 0 ? (empty($row['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $row['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $row['filename']) : '') : (stristr($row['avatar'], 'http://') ? $row['avatar'] : $modSettings['avatar_url'] . '/' . $row['avatar']),
'url' => $row['avatar'] == '' ? '' : (stristr($row['avatar'], 'http://') ? $row['avatar'] : $modSettings['avatar_url'] . '/' . $row['avatar'])
),
),
'topic' => array(
'id' => $row['id_topic'],
'replies' => $row['num_replies'],
'views' => $row['num_views'],
'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0',
'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>',
'locked' => !empty($row['locked']),
),
'board' => array(
'id' => $row['id_board'],
'name' => $row['bname'],
'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['bname'] . '</a>',
),
);
return $output;
}
function sportal_add_article()
{
global $smcFunc, $context, $scripturl, $sourcedir, $txt;
if (!allowedTo(array('sp_add_article', 'sp_manage_articles', 'sp_admin')))
fatal_lang_error('error_sp_cannot_add_article');
require_once($sourcedir . '/Subs-PortalAdmin.php');
loadLanguage('SPortalAdmin', sp_languageSelect('SPortalAdmin'));
loadTemplate('PortalArticles');
if (!empty($_POST['add_article']))
{
checkSession();
$article_options = array(
'id_category' => !empty($_POST['category']) ? (int) $_POST['category'] : 0,
'id_message' => !empty($_POST['message']) ? (int) $_POST['message'] : 0,
'approved' => allowedTo(array('sp_admin', 'sp_manage_articles', 'sp_auto_article_approval')) ? 1 : 0,
);
createArticle($article_options);
redirectexit('topic=' . $_POST['return']);
}
$context['message'] = !empty($_REQUEST['message']) ? (int) $_REQUEST['message'] : 0;
$context['return'] = !empty($_REQUEST['return']) ? $_REQUEST['return'] : '';
if (empty($context['message']))
fatal_lang_error('error_sp_no_message_id');
$request = $smcFunc['db_query']('','
SELECT id_message
FROM {db_prefix}sp_articles
WHERE id_message = {int:message}',
array(
'message' => $context['message'],
)
);
list ($exists) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
if ($exists)
fatal_lang_error('error_sp_article_exists');
$context['list_categories'] = getCategoryInfo(null, true);
if (empty($context['list_categories']))
fatal_error(allowedTo(array('sp_admin', 'sp_manage_articles')) ? $txt['error_sp_no_category'] . '<br />' . sprintf($txt['error_sp_no_category_sp_moderator'], $scripturl . '?action=admin;area=portalarticles;sa=addcategory') : $txt['error_sp_no_category_normaluser'], false);
$context['sub_template'] = 'add_article';
}
function sportal_remove_article()
{
global $smcFunc, $sourcedir;
checkSession('get');
if (!allowedTo(array('sp_remove_article', 'sp_manage_articles', 'sp_admin')))
fatal_lang_error('error_sp_cannot_remove_article');
require_once($sourcedir . '/Subs-PortalAdmin.php');
$message_id = !empty($_REQUEST['message']) ? (int) $_REQUEST['message'] : 0;
$topic_id = !empty($_REQUEST['return']) ? $_REQUEST['return'] : '';
$smcFunc['db_query']('','
DELETE FROM {db_prefix}sp_articles
WHERE id_message = {int:message}',
array(
'message' => $message_id,
)
);
fixCategoryArticles();
redirectexit('topic=' . $topic_id);
}
?> | SimplePortal/SimplePortal | smf2/Sources/PortalArticles.php | PHP | bsd-3-clause | 12,135 |
<?php
use yii\helpers\Html;
/* @var $this \yii\web\View view component instance */
/* @var $message \yii\mail\MessageInterface the message being composed */
/* @var $content string main view render result */
?>
<?php $this->beginPage() ?>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= Html::encode($this->title) ?></title>
<style type="text/css">
/* Client-specific Styles */
#outlook a {padding:0;} /* Force Outlook to provide a "view in browser" menu link. */
body{width:100% !important;background: #de4f4e; -webkit-text-size-adjust:100%; -ms-text-size-adjust:100%; margin:0; padding:0;}
/* Prevent Webkit and Windows Mobile platforms from changing default font sizes, while not breaking desktop design. */
.ExternalClass {width:100%;} /* Force Hotmail to display emails at full width */
.ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div {line-height: 100%;} /* Force Hotmail to display normal line spacing. More on that: http://www.emailonacid.com/forum/viewthread/43/ */
img {outline:none; text-decoration:none;border:none; -ms-interpolation-mode: bicubic;}
a img {border:none;}
.image_fix {display:block;}
p {margin: 0px 0px 1em !important;}
table td {border-collapse: collapse;}
table { border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt; }
/*a {color: #e95353;text-decoration: none;text-decoration:none!important;}*/
/*STYLES*/
table[class=full] { width: 100%; clear: both; }
/*################################################*/
/*IPAD STYLES*/
/*################################################*/
@media only screen and (max-width: 640px) {
a[href^="tel"], a[href^="sms"] {
text-decoration: none;
color: #ffffff; /* or whatever your want */
pointer-events: none;
cursor: default;
}
.mobile_link a[href^="tel"], .mobile_link a[href^="sms"] {
text-decoration: default;
color: #ffffff !important;
pointer-events: auto;
cursor: default;
}
table[class=devicewidth] {width: 440px!important;text-align:center!important;}
table[class=devicewidthinner] {width: 420px!important;text-align:center!important;}
table[class="sthide"]{display: none!important;}
img[class="bigimage"]{width: 420px!important;height:219px!important;}
img[class="col2img"]{width: 420px!important;height:258px!important;}
img[class="image-banner"]{width: 440px!important;height:106px!important;}
td[class="menu"]{text-align:center !important; padding: 0 0 10px 0 !important;}
td[class="logo"]{padding:10px 0 5px 0!important;margin: 0 auto !important;}
img[class="logo"]{padding:0!important;margin: 0 auto !important;}
}
/*##############################################*/
/*IPHONE STYLES*/
/*##############################################*/
@media only screen and (max-width: 480px) {
a[href^="tel"], a[href^="sms"] {
text-decoration: none;
color: #ffffff; /* or whatever your want */
pointer-events: none;
cursor: default;
}
.mobile_link a[href^="tel"], .mobile_link a[href^="sms"] {
text-decoration: default;
color: #ffffff !important;
pointer-events: auto;
cursor: default;
}
table[class=devicewidth] {width: 280px!important;text-align:center!important;}
table[class=devicewidthinner] {width: 260px!important;text-align:center!important;}
table[class="sthide"]{display: none!important;}
img[class="bigimage"]{width: 260px!important;height:136px!important;}
img[class="col2img"]{width: 260px!important;height:160px!important;}
img[class="image-banner"]{width: 280px!important;height:68px!important;}
}
</style>
</head>
<body>
<div class="block">
<table width="100%" cellpadding="0" cellspacing="0" border="0" st-sortable="header">
<tbody>
<tr>
<td height="20"></td>
</tr>
</tbody>
</table>
<!-- start of header -->
<table width="100%" bgcolor="#de4f4e" cellpadding="0" cellspacing="0" border="0" st-sortable="header">
<tbody>
<tr>
<td>
<table width="580" bgcolor="#FFF" cellpadding="0" cellspacing="0" border="0" align="center" class="devicewidth">
<tbody>
<tr>
<td>
<!-- logo -->
<table width="580" cellpadding="0" cellspacing="0" border="0" align="left" class="devicewidth">
<tbody>
<tr>
<td valign="middle" width="50%" style="padding: 20px 0 10px 20px;" class="logo">
<div class="imgpop">
<a href="http://www.keesonline.nl"><img src="http://keesonline.nl/images/logo.png" alt="/kees" border="0" height="60" style="display:block; border:none; outline:none; text-decoration:none;" class="logo"></a>
</div>
<td valign="bottom" style="text-align:right;padding-right:20px;" width="50%">
<p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;color:#efedee;font-size:13px;font-weight:700;line-height:18px;"></p>
</td>
</tr>
</tbody>
</table>
<!-- End of logo -->
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<!-- end of header -->
</div>
<div class="block">
<!-- image + text -->
<table width="100%" bgcolor="#de4f4e" cellpadding="0" cellspacing="0" border="0" st-sortable="bigimage">
<tbody>
<tr>
<td>
<table bgcolor="#ffffff" width="580" align="center" cellspacing="0" cellpadding="0" border="0" class="devicewidth" modulebg="edit">
<tbody>
<tr>
<td>
<table width="540" align="center" cellspacing="0" cellpadding="0" border="0" class="devicewidthinner">
<tbody>
<tr>
<!-- >
<td align="center">
<a target="_blank" href="#"><img width="540" border="0" height="282" alt="" style="display:block; border:none; outline:none; text-decoration:none;" src="img/bigimage.png" class="bigimage"></a>
</td>
</tr>
-->
<!-- content -->
<tr>
<td style="font-family:'Lora', serif;font-size:14px;color:#4E5860;text-align:left;line-height:20px;padding-top:30px;">
<?php $this->beginBody() ?>
<?= $content ?>
</td>
</tr>
<div class="block">
<!-- image + text -->
<table width="100%" bgcolor="#de4f4e" cellpadding="0" cellspacing="0" border="0" st-sortable="bigimage">
<tbody>
<tr>
<td>
<table bgcolor="#ffffff" width="580" align="center" cellspacing="0" cellpadding="0" border="0" class="devicewidth" modulebg="edit">
<tbody>
<tr>
<td>
<table width="580" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="4">
<p style="font-family: 'Lora', serif;color:#333333;font-size:14px;line-height:18px;padding:20px;">
Met vriendelijke groet,<br /><br /><br />
<strong style="font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;"><span style="color:#de4f4e;">/</span>kees</p></strong>
</td>
</tr>
<tr>
<td colspan="2" rowspan="2" style="padding:20px;text-align: center;">
<a style="color:#FFF;" href="https://www.facebook.com/releaz"><img width="50" src="http://www.releaz.nl/mail/mail-fb.png"/></a>
<a style="color:#FFF;" href="https://twitter.com/releaz"><img width="50" src="http://www.releaz.nl/mail/mail-tw.png"/></a>
<a style="color:#FFF;" href="https://www.linkedin.com/company/releaz"><img width="50" src="http://www.releaz.nl/mail/mail-li.png"/></a>
</td>
<td colspan="2" style="padding-left:20px;padding-top:15px;background:#3f3f3e;" width="30%">
<p style="font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;color:#FFF;font-size:20px;line-height:28px;">
085 876 99 57 <br/>
<a style="color:#FFF;text-decoration:none;" href="mailto:hallo@keesonline.nl">hallo@keesonline.nl</a><br />
<a style="color:#FFF;text-decoration:none;" href="http://www.keesonline.nl">www.keesonline.nl</a></p>
</td>
</tr>
<tr>
<td style="padding-left:20px;padding-top:15px;background:#3f3f3e;" width="30%">
<p style="font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;color:#FFF;font-size:11px;line-height:18px;">
<strong><span style="color:#de4f4e;">/</span>kees</strong> Groningen<br />
Zeewinde 3-11A<br />
9738 AM Groningen</p>
</td>
<td style="padding-left:20px;padding-top:15px;background:#3f3f3e;" width="30%">
<p style="font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;color:#FFF;font-size:11px;line-height:18px;">
<strong><span style="color:#de4f4e;">/</span>kees</strong> Amsterdam<br />
Bankastraat 24F<br />
1094 EE, Amsterdam</p>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div></body></html>
<?php $this->endPage() ?>
| releaznl/releaz-project-manager | common/mail/layouts/html.php | PHP | bsd-3-clause | 18,424 |
# proxy module
from __future__ import absolute_import
from apptools.help.help_plugin.help_doc import *
| enthought/etsproxy | enthought/help/help_plugin/help_doc.py | Python | bsd-3-clause | 103 |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using Castle.DynamicProxy;
using Rhino.Mocks.Interfaces;
namespace Rhino.Mocks.Impl
{
/// <summary>
/// Throw an object already verified when accessed
/// </summary>
public class VerifiedMockState : IMockState
{
IMockState previous;
/// <summary>
/// Create a new instance of VerifiedMockState
/// </summary>
/// <param name="previous">The previous mock state, used to get the initial record state</param>
public VerifiedMockState(IMockState previous)
{
this.previous = previous;
}
/// <summary>
/// Gets the matching verify state for this state
/// </summary>
public IMockState VerifyState
{
get { throw InvalidInVerifiedState(); }
}
/// <summary>
/// Add a method call for this state' mock.
/// </summary>
/// <param name="invocation">The invocation for this method</param>
/// <param name="method">The method that was called</param>
/// <param name="args">The arguments this method was called with</param>
public object MethodCall(IInvocation invocation, MethodInfo method, params object[] args)
{
if(method.Name == "Finalize") // skip finalizers
return null;
throw InvalidInVerifiedState();
}
/// <summary>
/// Verify that this mock expectations have passed.
/// </summary>
public void Verify()
{
throw InvalidInVerifiedState();
}
/// <summary>
/// Verify that we can move to replay state and move
/// to the reply state.
/// </summary>
public IMockState Replay()
{
throw InvalidInVerifiedState();
}
/// <summary>
/// Gets a mock state that match the original mock state of the object.
/// </summary>
public virtual IMockState BackToRecord()
{
return previous.BackToRecord();
}
/// <summary>
/// Get the options for the last method call
/// </summary>
public IMethodOptions<T> GetLastMethodOptions<T>()
{
throw InvalidInVerifiedState();
}
/// <summary>
/// Get the options for the last method call
/// </summary>
public IMethodOptions<object> LastMethodOptions
{
get { throw InvalidInVerifiedState(); }
}
/// <summary>
/// Set the exception to throw when Verify is called.
/// This is used to report exception that may have happened but where caught in the code.
/// This way, they are reported anyway when Verify() is called.
/// </summary>
public void SetExceptionToThrowOnVerify(Exception ex)
{
//not implementing this, we are already verified.
}
/// <summary>
/// not relevant
/// </summary>
public void NotifyCallOnPropertyBehavior()
{
// doesn't deal with recording anyway
}
private Exception InvalidInVerifiedState()
{
return new InvalidOperationException("This action is invalid when the mock object is in verified state.");
}
}
}
| alaendle/rhino-mocks | Rhino.Mocks/Impl/VerifiedMockState.cs | C# | bsd-3-clause | 4,580 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Test
* @subpackage PHPUnit
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** @see \PHPUnit_Framework_Constraint */
require_once 'PHPUnit/Framework/Constraint.php';
/**
* Redirection constraints
*
* @uses \PHPUnit_Framework_Constraint
* @category Zend
* @package Zend_Test
* @subpackage PHPUnit
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Test_PHPUnit_Constraint_Redirect extends \PHPUnit_Framework_Constraint
{
/**#@+
* Assertion type constants
*/
const ASSERT_REDIRECT = 'assertRedirect';
const ASSERT_REDIRECT_TO = 'assertRedirectTo';
const ASSERT_REDIRECT_REGEX = 'assertRedirectRegex';
/**#@-*/
/**
* Current assertion type
* @var string
*/
protected $_assertType = null;
/**
* Available assertion types
* @var array
*/
protected $_assertTypes = array(
self::ASSERT_REDIRECT,
self::ASSERT_REDIRECT_TO,
self::ASSERT_REDIRECT_REGEX,
);
/**
* Pattern to match against
* @var string
*/
protected $_match = null;
/**
* Whether or not assertion is negated
* @var bool
*/
protected $_negate = false;
/**
* Constructor; setup constraint state
*
* @return void
*/
public function __construct()
{
}
/**
* Indicate negative match
*
* @param bool $flag
* @return void
*/
public function setNegate($flag = true)
{
$this->_negate = $flag;
}
/**
* Evaluate an object to see if it fits the constraints
*
* @param string $other String to examine
* @param null|string Assertion type
* @return bool
*/
public function evaluate($other, $assertType = null, $returnResult = FALSE)
{
if (!$other instanceof \Zend_Controller_Response_Abstract) {
require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
throw new \Zend_Test_PHPUnit_Constraint_Exception('Redirect constraint assertions require a response object');
}
if (strstr($assertType, 'Not')) {
$this->setNegate(true);
$assertType = str_replace('Not', '', $assertType);
}
if (!in_array($assertType, $this->_assertTypes)) {
require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
throw new \Zend_Test_PHPUnit_Constraint_Exception(sprintf('Invalid assertion type "%s" provided to %s constraint', $assertType, __CLASS__));
}
$this->_assertType = $assertType;
$response = $other;
$argv = func_get_args();
$argc = func_num_args();
switch ($assertType) {
case self::ASSERT_REDIRECT_TO:
if (3 > $argc) {
require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
throw new \Zend_Test_PHPUnit_Constraint_Exception('No redirect URL provided against which to match');
}
$this->_match = $match = $argv[2];
return ($this->_negate)
? $this->_notMatch($response, $match)
: $this->_match($response, $match);
case self::ASSERT_REDIRECT_REGEX:
if (3 > $argc) {
require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
throw new \Zend_Test_PHPUnit_Constraint_Exception('No pattern provided against which to match redirect');
}
$this->_match = $match = $argv[2];
return ($this->_negate)
? $this->_notRegex($response, $match)
: $this->_regex($response, $match);
case self::ASSERT_REDIRECT:
default:
return ($this->_negate) ? !$response->isRedirect() : $response->isRedirect();
}
}
/**
* Report Failure
*
* @see \PHPUnit_Framework_Constraint for implementation details
* @param mixed $other
* @param string $description Additional message to display
* @param bool $not
* @return void
* @throws \PHPUnit_Framework_ExpectationFailedException
*/
public function fail($other, $description, \PHPUnit_Framework_ComparisonFailure $comparisonFailure = NULL)
{
require_once 'Zend/Test/PHPUnit/Constraint/Exception.php';
switch ($this->_assertType) {
case self::ASSERT_REDIRECT_TO:
$failure = 'Failed asserting response redirects to "%s"';
if ($this->_negate) {
$failure = 'Failed asserting response DOES NOT redirect to "%s"';
}
$failure = sprintf($failure, $this->_match);
break;
case self::ASSERT_REDIRECT_REGEX:
$failure = 'Failed asserting response redirects to URL MATCHING "%s"';
if ($this->_negate) {
$failure = 'Failed asserting response DOES NOT redirect to URL MATCHING "%s"';
}
$failure = sprintf($failure, $this->_match);
break;
case self::ASSERT_REDIRECT:
default:
$failure = 'Failed asserting response is a redirect';
if ($this->_negate) {
$failure = 'Failed asserting response is NOT a redirect';
}
break;
}
if (!empty($description)) {
$failure = $description . "\n" . $failure;
}
throw new \Zend_Test_PHPUnit_Constraint_Exception($failure);
}
/**
* Complete implementation
*
* @return string
*/
public function toString()
{
return '';
}
/**
* Check to see if content is matched in selected nodes
*
* @param \Zend_Controller_Response_HttpTestCase $response
* @param string $match Content to match
* @return bool
*/
protected function _match($response, $match)
{
if (!$response->isRedirect()) {
return false;
}
$headers = $response->sendHeaders();
$redirect = $headers['location'];
$redirect = str_replace('Location: ', '', $redirect);
return ($redirect == $match);
}
/**
* Check to see if content is NOT matched in selected nodes
*
* @param \Zend_Controller_Response_HttpTestCase $response
* @param string $match
* @return bool
*/
protected function _notMatch($response, $match)
{
if (!$response->isRedirect()) {
return true;
}
$headers = $response->sendHeaders();
$redirect = $headers['location'];
$redirect = str_replace('Location: ', '', $redirect);
return ($redirect != $match);
}
/**
* Check to see if content is matched by regex in selected nodes
*
* @param \Zend_Controller_Response_HttpTestCase $response
* @param string $pattern
* @return bool
*/
protected function _regex($response, $pattern)
{
if (!$response->isRedirect()) {
return false;
}
$headers = $response->sendHeaders();
$redirect = $headers['location'];
$redirect = str_replace('Location: ', '', $redirect);
return preg_match($pattern, $redirect);
}
/**
* Check to see if content is NOT matched by regex in selected nodes
*
* @param \Zend_Controller_Response_HttpTestCase $response
* @param string $pattern
* @return bool
*/
protected function _notRegex($response, $pattern)
{
if (!$response->isRedirect()) {
return true;
}
$headers = $response->sendHeaders();
$redirect = $headers['location'];
$redirect = str_replace('Location: ', '', $redirect);
return !preg_match($pattern, $redirect);
}
}
| GemsTracker/gemstracker-library | tests/library/Zend/Test/PHPUnit/Constraint/Redirect.php | PHP | bsd-3-clause | 8,713 |
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Mayo Clinic
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# Neither the name of the <ORGANIZATION> nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
from rf2db.schema import rf2
from rf2db.parameterparser.ParmParser import ParameterDefinitionList, enumparam, intparam, computedparam, \
strparam, booleanparam
from rf2db.utils import urlutil
# Iteration Parameters
#
# order - sort order of returned values. The specific sort keys depend on the type of resource
# accessed. Possible values are I{asc} for ascending and I{desc} for descending. Default: "asc"
# maxtoreturn - maximum values to return in a list. 0 we're just doing a count. Default: 100
# page - starting page number. Return begins at entry C{page * maxtoreturn}. Default: 0
# locked - if True, only return locked records. (Must be accompanied by a changeset id)
# sort - list of columns to sort by "None" means don't sort at all
# TODO: the default on maxtoreturn needs to be pulled from the rf2 parameter set
iter_parms = ParameterDefinitionList()
iter_parms.order = enumparam(['asc', 'desc'], default='asc')
iter_parms.page = intparam(default=0)
iter_parms.maxtoreturn = intparam(default=20)
iter_parms.start = computedparam(lambda p: p.page * p.maxtoreturn)
iter_parms.sort = strparam(splittable=True)
iter_parms.locked = booleanparam(default=False)
class RF2Iterator(rf2.Iterator, object):
def setup(self, parmlist, autoSkip=False):
""" Create a directory listing. This can be used in a number of ways, including:
@param autoSkip: if True, append will skip the leading entries. If false, the client does the skipping
@type autoSkip: C{bool}
"""
self._parmlist = parmlist
self._skip = parmlist.page * parmlist.maxtoreturn if autoSkip else 0
# This is deliberately left off because it forces callers to invoke finish
# self.complete = complete
self.numEntries = 0
self.at_end = False
return self
def add_entry(self, entry, **kw):
""" Add the entry to the directory. If the skip count is positive, the entry will be skipped. The general
pattern that can be used in this call is:
for e in list:
if not rval.append(e):
rval.finish(True)
return rval
rval.finish(False)
@param entry: The entry to append
@type entry: C{DirectoryEntry}
@return: True if appending should continue, False if no more should be added
"""
if self._skip > 0:
self._skip -= 1
return True
if self._parmlist.maxtoreturn < 0 or self.numEntries < self._parmlist.maxtoreturn:
self.entry.append(entry)
self.numEntries += 1
self.at_end = self._parmlist.maxtoreturn > 0 and self.numEntries >= self._parmlist.maxtoreturn
return not self.at_end
def finish(self, moreToCome=False, total=0):
""" Finalize an appending process, setting COMPLETE, next and prev
Returns the resource for convenience
"""
if not self._parmlist.maxtoreturn:
self.numEntries = total
self.complete = rf2.CompleteDirectory.COMPLETE
else:
if self._parmlist.maxtoreturn > 0 and self.numEntries >= self._parmlist.maxtoreturn and moreToCome:
self.next = urlutil.forxml(urlutil.append_params(urlutil.strip_control_params(urlutil.relative_uri()),
dict(self._parmlist.nondefaulteditems(),
**{'page': str(self._parmlist.page + 1),
'maxtoreturn': str(self._parmlist.maxtoreturn)})))
if self._parmlist.maxtoreturn > 0 and self._parmlist.page > 0:
self.prev = urlutil.forxml(urlutil.append_params(urlutil.strip_control_params(urlutil.relative_uri()),
dict(self._parmlist.nondefaulteditems(),
**{'page': str(self._parmlist.page - 1),
'maxtoreturn': str(self._parmlist.maxtoreturn)})))
self.complete = rf2.CompleteDirectory.COMPLETE if not (
self.next or self.prev) else rf2.CompleteDirectory.PARTIAL
return self
def rf2iterlink(pyxbElement, pyxbType):
def impl_link(impl_class):
def constructor(parmlist, autoSkip=False):
return pyxbElement().setup(parmlist, autoSkip=autoSkip)
pyxbType._SetSupersedingClass(impl_class)
return constructor
return impl_link
@rf2iterlink(rf2.ConceptList, rf2.ConceptList_)
class RF2ConceptList(rf2.ConceptList_, RF2Iterator):
pass
@rf2iterlink(rf2.DescriptionList, rf2.DescriptionList_)
class RF2DescriptionList(rf2.DescriptionList_, RF2Iterator):
pass
@rf2iterlink(rf2.RelationshipList, rf2.RelationshipList_)
class RF2RelationshipList(rf2.RelationshipList_, RF2Iterator):
pass
@rf2iterlink(rf2.ConceptList, rf2.ConceptList_)
class RF2ConceptList(rf2.ConceptList_, RF2Iterator):
pass
@rf2iterlink(rf2.IdentifierList, rf2.IdentifierList_)
class RF2IdentifierList(rf2.IdentifierList_, RF2Iterator):
pass
@rf2iterlink(rf2.TransitiveClosureHistoryList, rf2.TransitiveClosureHistoryList_)
class RF2TransitiveClosureHistoryList(rf2.TransitiveClosureHistoryList_, RF2Iterator):
pass
@rf2iterlink(rf2.DescriptorReferenceSet, rf2.DescriptorReferenceSet_)
class RF2DescriptorReferenceSet(rf2.DescriptorReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.OrderedReferenceSet, rf2.OrderedReferenceSet_)
class RF2OrderedReferenceSet(rf2.OrderedReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.AttributeValueReferenceSet, rf2.AttributeValueReferenceSet_)
class RF2AttributeValueReferenceSet(rf2.AttributeValueReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.SimpleReferenceSet, rf2.SimpleReferenceSet_)
class RF2SimpleReferenceSet(rf2.SimpleReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.SimpleMapReferenceSet, rf2.SimpleMapReferenceSet_)
class RF2SimpleMapReferenceSet(rf2.SimpleMapReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.ComplexMapReferenceSet, rf2.ComplexMapReferenceSet_)
class RF2ComplexMapReferenceSet(rf2.ComplexMapReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.LanguageReferenceSet, rf2.LanguageReferenceSet_)
class RF2LanguageReferenceSet(rf2.LanguageReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.QuerySpecificationReferenceSet, rf2.QuerySpecificationReferenceSet_)
class RF2QuerySpecificationReferenceSet(rf2.QuerySpecificationReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.AnnotationReferenceSet, rf2.AnnotationReferenceSet_)
class RF2AnnotationReferenceSet(rf2.AnnotationReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.AssociationReferenceSet, rf2.AssociationReferenceSet_)
class RF2AssociationReferenceSet(rf2.AssociationReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.ModuleDepencencyReferenceSet, rf2.ModuleDepencencyReferenceSet_)
class RF2ModuleDepencencyReferenceSet(rf2.ModuleDepencencyReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.DescriptionFormatReferenceSet, rf2.DescriptionFormatReferenceSet_)
class RF2DescriptionFormatReferenceSet(rf2.DescriptionFormatReferenceSet_, RF2Iterator):
pass
@rf2iterlink(rf2.ChangeSetReferenceSet, rf2.ChangeSetReferenceSet_)
class RF2ChangeSetReferenceSet(rf2.ChangeSetReferenceSet_, RF2Iterator):
pass | cts2/rf2db | rf2db/parsers/RF2Iterator.py | Python | bsd-3-clause | 9,117 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/html_viewer/web_test_delegate_impl.h"
#include <iostream>
#include "base/time/time.h"
#include "cc/layers/texture_layer.h"
#include "components/test_runner/web_task.h"
#include "components/test_runner/web_test_interfaces.h"
#include "components/test_runner/web_test_proxy.h"
#include "third_party/WebKit/public/platform/Platform.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebTaskRunner.h"
#include "third_party/WebKit/public/platform/WebThread.h"
#include "third_party/WebKit/public/platform/WebTraceLocation.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "url/gurl.h"
namespace html_viewer {
namespace {
class InvokeTaskHelper : public blink::WebTaskRunner::Task {
public:
InvokeTaskHelper(scoped_ptr<test_runner::WebTask> task)
: task_(task.Pass()) {}
// WebThread::Task implementation:
void run() override { task_->run(); }
private:
scoped_ptr<test_runner::WebTask> task_;
};
} // namespace
WebTestDelegateImpl::WebTestDelegateImpl()
: test_interfaces_(nullptr), proxy_(nullptr) {
}
WebTestDelegateImpl::~WebTestDelegateImpl() {
}
void WebTestDelegateImpl::ClearEditCommand() {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetEditCommand(const std::string& name,
const std::string& value) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetGamepadProvider(
test_runner::GamepadController* controller) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetDeviceLightData(const double data) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetDeviceMotionData(
const blink::WebDeviceMotionData& data) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetDeviceOrientationData(
const blink::WebDeviceOrientationData& data) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetScreenOrientation(
const blink::WebScreenOrientationType& orientation) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::ResetScreenOrientation() {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::DidChangeBatteryStatus(
const blink::WebBatteryStatus& status) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::PrintMessage(const std::string& message) {
std::cout << message;
}
void WebTestDelegateImpl::PostTask(test_runner::WebTask* task) {
blink::Platform::current()->currentThread()->taskRunner()->postTask(
blink::WebTraceLocation(__FUNCTION__, __FILE__),
new InvokeTaskHelper(make_scoped_ptr(task)));
}
void WebTestDelegateImpl::PostDelayedTask(test_runner::WebTask* task,
long long ms) {
blink::Platform::current()->currentThread()->taskRunner()->postDelayedTask(
blink::WebTraceLocation(__FUNCTION__, __FILE__),
new InvokeTaskHelper(make_scoped_ptr(task)), ms);
}
blink::WebString WebTestDelegateImpl::RegisterIsolatedFileSystem(
const blink::WebVector<blink::WebString>& absolute_filenames) {
NOTIMPLEMENTED();
return blink::WebString();
}
long long WebTestDelegateImpl::GetCurrentTimeInMillisecond() {
return base::TimeDelta(base::Time::Now() - base::Time::UnixEpoch())
.ToInternalValue() /
base::Time::kMicrosecondsPerMillisecond;
}
blink::WebString WebTestDelegateImpl::GetAbsoluteWebStringFromUTF8Path(
const std::string& path) {
NOTIMPLEMENTED();
return blink::WebString::fromUTF8(path);
}
blink::WebURL WebTestDelegateImpl::LocalFileToDataURL(
const blink::WebURL& file_url) {
NOTIMPLEMENTED();
return blink::WebURL();
}
blink::WebURL WebTestDelegateImpl::RewriteLayoutTestsURL(
const std::string& utf8_url) {
return blink::WebURL(GURL(utf8_url));
}
test_runner::TestPreferences* WebTestDelegateImpl::Preferences() {
return &prefs_;
}
void WebTestDelegateImpl::ApplyPreferences() {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::UseUnfortunateSynchronousResizeMode(bool enable) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::EnableAutoResizeMode(const blink::WebSize& min_size,
const blink::WebSize& max_size) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::DisableAutoResizeMode(
const blink::WebSize& new_size) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::ClearDevToolsLocalStorage() {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::ShowDevTools(const std::string& settings,
const std::string& frontend_url) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::CloseDevTools() {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::EvaluateInWebInspector(long call_id,
const std::string& script) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::ClearAllDatabases() {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetDatabaseQuota(int quota) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SimulateWebNotificationClick(
const std::string& title, int action_index) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetDeviceScaleFactor(float factor) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetDeviceColorProfile(const std::string& name) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetBluetoothMockDataSet(const std::string& data_set) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetBluetoothManualChooser() {
NOTIMPLEMENTED();
}
std::vector<std::string>
WebTestDelegateImpl::GetBluetoothManualChooserEvents() {
NOTIMPLEMENTED();
return std::vector<std::string>();
}
void WebTestDelegateImpl::SendBluetoothManualChooserEvent(
const std::string& event,
const std::string& argument) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetGeofencingMockProvider(bool service_available) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::ClearGeofencingMockProvider() {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetGeofencingMockPosition(double latitude,
double longitude) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetFocus(test_runner::WebTestProxyBase* proxy,
bool focus) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetAcceptAllCookies(bool accept) {
NOTIMPLEMENTED();
}
std::string WebTestDelegateImpl::PathToLocalResource(
const std::string& resource) {
NOTIMPLEMENTED();
return std::string();
}
void WebTestDelegateImpl::SetLocale(const std::string& locale) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::TestFinished() {
std::cout << "Content-Type: text/plain\n";
std::cout << (proxy_ ? proxy_->CaptureTree(false, false) : dump_tree_);
std::cout << "#EOF\n";
test_interfaces_->SetTestIsRunning(false);
if (!completion_callback_.is_null())
completion_callback_.Run();
}
void WebTestDelegateImpl::CloseRemainingWindows() {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::DeleteAllCookies() {
NOTIMPLEMENTED();
}
int WebTestDelegateImpl::NavigationEntryCount() {
NOTIMPLEMENTED();
return 0;
}
void WebTestDelegateImpl::GoToOffset(int offset) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::Reload() {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::LoadURLForFrame(const blink::WebURL& url,
const std::string& frame_name) {
NOTIMPLEMENTED();
}
bool WebTestDelegateImpl::AllowExternalPages() {
NOTIMPLEMENTED();
return false;
}
std::string WebTestDelegateImpl::DumpHistoryForWindow(
test_runner::WebTestProxyBase* proxy) {
NOTIMPLEMENTED();
return std::string();
}
void WebTestDelegateImpl::FetchManifest(
blink::WebView* view,
const GURL& url,
const base::Callback<void(const blink::WebURLResponse& response,
const std::string& data)>& callback) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::SetPermission(const std::string& permission_name,
const std::string& permission_value,
const GURL& origin,
const GURL& embedding_origin) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::ResetPermissions() {
NOTIMPLEMENTED();
}
cc::SharedBitmapManager* WebTestDelegateImpl::GetSharedBitmapManager() {
NOTIMPLEMENTED();
return nullptr;
}
void WebTestDelegateImpl::DispatchBeforeInstallPromptEvent(
int request_id,
const std::vector<std::string>& event_platforms,
const base::Callback<void(bool)>& callback) {
NOTIMPLEMENTED();
}
void WebTestDelegateImpl::ResolveBeforeInstallPromptPromise(int request_id,
const std::string& platform) {
NOTIMPLEMENTED();
}
blink::WebPlugin* WebTestDelegateImpl::CreatePluginPlaceholder(
blink::WebLocalFrame* frame,
const blink::WebPluginParams& params) {
NOTIMPLEMENTED();
return nullptr;
}
void WebTestDelegateImpl::OnWebTestProxyBaseDestroy(
test_runner::WebTestProxyBase* base) {
DCHECK_EQ(proxy_, base);
dump_tree_ = proxy_->CaptureTree(false, false);
proxy_ = nullptr;
}
} // namespace html_viewer
| Chilledheart/chromium | components/html_viewer/web_test_delegate_impl.cc | C++ | bsd-3-clause | 9,116 |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Class for running uiautomator tests on a single device."""
from pylib.instrumentation import test_options as instr_test_options
from pylib.instrumentation import test_runner as instr_test_runner
class TestRunner(instr_test_runner.TestRunner):
"""Responsible for running a series of tests connected to a single device."""
def __init__(self, test_options, device, shard_index, test_pkg,
ports_to_forward):
"""Create a new TestRunner.
Args:
test_options: A UIAutomatorOptions object.
device: Attached android device.
shard_index: Shard index.
test_pkg: A TestPackage object.
ports_to_forward: A list of port numbers for which to set up forwarders.
Can be optionally requested by a test case.
"""
# Create an InstrumentationOptions object to pass to the super class
instrumentation_options = instr_test_options.InstrumentationOptions(
test_options.tool,
test_options.cleanup_test_files,
test_options.push_deps,
test_options.annotations,
test_options.exclude_annotations,
test_options.test_filter,
test_options.test_data,
test_options.save_perf_json,
test_options.screenshot_failures,
wait_for_debugger=False,
coverage_dir=None,
test_apk=None,
test_apk_path=None,
test_apk_jar_path=None)
super(TestRunner, self).__init__(instrumentation_options, device,
shard_index, test_pkg, ports_to_forward)
self.package_name = test_options.package_name
#override
def InstallTestPackage(self):
self.test_pkg.Install(self.adb)
#override
def PushDataDeps(self):
pass
#override
def _RunTest(self, test, timeout):
self.adb.ClearApplicationState(self.package_name)
if 'Feature:FirstRunExperience' in self.test_pkg.GetTestAnnotations(test):
self.flags.RemoveFlags(['--disable-fre'])
else:
self.flags.AddFlags(['--disable-fre'])
return self.adb.RunUIAutomatorTest(
test, self.test_pkg.GetPackageName(), timeout)
| mogoweb/chromium-crosswalk | build/android/pylib/uiautomator/test_runner.py | Python | bsd-3-clause | 2,258 |
import numpy as np
import h5py
from checkpoint import Writer, create_reader
class Baz:
def __init__(self):
self.z = {1:'one', 'two': 2, 'tree': [1,2,'three']}
def write(self, group):
writer = Writer(group, self)
writer.yaml('z')
@staticmethod
def read(group):
foo, reader = create_reader(Baz, group)
reader.yaml('z')
return foo
class Bar:
def __init__(self):
self.x = np.linspace(0,5,11)
self.y = np.linspace(0,1,11)
self.baz = Baz()
def write(self, group):
writer = Writer(group, self)
writer.arrays('x', 'y')
writer.recurse('baz')
@staticmethod
def read(group):
foo, reader = create_reader(Bar, group)
reader.arrays('x', 'y')
reader.recurse(Baz, 'baz')
return foo
class Foo:
def __init__(self):
self.a = 1.1
self.l = [ [1,5,2], [6,0], [], [1,3,4], [7] ]
self.d = {(1,2): [10,20], (3,4): [30,40]}
self.bar = Bar()
def write(self, group):
writer = Writer(group, self)
writer.scalar('a')
writer.crs('l')
writer.dict('d')
writer.recurse('bar')
@staticmethod
def read(group):
foo, reader = create_reader(Foo, group)
reader.scalar('a')
reader.crs('l')
reader.dict('d')
reader.recurse(Bar, 'bar')
return foo
def main():
foo = Foo()
with h5py.File('foo.h5', 'w') as f:
foo.write(f)
with h5py.File('foo.h5', 'r') as f:
foo_bis = Foo.read(f)
assert foo_bis.a == foo.a
assert foo_bis.l == foo.l
assert foo_bis.d == foo.d
np.testing.assert_array_equal(foo_bis.bar.x, foo.bar.x)
np.testing.assert_array_equal(foo_bis.bar.y, foo.bar.y)
assert foo_bis.bar.baz.z == foo.bar.baz.z
if __name__ == '__main__':
main()
| thni/clash | checkpoint/example/main.py | Python | bsd-3-clause | 1,870 |
package net.apnic.rdapd.ip.controller;
import java.util.Optional;
import net.apnic.rdapd.history.ObjectClass;
import net.apnic.rdapd.history.ObjectHistory;
import net.apnic.rdapd.history.ObjectKey;
import net.apnic.rdapd.intervaltree.IntervalTree;
import net.apnic.rdapd.ip.IpService;
import static net.apnic.rdapd.rdap.controller.RDAPControllerTesting.testObjectHistory;
import static net.apnic.rdapd.rdap.controller.RDAPControllerTesting.isRDAP;
import static net.apnic.rdapd.rdap.controller.RDAPControllerTesting.isRDAPHeader;
import net.apnic.rdapd.rdap.IpNetwork;
import net.apnic.rdapd.types.Parsing;
import net.apnic.rdapd.types.Tuple;
import static org.hamcrest.Matchers.is;
import org.junit.runner.RunWith;
import org.junit.Test;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.head;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(IpRouteController.class)
public class IpRouteControllerTest
{
@TestConfiguration
@ComponentScan(basePackages="net.apnic.rdapd.rdap.config")
static class TestRDAPControllerConfiguration {}
@MockBean
IpService ipService;
@Autowired
private MockMvc mvc;
@Test
public void indexLookupHasResults()
throws Exception
{
given(ipService.find(any())).willReturn(
Optional.of(new IpNetwork(
new ObjectKey(ObjectClass.IP_NETWORK, "10.0.0.0 - 10.255.255.255"),
Parsing.parseInterval("10.0.0.0/8"))));
mvc.perform(get("/ip/10.0.0.0"))
.andExpect(status().isOk())
.andExpect(isRDAP());
mvc.perform(head("/ip/10.0.0.0"))
.andExpect(status().isOk())
.andExpect(isRDAPHeader());
}
@Test
public void runtimeExceptionIs500()
throws Exception
{
given(ipService.find(any())).willThrow(
new RuntimeException("Test exception"));
mvc.perform(get("/ip/10.0.0.0"))
.andExpect(status().isInternalServerError())
.andExpect(isRDAP())
.andExpect(jsonPath("$.errorCode", is(500)));
}
@Test
public void noSearchResultsIsNotFoundRDAPResponse()
throws Exception
{
given(ipService.find(any())).willReturn(Optional.empty());
mvc.perform(get("/ip/10.0.0.0"))
.andExpect(status().isNotFound())
.andExpect(isRDAP());
}
@Test
public void malformedRequest()
throws Exception
{
given(ipService.find(any())).willReturn(Optional.empty());
mvc.perform(get("/ip/bad-ip"))
.andExpect(status().isBadRequest())
.andExpect(isRDAP());
mvc.perform(get("/ip/10.1.1.2/16"))
.andExpect(status().isBadRequest())
.andExpect(isRDAP());
mvc.perform(get("/ip/2001:abcd::/16"))
.andExpect(status().isBadRequest())
.andExpect(isRDAP());
}
}
| APNIC-net/whowas-service | src/test/java/net/apnic/rdapd/ip/controller/IpRouteControllerTest.java | Java | bsd-3-clause | 3,700 |
/* Sirikata Transfer -- Content Distribution Network
* CachedServiceLookup.hpp
*
* Copyright (c) 2009, Patrick Reiter Horn
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Created on: Feb 8, 2009 */
#ifndef SIRIKATA_CachedServiceLookup_HPP__
#define SIRIKATA_CachedServiceLookup_HPP__
#include <boost/thread.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread/mutex.hpp>
#include "ServiceLookup.hpp"
namespace Sirikata {
namespace Transfer {
/** A ServiceLookup that keeps a local cache. This cache might not be
* written to disk--it makes more sense to be in the options system.
*
* Currently, you can use addToCache to fill the cache.
*/
class CachedServiceLookup : public ServiceLookup {
typedef std::map<URIContext, std::pair<int, ListOfServicesPtr> > ServiceMap;
ServiceMap mLookupCache;
boost::shared_mutex mMut;
class CachedServiceIterator : public ServiceIterator {
unsigned int mCurrentService;
unsigned int mIteration;
ListOfServicesPtr mServicesList;
CachedServiceLookup *mCache;
URIContext origContext;
public:
virtual bool tryNext(ErrorType reason, URI &uri, ServiceParams &outParams) {
unsigned int length = mServicesList->size();
if (++mIteration > length) {
delete this;
return false;
}
mCurrentService %= length;
uri.getContext() = (*mServicesList)[mCurrentService].first;
outParams = (*mServicesList)[mCurrentService].second;
mCurrentService++;
return true;
}
CachedServiceIterator(CachedServiceLookup *parent,
unsigned int num,
const ListOfServicesPtr &services,
const URIContext &origService)
: mCurrentService(num), mIteration(0), mServicesList(services), mCache(parent), origContext(origService) {
}
virtual ~CachedServiceIterator() {
}
/** Notification that the download was successful.
* This may help ServiceLookup to pick a better service next time.
*/
virtual void finished(ErrorType reason=SUCCESS) {
if (reason == SUCCESS) {
boost::shared_lock<boost::shared_mutex> lookuplock(mCache->mMut);
ServiceMap::iterator iter = mCache->mLookupCache.find(origContext);
if (iter != mCache->mLookupCache.end()) {
(*iter).second.first = mCurrentService-1;
}
}
delete this;
}
};
public:
virtual bool addToCache(const URIContext &origService, const ListOfServicesPtr &toCache,const Callback &cb=Callback()) {
{
boost::unique_lock<boost::shared_mutex> insertlock(mMut);
mLookupCache.insert(ServiceMap::value_type(origService,
std::pair<int, ListOfServicesPtr>(0, toCache)));
}
if (!ServiceLookup::addToCache(origService, toCache, cb)) {
if (cb) {
cb(new CachedServiceIterator(this, 0, toCache, origService));
}
}
return true;
}
virtual void lookupService(const URIContext &context, const Callback &cb) {
ListOfServicesPtr found;
int num = 0;
{
boost::shared_lock<boost::shared_mutex> lookuplock(mMut);
ServiceMap::const_iterator iter = mLookupCache.find(context);
if (iter != mLookupCache.end()) {
found = (*iter).second.second;
num = (*iter).second.first;
}
}
if (found) {
if (!ServiceLookup::addToCache(context, found, cb)) {
cb(new CachedServiceIterator(this, num, found, context));
}
} else {
ServiceLookup::lookupService(context, cb);
}
}
};
}
}
#endif /* SIRIKATA_CachedServiceLookup_HPP__ */
| robertkhamilton/sirikata | libcore/src/transfer/CachedServiceLookup.hpp | C++ | bsd-3-clause | 4,840 |
//---------------------------------------------------------------------------//
//!
//! \file tstElectroatomCore.cpp
//! \author Luke Kersting
//! \brief ElectroatomCore unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
#include <algorithm>
// Trilinos Includes
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_VerboseObject.hpp>
#include <Teuchos_RCP.hpp>
// FRENSIE Includes
#include "MonteCarlo_ElectroatomCore.hpp"
#include "MonteCarlo_BremsstrahlungElectroatomicReaction.hpp"
#include "MonteCarlo_AtomicExcitationElectroatomicReaction.hpp"
#include "MonteCarlo_VoidAbsorptionElectroatomicReaction.hpp"
#include "MonteCarlo_VoidAtomicRelaxationModel.hpp"
#include "MonteCarlo_ElectronState.hpp"
#include "Data_ACEFileHandler.hpp"
#include "Data_XSSEPRDataExtractor.hpp"
#include "Utility_TabularDistribution.hpp"
#include "Utility_HistogramDistribution.hpp"
#include "Utility_InterpolationPolicy.hpp"
#include "Utility_PhysicalConstants.hpp"
//---------------------------------------------------------------------------//
// Testing Variables
//---------------------------------------------------------------------------//
Teuchos::RCP<MonteCarlo::ElectroatomCore> ace_electroatom_core;
//---------------------------------------------------------------------------//
// Testing Functions.
//---------------------------------------------------------------------------//
bool notEqualZero( const double value )
{
return value != 0.0;
}
//---------------------------------------------------------------------------//
// Check that the total reaction can be returned
TEUCHOS_UNIT_TEST( ElectroatomCore, getTotalReaction )
{
const MonteCarlo::ElectroatomicReaction& total_reaction =
ace_electroatom_core->getTotalReaction();
double cross_section =
total_reaction.getCrossSection( 2.000000000000E-03 );
TEST_FLOATING_EQUALITY( cross_section,
9.258661418255E+03 + 1.965170000000E+08,
1e-12 );
cross_section =
total_reaction.getCrossSection( 4.000000000000E-04 );
TEST_FLOATING_EQUALITY( cross_section,
8.914234996439E+03 + 6.226820000000E+08,
1e-12 );
cross_section =
total_reaction.getCrossSection( 9.000000000000E-05 );
TEST_FLOATING_EQUALITY( cross_section,
7.249970966838E+03 + 1.160420000000E+09,
1e-12 );
}
//---------------------------------------------------------------------------//
// Check that the absorption reaction can be returned
TEUCHOS_UNIT_TEST( ElectroatomCore, getTotalAbsorptionReaction )
{
const MonteCarlo::ElectroatomicReaction& absorption_reaction =
ace_electroatom_core->getTotalAbsorptionReaction();
double cross_section = absorption_reaction.getCrossSection( 1.000000000E-02 );
TEST_FLOATING_EQUALITY( cross_section, 0.000000000000, 1e-12 );
cross_section = absorption_reaction.getCrossSection( 2.000000000000E-03 );
TEST_FLOATING_EQUALITY( cross_section, 0.000000000000, 1e-12 );
cross_section = absorption_reaction.getCrossSection( 4.000000000000E-04 );
TEST_FLOATING_EQUALITY( cross_section, 0.000000000000, 1e-12 );
cross_section = absorption_reaction.getCrossSection( 9.000000000000E-05 );
TEST_FLOATING_EQUALITY( cross_section, 0.000000000000, 1e-12 );
}
//---------------------------------------------------------------------------//
// Check that the scattering reactions can be returned
TEUCHOS_UNIT_TEST( ElectroatomCore, getScatteringReactions )
{
const MonteCarlo::ElectroatomCore::ConstReactionMap& scattering_reactions =
ace_electroatom_core->getScatteringReactions();
TEST_EQUALITY_CONST( scattering_reactions.size(), 2 );
const MonteCarlo::ElectroatomicReaction& ae_reaction =
*(scattering_reactions.find(MonteCarlo::ATOMIC_EXCITATION_ELECTROATOMIC_REACTION)->second);
const MonteCarlo::ElectroatomicReaction& b_reaction =
*(scattering_reactions.find(MonteCarlo::BREMSSTRAHLUNG_ELECTROATOMIC_REACTION)->second);
double cross_section =
ae_reaction.getCrossSection( 2.000000000000E-03 ) +
b_reaction.getCrossSection( 2.000000000000E-03 );
TEST_FLOATING_EQUALITY( cross_section,
9.258661418255E+03 + 1.965170000000E+08,
1e-12 );
cross_section = ae_reaction.getCrossSection( 4.000000000000E-04 ) +
b_reaction.getCrossSection( 4.000000000000E-04 );
TEST_FLOATING_EQUALITY( cross_section,
8.914234996439E+03 + 6.226820000000E+08,
1e-12 );
cross_section = ae_reaction.getCrossSection( 9.000000000000E-05 ) +
b_reaction.getCrossSection( 9.000000000000E-05 );
TEST_FLOATING_EQUALITY( cross_section,
7.249970966838E+03 + 1.160420000000E+09,
1e-12 );
}
//---------------------------------------------------------------------------//
// Check that the absorption reactions can be returned
TEUCHOS_UNIT_TEST( ElectroatomCore, getAbsorptionReactions )
{
const MonteCarlo::ElectroatomCore::ConstReactionMap& absorption_reactions =
ace_electroatom_core->getAbsorptionReactions();
TEST_EQUALITY_CONST( absorption_reactions.size(), 0 );
}
//---------------------------------------------------------------------------//
// Check that miscellaneous reactions can be returned
TEUCHOS_UNIT_TEST( ElectroatomCore, getMiscReactions )
{
const MonteCarlo::ElectroatomCore::ConstReactionMap& misc_reactions =
ace_electroatom_core->getMiscReactions();
TEST_EQUALITY_CONST( misc_reactions.size(), 0 );
}
//---------------------------------------------------------------------------//
// Check that the atomic relaxation model can be returned
TEUCHOS_UNIT_TEST( ElectroatomCore, getAtomicRelaxationModel )
{
MonteCarlo::SubshellType vacancy = MonteCarlo::K_SUBSHELL;
MonteCarlo::ElectronState electron( 0u );
electron.setEnergy( 1.0 );
electron.setDirection( 0.0, 0.0, 1.0 );
electron.setPosition( 0.0, 0.0, 0.0 );
MonteCarlo::ParticleBank bank;
const MonteCarlo::AtomicRelaxationModel& relaxation_model =
ace_electroatom_core->getAtomicRelaxationModel();
relaxation_model.relaxAtom( vacancy, electron, bank );
TEST_EQUALITY_CONST( bank.size(), 0u );
}
//---------------------------------------------------------------------------//
// Custom main function
//---------------------------------------------------------------------------//
int main( int argc, char** argv )
{
std::string test_ace_file_name, test_ace_table_name;
Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();
clp.setOption( "test_ace_file",
&test_ace_file_name,
"Test ACE file name" );
clp.setOption( "test_ace_table",
&test_ace_table_name,
"Test ACE table name" );
const Teuchos::RCP<Teuchos::FancyOStream> out =
Teuchos::VerboseObjectBase::getDefaultOStream();
Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return =
clp.parse(argc,argv);
if ( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) {
*out << "\nEnd Result: TEST FAILED" << std::endl;
return parse_return;
}
{
// Create a file handler and data extractor
Teuchos::RCP<Data::ACEFileHandler> ace_file_handler(
new Data::ACEFileHandler( test_ace_file_name,
test_ace_table_name,
1u ) );
Teuchos::RCP<Data::XSSEPRDataExtractor> xss_data_extractor(
new Data::XSSEPRDataExtractor(
ace_file_handler->getTableNXSArray(),
ace_file_handler->getTableJXSArray(),
ace_file_handler->getTableXSSArray() ) );
// Create the atomic excitation, bremsstrahlung cross sections
Teuchos::ArrayRCP<double> energy_grid;
energy_grid.deepCopy( xss_data_extractor->extractElectronEnergyGrid() );
Teuchos::ArrayView<const double> raw_ae_cross_section =
xss_data_extractor->extractExcitationCrossSection();
Teuchos::ArrayView<const double>::iterator start =
std::find_if( raw_ae_cross_section.begin(),
raw_ae_cross_section.end(),
notEqualZero );
Teuchos::ArrayRCP<double> ae_cross_section;
ae_cross_section.assign( start, raw_ae_cross_section.end() );
unsigned ae_threshold_index =
energy_grid.size() - ae_cross_section.size();
// Extract the atomic excitation information data block (EXCIT)
Teuchos::ArrayView<const double> excit_block(
xss_data_extractor->extractEXCITBlock() );
// Extract the number of tabulated energies
int size = excit_block.size()/2;
// Extract the energy grid for atomic excitation energy loss
Teuchos::Array<double> ae_energy_grid(excit_block(0,size));
// Extract the energy loss for atomic excitation
Teuchos::Array<double> energy_loss(excit_block(size,size));
// Create the energy loss distributions
MonteCarlo::AtomicExcitationElectronScatteringDistribution::AtomicDistribution
ae_energy_loss_function;
ae_energy_loss_function.reset(
new Utility::TabularDistribution<Utility::LinLin>( ae_energy_grid,
energy_loss ) );
Teuchos::RCP<const MonteCarlo::AtomicExcitationElectronScatteringDistribution>
ae_energy_loss_distribution;
ae_energy_loss_distribution.reset(
new MonteCarlo::AtomicExcitationElectronScatteringDistribution(
ae_energy_loss_function ) );
Teuchos::RCP<MonteCarlo::ElectroatomicReaction> ae_reaction(
new MonteCarlo::AtomicExcitationElectroatomicReaction<Utility::LinLin>(
energy_grid,
ae_cross_section,
ae_threshold_index,
ae_energy_loss_distribution ) );
Teuchos::ArrayView<const double> raw_b_cross_section =
xss_data_extractor->extractBremsstrahlungCrossSection();
start = std::find_if( raw_b_cross_section.begin(),
raw_b_cross_section.end(),
notEqualZero );
Teuchos::ArrayRCP<double> b_cross_section;
b_cross_section.assign( start, raw_b_cross_section.end() );
unsigned b_threshold_index =
energy_grid.size() - b_cross_section.size();
//! \todo Find real bremsstrahlung photon angular distribution
// Create the tabular angular distribution
Teuchos::Array<double> b_energy_bins( 3 ); // (MeV)
b_energy_bins[0] = 1e-7;
b_energy_bins[1] = 1.0;
b_energy_bins[2] = 1e5;
Teuchos::Array<double> b_angular_distribution_values( 3 );
b_angular_distribution_values[0] = 0.0;
b_angular_distribution_values[1] = 0.5;
b_angular_distribution_values[2] = 1.0;
Teuchos::RCP<const Utility::OneDDistribution> b_angular_distribution(
new Utility::TabularDistribution<Utility::LinLin>(
b_energy_bins,
b_angular_distribution_values ) );
// Extract the elastic scattering information data block (BREMI)
Teuchos::ArrayView<const double> bremi_block(
xss_data_extractor->extractBREMIBlock() );
// Extract the number of tabulated distributions
int N = bremi_block.size()/3;
// Extract the electron energy grid for bremsstrahlung energy distributions
Teuchos::Array<double> b_energy_grid(bremi_block(0,N));
// Extract the table lengths for bremsstrahlung energy distributions
Teuchos::Array<double> table_length(bremi_block(N,N));
// Extract the offsets for bremsstrahlung energy distributions
Teuchos::Array<double> offset(bremi_block(2*N,N));
// Extract the bremsstrahlung photon energy distributions block (BREME)
Teuchos::ArrayView<const double> breme_block =
xss_data_extractor->extractBREMEBlock();
// Create the bremsstrahlung scattering distributions
MonteCarlo::BremsstrahlungElectronScatteringDistribution::BremsstrahlungDistribution
b_scattering_function( N );
for( unsigned n = 0; n < N; ++n )
{
b_scattering_function[n].first = b_energy_grid[n];
b_scattering_function[n].second.reset(
new Utility::HistogramDistribution(
breme_block( offset[n], table_length[n] ),
breme_block( offset[n] + 1 + table_length[n], table_length[n]-1 ),
true ) );
}
Teuchos::RCP<const MonteCarlo::BremsstrahlungElectronScatteringDistribution>
b_scattering_distribution;
b_scattering_distribution.reset(
new MonteCarlo::BremsstrahlungElectronScatteringDistribution(
b_scattering_function,
xss_data_extractor->extractAtomicNumber() ) );
// Create the bremsstrahlung scattering reaction
Teuchos::RCP<MonteCarlo::ElectroatomicReaction> b_reaction(
new MonteCarlo::BremsstrahlungElectroatomicReaction<Utility::LinLin>(
energy_grid,
b_cross_section,
b_threshold_index,
b_scattering_distribution ) );
// Create the reaction maps
MonteCarlo::ElectroatomCore::ReactionMap scattering_reactions,
absorption_reactions;
scattering_reactions[ae_reaction->getReactionType()] = ae_reaction;
scattering_reactions[b_reaction->getReactionType()] = b_reaction;
// Create a void atomic relaxation model
Teuchos::RCP<MonteCarlo::AtomicRelaxationModel> relaxation_model(
new MonteCarlo::VoidAtomicRelaxationModel );
// Create a test electroatom core
ace_electroatom_core.reset(
new MonteCarlo::ElectroatomCore( energy_grid,
scattering_reactions,
absorption_reactions,
relaxation_model,
false,
Utility::LinLin() ) );
// Run the unit tests
Teuchos::GlobalMPISession mpiSession( &argc, &argv );
}
const bool success = Teuchos::UnitTestRepository::runUnitTests( *out );
if (success)
*out << "\nEnd Result: TEST PASSED" << std::endl;
else
*out << "\nEnd Result: TEST FAILED" << std::endl;
clp.printFinalTimerSummary(out.ptr());
return (success ? 0 : 1);
}
//---------------------------------------------------------------------------//
// end tstElectroatomCore.cpp
//---------------------------------------------------------------------------//
| lkersting/SCR-2123 | packages/monte_carlo/collision/native/test/tstElectroatomCore.cpp | C++ | bsd-3-clause | 14,267 |
// Copyright (c) 2016 Mirants Lu. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "voyager/core/dispatch.h"
#include "voyager/core/eventloop.h"
#include "voyager/util/logging.h"
namespace voyager {
Dispatch::Dispatch(EventLoop* eventloop, int fd)
: eventloop_(eventloop),
fd_(fd),
events_(0),
revents_(0),
index_(-1),
modify_(kNoModify),
add_write_(false),
tied_(false),
event_handling_(false) {}
Dispatch::~Dispatch() { assert(!event_handling_); }
void Dispatch::EnableRead() {
events_ |= kReadEvent;
modify_ = kAddRead;
UpdateEvents();
}
void Dispatch::EnableWrite() {
events_ |= kWriteEvent;
if (add_write_) {
modify_ = kEnableWrite;
} else {
modify_ = kAddWrite;
add_write_ = true;
}
UpdateEvents();
}
void Dispatch::DisableRead() {
events_ &= ~kReadEvent;
modify_ = kDeleteRead;
UpdateEvents();
}
void Dispatch::DisableWrite() {
if (add_write_) {
events_ &= ~kWriteEvent;
modify_ = kDisableWrite;
UpdateEvents();
}
}
void Dispatch::DisableAll() {
if (IsReading() && add_write_) {
modify_ = kDeleteAll;
} else if (IsReading()) {
modify_ = kDeleteRead;
} else if (add_write_) {
modify_ = kDeleteWrite;
} else {
modify_ = kNoModify;
return;
}
add_write_ = false;
events_ = kNoneEvent;
UpdateEvents();
}
void Dispatch::UpdateEvents() { eventloop_->UpdateDispatch(this); }
void Dispatch::RemoveEvents() {
assert(IsNoneEvent());
eventloop_->RemoveDispatch(this);
}
void Dispatch::HandleEvent() {
std::shared_ptr<void> guard;
if (tied_) {
guard = tie_.lock();
if (guard) {
HandleEventWithGuard();
}
} else {
HandleEventWithGuard();
}
}
void Dispatch::HandleEventWithGuard() {
event_handling_ = true;
if ((revents_ & POLLHUP) && !(revents_ & POLLIN)) {
if (close_cb_) {
close_cb_();
}
}
if (revents_ & POLLNVAL) {
VOYAGER_LOG(WARN) << "Dispatch::HandleEvent() POLLNVAL";
}
if (revents_ & (POLLERR | POLLNVAL)) {
if (error_cb_) {
error_cb_();
}
}
#ifndef POLLRDHUP
const int POLLRDHUP = 0;
#endif
if (revents_ & (POLLIN | POLLPRI | POLLRDHUP)) {
if (read_cb_) {
read_cb_();
}
}
if (revents_ & POLLOUT) {
if (write_cb_) {
write_cb_();
}
}
revents_ = 0;
event_handling_ = false;
}
void Dispatch::Tie(const std::shared_ptr<void>& obj) {
tie_ = obj;
tied_ = true;
}
} // namespace voyager
| QiumingLu/voyager | voyager/core/dispatch.cc | C++ | bsd-3-clause | 2,547 |
/*
* Copyright Northwestern University
* Copyright Stanford University (ATB 1.0 and ATS 1.0)
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
*/
package edu.stanford.isis.atb.domain.template;
import javax.validation.constraints.NotNull;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;
/**
* @author Vitaliy Semeshko
*/
@Root(name="GeometricShape", strict=false)
public class GeometricShape extends AbstractRemovableElement {
@NotNull(message = "{geometricShape.value.notNull}")
@Text(required=false)
private GeometricShapeType value;
public GeometricShapeType getValue() {
return value;
}
public void setValue(GeometricShapeType value) {
this.value = value;
}
@Override
public String toString() {
return "Geometric Shape: " + (value == null ? "" : value.toString());
}
}
| NCIP/annotation-and-image-markup | ATB_1.1_src/src/main/java/edu/stanford/isis/atb/domain/template/GeometricShape.java | Java | bsd-3-clause | 926 |
<?php
return array(
'Blog' => 'Блог',
'joke' => 'Шутка',
'Login' => 'Вход',
); | Alcatraz1907/test | web/lang/ru/main.php | PHP | bsd-3-clause | 94 |
# proxy module
from pyface.layered_panel import *
| enthought/etsproxy | enthought/pyface/layered_panel.py | Python | bsd-3-clause | 50 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
# This plugin was based on the contrib/trac-post-commit-hook script, which
# had the following copyright notice:
# ----------------------------------------------------------------------------
# Copyright (c) 2004 Stephen Hansen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# ----------------------------------------------------------------------------
from __future__ import with_statement
from datetime import datetime
import re
from genshi.builder import tag
from trac.config import BoolOption, Option
from trac.core import Component, implements
from trac.perm import PermissionCache
from trac.resource import Resource
from trac.ticket import Ticket
from trac.ticket.notification import TicketNotifyEmail
from trac.util.datefmt import utc
from trac.util.text import exception_to_unicode
from trac.util.translation import _, cleandoc_
from trac.versioncontrol import IRepositoryChangeListener, RepositoryManager
from trac.versioncontrol.web_ui.changeset import ChangesetModule
from trac.wiki.formatter import format_to_html
from trac.wiki.macros import WikiMacroBase
class CommitTicketUpdater(Component):
"""Update tickets based on commit messages.
This component hooks into changeset notifications and searches commit
messages for text in the form of:
{{{
command #1
command #1, #2
command #1 & #2
command #1 and #2
}}}
Instead of the short-hand syntax "#1", "ticket:1" can be used as well,
e.g.:
{{{
command ticket:1
command ticket:1, ticket:2
command ticket:1 & ticket:2
command ticket:1 and ticket:2
}}}
In addition, the ':' character can be omitted and issue or bug can be used
instead of ticket.
You can have more than one command in a message. The following commands
are supported. There is more than one spelling for each command, to make
this as user-friendly as possible.
close, closed, closes, fix, fixed, fixes::
The specified tickets are closed, and the commit message is added to
them as a comment.
references, refs, addresses, re, see::
The specified tickets are left in their current status, and the commit
message is added to them as a comment.
A fairly complicated example of what you can do is with a commit message
of:
Changed blah and foo to do this or that. Fixes #10 and #12,
and refs #12.
This will close #10 and #12, and add a note to #12.
"""
implements(IRepositoryChangeListener)
envelope = Option('ticket', 'commit_ticket_update_envelope', '',
"""Require commands to be enclosed in an envelope.
Must be empty or contain two characters. For example, if set to "[]",
then commands must be in the form of [closes #4].""")
commands_close = Option('ticket', 'commit_ticket_update_commands.close',
'close closed closes fix fixed fixes',
"""Commands that close tickets, as a space-separated list.""")
commands_refs = Option('ticket', 'commit_ticket_update_commands.refs',
'addresses re references refs see',
"""Commands that add a reference, as a space-separated list.
If set to the special value <ALL>, all tickets referenced by the
message will get a reference to the changeset.""")
check_perms = BoolOption('ticket', 'commit_ticket_update_check_perms',
'true',
"""Check that the committer has permission to perform the requested
operations on the referenced tickets.
This requires that the user names be the same for Trac and repository
operations.""")
notify = BoolOption('ticket', 'commit_ticket_update_notify', 'true',
"""Send ticket change notification when updating a ticket.""")
ticket_prefix = '(?:#|(?:ticket|issue|bug)[: ]?)'
ticket_reference = ticket_prefix + '[0-9]+'
ticket_command = (r'(?P<action>[A-Za-z]*)\s*.?\s*'
r'(?P<ticket>%s(?:(?:[, &]*|[ ]?and[ ]?)%s)*)' %
(ticket_reference, ticket_reference))
@property
def command_re(self):
(begin, end) = (re.escape(self.envelope[0:1]),
re.escape(self.envelope[1:2]))
return re.compile(begin + self.ticket_command + end)
ticket_re = re.compile(ticket_prefix + '([0-9]+)')
_last_cset_id = None
# IRepositoryChangeListener methods
def changeset_added(self, repos, changeset):
if self._is_duplicate(changeset):
return
tickets = self._parse_message(changeset.message)
comment = self.make_ticket_comment(repos, changeset)
self._update_tickets(tickets, changeset, comment,
datetime.now(utc))
def changeset_modified(self, repos, changeset, old_changeset):
if self._is_duplicate(changeset):
return
tickets = self._parse_message(changeset.message)
old_tickets = {}
if old_changeset is not None:
old_tickets = self._parse_message(old_changeset.message)
tickets = dict(each for each in tickets.iteritems()
if each[0] not in old_tickets)
comment = self.make_ticket_comment(repos, changeset)
self._update_tickets(tickets, changeset, comment,
datetime.now(utc))
def _is_duplicate(self, changeset):
# Avoid duplicate changes with multiple scoped repositories
cset_id = (changeset.rev, changeset.message, changeset.author,
changeset.date)
if cset_id != self._last_cset_id:
self._last_cset_id = cset_id
return False
return True
def _parse_message(self, message):
"""Parse the commit message and return the ticket references."""
cmd_groups = self.command_re.finditer(message)
functions = self._get_functions()
tickets = {}
for m in cmd_groups:
cmd, tkts = m.group('action', 'ticket')
func = functions.get(cmd.lower())
if not func and self.commands_refs.strip() == '<ALL>':
func = self.cmd_refs
if func:
for tkt_id in self.ticket_re.findall(tkts):
tickets.setdefault(int(tkt_id), []).append(func)
return tickets
def make_ticket_comment(self, repos, changeset):
"""Create the ticket comment from the changeset data."""
rev = changeset.rev
revstring = str(rev)
drev = str(repos.display_rev(rev))
if repos.reponame:
revstring += '/' + repos.reponame
drev += '/' + repos.reponame
return """\
In [changeset:"%s" %s]:
{{{
#!CommitTicketReference repository="%s" revision="%s"
%s
}}}""" % (revstring, drev, repos.reponame, rev, changeset.message.strip())
def _update_tickets(self, tickets, changeset, comment, date):
"""Update the tickets with the given comment."""
authname = self._authname(changeset)
perm = PermissionCache(self.env, authname)
for tkt_id, cmds in tickets.iteritems():
try:
self.log.debug("Updating ticket #%d", tkt_id)
save = False
with self.env.db_transaction:
ticket = Ticket(self.env, tkt_id)
ticket_perm = perm(ticket.resource)
for cmd in cmds:
if cmd(ticket, changeset, ticket_perm) is not False:
save = True
if save:
ticket.save_changes(authname, comment, date)
if save:
self._notify(ticket, date)
except Exception, e:
self.log.error("Unexpected error while processing ticket "
"#%s: %s", tkt_id, exception_to_unicode(e))
def _notify(self, ticket, date):
"""Send a ticket update notification."""
if not self.notify:
return
tn = TicketNotifyEmail(self.env)
try:
tn.notify(ticket, newticket=False, modtime=date)
except Exception, e:
self.log.error("Failure sending notification on change to "
"ticket #%s: %s", ticket.id,
exception_to_unicode(e))
def _get_functions(self):
"""Create a mapping from commands to command functions."""
functions = {}
for each in dir(self):
if not each.startswith('cmd_'):
continue
func = getattr(self, each)
for cmd in getattr(self, 'commands_' + each[4:], '').split():
functions[cmd] = func
return functions
def _authname(self, changeset):
return changeset.author.lower() \
if self.env.config.getbool('trac', 'ignore_auth_case') \
else changeset.author
# Command-specific behavior
# The ticket isn't updated if all extracted commands return False.
def cmd_close(self, ticket, changeset, perm):
authname = self._authname(changeset)
if self.check_perms and not 'TICKET_MODIFY' in perm:
self.log.info("%s doesn't have TICKET_MODIFY permission for #%d",
authname, ticket.id)
return False
ticket['status'] = 'closed'
ticket['resolution'] = 'fixed'
if not ticket['owner']:
ticket['owner'] = authname
def cmd_refs(self, ticket, changeset, perm):
if self.check_perms and not 'TICKET_APPEND' in perm:
self.log.info("%s doesn't have TICKET_APPEND permission for #%d",
self._authname(changeset), ticket.id)
return False
class CommitTicketReferenceMacro(WikiMacroBase):
_domain = 'messages'
_description = cleandoc_(
"""Insert a changeset message into the output.
This macro must be called using wiki processor syntax as follows:
{{{
{{{
#!CommitTicketReference repository="reponame" revision="rev"
}}}
}}}
where the arguments are the following:
- `repository`: the repository containing the changeset
- `revision`: the revision of the desired changeset
""")
def expand_macro(self, formatter, name, content, args={}):
reponame = args.get('repository') or ''
rev = args.get('revision')
repos = RepositoryManager(self.env).get_repository(reponame)
try:
changeset = repos.get_changeset(rev)
message = changeset.message
rev = changeset.rev
resource = repos.resource
except Exception:
message = content
resource = Resource('repository', reponame)
if formatter.context.resource.realm == 'ticket':
ticket_re = CommitTicketUpdater.ticket_re
if not any(int(tkt_id) == int(formatter.context.resource.id)
for tkt_id in ticket_re.findall(message)):
return tag.p(_("(The changeset message doesn't reference this "
"ticket)"), class_='hint')
if ChangesetModule(self.env).wiki_format_messages:
return tag.div(format_to_html(self.env,
formatter.context.child('changeset', rev, parent=resource),
message, escape_newlines=True), class_='message')
else:
return tag.pre(message, class_='message')
| exocad/exotrac | tracopt/ticket/commit_updater.py | Python | bsd-3-clause | 12,921 |
import shutil
import subprocess as sub
pdf = '_build/latex/gcmstools.pdf'
try:
sub.call(['make', 'latexpdf'])
except:
print("There was an error in latexpdf generation.")
else:
shutil.copy(pdf, '..')
sub.call(['make', 'clean'])
| rnelsonchem/gcmstools | docs/makepdf.py | Python | bsd-3-clause | 246 |
/*
* Copyright (C)2015,2016,2017 Amos Brocco (amos.brocco@supsi.ch)
* Scuola Universitaria Professionale della
* Svizzera Italiana (SUPSI)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Scuola Universitaria Professionale della Svizzera
* Italiana (SUPSI) nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.
*/
#include "Blocker.h"
#include <chrono>
#include <thread>
DEFAULT_EXPORT_ALL(Blocker, "Blocker module (delays packets for the specified amount of time)", "", false)
Blocker::Blocker(const std::string& mid) : Module<Blocker, PomaDataType>(mid)
{
}
void Blocker::on_incoming_data(PomaPacketType& dta, const std::string& channel)
{
if (m_wait < 0) {
for(;;) {};
} else if (m_wait > 0) {
std::this_thread::sleep_for(std::chrono::seconds(m_wait));
}
submit_data(dta);
}
void Blocker::setup_cli(boost::program_options::options_description& desc) const
{
boost::program_options::options_description buf("Blocker options");
buf.add_options()
("wait", boost::program_options::value<int>()->default_value(1), "wait time in seconds (-1 infinite)");
desc.add(buf);
}
void Blocker::process_cli(boost::program_options::variables_map& vm)
{
m_wait = vm["wait"].as<int>();
}
| slashdotted/PomaPure | Modules/Blocker/src/Blocker.cpp | C++ | bsd-3-clause | 2,711 |
exports.testFuncPointerFailed = function() {
console.log("[JS]: Test function pointer Start!!!");
var IOLIB = (typeof require === 'function') ? require('../../../../'): this.IOLIB;
var io = new IOLIB.IO({
log: true,
//rpc: true,
port: 2000,
hostname: 'localhost',
quickInit: false
});
var cb_v_r_intp = function(a) {
io.fail_func_v_r_intp(a);
}
ret = io.fail_func_int_r_int_fp1(2, cb_v_r_intp);
ga = io.getFail_gafpV8();
if (ret != 2 || ga != 26)
throw Error("Failed!!!")
console.log("[JS]: Test function pointer Passed!!!");
}
| ilc-opensource/io-js | utils/autogen/testSuite/test_failed/funcPoint_failed.js | JavaScript | bsd-3-clause | 582 |
/*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
// Start the main app logic.
requirejs([
'../node_modules/happyfuntimes/dist/hft',
'../node_modules/hft-sample-ui/dist/sample-ui',
'../node_modules/hft-game-utils/dist/game-utils',
], function(
hft,
sampleUI,
gameUtils) {
var GameClient = hft.GameClient;
var CommonUI = sampleUI.commonUI;
var Input = sampleUI.input;
var Misc = sampleUI.misc;
var MobileHacks = sampleUI.mobileHacks;
var Touch = sampleUI.touch;
var globals = {
debug: false,
};
Misc.applyUrlSettings(globals);
MobileHacks.fixHeightHack();
var score = 0;
var statusElem = document.getElementById("gamestatus");
var inputElem = document.getElementById("inputarea");
var colorElem = document.getElementById("display");
var client = new GameClient();
CommonUI.setupStandardControllerUI(client, globals);
CommonUI.askForNameOnce(); // ask for the user's name if not set
CommonUI.showMenu(true); // shows the gear menu
var randInt = function(range) {
return Math.floor(Math.random() * range);
};
// Sends a move command to the game.
//
// This will generate a 'move' event in the corresponding
// NetPlayer object in the game.
var sendMoveCmd = function(position, target) {
client.sendCmd('move', {
x: position.x / target.clientWidth,
y: position.y / target.clientHeight,
});
};
// Pick a random color
var color = 'rgb(' + randInt(256) + "," + randInt(256) + "," + randInt(256) + ")";
// Send the color to the game.
//
// This will generate a 'color' event in the corresponding
// NetPlayer object in the game.
client.sendCmd('color', {
color: color,
});
colorElem.style.backgroundColor = color;
// Send a message to the game when the screen is touched
inputElem.addEventListener('pointermove', function(event) {
var position = Input.getRelativeCoordinates(event.target, event);
sendMoveCmd(position, event.target);
event.preventDefault();
});
// Update our score when the game tells us.
client.addEventListener('scored', function(cmd) {
score += cmd.points;
statusElem.innerHTML = "You scored: " + cmd.points + " total: " + score;
});
});
| greggman/hft-simple | scripts/controller.js | JavaScript | bsd-3-clause | 3,761 |
<?php
/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */
use yii\helpers\Html;
$this->title = $name;
?>
<div class="site-error">
<h1><?= Html::encode("Page Not Found(#404)"); ?></h1>
<div class="alert alert-danger">
<?= nl2br(Html::encode($error)) ?>
</div>
</div>
| yinye12345/StockWebService | views/doc/404.php | PHP | bsd-3-clause | 352 |
// Copyright (C) 2001 Kral Ferch, Jason Diamond
// Parts Copyright (C) 2004 Kevin Downs
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.ComponentModel;
namespace NDoc.Core.Reflection
{
/// <summary>
/// Summary description for ReflectionEngine.
/// </summary>
public class ReflectionEngine : MarshalByRefObject
{
/// <summary>
/// constructor for ReflectionEngine.
/// </summary>
public ReflectionEngine()
{
}
ReflectionEngineParameters rep;
AssemblyLoader assemblyLoader;
AssemblyXmlDocCache assemblyDocCache;
ExternalXmlSummaryCache externalSummaryCache;
Hashtable notEmptyNamespaces;
Hashtable documentedTypes;
ImplementsCollection implementations;
TypeHierarchy derivedTypes;
TypeHierarchy interfaceImplementingTypes;
NamespaceHierarchyCollection namespaceHierarchies;
TypeHierarchy baseInterfaces;
AttributeUsageDisplayFilter attributeFilter;
/// <summary>
/// Gets the namespaces from assembly.
/// </summary>
/// <param name="rep">ReflectionEngine Parameters.</param>
/// <param name="assemblyFile">Assembly file name.</param>
/// <returns></returns>
public SortedList GetNamespacesFromAssembly(ReflectionEngineParameters rep, string assemblyFile)
{
this.rep = rep;
assemblyLoader = SetupAssemblyLoader();
try
{
Assembly a = assemblyLoader.LoadAssembly(assemblyFile);
SortedList namespaces = new SortedList();
foreach (Type t in a.GetTypes())
{
string ns = t.Namespace;
{
if (ns == null)
{
if ((!namespaces.ContainsKey("(global)")))
namespaces.Add("(global)", null);
}
else
{
if ((!namespaces.ContainsKey(ns)))
namespaces.Add(ns, null);
}
}
}
return namespaces;
}
catch (ReflectionTypeLoadException rtle)
{
StringBuilder sb = new StringBuilder();
if (assemblyLoader.UnresolvedAssemblies.Count > 0)
{
sb.Append("One or more required assemblies could not be located : \n");
foreach (string ass in assemblyLoader.UnresolvedAssemblies)
{
sb.AppendFormat(" {0}\n", ass);
}
sb.Append("\nThe following directories were searched, \n");
foreach (string dir in assemblyLoader.SearchedDirectories)
{
sb.AppendFormat(" {0}\n", dir);
}
}
else
{
Hashtable fileLoadExceptions = new Hashtable();
foreach (Exception loaderEx in rtle.LoaderExceptions)
{
System.IO.FileLoadException fileLoadEx = loaderEx as System.IO.FileLoadException;
if (fileLoadEx != null)
{
if (!fileLoadExceptions.ContainsKey(fileLoadEx.FileName))
{
fileLoadExceptions.Add(fileLoadEx.FileName, null);
sb.Append("Unable to load: " + fileLoadEx.FileName + "\r\n");
}
}
sb.Append(loaderEx.Message + Environment.NewLine);
sb.Append(loaderEx.StackTrace + Environment.NewLine);
sb.Append("--------------------" + Environment.NewLine + Environment.NewLine);
}
}
throw new DocumenterException(sb.ToString());
}
finally
{
assemblyLoader.Deinstall();
}
}
/// <summary>Builds an Xml file combining the reflected metadata with the /doc comments.</summary>
/// <returns>full pathname of XML file</returns>
/// <remarks>The caller is responsible for deleting the xml file after use...</remarks>
internal void MakeXmlFile(ReflectionEngineParameters rep, string xmlFile)
{
this.rep = rep;
XmlTextWriter writer = null;
try
{
writer = new XmlTextWriter(xmlFile, Encoding.UTF8);
BuildXml(writer);
}
finally
{
if (writer != null) writer.Close();
}
}
/// <summary>Builds an Xml string combining the reflected metadata with the /doc comments.</summary>
/// <remarks>This now evidently writes the string in utf-16 format (and
/// says so, correctly I suppose, in the xml text) so if you write this string to a file with
/// utf-8 encoding it will be unparseable because the file will claim to be utf-16
/// but will actually be utf-8.</remarks>
/// <returns>XML string</returns>
internal string MakeXml(ReflectionEngineParameters rep)
{
this.rep = rep;
StringWriter swriter = new StringWriter();
XmlWriter writer = new XmlTextWriter(swriter);
try
{
BuildXml(writer);
return swriter.ToString();
}
finally
{
if (writer != null) writer.Close();
if (swriter != null) swriter.Close();
}
}
/// <summary>Builds an Xml file combining the reflected metadata with the /doc comments.</summary>
private void BuildXml(XmlWriter writer)
{
int start = Environment.TickCount;
Debug.WriteLine("Memory making xml: " + GC.GetTotalMemory(false).ToString());
try
{
assemblyLoader = SetupAssemblyLoader();
string DocLangCode = Enum.GetName(typeof(SdkLanguage), this.rep.SdkDocLanguage).Replace("_", "-");
externalSummaryCache = new ExternalXmlSummaryCache(DocLangCode);
notEmptyNamespaces = new Hashtable();
namespaceHierarchies = new NamespaceHierarchyCollection();
baseInterfaces = new TypeHierarchy();
derivedTypes = new TypeHierarchy();
interfaceImplementingTypes = new TypeHierarchy();
attributeFilter = new AttributeUsageDisplayFilter(this.rep.DocumentedAttributes);
documentedTypes = new Hashtable();
PreReflectionProcess();
string currentAssemblyFilename = "";
try
{
// Start the document with the XML declaration tag
writer.WriteStartDocument();
// Start the root element
writer.WriteStartElement("ndoc");
writer.WriteAttributeString("SchemaVersion", "1.4");
if (this.rep.FeedbackEmailAddress.Length > 0)
WriteFeedBackEmailAddress(writer);
if (this.rep.CopyrightText.Length > 0)
WriteCopyright(writer);
if (this.rep.IncludeDefaultThreadSafety)
WriteDefaultThreadSafety(writer);
if (this.rep.Preliminary)
writer.WriteElementString("preliminary", "");
WriteNamespaceHierarchies(writer);
foreach (string AssemblyFileName in this.rep.AssemblyFileNames)
{
currentAssemblyFilename = AssemblyFileName;
Assembly assembly = assemblyLoader.LoadAssembly(currentAssemblyFilename);
int starta = Environment.TickCount;
WriteAssembly(writer, assembly);
Trace.WriteLine("Completed " + assembly.FullName);
Trace.WriteLine(((Environment.TickCount - starta) / 1000.0).ToString() + " sec.");
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
Trace.WriteLine("MakeXML : " + ((Environment.TickCount - start) / 1000.0).ToString() + " sec.");
// if you want to see NDoc's intermediate XML file, use the XML documenter.
}
finally
{
if (assemblyLoader != null)
{
assemblyLoader.Deinstall();
}
}
}
catch (ReflectionTypeLoadException rtle)
{
StringBuilder sb = new StringBuilder();
if (assemblyLoader.UnresolvedAssemblies.Count > 0)
{
sb.Append("One or more required assemblies could not be located : \n");
foreach (string ass in assemblyLoader.UnresolvedAssemblies)
{
sb.AppendFormat(" {0}\n", ass);
}
sb.Append("\nThe following directories were searched, \n");
foreach (string dir in assemblyLoader.SearchedDirectories)
{
sb.AppendFormat(" {0}\n", dir);
}
}
else
{
Hashtable fileLoadExceptions = new Hashtable();
foreach (Exception loaderEx in rtle.LoaderExceptions)
{
System.IO.FileLoadException fileLoadEx = loaderEx as System.IO.FileLoadException;
if (fileLoadEx != null)
{
if (!fileLoadExceptions.ContainsKey(fileLoadEx.FileName))
{
fileLoadExceptions.Add(fileLoadEx.FileName, null);
sb.Append("Unable to load: " + fileLoadEx.FileName + "\r\n");
}
}
sb.Append(loaderEx.Message + Environment.NewLine);
sb.Append(loaderEx.StackTrace + Environment.NewLine);
sb.Append("--------------------" + Environment.NewLine + Environment.NewLine);
}
}
throw new DocumenterException(sb.ToString());
}
}
#region Global Xml Elements
// writes out the default thead safety settings for the project
private void WriteDefaultThreadSafety(XmlWriter writer)
{
writer.WriteStartElement("threadsafety");
writer.WriteAttributeString("static", XmlConvert.ToString(this.rep.StaticMembersDefaultToSafe));
writer.WriteAttributeString("instance", XmlConvert.ToString(this.rep.InstanceMembersDefaultToSafe));
writer.WriteEndElement();
}
private void WriteFeedBackEmailAddress(XmlWriter writer)
{
writer.WriteElementString("feedbackEmail", this.rep.FeedbackEmailAddress);
}
// writes the copyright node to the documentation
private void WriteCopyright(XmlWriter writer)
{
writer.WriteStartElement("copyright");
writer.WriteAttributeString("text", this.rep.CopyrightText);
if (this.rep.CopyrightHref.Length > 0)
{
if (!this.rep.CopyrightHref.StartsWith("http:"))
{
writer.WriteAttributeString("href", Path.GetFileName(this.rep.CopyrightHref));
}
else
{
writer.WriteAttributeString("href", this.rep.CopyrightHref);
}
}
writer.WriteEndElement();
}
#endregion
#region EditorBrowsable filter
//checks if the member has been flagged with the
//EditorBrowsableState.Never value
private bool IsEditorBrowsable(MemberInfo minfo)
{
if (this.rep.EditorBrowsableFilter == EditorBrowsableFilterLevel.Off)
{
return true;
}
EditorBrowsableAttribute[] browsables =
Attribute.GetCustomAttributes(minfo, typeof(EditorBrowsableAttribute), false)
as EditorBrowsableAttribute[];
if (browsables.Length == 0)
{
return true;
}
else
{
EditorBrowsableAttribute browsable = browsables[0];
return (browsable.State == EditorBrowsableState.Always) ||
((browsable.State == EditorBrowsableState.Advanced) &&
(this.rep.EditorBrowsableFilter != EditorBrowsableFilterLevel.HideAdvanced));
}
}
#endregion
#region MustDocument * filters
private bool MustDocumentType(Type type)
{
Type declaringType = type.DeclaringType;
//If type name starts with a digit it is not a valid identifier
//in any of the MS .Net languages.
//It's probably a J# anonomous inner class...
//Whatever, do not document it.
if (Char.IsDigit(type.Name, 0))
return false;
#if NET_2_0
if (type.IsGenericType)
type = type.GetGenericTypeDefinition();
//If the type has a CompilerGenerated attribute then we don't want to document it
//as it is an internal artifact of the compiler
if (type.IsDefined(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false))
{
return false;
}
#else
//HACK: exclude Net 2.0 compiler generated iterators
//These are nested classes with name starting with "<"
if (type.DeclaringType != null && type.Name.StartsWith("<"))
{
return false;
}
#endif
//exclude types that are internal to the .Net framework.
if (type.FullName.StartsWith("System.") || type.FullName.StartsWith("Microsoft."))
{
if (type.IsNotPublic) return false;
if (type.DeclaringType != null &&
!MustDocumentType(type.DeclaringType))
return false;
// There are a group of *public* interfaces in System.Runtime.InteropServices
// that are not documented by MS and should be considered internal to the framework...
if (type.IsInterface && type.Namespace == "System.Runtime.InteropServices" && type.Name.StartsWith("_"))
return false;
}
return
!type.FullName.StartsWith("<PrivateImplementationDetails>") &&
(declaringType == null || MustDocumentType(declaringType)) &&
(
(type.IsPublic) ||
(type.IsNotPublic && this.rep.DocumentInternals) ||
(type.IsNestedPublic) ||
(type.IsNestedFamily && this.rep.DocumentProtected) ||
(type.IsNestedFamORAssem && this.rep.DocumentProtected) ||
(type.IsNestedAssembly && this.rep.DocumentInternals) ||
(type.IsNestedFamANDAssem && this.rep.DocumentInternals) ||
(type.IsNestedPrivate && this.rep.DocumentPrivates)
) &&
IsEditorBrowsable(type) &&
(!this.rep.UseNamespaceDocSummaries || (type.Name != "NamespaceDoc")) &&
!assemblyDocCache.HasExcludeTag(MemberID.GetMemberID(type));
}
private bool MustDocumentMethod(MethodBase method)
{
//Ignore MC++ destructor.
//The __dtor function is just a wrapper that just calls the
//Finalize method; all code you write in the destructor is
//actually written to the finalize method. So, we will filter
//it out of the documentation by default...
if (method.Name == "__dtor")
return false;
//check the basic visibility options
if (!
(
(method.IsPublic) ||
(method.IsFamily && this.rep.DocumentProtected &&
(this.rep.DocumentSealedProtected || !method.ReflectedType.IsSealed)) ||
(method.IsFamilyOrAssembly && this.rep.DocumentProtected) ||
(method.ReflectedType.Assembly == method.DeclaringType.Assembly &&
((method.IsAssembly && this.rep.DocumentInternals) ||
(method.IsFamilyAndAssembly && this.rep.DocumentInternals))) ||
(method.IsPrivate)
)
)
{
return false;
}
//HACK: exclude Net 2.0 Anonymous Methods
//These have name starting with "<"
if (method.Name.StartsWith("<"))
{
return false;
}
var declaringTypeDef = method.DeclaringType;
if (declaringTypeDef.IsGenericType)
declaringTypeDef = declaringTypeDef.GetGenericTypeDefinition();
//Inherited Framework Members
if ((!this.rep.DocumentInheritedFrameworkMembers) &&
(method.ReflectedType != method.DeclaringType) &&
(declaringTypeDef.FullName.StartsWith("System.") ||
declaringTypeDef.FullName.StartsWith("Microsoft.")))
{
return false;
}
// Methods containing '.' in their name that aren't constructors are probably
// explicit interface implementations, we check whether we document those or not.
if ((method.Name.IndexOf('.') != -1) &&
(method.Name != ".ctor") &&
(method.Name != ".cctor") &&
this.rep.DocumentExplicitInterfaceImplementations)
{
string interfaceName = null;
int lastIndexOfDot = method.Name.LastIndexOf('.');
if (lastIndexOfDot != -1)
{
interfaceName = method.Name.Substring(0, lastIndexOfDot);
Type interfaceType = method.ReflectedType.GetInterface(interfaceName);
// Document method if interface is (public) or (isInternal and documentInternal).
if (interfaceType != null && (interfaceType.IsPublic ||
(interfaceType.IsNotPublic && this.rep.DocumentInternals)))
{
return IsEditorBrowsable(method);
}
}
}
else
{
if (method.IsPrivate && !this.rep.DocumentPrivates)
return false;
}
//check if the member has an exclude tag
if (method.DeclaringType != method.ReflectedType) // inherited
{
if (assemblyDocCache.HasExcludeTag(GetMemberName(method, method.DeclaringType)))
return false;
}
else
{
if (assemblyDocCache.HasExcludeTag(MemberID.GetMemberID(method)))
return false;
}
return IsEditorBrowsable(method);
}
private bool MustDocumentProperty(PropertyInfo property)
{
// here we decide if the property is to be documented
// note that we cannot directly test 'visibility' - it has to
// be done for both the accessors individualy...
if (IsEditorBrowsable(property))
{
MethodInfo getMethod = null;
MethodInfo setMethod = null;
if (property.CanRead)
{
try { getMethod = property.GetGetMethod(true); }
catch (System.Security.SecurityException) {}
}
if (property.CanWrite)
{
try { setMethod = property.GetSetMethod(true); }
catch (System.Security.SecurityException) {}
}
bool hasGetter = (getMethod != null) && MustDocumentMethod(getMethod);
bool hasSetter = (setMethod != null) && MustDocumentMethod(setMethod);
bool IsExcluded = false;
//check if the member has an exclude tag
if (property.DeclaringType != property.ReflectedType) // inherited
{
IsExcluded = assemblyDocCache.HasExcludeTag(GetMemberName(property, property.DeclaringType));
}
else
{
IsExcluded = assemblyDocCache.HasExcludeTag(MemberID.GetMemberID(property));
}
if ((hasGetter || hasSetter)
&& !IsExcluded)
return true;
}
return false;
}
private bool MustDocumentField(FieldInfo field)
{
if (!
(
(field.IsPublic) ||
(field.IsFamily && this.rep.DocumentProtected &&
(this.rep.DocumentSealedProtected || !field.ReflectedType.IsSealed)) ||
(field.IsFamilyOrAssembly && this.rep.DocumentProtected) ||
(field.ReflectedType.Assembly == field.DeclaringType.Assembly &&
((field.IsAssembly && this.rep.DocumentInternals) ||
(field.IsFamilyAndAssembly && this.rep.DocumentInternals))) ||
(field.IsPrivate && this.rep.DocumentPrivates))
)
{
return false;
}
//HACK: exclude Net 2.0 Anonymous Method Delegates
//These have name starting with "<"
if (field.Name.StartsWith("<"))
{
return false;
}
if ((!this.rep.DocumentInheritedFrameworkMembers) &&
(field.ReflectedType != field.DeclaringType) &&
(field.DeclaringType.FullName.StartsWith("System.") ||
field.DeclaringType.FullName.StartsWith("Microsoft.")))
{
return false;
}
//check if the member has an exclude tag
if (field.DeclaringType != field.ReflectedType) // inherited
{
if (assemblyDocCache.HasExcludeTag(GetMemberName(field, field.DeclaringType)))
return false;
}
else
{
if (assemblyDocCache.HasExcludeTag(MemberID.GetMemberID(field)))
return false;
}
return IsEditorBrowsable(field);
}
#endregion
#region IsHidden\IsHiding
private bool IsHidden(MemberInfo member, Type type)
{
if (member.DeclaringType == member.ReflectedType)
return false;
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
MemberInfo[] members = type.GetMember(member.Name, bindingFlags);
foreach (MemberInfo m in members)
{
if ((m != member)
&& m.DeclaringType.IsSubclassOf(member.DeclaringType))
{
return true;
}
}
return false;
}
private bool IsHidden(MethodInfo method, Type type)
{
if (method.DeclaringType == method.ReflectedType)
return false;
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
MemberInfo[] members = type.GetMember(method.Name, bindingFlags);
foreach (MemberInfo m in members)
{
if ((m != method)
&& (m.DeclaringType.IsSubclassOf(method.DeclaringType))
&& ((m.MemberType != MemberTypes.Method)
|| HaveSameSig(m as MethodInfo, method)))
{
return true;
}
}
return false;
}
private bool IsHiding(MemberInfo member, Type type)
{
if (member.DeclaringType != member.ReflectedType)
return false;
Type baseType = type.BaseType;
if (baseType == null)
return false;
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
MemberInfo[] members = baseType.GetMember(member.Name, bindingFlags);
if (members.Length > 0)
return true;
return false;
}
private bool IsHiding(MethodInfo method, Type type)
{
if (method.DeclaringType != method.ReflectedType)
return false;
Type baseType = type.BaseType;
if (baseType == null)
return false;
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
MemberInfo[] members = baseType.GetMember(method.Name, bindingFlags);
foreach (MemberInfo m in members)
{
if (m == method)
continue;
if (m.MemberType != MemberTypes.Method)
return true;
MethodInfo meth = m as MethodInfo;
if (HaveSameSig(meth, method)
&& (((method.Attributes & MethodAttributes.Virtual) == 0)
|| ((method.Attributes & MethodAttributes.NewSlot) != 0)))
{
return true;
}
}
return false;
}
private bool IsHiding(PropertyInfo property, Type type)
{
if (!IsHiding((MemberInfo)property, type))
return false;
bool isIndexer = (property.Name == "Item");
foreach (MethodInfo accessor in property.GetAccessors(true))
{
if (((accessor.Attributes & MethodAttributes.Virtual) != 0)
&& ((accessor.Attributes & MethodAttributes.NewSlot) == 0))
return false;
// indexers only hide indexers with the same signature
if (isIndexer && !IsHiding(accessor, type))
return false;
}
return true;
}
private bool HaveSameSig(MethodInfo m1, MethodInfo m2)
{
ParameterInfo[] ps1 = m1.GetParameters();
ParameterInfo[] ps2 = m2.GetParameters();
if (ps1.Length != ps2.Length)
return false;
for (int i = 0; i < ps1.Length; i++)
{
ParameterInfo p1 = ps1[i];
ParameterInfo p2 = ps2[i];
if (p1.ParameterType != p2.ParameterType)
return false;
if (p1.IsIn != p2.IsIn)
return false;
if (p1.IsOut != p2.IsOut)
return false;
if (p1.IsRetval != p2.IsRetval)
return false;
}
return true;
}
#endregion
#region Assembly
private void WriteAssembly(XmlWriter writer, Assembly assembly)
{
AssemblyName assemblyName = assembly.GetName();
writer.WriteStartElement("assembly");
writer.WriteAttributeString("name", assemblyName.Name);
if (this.rep.AssemblyVersionInfo == AssemblyVersionInformationType.AssemblyVersion)
{
writer.WriteAttributeString("version", assemblyName.Version.ToString());
}
if (this.rep.AssemblyVersionInfo == AssemblyVersionInformationType.AssemblyFileVersion)
{
object[] attrs = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
if (attrs.Length > 0)
{
string version = ((AssemblyFileVersionAttribute)attrs[0]).Version;
writer.WriteAttributeString("version", version);
}
}
WriteCustomAttributes(writer, assembly);
foreach (Module module in assembly.GetModules())
{
WriteModule(writer, module);
}
writer.WriteEndElement(); // assembly
}
#endregion
#region Module
/// <summary>Writes documentation about a module out as XML.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="module">Module to document.</param>
private void WriteModule(XmlWriter writer, Module module)
{
writer.WriteStartElement("module");
writer.WriteAttributeString("name", module.ScopeName);
WriteCustomAttributes(writer, module);
WriteNamespaces(writer, module);
writer.WriteEndElement();
}
#endregion
#region Namespace
private void WriteNamespaces(XmlWriter writer, Module module)
{
Type[] types = module.GetTypes();
StringCollection namespaceNames = GetNamespaceNames(types);
foreach (string namespaceName in namespaceNames)
{
string ourNamespaceName;
if (namespaceName == null)
{
ourNamespaceName = "(global)";
}
else
{
ourNamespaceName = namespaceName;
}
if (notEmptyNamespaces.ContainsKey(ourNamespaceName) || this.rep.DocumentEmptyNamespaces)
{
string namespaceSummary = null;
if (this.rep.UseNamespaceDocSummaries)
{
if (namespaceName == null)
namespaceSummary = assemblyDocCache.GetDoc("T:NamespaceDoc");
else
namespaceSummary = assemblyDocCache.GetDoc("T:" + namespaceName + ".NamespaceDoc");
}
bool isNamespaceDoc = false;
if ((namespaceSummary == null) || (namespaceSummary.Length == 0))
namespaceSummary = this.rep.NamespaceSummaries[ourNamespaceName] as string;
else
isNamespaceDoc = true;
if (this.rep.SkipNamespacesWithoutSummaries &&
(namespaceSummary == null || namespaceSummary.Length == 0))
{
Trace.WriteLine(string.Format("Skipping namespace {0} because it has no summary...", namespaceName));
}
else
{
Trace.WriteLine(string.Format("Writing namespace {0}...", namespaceName));
writer.WriteStartElement("namespace");
writer.WriteAttributeString("name", ourNamespaceName);
if (namespaceSummary != null && namespaceSummary.Length > 0)
{
WriteStartDocumentation(writer);
if (isNamespaceDoc)
{
writer.WriteRaw(namespaceSummary);
}
else
{
writer.WriteStartElement("summary");
writer.WriteRaw(namespaceSummary);
writer.WriteEndElement();
}
WriteEndDocumentation(writer);
}
else if (this.rep.ShowMissingSummaries)
{
WriteStartDocumentation(writer);
WriteMissingDocumentation(writer, "summary", null, "Missing <summary> Documentation for " + namespaceName);
WriteEndDocumentation(writer);
}
int classCount = WriteClasses(writer, types, namespaceName);
Trace.WriteLine(string.Format("Wrote {0} classes.", classCount));
int interfaceCount = WriteInterfaces(writer, types, namespaceName);
Trace.WriteLine(string.Format("Wrote {0} interfaces.", interfaceCount));
int structureCount = WriteStructures(writer, types, namespaceName);
Trace.WriteLine(string.Format("Wrote {0} structures.", structureCount));
int delegateCount = WriteDelegates(writer, types, namespaceName);
Trace.WriteLine(string.Format("Wrote {0} delegates.", delegateCount));
int enumCount = WriteEnumerations(writer, types, namespaceName);
Trace.WriteLine(string.Format("Wrote {0} enumerations.", enumCount));
writer.WriteEndElement();
}
}
else
{
Trace.WriteLine(string.Format("Discarding namespace {0} because it does not contain any documented types.", ourNamespaceName));
}
}
}
#endregion
#region TypeCollections
private int WriteClasses(XmlWriter writer, Type[] types, string namespaceName)
{
int nbWritten = 0;
foreach (Type type in types)
{
if (type.IsClass &&
!IsDelegate(type) &&
type.Namespace == namespaceName)
{
string typeID = MemberID.GetMemberID(type);
if (!documentedTypes.ContainsKey(typeID))
{
documentedTypes.Add(typeID, null);
if (MustDocumentType(type))
{
bool hiding = ((type.MemberType & MemberTypes.NestedType) != 0)
&& IsHiding(type, type.DeclaringType);
WriteClass(writer, type, hiding);
nbWritten++;
}
}
else
{
Trace.WriteLine(typeID + " already documented - skipped...");
}
}
}
return nbWritten;
}
private int WriteInterfaces(XmlWriter writer, Type[] types, string namespaceName)
{
int nbWritten = 0;
foreach (Type type in types)
{
if (type.IsInterface &&
type.Namespace == namespaceName &&
MustDocumentType(type))
{
string typeID = MemberID.GetMemberID(type);
if (!documentedTypes.ContainsKey(typeID))
{
documentedTypes.Add(typeID, null);
WriteInterface(writer, type);
nbWritten++;
}
else
{
Trace.WriteLine(typeID + " already documented - skipped...");
}
}
}
return nbWritten;
}
private int WriteStructures(XmlWriter writer, Type[] types, string namespaceName)
{
int nbWritten = 0;
foreach (Type type in types)
{
if (type.IsValueType &&
!type.IsEnum &&
type.Namespace == namespaceName &&
MustDocumentType(type))
{
string typeID = MemberID.GetMemberID(type);
if (!documentedTypes.ContainsKey(typeID))
{
documentedTypes.Add(typeID, null);
bool hiding = ((type.MemberType & MemberTypes.NestedType) != 0)
&& IsHiding(type, type.DeclaringType);
WriteClass(writer, type, hiding);
nbWritten++;
}
else
{
Trace.WriteLine(typeID + " already documented - skipped...");
}
}
}
return nbWritten;
}
private int WriteDelegates(XmlWriter writer, Type[] types, string namespaceName)
{
int nbWritten = 0;
foreach (Type type in types)
{
if (type.IsClass &&
IsDelegate(type) &&
type.Namespace == namespaceName &&
MustDocumentType(type))
{
string typeID = MemberID.GetMemberID(type);
if (!documentedTypes.ContainsKey(typeID))
{
documentedTypes.Add(typeID, null);
WriteDelegate(writer, type);
nbWritten++;
}
else
{
Trace.WriteLine(typeID + " already documented - skipped...");
}
}
}
return nbWritten;
}
private int WriteEnumerations(XmlWriter writer, Type[] types, string namespaceName)
{
int nbWritten = 0;
foreach (Type type in types)
{
if (type.IsEnum &&
type.Namespace == namespaceName &&
MustDocumentType(type))
{
string typeID = MemberID.GetMemberID(type);
if (!documentedTypes.ContainsKey(typeID))
{
documentedTypes.Add(typeID, null);
WriteEnumeration(writer, type);
nbWritten++;
}
else
{
Trace.WriteLine(typeID + " already documented - skipped...");
}
}
}
return nbWritten;
}
private bool IsDelegate(Type type)
{
if (type.BaseType == null) return false;
return type.BaseType.FullName == "System.Delegate" ||
type.BaseType.FullName == "System.MulticastDelegate";
}
#endregion
private int GetMethodOverload(MethodInfo method, Type type)
{
int count = 0;
int overload = 0;
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
MemberInfo[] methods = type.GetMember(method.Name, MemberTypes.Method, bindingFlags);
foreach (MethodInfo m in methods)
{
if (!IsHidden(m, type) && MustDocumentMethod(m))
{
++count;
}
if (m == method)
{
overload = count;
}
}
return (count > 1) ? overload : 0;
}
private int GetPropertyOverload(PropertyInfo property, PropertyInfo[] properties)
{
int count = 0;
int overload = 0;
foreach (PropertyInfo p in properties)
{
if ((p.Name == property.Name)
/*&& !IsHidden(p, properties)*/)
{
++count;
}
if (p == property)
{
overload = count;
}
}
return (count > 1) ? overload : 0;
}
#region Types
/// <summary>Writes XML documenting a class.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="type">Class to document.</param>
/// <param name="hiding">true if hiding base members</param>
private void WriteClass(XmlWriter writer, Type type, bool hiding)
{
bool isStruct = type.IsValueType;
string memberName = MemberID.GetMemberID(type);
string fullNameWithoutNamespace = type.FullName.Replace('+', '.');
if (type.Namespace != null)
{
fullNameWithoutNamespace = fullNameWithoutNamespace.Substring(type.Namespace.Length + 1);
}
writer.WriteStartElement(isStruct ? "structure" : "class");
writer.WriteAttributeString("name", fullNameWithoutNamespace);
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(type));
writer.WriteAttributeString("namespace", type.Namespace);
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("access", GetTypeAccessValue(type));
if (hiding)
{
writer.WriteAttributeString("hiding", "true");
}
// structs can't be abstract and always derive from System.ValueType
// so don't bother including those attributes.
if (!isStruct)
{
if (type.IsAbstract)
{
writer.WriteAttributeString("abstract", "true");
}
if (type.IsSealed)
{
writer.WriteAttributeString("sealed", "true");
}
if (type.BaseType != null && type.BaseType.FullName != "System.Object")
{
writer.WriteAttributeString("baseType", type.BaseType.Name);
}
}
WriteTypeDocumentation(writer, memberName, type);
WriteCustomAttributes(writer, type);
if (type.BaseType != null)
WriteBaseType(writer, type.BaseType);
WriteDerivedTypes(writer, type);
implementations = new ImplementsCollection();
//build a collection of the base type's interfaces
//to determine which have been inherited
StringCollection baseInterfaces = new StringCollection();
if (type.BaseType != null)
{
foreach (Type baseInterfaceType in type.BaseType.GetInterfaces())
{
baseInterfaces.Add(baseInterfaceType.FullName);
}
}
foreach (Type interfaceType in type.GetInterfaces())
{
var interfaceTypeDef = interfaceType;
if (interfaceTypeDef.IsGenericType)
interfaceTypeDef = interfaceTypeDef.GetGenericTypeDefinition();
if (MustDocumentType(interfaceTypeDef))
{
writer.WriteStartElement("implements");
writer.WriteAttributeString("type", interfaceTypeDef.FullName.Replace('+', '.'));
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(interfaceTypeDef));
writer.WriteAttributeString("namespace", interfaceTypeDef.Namespace);
if (baseInterfaces.Contains(interfaceTypeDef.FullName))
{
writer.WriteAttributeString("inherited", "true");
}
writer.WriteEndElement();
InterfaceMapping interfaceMap = type.GetInterfaceMap(interfaceType);
int numberOfMethods = interfaceMap.InterfaceMethods.Length;
for (int i = 0; i < numberOfMethods; i++)
{
if (interfaceMap.TargetMethods[i] != null)
{
string implementation = interfaceMap.TargetMethods[i].ToString();
ImplementsInfo implements = new ImplementsInfo();
implements.InterfaceMethod = interfaceMap.InterfaceMethods[i];
implements.InterfaceType = interfaceMap.InterfaceType;
implements.TargetMethod = interfaceMap.TargetMethods[i];
implements.TargetType = interfaceMap.TargetType;
implementations[implementation] = implements;
}
}
}
}
WriteConstructors(writer, type);
WriteStaticConstructor(writer, type);
WriteFields(writer, type);
WriteProperties(writer, type);
WriteMethods(writer, type);
WriteOperators(writer, type);
WriteEvents(writer, type);
implementations = null;
writer.WriteEndElement();
}
/// <summary>Writes XML documenting an interface.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="type">Interface to document.</param>
private void WriteInterface(XmlWriter writer, Type type)
{
string memberName = MemberID.GetMemberID(type);
string fullNameWithoutNamespace = type.FullName.Replace('+', '.');
if (type.Namespace != null)
{
fullNameWithoutNamespace = fullNameWithoutNamespace.Substring(type.Namespace.Length + 1);
}
writer.WriteStartElement("interface");
writer.WriteAttributeString("name", fullNameWithoutNamespace);
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(type));
writer.WriteAttributeString("namespace", type.Namespace);
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("access", GetTypeAccessValue(type));
WriteTypeDocumentation(writer, memberName, type);
WriteCustomAttributes(writer, type);
WriteDerivedTypes(writer, type);
foreach (Type interfaceType in type.GetInterfaces())
{
if (MustDocumentType(interfaceType))
{
writer.WriteStartElement("implements");
writer.WriteAttributeString("type", interfaceType.FullName.Replace('+', '.'));
writer.WriteEndElement();
}
}
WriteInterfaceImplementingTypes(writer, type);
WriteProperties(writer, type);
WriteMethods(writer, type);
WriteEvents(writer, type);
writer.WriteEndElement();
}
/// <summary>Writes XML documenting a delegate.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="type">Delegate to document.</param>
private void WriteDelegate(XmlWriter writer, Type type)
{
string memberName = MemberID.GetMemberID(type);
writer.WriteStartElement("delegate");
writer.WriteAttributeString("name", GetNestedTypeName(type));
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(type));
writer.WriteAttributeString("namespace", type.Namespace);
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("access", GetTypeAccessValue(type));
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
MethodInfo[] methods = type.GetMethods(bindingFlags);
foreach (MethodInfo method in methods)
{
if (method.Name == "Invoke")
{
Type t = method.ReturnType;
writer.WriteAttributeString("returnType", MemberID.GetTypeName(t));
writer.WriteAttributeString("valueType", t.IsValueType.ToString().ToLower());
WriteDelegateDocumentation(writer, memberName, type, method);
WriteCustomAttributes(writer, type);
foreach (ParameterInfo parameter in method.GetParameters())
{
WriteParameter(writer, MemberID.GetMemberID(method), parameter);
}
}
}
writer.WriteEndElement();
}
private string GetNestedTypeName(Type type)
{
int indexOfPlus = type.FullName.IndexOf('+');
if (indexOfPlus != -1)
{
int lastIndexOfDot = type.FullName.LastIndexOf('.');
return type.FullName.Substring(lastIndexOfDot + 1).Replace('+', '.');
}
else
{
return type.Name;
}
}
/// <summary>Writes XML documenting an enumeration.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="type">Enumeration to document.</param>
private void WriteEnumeration(XmlWriter writer, Type type)
{
string memberName = MemberID.GetMemberID(type);
writer.WriteStartElement("enumeration");
writer.WriteAttributeString("name", GetNestedTypeName(type));
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(type));
writer.WriteAttributeString("namespace", type.Namespace);
writer.WriteAttributeString("access", GetTypeAccessValue(type));
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.DeclaredOnly;
foreach (FieldInfo field in type.GetFields(bindingFlags))
{
// Enums are normally based on Int32, but this is not a CLR requirement.
// In fact, they may be based on any integer type. The value__ field
// defines the enum's base type, so we will treat this seperately...
if (field.Name == "value__")
{
if (field.FieldType.FullName != "System.Int32")
{
writer.WriteAttributeString("baseType", field.FieldType.FullName);
}
break;
}
}
if (type.IsDefined(typeof(System.FlagsAttribute), false))
{
writer.WriteAttributeString("flags", "true");
}
WriteEnumerationDocumentation(writer, memberName);
WriteCustomAttributes(writer, type);
foreach (FieldInfo field in type.GetFields(bindingFlags))
{
if (field.Name == "value__" || !IsEditorBrowsable (field))
continue;
WriteField(writer, field, type, IsHiding(field, type));
}
writer.WriteEndElement();
}
#endregion
#region Attributes
private void WriteStructLayoutAttribute(XmlWriter writer, Type type)
{
string charSet = null;
string layoutKind = null;
if (!attributeFilter.Show("System.Runtime.InteropServices.StructLayoutAttribute", "CharSet"))
{
// determine if CharSet property should be documented
if ((type.Attributes & TypeAttributes.AutoClass) == TypeAttributes.AutoClass)
{
charSet = CharSet.Auto.ToString();
}
// //Do not document if default value....
// if ((type.Attributes & TypeAttributes.AnsiClass) == TypeAttributes.AnsiClass)
// {
// charSet = CharSet.Ansi.ToString(CultureInfo.InvariantCulture);
// }
if ((type.Attributes & TypeAttributes.UnicodeClass) == TypeAttributes.UnicodeClass)
{
charSet = CharSet.Unicode.ToString();
}
}
if (!attributeFilter.Show("System.Runtime.InteropServices.StructLayoutAttribute", "Value"))
{
// determine if Value property should be documented
// //Do not document if default value....
// if ((type.Attributes & TypeAttributes.AutoLayout) == TypeAttributes.AutoLayout)
// {
// layoutKind = LayoutKind.Auto.ToString(CultureInfo.InvariantCulture);
// }
if ((type.Attributes & TypeAttributes.ExplicitLayout) == TypeAttributes.ExplicitLayout)
{
layoutKind = LayoutKind.Explicit.ToString();
}
if ((type.Attributes & TypeAttributes.SequentialLayout) == TypeAttributes.SequentialLayout)
{
layoutKind = LayoutKind.Sequential.ToString();
}
}
if (charSet == null && layoutKind == null)
{
return;
}
// create attribute element
writer.WriteStartElement("attribute");
writer.WriteAttributeString("name", "System.Runtime.InteropServices.StructLayoutAttribute");
if (charSet != null)
{
// create CharSet property element
writer.WriteStartElement("property");
writer.WriteAttributeString("name", "CharSet");
writer.WriteAttributeString("type", "System.Runtime.InteropServices.CharSet");
writer.WriteAttributeString("value", charSet);
writer.WriteEndElement();
}
if (layoutKind != null)
{
// create Value property element
writer.WriteStartElement("property");
writer.WriteAttributeString("name", "Value");
writer.WriteAttributeString("type", "System.Runtime.InteropServices.LayoutKind");
writer.WriteAttributeString("value", layoutKind);
writer.WriteEndElement();
}
// end attribute element
writer.WriteEndElement();
}
private void WriteSpecialAttributes(XmlWriter writer, Type type)
{
if ((type.Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable)
{
if (attributeFilter.Show("System.SerializableAttribute"))
{
writer.WriteStartElement("attribute");
writer.WriteAttributeString("name", "System.SerializableAttribute");
writer.WriteEndElement(); // attribute
}
}
WriteStructLayoutAttribute(writer, type);
}
private void WriteSpecialAttributes(XmlWriter writer, FieldInfo field)
{
if ((field.Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized)
{
if (attributeFilter.Show("System.NonSerializedAttribute"))
{
writer.WriteStartElement("attribute");
writer.WriteAttributeString("name", "System.NonSerializedAttribute");
writer.WriteEndElement(); // attribute
}
}
//TODO: more special attributes here?
}
private void WriteCustomAttributes(XmlWriter writer, Assembly assembly)
{
WriteCustomAttributes(writer, assembly.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "assembly");
}
private void WriteCustomAttributes(XmlWriter writer, Module module)
{
WriteCustomAttributes(writer, module.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "module");
}
private void WriteCustomAttributes(XmlWriter writer, Type type)
{
try
{
WriteSpecialAttributes(writer, type);
WriteCustomAttributes(writer, type.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "");
}
catch (Exception e)
{
TraceErrorOutput("Error retrieving custom attributes for " + MemberID.GetMemberID(type), e);
}
}
private void WriteCustomAttributes(XmlWriter writer, FieldInfo fieldInfo)
{
try
{
WriteSpecialAttributes(writer, fieldInfo);
WriteCustomAttributes(writer, fieldInfo.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "");
}
catch (Exception e)
{
TraceErrorOutput("Error retrieving custom attributes for " + MemberID.GetMemberID(fieldInfo), e);
}
}
private void WriteCustomAttributes(XmlWriter writer, ConstructorInfo constructorInfo)
{
try
{
WriteCustomAttributes(writer, constructorInfo.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "");
}
catch (Exception e)
{
TraceErrorOutput("Error retrieving custom attributes for " + MemberID.GetMemberID(constructorInfo), e);
}
}
private void WriteCustomAttributes(XmlWriter writer, MethodInfo methodInfo)
{
try
{
WriteCustomAttributes(writer, methodInfo.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "");
WriteCustomAttributes(writer, methodInfo.ReturnTypeCustomAttributes.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "return");
}
catch (Exception e)
{
TraceErrorOutput("Error retrieving custom attributes for " + MemberID.GetMemberID(methodInfo), e);
}
}
private void WriteCustomAttributes(XmlWriter writer, PropertyInfo propertyInfo)
{
try
{
WriteCustomAttributes(writer, propertyInfo.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "");
}
catch (Exception e)
{
TraceErrorOutput("Error retrieving custom attributes for " + MemberID.GetMemberID(propertyInfo), e);
}
}
private void WriteCustomAttributes(XmlWriter writer, ParameterInfo parameterInfo)
{
try
{
WriteCustomAttributes(writer, parameterInfo.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "");
}
catch (Exception e)
{
TraceErrorOutput("Error retrieving custom attributes for " + parameterInfo.Member.ReflectedType.FullName + "." + parameterInfo.Member.Name + " param " + parameterInfo.Name, e);
}
}
private void WriteCustomAttributes(XmlWriter writer, EventInfo eventInfo)
{
try
{
WriteCustomAttributes(writer, eventInfo.GetCustomAttributes(this.rep.DocumentInheritedAttributes), "");
}
catch (Exception e)
{
TraceErrorOutput("Error retrieving custom attributes for " + MemberID.GetMemberID(eventInfo), e);
}
}
private void WriteCustomAttributes(XmlWriter writer, object[] attributes, string target)
{
foreach (Attribute attribute in attributes)
{
if (this.rep.DocumentAttributes)
{
if (MustDocumentType(attribute.GetType()) && attributeFilter.Show(attribute.GetType().FullName))
{
WriteCustomAttribute(writer, attribute, target);
}
}
if (attribute.GetType().FullName == "System.ObsoleteAttribute")
{
writer.WriteElementString("obsolete", ((ObsoleteAttribute)attribute).Message);
}
}
}
private void WriteCustomAttribute(XmlWriter writer, Attribute attribute, string target)
{
writer.WriteStartElement("attribute");
string fullName = attribute.GetType().FullName;
writer.WriteAttributeString("name", fullName);
if (target.Length > 0)
{
writer.WriteAttributeString("target", target);
}
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Public;
foreach (FieldInfo field in attribute.GetType().GetFields(bindingFlags))
{
if (MustDocumentField(field) && attributeFilter.Show(fullName, field.Name))
{
string fieldValue = null;
try
{
fieldValue = GetDisplayValue(field.DeclaringType, field.GetValue(attribute));
}
catch (Exception e)
{
TraceErrorOutput("Value for attribute field " + MemberID.GetMemberID(field).Substring(2) + " cannot be determined", e);
fieldValue = "***UNKNOWN***";
}
if (fieldValue.Length > 0)
{
writer.WriteStartElement("field");
writer.WriteAttributeString("name", field.Name);
writer.WriteAttributeString("type", field.FieldType.FullName);
writer.WriteAttributeString("value", fieldValue);
writer.WriteEndElement(); // field
}
}
}
foreach (PropertyInfo property in attribute.GetType().GetProperties(bindingFlags))
{
//skip the TypeId property
if ((!this.rep.ShowTypeIdInAttributes) && (property.Name == "TypeId"))
{
continue;
}
if (MustDocumentProperty(property) && attributeFilter.Show(fullName, property.Name))
{
if (property.CanRead)
{
string propertyValue = null;
try
{
propertyValue = GetDisplayValue(property.DeclaringType, property.GetValue(attribute, null));
}
catch (Exception e)
{
TraceErrorOutput("Value for attribute property " + MemberID.GetMemberID(property).Substring(2) + " cannot be determined", e);
propertyValue = "***UNKNOWN***";
}
if (propertyValue.Length > 0)
{
writer.WriteStartElement("property");
writer.WriteAttributeString("name", property.Name);
writer.WriteAttributeString("type", property.PropertyType.FullName);
writer.WriteAttributeString("value", propertyValue);
writer.WriteEndElement(); // property
}
}
}
}
writer.WriteEndElement(); // attribute
}
#endregion
#region MemberCollections
private void WriteConstructors(XmlWriter writer, Type type)
{
int overload = 0;
BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.NonPublic;
if (!this.rep.DocumentInheritedMembers)
{
bindingFlags = bindingFlags | BindingFlags.DeclaredOnly;
}
ConstructorInfo[] constructors = type.GetConstructors(bindingFlags);
if (constructors.Length > 1)
{
overload = 1;
}
foreach (ConstructorInfo constructor in constructors)
{
if (MustDocumentMethod(constructor))
{
WriteConstructor(writer, constructor, overload++);
}
}
}
private void WriteStaticConstructor(XmlWriter writer, Type type)
{
BindingFlags bindingFlags =
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
if (!this.rep.DocumentInheritedMembers)
{
bindingFlags = bindingFlags | BindingFlags.DeclaredOnly;
}
ConstructorInfo[] constructors = type.GetConstructors(bindingFlags);
foreach (ConstructorInfo constructor in constructors)
{
if (MustDocumentMethod(constructor))
{
WriteConstructor(writer, constructor, 0);
}
}
}
private void WriteFields(XmlWriter writer, Type type)
{
BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
if (!this.rep.DocumentInheritedMembers)
{
bindingFlags = bindingFlags | BindingFlags.DeclaredOnly;
}
FieldInfo[] fields = type.GetFields(bindingFlags);
foreach (FieldInfo field in fields)
{
if (MustDocumentField(field)
&& !IsAlsoAnEvent(field)
&& !IsHidden(field, type))
{
WriteField(
writer,
field,
type,
IsHiding(field, type));
}
}
}
private void WriteProperties(XmlWriter writer, Type type)
{
BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
if (!this.rep.DocumentInheritedMembers)
{
bindingFlags = bindingFlags | BindingFlags.DeclaredOnly;
}
PropertyInfo[] properties = type.GetProperties(bindingFlags);
foreach (PropertyInfo property in properties)
{
if (MustDocumentProperty(property)
&& !IsAlsoAnEvent(property)
&& !IsHidden(property, type)
)
{
WriteProperty(
writer,
property,
property.DeclaringType.FullName != type.FullName,
GetPropertyOverload(property, properties),
IsHiding(property, type));
}
}
}
private void WriteMethods(XmlWriter writer, Type type)
{
BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
if (!this.rep.DocumentInheritedMembers)
{
bindingFlags = bindingFlags | BindingFlags.DeclaredOnly;
}
MethodInfo[] methods = type.GetMethods(bindingFlags);
foreach (MethodInfo method in methods)
{
string name = method.Name;
int lastIndexOfDot = name.LastIndexOf('.');
if (lastIndexOfDot != -1)
{
name = method.Name.Substring(lastIndexOfDot + 1);
}
if (
!(
method.IsSpecialName &&
(
name.StartsWith("get_") ||
name.StartsWith("set_") ||
name.StartsWith("add_") ||
name.StartsWith("remove_") ||
name.StartsWith("raise_") ||
name.StartsWith("op_")
)
) &&
MustDocumentMethod(method) &&
!IsHidden(method, type))
{
WriteMethod(
writer,
method,
method.DeclaringType.FullName != type.FullName,
GetMethodOverload(method, type),
IsHiding(method, type));
}
}
}
private void WriteOperators(XmlWriter writer, Type type)
{
BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
if (!this.rep.DocumentInheritedMembers)
{
bindingFlags = bindingFlags | BindingFlags.DeclaredOnly;
}
MethodInfo[] methods = type.GetMethods(bindingFlags);
foreach (MethodInfo method in methods)
{
if (method.Name.StartsWith("op_") &&
MustDocumentMethod(method))
{
WriteOperator(
writer,
method,
GetMethodOverload(method, type));
}
}
}
private void WriteEvents(XmlWriter writer, Type type)
{
BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
if (!this.rep.DocumentInheritedMembers)
{
bindingFlags = bindingFlags | BindingFlags.DeclaredOnly;
}
EventInfo[] events = type.GetEvents(bindingFlags);
foreach (EventInfo eventInfo in events)
{
bool IsExcluded = false;
//check if the event has an exclude tag
if (eventInfo.DeclaringType != eventInfo.ReflectedType) // inherited
{
IsExcluded = assemblyDocCache.HasExcludeTag(GetMemberName(eventInfo, eventInfo.DeclaringType));
}
else
{
IsExcluded = assemblyDocCache.HasExcludeTag(MemberID.GetMemberID(eventInfo));
}
if (!IsExcluded)
{
MethodInfo addMethod = eventInfo.GetAddMethod(true);
if (addMethod != null &&
MustDocumentMethod(addMethod) &&
IsEditorBrowsable(eventInfo))
{
WriteEvent(writer, eventInfo);
}
}
}
}
private bool IsAlsoAnEvent(Type type, string fullName)
{
bool isEvent = false;
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.DeclaredOnly;
EventInfo[] events = type.GetEvents(bindingFlags);
foreach (EventInfo eventInfo in events)
{
if (eventInfo.EventHandlerType.FullName == fullName)
{
isEvent = true;
break;
}
}
return isEvent;
}
private bool IsAlsoAnEvent(FieldInfo field)
{
return IsAlsoAnEvent(field.DeclaringType, field.FieldType.FullName);
}
private bool IsAlsoAnEvent(PropertyInfo property)
{
return IsAlsoAnEvent(property.DeclaringType, property.PropertyType.FullName);
}
private void WriteBaseType(XmlWriter writer, Type type)
{
if (!"System.Object".Equals(type.FullName))
{
writer.WriteStartElement("base");
writer.WriteAttributeString("name", type.Name);
writer.WriteAttributeString("id", MemberID.GetMemberID(type));
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(type));
writer.WriteAttributeString("namespace", type.Namespace);
WriteBaseType(writer, type.BaseType);
writer.WriteEndElement();
}
}
#endregion
#region Members
/// <summary>Writes XML documenting a field.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="field">Field to document.</param>
/// <param name="type">Type containing the field.</param>
/// <param name="hiding">true if hiding base members</param>
private void WriteField(XmlWriter writer, FieldInfo field, Type type, bool hiding)
{
string memberName = MemberID.GetMemberID(field);
writer.WriteStartElement("field");
writer.WriteAttributeString("name", field.Name);
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("access", GetFieldAccessValue(field));
if (field.IsStatic)
{
writer.WriteAttributeString("contract", "Static");
}
else
{
writer.WriteAttributeString("contract", "Normal");
}
Type t = field.FieldType;
#if NET_2_0
writer.WriteAttributeString("type", MemberID.GetTypeName(t, false));
#else
writer.WriteAttributeString("type", MemberID.GetTypeName(t));
#endif
writer.WriteAttributeString("valueType", t.IsValueType.ToString().ToLower());
bool inherited = (field.DeclaringType != field.ReflectedType);
if (inherited)
{
writer.WriteAttributeString("declaringType", MemberID.GetDeclaringTypeName(field));
}
if (!IsMemberSafe(field))
writer.WriteAttributeString("unsafe", "true");
if (hiding)
{
writer.WriteAttributeString("hiding", "true");
}
if (field.IsInitOnly)
{
writer.WriteAttributeString("initOnly", "true");
}
if (field.IsLiteral)
{
writer.WriteAttributeString("literal", "true");
string fieldValue = null;
try
{
fieldValue = GetDisplayValue(field.DeclaringType, field.GetValue(null));
}
catch (Exception e)
{
TraceErrorOutput("Literal value for " + memberName.Substring(2) + " cannot be determined", e);
}
if (fieldValue != null)
{
writer.WriteAttributeString("value", fieldValue);
}
}
if (inherited)
{
WriteInheritedDocumentation(writer, memberName, field.DeclaringType);
}
else
{
WriteFieldDocumentation(writer, memberName, type);
}
WriteCustomAttributes(writer, field);
writer.WriteEndElement();
}
/// <summary>
///
/// </summary>
/// <param name="parent"></param>
/// <param name="value"></param>
/// <returns></returns>
protected string GetDisplayValue(Type parent, object value)
{
if (value == null) return "null";
if (value is string)
{
return (value.ToString());
}
if (value is Enum)
{
if (parent.IsEnum)
{
return Enum.Format(value.GetType(), value, "d");
}
else
{
string enumTypeName = value.GetType().Name;
string enumValue = value.ToString();
string[] enumValues = enumValue.Split(new char[] {','});
if (enumValues.Length > 1)
{
for (int i = 0; i < enumValues.Length; i++)
{
enumValues[i] = enumTypeName + "." + enumValues[i].Trim();
}
return "(" + String.Join("|", enumValues) + ")";
}
else
{
return enumTypeName + "." + enumValue;
}
}
}
return value.ToString();
}
/// <summary>Writes XML documenting an event.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="eventInfo">Event to document.</param>
private void WriteEvent(XmlWriter writer, EventInfo eventInfo)
{
string memberName = MemberID.GetMemberID(eventInfo);
string name = eventInfo.Name;
string interfaceName = null;
int lastIndexOfDot = name.LastIndexOf('.');
if (lastIndexOfDot != -1)
{
//this is an explicit interface implementation. if we don't want
//to document them, get out of here quick...
if (!this.rep.DocumentExplicitInterfaceImplementations) return;
interfaceName = name.Substring(0, lastIndexOfDot);
lastIndexOfDot = interfaceName.LastIndexOf('.');
if (lastIndexOfDot != -1)
name = name.Substring(lastIndexOfDot + 1);
//check if we want to document this interface.
ImplementsInfo implements = null;
MethodInfo adder = eventInfo.GetAddMethod(true);
if (adder != null)
{
implements = implementations[adder.ToString()];
}
if (implements == null)
{
MethodInfo remover = eventInfo.GetRemoveMethod(true);
if (remover != null)
{
implements = implementations[remover.ToString()];
}
}
if (implements != null) return;
}
writer.WriteStartElement("event");
writer.WriteAttributeString("name", name);
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("access", GetMethodAccessValue(eventInfo.GetAddMethod(true)));
writer.WriteAttributeString("contract", GetMethodContractValue(eventInfo.GetAddMethod(true)));
Type t = eventInfo.EventHandlerType;
writer.WriteAttributeString("type", MemberID.GetTypeName(t));
writer.WriteAttributeString("valueType", t.IsValueType.ToString().ToLower());
bool inherited = eventInfo.DeclaringType != eventInfo.ReflectedType;
if (inherited)
{
writer.WriteAttributeString("declaringType", MemberID.GetDeclaringTypeName(eventInfo));
}
if (interfaceName != null)
{
writer.WriteAttributeString("interface", interfaceName);
}
if (eventInfo.IsMulticast)
{
writer.WriteAttributeString("multicast", "true");
}
if (inherited)
{
WriteInheritedDocumentation(writer, memberName, eventInfo.DeclaringType);
}
else
{
WriteEventDocumentation(writer, memberName, true);
}
WriteCustomAttributes(writer, eventInfo);
if (implementations != null)
{
ImplementsInfo implements = null;
MethodInfo adder = eventInfo.GetAddMethod(true);
if (adder != null)
{
implements = implementations[adder.ToString()];
}
if (implements == null)
{
MethodInfo remover = eventInfo.GetRemoveMethod(true);
if (remover != null)
{
implements = implementations[remover.ToString()];
}
}
if (implements != null)
{
writer.WriteStartElement("implements");
MemberInfo InterfaceMethod = (MemberInfo)implements.InterfaceMethod;
EventInfo InterfaceEvent =
InterfaceMethod.DeclaringType.GetEvent(InterfaceMethod.Name.Substring(4));
writer.WriteAttributeString("name", InterfaceEvent.Name);
writer.WriteAttributeString("id", MemberID.GetMemberID(InterfaceEvent));
writer.WriteAttributeString("interface", implements.InterfaceType.Name);
writer.WriteAttributeString("interfaceId", MemberID.GetMemberID(implements.InterfaceType));
writer.WriteAttributeString("declaringType", implements.InterfaceType.FullName.Replace('+', '.'));
writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
/// <summary>Writes XML documenting a constructor.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="constructor">Constructor to document.</param>
/// <param name="overload">If > 0, indicates this is the nth overloaded constructor.</param>
private void WriteConstructor(XmlWriter writer, ConstructorInfo constructor, int overload)
{
string memberName = MemberID.GetMemberID(constructor);
writer.WriteStartElement("constructor");
writer.WriteAttributeString("name", constructor.Name);
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("access", GetMethodAccessValue(constructor));
writer.WriteAttributeString("contract", GetMethodContractValue(constructor));
if (overload > 0)
{
writer.WriteAttributeString("overload", overload.ToString());
}
if (!IsMemberSafe(constructor))
writer.WriteAttributeString("unsafe", "true");
WriteConstructorDocumentation(writer, memberName, constructor);
WriteCustomAttributes(writer, constructor);
foreach (ParameterInfo parameter in constructor.GetParameters())
{
WriteParameter(writer, MemberID.GetMemberID(constructor), parameter);
}
writer.WriteEndElement();
}
/// <summary>Writes XML documenting a property.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="property">Property to document.</param>
/// <param name="inherited">true if a declaringType attribute should be included.</param>
/// <param name="overload">If > 0, indicates this it the nth overloaded method with the same name.</param>
/// <param name="hiding">true if this property is hiding base class members with the same name.</param>
private void WriteProperty(XmlWriter writer, PropertyInfo property, bool inherited, int overload, bool hiding)
{
if (property != null)
{
string memberName = MemberID.GetMemberID(property);
string name = property.Name;
string interfaceName = null;
MethodInfo getter = property.GetGetMethod(true);
MethodInfo setter = property.GetSetMethod(true);
int lastIndexOfDot = name.LastIndexOf('.');
if (lastIndexOfDot != -1)
{
//this is an explicit interface implementation. if we don't want
//to document them, get out of here quick...
if (!this.rep.DocumentExplicitInterfaceImplementations) return;
interfaceName = name.Substring(0, lastIndexOfDot);
lastIndexOfDot = interfaceName.LastIndexOf('.');
if (lastIndexOfDot != -1)
name = name.Substring(lastIndexOfDot + 1);
//check if we want to document this interface.
ImplementsInfo implements = null;
if (getter != null)
{
implements = implementations[getter.ToString()];
}
if (implements == null)
{
if (setter != null)
{
implements = implementations[setter.ToString()];
}
}
if (implements == null) return;
}
writer.WriteStartElement("property");
writer.WriteAttributeString("name", name);
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("access", GetPropertyAccessValue(property));
writer.WriteAttributeString("contract", GetPropertyContractValue(property));
Type t = property.PropertyType;
#if NET_2_0
writer.WriteAttributeString("type", MemberID.GetTypeName(t, false));
#else
writer.WriteAttributeString("type", MemberID.GetTypeName(t));
#endif
writer.WriteAttributeString("valueType", t.IsValueType.ToString().ToLower());
if (inherited)
{
writer.WriteAttributeString("declaringType", MemberID.GetDeclaringTypeName(property));
}
if (overload > 0)
{
writer.WriteAttributeString("overload", overload.ToString());
}
if (!IsMemberSafe(property))
writer.WriteAttributeString("unsafe", "true");
if (hiding)
{
writer.WriteAttributeString("hiding", "true");
}
if (interfaceName != null)
{
writer.WriteAttributeString("interface", interfaceName);
}
writer.WriteAttributeString("get", getter != null ? "true" : "false");
writer.WriteAttributeString("set", setter != null ? "true" : "false");
if (inherited)
{
WriteInheritedDocumentation(writer, memberName, property.DeclaringType);
}
else
{
WritePropertyDocumentation(writer, memberName, property, true);
}
WriteCustomAttributes(writer, property);
if (getter != null)
{
WriteCustomAttributes(writer, getter.ReturnTypeCustomAttributes.GetCustomAttributes(true), "return");
}
foreach (ParameterInfo parameter in GetIndexParameters(property))
{
WriteParameter(writer, memberName, parameter);
}
if (implementations != null)
{
ImplementsInfo implements = null;
if (getter != null)
{
implements = implementations[getter.ToString()];
}
if (implements == null)
{
if (setter != null)
{
implements = implementations[setter.ToString()];
}
}
if (implements != null)
{
MethodInfo InterfaceMethod = (MethodInfo)implements.InterfaceMethod;
PropertyInfo InterfaceProperty = DerivePropertyFromAccessorMethod(InterfaceMethod);
if (InterfaceProperty != null)
{
var interfaceTypeDef = implements.InterfaceType;
if (interfaceTypeDef.IsGenericType)
interfaceTypeDef = interfaceTypeDef.GetGenericTypeDefinition();
string InterfacePropertyID = MemberID.GetMemberID(InterfaceProperty);
writer.WriteStartElement("implements");
writer.WriteAttributeString("name", InterfaceProperty.Name);
writer.WriteAttributeString("id", InterfacePropertyID);
writer.WriteAttributeString("interface", implements.InterfaceType.Name);
writer.WriteAttributeString("interfaceId", MemberID.GetMemberID(implements.InterfaceType));
writer.WriteAttributeString("declaringType", interfaceTypeDef.FullName.Replace('+', '.'));
writer.WriteEndElement();
}
else if (InterfaceMethod != null)
{
string InterfaceMethodID = MemberID.GetMemberID(InterfaceMethod);
writer.WriteStartElement("implements");
writer.WriteAttributeString("name", InterfaceMethod.Name);
writer.WriteAttributeString("id", InterfaceMethodID);
writer.WriteAttributeString("interface", implements.InterfaceType.Name);
writer.WriteAttributeString("interfaceId", MemberID.GetMemberID(implements.InterfaceType));
writer.WriteAttributeString("declaringType", implements.InterfaceType.FullName.Replace('+', '.'));
writer.WriteEndElement();
}
}
}
writer.WriteEndElement();
}
}
private PropertyInfo DerivePropertyFromAccessorMethod(MemberInfo accessor)
{
MethodInfo accessorMethod = (MethodInfo)accessor;
string accessortype = accessorMethod.Name.Substring(0, 3);
string propertyName = accessorMethod.Name.Substring(4);
ParameterInfo[] parameters;
parameters = accessorMethod.GetParameters();
int parmCount = parameters.GetLength(0);
Type returnType = null;
Type[] types = null;
if (accessortype == "get")
{
returnType = accessorMethod.ReturnType;
types = new Type[parmCount];
for (int i = 0; i < parmCount; i++)
{
types[i] = ((ParameterInfo)parameters.GetValue(i)).ParameterType;
}
}
else
{
returnType = ((ParameterInfo)parameters.GetValue(parmCount - 1)).ParameterType;
parmCount--;
types = new Type[parmCount];
for (int i = 0; i < parmCount; i++)
{
types[i] = ((ParameterInfo)parameters.GetValue(i + 1)).ParameterType;
}
}
PropertyInfo derivedProperty = accessorMethod.DeclaringType.GetProperty(propertyName, returnType, types);
return derivedProperty;
}
private string GetPropertyContractValue(PropertyInfo property)
{
return GetMethodContractValue(property.GetAccessors(true)[0]);
}
private ParameterInfo[] GetIndexParameters(PropertyInfo property)
{
// The ParameterInfo[] returned by GetIndexParameters()
// contains ParameterInfo objects with empty names so
// we have to get the parameters from the getter or
// setter instead.
ParameterInfo[] parameters;
int length = 0;
if (property.GetGetMethod(true) != null)
{
parameters = property.GetGetMethod(true).GetParameters();
if (parameters != null)
{
length = parameters.Length;
}
}
else
{
parameters = property.GetSetMethod(true).GetParameters();
if (parameters != null)
{
// If the indexer only has a setter, we neet
// to subtract 1 so that the value parameter
// isn't displayed.
length = parameters.Length - 1;
}
}
ParameterInfo[] result = new ParameterInfo[length];
if (length > 0)
{
for (int i = 0; i < length; ++i)
{
result[i] = parameters[i];
}
}
return result;
}
/// <summary>Writes XML documenting a method.</summary>
/// <param name="writer">XmlWriter to write on.</param>
/// <param name="method">Method to document.</param>
/// <param name="inherited">true if a declaringType attribute should be included.</param>
/// <param name="overload">If > 0, indicates this it the nth overloaded method with the same name.</param>
/// <param name="hiding">true if this method hides methods of the base class with the same signature.</param>
private void WriteMethod(XmlWriter writer, MethodInfo method, bool inherited, int overload, bool hiding)
{
if (method != null)
{
string memberName = MemberID.GetMemberID(method);
string name = method.Name;
string interfaceName = null;
name = name.Replace('+', '.');
int lastIndexOfDot = name.LastIndexOf('.');
if (lastIndexOfDot != -1)
{
//this is an explicit interface implementation. if we don't want
//to document them, get out of here quick...
if (!this.rep.DocumentExplicitInterfaceImplementations) return;
interfaceName = name.Substring(0, lastIndexOfDot);
lastIndexOfDot = interfaceName.LastIndexOf('.');
if (lastIndexOfDot != -1)
name = name.Substring(lastIndexOfDot + 1);
//check if we want to document this interface.
ImplementsInfo implements = implementations[method.ToString()];
if (implements == null) return;
}
writer.WriteStartElement("method");
writer.WriteAttributeString("name", name);
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("access", GetMethodAccessValue(method));
writer.WriteAttributeString("contract", GetMethodContractValue(method));
Type t = method.ReturnType;
writer.WriteAttributeString("returnType", MemberID.GetTypeName(t));
writer.WriteAttributeString("valueType", t.IsValueType.ToString().ToLower());
if (inherited)
{
writer.WriteAttributeString("declaringType", MemberID.GetDeclaringTypeName(method));
}
if (overload > 0)
{
writer.WriteAttributeString("overload", overload.ToString());
}
if (!IsMemberSafe(method))
writer.WriteAttributeString("unsafe", "true");
if (hiding)
{
writer.WriteAttributeString("hiding", "true");
}
if (interfaceName != null)
{
writer.WriteAttributeString("interface", interfaceName);
}
if (inherited)
{
WriteInheritedDocumentation(writer, memberName, method.DeclaringType);
}
else
{
WriteMethodDocumentation(writer, memberName, method, true);
}
WriteCustomAttributes(writer, method);
foreach (ParameterInfo parameter in method.GetParameters())
{
WriteParameter(writer, MemberID.GetMemberID(method), parameter);
}
if (implementations != null)
{
ImplementsInfo implements = implementations[method.ToString()];
if (implements != null)
{
var interfaceTypeDef = implements.InterfaceType;
if (interfaceTypeDef.IsGenericType)
interfaceTypeDef = interfaceTypeDef.GetGenericTypeDefinition();
writer.WriteStartElement("implements");
writer.WriteAttributeString("name", implements.InterfaceMethod.Name);
writer.WriteAttributeString("id", MemberID.GetMemberID((MethodBase)implements.InterfaceMethod));
writer.WriteAttributeString("interface", MemberDisplayName.GetMemberDisplayName(implements.InterfaceType));
writer.WriteAttributeString("interfaceId", MemberID.GetMemberID(implements.InterfaceType));
writer.WriteAttributeString("declaringType", interfaceTypeDef.FullName.Replace('+', '.'));
writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
}
private void WriteParameter(XmlWriter writer, string memberName, ParameterInfo parameter)
{
string direction = "in";
bool isParamArray = false;
if (parameter.ParameterType.IsByRef)
{
direction = parameter.IsOut ? "out" : "ref";
}
if (parameter.GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0)
{
isParamArray = true;
}
writer.WriteStartElement("parameter");
writer.WriteAttributeString("name", parameter.Name);
Type t = parameter.ParameterType;
#if NET_2_0
writer.WriteAttributeString("type", MemberID.GetTypeName(t, false));
#else
writer.WriteAttributeString("type", MemberID.GetTypeName(t));
#endif
writer.WriteAttributeString("valueType", t.IsValueType.ToString().ToLower());
if (t.IsPointer)
writer.WriteAttributeString("unsafe", "true");
if (parameter.IsOptional)
{
writer.WriteAttributeString("optional", "true");
if (parameter.DefaultValue != null)
{
writer.WriteAttributeString("defaultValue", parameter.DefaultValue.ToString());
}
else
{
//HACK: assuming this is only for VB syntax
writer.WriteAttributeString("defaultValue", "Nothing");
}
}
if (direction != "in")
{
writer.WriteAttributeString("direction", direction);
}
if (isParamArray)
{
writer.WriteAttributeString("isParamArray", "true");
}
WriteCustomAttributes(writer, parameter);
writer.WriteEndElement();
}
private void WriteOperator(XmlWriter writer, MethodInfo method, int overload)
{
if (method != null)
{
string memberName = MemberID.GetMemberID(method);
writer.WriteStartElement("operator");
writer.WriteAttributeString("name", method.Name);
writer.WriteAttributeString("id", memberName);
writer.WriteAttributeString("access", GetMethodAccessValue(method));
writer.WriteAttributeString("contract", GetMethodContractValue(method));
Type t = method.ReturnType;
writer.WriteAttributeString("returnType", MemberID.GetTypeName(t));
writer.WriteAttributeString("valueType", t.IsValueType.ToString().ToLower());
bool inherited = method.DeclaringType != method.ReflectedType;
if (inherited)
{
writer.WriteAttributeString("declaringType", MemberID.GetDeclaringTypeName(method));
}
if (overload > 0)
{
writer.WriteAttributeString("overload", overload.ToString());
}
if (!IsMemberSafe(method))
writer.WriteAttributeString("unsafe", "true");
if (inherited)
{
WriteInheritedDocumentation(writer, memberName, method.DeclaringType);
}
else
{
WriteMethodDocumentation(writer, memberName, method, true);
}
WriteCustomAttributes(writer, method);
foreach (ParameterInfo parameter in method.GetParameters())
{
WriteParameter(writer, MemberID.GetMemberID(method), parameter);
}
writer.WriteEndElement();
}
}
#endregion
#region IsMemberSafe
private bool IsMemberSafe(FieldInfo field)
{
return!field.FieldType.IsPointer;
}
private bool IsMemberSafe(PropertyInfo property)
{
return!property.PropertyType.IsPointer;
}
private bool IsMemberSafe(MethodBase method)
{
foreach (ParameterInfo parameter in method.GetParameters())
{
if (parameter.GetType().IsPointer)
return false;
}
return true;
}
private bool IsMemberSafe(MethodInfo method)
{
if (method.ReturnType.IsPointer)
return false;
return IsMemberSafe((MethodBase)method);
}
#endregion
#region Get MemberID of base of inherited member
//TODO: Refactor into get base member and then use MemberID to get ID
/// <summary>Used by GetFullNamespaceName(MemberInfo member) functions to build
/// up most of the /doc member name.</summary>
/// <param name="type"></param>
private string GetTypeNamespaceName(Type type)
{
if (type.IsGenericType)
type = type.GetGenericTypeDefinition();
return type.FullName.Replace('+', '.');
}
/// <summary>Derives the member name ID for the base of an inherited field.</summary>
/// <param name="field">The field to derive the member name ID from.</param>
/// <param name="declaringType">The declaring type.</param>
private string GetMemberName(FieldInfo field, Type declaringType)
{
if (declaringType.IsGenericType)
declaringType = declaringType.GetGenericTypeDefinition();
return "F:" + declaringType.FullName.Replace("+", ".") + "." + field.Name;
}
/// <summary>Derives the member name ID for an event. Used to match nodes in the /doc XML.</summary>
/// <param name="eventInfo">The event to derive the member name ID from.</param>
/// <param name="declaringType">The declaring type.</param>
private string GetMemberName(EventInfo eventInfo, Type declaringType)
{
if (declaringType.IsGenericType)
declaringType = declaringType.GetGenericTypeDefinition();
return "E:" + declaringType.FullName.Replace("+", ".") +
"." + eventInfo.Name.Replace('.', '#').Replace('+', '#');
}
/// <summary>Derives the member name ID for the base of an inherited property.</summary>
/// <param name="property">The property to derive the member name ID from.</param>
/// <param name="declaringType">The declaring type.</param>
private string GetMemberName(PropertyInfo property, Type declaringType)
{
string memberID = MemberID.GetMemberID(property);
//extract member type (T:, P:, etc.)
string memberType = memberID.Substring(0, 2);
//extract member name
int i = memberID.IndexOf('(');
string memberName;
if (i > -1)
{
memberName = memberID.Substring(memberID.LastIndexOf('.', i) + 1);
}
else
{
memberName = memberID.Substring(memberID.LastIndexOf('.') + 1);
}
//the member id in the declaring type
string key = memberType + GetTypeNamespaceName(declaringType) + "." + memberName;
return key;
}
/// <summary>Derives the member name ID for the basse of an inherited member function.</summary>
/// <param name="method">The method to derive the member name ID from.</param>
/// <param name="declaringType">The declaring type.</param>
private string GetMemberName(MethodBase method, Type declaringType)
{
string memberID = MemberID.GetMemberID(method);
//extract member type (T:, P:, etc.)
string memberType = memberID.Substring(0, 2);
//extract member name
int i = memberID.IndexOf('(');
string memberName;
if (i > -1)
{
memberName = memberID.Substring(memberID.LastIndexOf('.', i) + 1);
}
else
{
memberName = memberID.Substring(memberID.LastIndexOf('.') + 1);
}
//the member id in the declaring type
string key = memberType + GetTypeNamespaceName(declaringType) + "." + memberName;
return key;
}
#endregion
#region Enumeration Values
private string GetTypeAccessValue(Type type)
{
string result = "Unknown";
switch (type.Attributes & TypeAttributes.VisibilityMask)
{
case TypeAttributes.Public :
result = "Public";
break;
case TypeAttributes.NotPublic :
result = "NotPublic";
break;
case TypeAttributes.NestedPublic :
result = "NestedPublic";
break;
case TypeAttributes.NestedFamily :
result = "NestedFamily";
break;
case TypeAttributes.NestedFamORAssem :
if (this.rep.DocumentProtectedInternalAsProtected)
{
result = "NestedFamily";
}
else
{
result = "NestedFamilyOrAssembly";
}
break;
case TypeAttributes.NestedAssembly :
result = "NestedAssembly";
break;
case TypeAttributes.NestedFamANDAssem :
result = "NestedFamilyAndAssembly";
break;
case TypeAttributes.NestedPrivate :
result = "NestedPrivate";
break;
}
return result;
}
private string GetFieldAccessValue(FieldInfo field)
{
string result = "Unknown";
switch (field.Attributes & FieldAttributes.FieldAccessMask)
{
case FieldAttributes.Public :
result = "Public";
break;
case FieldAttributes.Family :
result = "Family";
break;
case FieldAttributes.FamORAssem :
if (this.rep.DocumentProtectedInternalAsProtected)
{
result = "Family";
}
else
{
result = "FamilyOrAssembly";
}
break;
case FieldAttributes.Assembly :
result = "Assembly";
break;
case FieldAttributes.FamANDAssem :
result = "FamilyAndAssembly";
break;
case FieldAttributes.Private :
result = "Private";
break;
case FieldAttributes.PrivateScope :
result = "PrivateScope";
break;
}
return result;
}
private string GetPropertyAccessValue(PropertyInfo property)
{
MethodInfo method;
if (property.GetGetMethod(true) != null)
{
method = property.GetGetMethod(true);
}
else
{
method = property.GetSetMethod(true);
}
return GetMethodAccessValue(method);
}
private string GetMethodAccessValue(MethodBase method)
{
string result;
switch (method.Attributes & MethodAttributes.MemberAccessMask)
{
case MethodAttributes.Public :
result = "Public";
break;
case MethodAttributes.Family :
result = "Family";
break;
case MethodAttributes.FamORAssem :
if (this.rep.DocumentProtectedInternalAsProtected)
{
result = "Family";
}
else
{
result = "FamilyOrAssembly";
}
break;
case MethodAttributes.Assembly :
result = "Assembly";
break;
case MethodAttributes.FamANDAssem :
result = "FamilyAndAssembly";
break;
case MethodAttributes.Private :
result = "Private";
break;
case MethodAttributes.PrivateScope :
result = "PrivateScope";
break;
default :
result = "Unknown";
break;
}
return result;
}
private string GetMethodContractValue(MethodBase method)
{
string result;
MethodAttributes methodAttributes = method.Attributes;
if ((methodAttributes & MethodAttributes.Static) > 0)
{
result = "Static";
}
else if ((methodAttributes & MethodAttributes.Abstract) > 0)
{
result = "Abstract";
}
else if ((methodAttributes & MethodAttributes.Final) > 0)
{
result = "Final";
}
else if ((methodAttributes & MethodAttributes.Virtual) > 0)
{
if ((methodAttributes & MethodAttributes.NewSlot) > 0)
{
result = "Virtual";
}
else
{
result = "Override";
}
}
else
{
result = "Normal";
}
return result;
}
#endregion
private StringCollection GetNamespaceNames(Type[] types)
{
StringCollection namespaceNames = new StringCollection();
foreach (Type type in types)
{
if (namespaceNames.Contains(type.Namespace) == false)
{
namespaceNames.Add(type.Namespace);
}
}
return namespaceNames;
}
#region Missing Documentation
private void CheckForMissingSummaryAndRemarks(
XmlWriter writer,
string memberName)
{
if (this.rep.ShowMissingSummaries)
{
bool bMissingSummary = true;
string xmldoc = assemblyDocCache.GetDoc(memberName);
if (xmldoc != null)
{
XmlTextReader reader = new XmlTextReader(xmldoc, XmlNodeType.Element, null);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "summary")
{
string summarydetails = reader.ReadInnerXml();
if (summarydetails.Length > 0 && !summarydetails.Trim().StartsWith("Summary description for"))
{
bMissingSummary = false;
break;
}
}
}
}
}
if (bMissingSummary)
{
WriteMissingDocumentation(writer, "summary", null,
"Missing <summary> documentation for " + memberName);
//Debug.WriteLine("@@missing@@\t" + memberName);
}
}
if (this.rep.ShowMissingRemarks)
{
bool bMissingRemarks = true;
string xmldoc = assemblyDocCache.GetDoc(memberName);
if (xmldoc != null)
{
XmlTextReader reader = new XmlTextReader(xmldoc, XmlNodeType.Element, null);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "remarks")
{
string remarksdetails = reader.ReadInnerXml();
if (remarksdetails.Length > 0)
{
bMissingRemarks = false;
break;
}
}
}
}
}
if (bMissingRemarks)
{
WriteMissingDocumentation(writer, "remarks", null,
"Missing <remarks> documentation for " + memberName);
}
}
}
private void CheckForMissingParams(
XmlWriter writer,
string memberName,
ParameterInfo[] parameters)
{
if (this.rep.ShowMissingParams)
{
string xmldoc = assemblyDocCache.GetDoc(memberName);
foreach (ParameterInfo parameter in parameters)
{
bool bMissingParams = true;
if (xmldoc != null)
{
XmlTextReader reader = new XmlTextReader(xmldoc, XmlNodeType.Element, null);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "param")
{
string name = reader.GetAttribute("name");
if (name == parameter.Name)
{
string paramsdetails = reader.ReadInnerXml();
if (paramsdetails.Length > 0)
{
bMissingParams = false;
break; // we can stop if we locate what we are looking for
}
}
}
}
}
}
if (bMissingParams)
{
WriteMissingDocumentation(writer, "param", parameter.Name,
"Missing <param> documentation for " + parameter.Name);
}
}
}
}
private void CheckForMissingReturns(
XmlWriter writer,
string memberName,
MethodInfo method)
{
if (this.rep.ShowMissingReturns &&
!"System.Void".Equals(method.ReturnType.FullName))
{
string xmldoc = assemblyDocCache.GetDoc(memberName);
bool bMissingReturns = true;
if (xmldoc != null)
{
XmlTextReader reader = new XmlTextReader(xmldoc, XmlNodeType.Element, null);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "returns")
{
string returnsdetails = reader.ReadInnerXml();
if (returnsdetails.Length > 0)
{
bMissingReturns = false;
break; // we can stop if we locate what we are looking for
}
}
}
}
}
if (bMissingReturns)
{
WriteMissingDocumentation(writer, "returns", null,
"Missing <returns> documentation for " + memberName);
}
}
}
private void CheckForMissingValue(
XmlWriter writer,
string memberName)
{
if (this.rep.ShowMissingValues)
{
string xmldoc = assemblyDocCache.GetDoc(memberName);
bool bMissingValues = true;
if (xmldoc != null)
{
XmlTextReader reader = new XmlTextReader(xmldoc, XmlNodeType.Element, null);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "value")
{
string valuesdetails = reader.ReadInnerXml();
if (valuesdetails.Length > 0)
{
bMissingValues = false;
break; // we can stop if we locate what we are looking for
}
}
}
}
}
if (bMissingValues)
{
WriteMissingDocumentation(writer, "values", null,
"Missing <values> documentation for " + memberName);
}
}
}
private void WriteMissingDocumentation(
XmlWriter writer,
string element,
string name,
string message)
{
WriteStartDocumentation(writer);
writer.WriteStartElement(element);
if (name != null)
{
writer.WriteAttributeString("name", name);
}
writer.WriteStartElement("span");
writer.WriteAttributeString("class", "missing");
writer.WriteString(message);
writer.WriteEndElement();
writer.WriteEndElement();
}
#endregion
#region Write Documentation
private bool didWriteStartDocumentation = false;
private void WriteStartDocumentation(XmlWriter writer)
{
if (!didWriteStartDocumentation)
{
writer.WriteStartElement("documentation");
didWriteStartDocumentation = true;
}
}
private void WriteEndDocumentation(XmlWriter writer)
{
if (didWriteStartDocumentation)
{
writer.WriteEndElement();
didWriteStartDocumentation = false;
}
}
private void WriteSlashDocElements(XmlWriter writer, string memberName)
{
string temp = assemblyDocCache.GetDoc(memberName);
if (temp != null)
{
WriteStartDocumentation(writer);
writer.WriteRaw(temp);
}
}
private void WriteInheritedDocumentation(
XmlWriter writer,
string memberName,
Type declaringType)
{
#if NET_2_0
if (declaringType.IsGenericType) declaringType = declaringType.GetGenericTypeDefinition();
#endif
string summary = externalSummaryCache.GetSummary(memberName, declaringType);
if (summary.Length > 0)
{
WriteStartDocumentation(writer);
writer.WriteRaw(summary);
WriteEndDocumentation(writer);
}
}
private void WriteTypeDocumentation(
XmlWriter writer,
string memberName,
Type type)
{
CheckForMissingSummaryAndRemarks(writer, memberName);
WriteSlashDocElements(writer, memberName);
WriteEndDocumentation(writer);
}
private void WriteDelegateDocumentation(
XmlWriter writer,
string memberName,
Type type,
MethodInfo method)
{
CheckForMissingParams(writer, memberName, method.GetParameters());
CheckForMissingReturns(writer, memberName, method);
WriteTypeDocumentation(writer, memberName, type);
WriteEndDocumentation(writer);
}
private void WriteEnumerationDocumentation(XmlWriter writer, string memberName)
{
CheckForMissingSummaryAndRemarks(writer, memberName);
WriteSlashDocElements(writer, memberName);
WriteEndDocumentation(writer);
}
//if the constructor has no parameters and no summary,
//add a default summary text.
private bool DoAutoDocumentConstructor(
XmlWriter writer,
string memberName,
ConstructorInfo constructor)
{
if (rep.AutoDocumentConstructors)
{
if (constructor.GetParameters().Length == 0)
{
string xmldoc = assemblyDocCache.GetDoc(memberName);
bool bMissingSummary = true;
if (xmldoc != null)
{
XmlTextReader reader = new XmlTextReader(xmldoc, XmlNodeType.Element, null);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "summary")
{
string summarydetails = reader.ReadInnerXml();
if (summarydetails.Length > 0 && !summarydetails.Trim().StartsWith("Summary description for"))
{
bMissingSummary = false;
}
}
}
}
}
if (bMissingSummary)
{
WriteStartDocumentation(writer);
writer.WriteStartElement("summary");
if (constructor.IsStatic)
{
writer.WriteString("Initializes the static fields of the ");
}
else
{
writer.WriteString("Initializes a new instance of the ");
}
writer.WriteStartElement("see");
writer.WriteAttributeString("cref", MemberID.GetMemberID(constructor.DeclaringType));
writer.WriteEndElement();
writer.WriteString(" class.");
writer.WriteEndElement();
return true;
}
}
}
return false;
}
private void WriteConstructorDocumentation(
XmlWriter writer,
string memberName,
ConstructorInfo constructor)
{
if (!DoAutoDocumentConstructor(writer, memberName, constructor))
{
CheckForMissingSummaryAndRemarks(writer, memberName);
CheckForMissingParams(writer, memberName, constructor.GetParameters());
}
WriteSlashDocElements(writer, memberName);
WriteEndDocumentation(writer);
}
private void WriteFieldDocumentation(
XmlWriter writer,
string memberName,
Type type)
{
if (!CheckForPropertyBacker(writer, memberName, type))
{
CheckForMissingSummaryAndRemarks(writer, memberName);
}
WriteSlashDocElements(writer, memberName);
WriteEndDocumentation(writer);
}
private void WritePropertyDocumentation(
XmlWriter writer,
string memberName,
PropertyInfo property,
bool writeMissing)
{
if (writeMissing)
{
CheckForMissingSummaryAndRemarks(writer, memberName);
CheckForMissingParams(writer, memberName, GetIndexParameters(property));
CheckForMissingValue(writer, memberName);
}
WriteSlashDocElements(writer, memberName);
WriteEndDocumentation(writer);
}
private void WriteMethodDocumentation(
XmlWriter writer,
string memberName,
MethodInfo method,
bool writeMissing)
{
if (writeMissing)
{
CheckForMissingSummaryAndRemarks(writer, memberName);
CheckForMissingParams(writer, memberName, method.GetParameters());
CheckForMissingReturns(writer, memberName, method);
}
WriteSlashDocElements(writer, memberName);
WriteEndDocumentation(writer);
}
private void WriteEventDocumentation(
XmlWriter writer,
string memberName,
bool writeMissing)
{
if (writeMissing)
{
CheckForMissingSummaryAndRemarks(writer, memberName);
}
WriteSlashDocElements(writer, memberName);
WriteEndDocumentation(writer);
}
#endregion
#region Property Backers
/// <summary>
/// This checks whether a field is a property backer, meaning
/// it stores the information for the property.
/// </summary>
/// <remarks>
/// <para>This takes advantage of the fact that most people
/// have a simple convention for the names of the fields
/// and the properties that they back.
/// If the field doesn't have a summary already, and it
/// looks like it backs a property, and the BaseDocumenterConfig
/// property is set appropriately, then this adds a
/// summary indicating that.</para>
/// <para>Note that this design will call multiple fields the
/// backer for a single property.</para>
/// <para/>This also will call a public field a backer for a
/// property, when typically that wouldn't be the case.
/// </remarks>
/// <param name="writer">The XmlWriter to write to.</param>
/// <param name="memberName">The full name of the field.</param>
/// <param name="type">The Type which contains the field
/// and potentially the property.</param>
/// <returns>True only if a property backer is auto-documented.</returns>
private bool CheckForPropertyBacker(
XmlWriter writer,
string memberName,
Type type)
{
if (!this.rep.AutoPropertyBackerSummaries) return false;
// determine if field is non-public
// (because public fields are probably not backers for properties)
bool isNonPublic = true; // stubbed out for now
//check whether or not we have a valid summary
bool isMissingSummary = true;
string xmldoc = assemblyDocCache.GetDoc(memberName);
if (xmldoc != null)
{
XmlTextReader reader = new XmlTextReader(xmldoc, XmlNodeType.Element, null);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "summary")
{
string summarydetails = reader.ReadInnerXml();
if (summarydetails.Length > 0 && !summarydetails.Trim().StartsWith("Summary description for"))
{
isMissingSummary = false;
}
}
}
}
}
// only do this if there is no summary already
if (isMissingSummary && isNonPublic)
{
// find the property (if any) that this field backs
// generate the possible property names that this could back
// so far have: property Name could be backed by _Name or name
// but could be other conventions
string[] words = memberName.Split('.');
string fieldBaseName = words[words.Length - 1];
string firstLetter = fieldBaseName.Substring(0, 1);
string camelCasePropertyName = firstLetter.ToUpper()
+ fieldBaseName.Remove(0, 1);
string usPropertyName = fieldBaseName.Replace("_", "");
// find it
PropertyInfo propertyInfo;
if (((propertyInfo = FindProperty(camelCasePropertyName,
type)) != null)
|| ((propertyInfo = FindProperty(usPropertyName,
type)) != null))
{
WritePropertyBackerDocumentation(writer, "summary",
propertyInfo);
return true;
}
}
return false;
}
/// <summary>
/// Find a particular property of the specified type, by name.
/// Return the PropertyInfo for it.
/// </summary>
/// <param name="expectedPropertyName">The name of the property to
/// find.</param>
/// <param name="type">The type in which to search for
/// the property.</param>
/// <returns>PropertyInfo - The property info, or null for
/// not found.</returns>
private PropertyInfo FindProperty(string expectedPropertyName,
Type type)
{
const BindingFlags bindingFlags =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
PropertyInfo[] properties = type.GetProperties(bindingFlags);
foreach (PropertyInfo property in properties)
{
if (property.Name.Equals(expectedPropertyName))
{
MethodInfo getMethod = property.GetGetMethod(true);
MethodInfo setMethod = property.GetSetMethod(true);
bool hasGetter = (getMethod != null) && MustDocumentMethod(getMethod);
bool hasSetter = (setMethod != null) && MustDocumentMethod(setMethod);
if ((hasGetter || hasSetter) && !IsAlsoAnEvent(property))
{
return (property);
}
}
}
return (null);
}
/// <summary>
/// Write xml info for a property's backer field to the specified writer.
/// This writes a string with a link to the property.
/// </summary>
/// <param name="writer">The XmlWriter to write to.</param>
/// <param name="element">The field which backs the property.</param>
/// <param name="property">The property backed by the field.</param>
private void WritePropertyBackerDocumentation(
XmlWriter writer,
string element,
PropertyInfo property)
{
string propertyName = property.Name;
string propertyId = "P:" + property.DeclaringType.FullName + "."
+ propertyName;
WriteStartDocumentation(writer);
writer.WriteStartElement(element);
writer.WriteRaw("Backer for property <see cref=\""
+ propertyId + "\">" + property.Name + "</see>");
writer.WriteEndElement();
}
#endregion
#region PreReflectionProcess
private void PreReflectionProcess()
{
PreLoadXmlDocumentation();
BuildXrefs();
}
private void PreLoadXmlDocumentation()
{
if (assemblyDocCache == null) assemblyDocCache = new AssemblyXmlDocCache();
//preload all xml documentation
foreach (string xmlDocFilename in this.rep.XmlDocFileNames)
{
externalSummaryCache.AddXmlDoc(xmlDocFilename);
assemblyDocCache.CacheDocFile(xmlDocFilename);
}
}
private void BuildXrefs()
{
//build derived members and implementing types xrefs.
foreach (string assemblyFileName in this.rep.AssemblyFileNames)
{
//attempt to load the assembly
Assembly assembly = assemblyLoader.LoadAssembly(assemblyFileName);
// loop through all types in assembly
foreach (Type type in assembly.GetTypes())
{
if (MustDocumentType(type))
{
BuildDerivedMemberXref(type);
BuildDerivedInterfaceXref(type);
string friendlyNamespaceName;
if (type.Namespace == null)
{
friendlyNamespaceName = "(global)";
}
else
{
friendlyNamespaceName = type.Namespace;
}
BuildNamespaceHierarchy(friendlyNamespaceName, type);
notEmptyNamespaces[friendlyNamespaceName] = null;
}
}
}
}
private void BuildDerivedMemberXref(Type type)
{
if (type.BaseType != null &&
MustDocumentType(type.BaseType)) // we don't care about undocumented types
{
derivedTypes.Add(type.BaseType, type);
}
}
private void BuildNamespaceHierarchy(string namespaceName, Type type)
{
if ((type.BaseType != null) &&
MustDocumentType(type.BaseType)) // we don't care about undocumented types
{
namespaceHierarchies.Add(namespaceName, type.BaseType, type);
BuildNamespaceHierarchy(namespaceName, type.BaseType);
}
if (type.IsInterface)
{
namespaceHierarchies.Add(namespaceName, typeof(System.Object), type /*.BaseType*/);
}
//build a collection of the base type's interfaces
//to determine which have been inherited
StringCollection interfacesOnBase = new StringCollection();
if (type.BaseType != null)
{
foreach (Type baseInterfaceType in type.BaseType.GetInterfaces())
{
interfacesOnBase.Add(MemberID.GetMemberID(baseInterfaceType));
}
}
foreach (Type interfaceType in type.GetInterfaces())
{
if (MustDocumentType(interfaceType))
{
if (!interfacesOnBase.Contains(MemberID.GetMemberID(interfaceType)))
{
baseInterfaces.Add(type, interfaceType);
}
}
}
}
private void BuildDerivedInterfaceXref(Type type)
{
foreach (Type interfaceType in type.GetInterfaces())
{
if (MustDocumentType(interfaceType)) // we don't care about undocumented types
{
if (type.IsInterface)
{
derivedTypes.Add(interfaceType, type);
}
else
{
interfaceImplementingTypes.Add(interfaceType, type);
}
}
}
}
#endregion
#region Write Hierarchies
private void WriteDerivedTypes(XmlWriter writer, Type type)
{
foreach (Type derived in derivedTypes.GetDerivedTypes(type))
{
writer.WriteStartElement("derivedBy");
writer.WriteAttributeString("id", MemberID.GetMemberID(derived));
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(derived));
writer.WriteAttributeString("namespace", derived.Namespace);
writer.WriteEndElement();
}
}
private void WriteInterfaceImplementingTypes(XmlWriter writer, Type type)
{
foreach (Type implementingType in interfaceImplementingTypes.GetDerivedTypes(type))
{
writer.WriteStartElement("implementedBy");
writer.WriteAttributeString("id", MemberID.GetMemberID(implementingType));
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(implementingType));
writer.WriteAttributeString("namespace", implementingType.Namespace);
writer.WriteEndElement();
}
}
private void WriteNamespaceHierarchies(XmlWriter writer)
{
writer.WriteStartElement("namespaceHierarchies");
foreach (string namespaceName in namespaceHierarchies.DefinedNamespaces)
{
WriteNamespaceTypeHierarchy(writer, namespaceName);
}
writer.WriteEndElement();
}
private void WriteNamespaceTypeHierarchy(XmlWriter writer, string namespaceName)
{
//get all base types from which members of this namespace are derived
TypeHierarchy derivedTypesCollection = namespaceHierarchies.GetDerivedTypesCollection(namespaceName);
if (derivedTypesCollection != null)
{
//we will always start the hierarchy with System.Object (hopefully for obvious reasons)
writer.WriteStartElement("namespaceHierarchy");
writer.WriteAttributeString("name", namespaceName);
WriteTypeHierarchy(writer, derivedTypesCollection, typeof(System.Object));
writer.WriteEndElement();
}
}
private void WriteTypeHierarchy(XmlWriter writer, TypeHierarchy derivedTypes, Type type)
{
writer.WriteStartElement("hierarchyType");
writer.WriteAttributeString("id", MemberID.GetMemberID(type));
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(type));
writer.WriteAttributeString("namespace", type.Namespace);
ArrayList interfaces = baseInterfaces.GetDerivedTypes(type);
if (interfaces.Count > 0)
{
writer.WriteStartElement("hierarchyInterfaces");
foreach (Type baseInterfaceType in interfaces)
{
writer.WriteStartElement("hierarchyInterface");
writer.WriteAttributeString("id", MemberID.GetMemberID(baseInterfaceType));
writer.WriteAttributeString("displayName", MemberDisplayName.GetMemberDisplayName(baseInterfaceType));
writer.WriteAttributeString("namespace", baseInterfaceType.Namespace);
writer.WriteAttributeString("fullName", baseInterfaceType.FullName);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
ArrayList childTypesList = derivedTypes.GetDerivedTypes(type);
foreach (Type childType in childTypesList)
{
WriteTypeHierarchy(writer, derivedTypes, childType);
}
writer.WriteEndElement();
}
#endregion
private void TraceErrorOutput(string message, Exception ex)
{
Trace.WriteLine("[WARNING] " + message);
if (ex != null)
{
Exception tempEx = ex;
do
{
Trace.WriteLine("-> " + tempEx.GetType().ToString() + ":" + ex.Message);
tempEx = tempEx.InnerException;
} while (tempEx != null);
Trace.WriteLine(ex.StackTrace);
}
}
private AssemblyLoader SetupAssemblyLoader()
{
AssemblyLoader assemblyLoader = new AssemblyLoader(rep.ReferencePaths);
assemblyLoader.Install();
return (assemblyLoader);
}
#region ImplementsInfo
private class ImplementsInfo
{
public Type TargetType;
public MemberInfo TargetMethod;
public Type InterfaceType;
public MemberInfo InterfaceMethod;
}
private class ImplementsCollection
{
private Hashtable data;
public ImplementsCollection()
{
data = new Hashtable(15); // give it an initial capacity...
}
public ImplementsInfo this[string name]
{
get { return (ImplementsInfo)data[name]; }
set { data[name] = value; }
}
}
#endregion
}
}
| hmah/boo | tools/ndoc/src/Core/ReflectionEngine/ReflectionEngine.cs | C# | bsd-3-clause | 110,255 |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
function CoayoloDAO(){
if (false === (this instanceof CoayoloDAO)) {
console.log('Warning: CoayoloDAO constructor called without "new" operator');
return new CoayoloDAO();
}
//fix
this.Alumno = new Schema({
//hay dos campos que pueden usarse como id_alumno con cual nos vamos aquedar
id_alumno : Number,
id_avatar : Number,
matricula : String,
email : String,
pass : String,
nombre_usu : String,
id_avatar : Number,
sexo : String,
pass : String,
fecha_nacimiento : String,
escuela : [],
casa : [],
misiones : []
});
/*
db.alumnos.insert({
id_alumno : 0, id_avatar : 0, matricula : 'whatever', id_avatar : 0,nombre_usu : 'none', sexo : 'hombre', pass : 'none',
id_casa : 0, fecha_nacimiento : new Date(), area : [{ id_area : 0, nombre_area : 'hola'}], escuela : [{id_escuela : 0, nombre_escuela : 'ctin'}],
misiones : [{id_mision : 0, nombre_mision : 'marte', avance : 0, fecha_ini_mision : new Date()}]
})
*/
this.Casa = new Schema({
id_casa : Number,
nombre_casa : String,
id_administrador : Number
});
this.Escuela = new Schema({
id_escuela : Number,
nombre_esc : String
});
this.Mision = new Schema({
id_mision : Number,
nombre_mision : String,
avance : Number,
fecha_ini_mision : {type : Date, default : Date.now}
});
////////////////////////////////
//fix
this.Avatar = new Schema({
id_avatar : Number,
url_avatar : String,
alumnos_id_alumnos : Number,
piel : [],
cabello : []
});
this.Cabello = new Schema({
id_cabello : Number,
url_cabello : String
});
/*
this.Piel = new Schema({
id_piel : Number,
url_piel : String
});
*/
this.Top = new Schema({
id_top = Number,
url_top = String
})
this.Bottom = new Schema({
id_bottom = Number,
url bottom = Stirng
});
/*
db.avatar.insert({
id_avatar : 0, url_avatar : '/src/photo.jpg', alumno_id : 0, piel : [{id_piel : 0, url_piel : '/src/piel.jpg'}], cabello : [{id_cabello : 0, url_cabello : '/src/cabello.jpg'}]
});
Ejemplos de queries: encontrar avatar donde id_avatar sea mayor o igual a 1
db.avatar.find({id_avatar : {$gte : 1}});
Ejemplos de queries: encontrar avatar donde alumno_id sea mayor o igual a 10 y no projecta el id_avatar
db.avatar.find({alumno_id : {$gte : 10}}, {id_avatar : 0});
*/
this.Administrador = new Schema({
id_admin : Number,
nombre_admin : String,
pass_admin : String
});
//Son como las misiones
this.Experimento = new Schema({
id_experimento : Number,
descripcion_experimento : String,
id_experimento : Number
});
/*
db.casa.insert({
id_casa : 0, nombre_casa : 'Griffindor', administrador : [{id_administrador : 0, nombre_administrador : 'vatslavds', pass_admin : 'Hola pass'}],
})
*/
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
this.hcAll = new Schema({
phc : [],
rhc : []
});
this.gralAll = new Schema({
pgral : [],
rgral : []
});
this.Respuestashc = new Schema({
id_respuestashc : Number,
texto_resp_hc : String,
f_v_hc : Boolean,
preghc_id_preghc : Number
});
this.Preghc = new Schema({
id_preghc : Number,
descripcion_hc : String,
id_mision : Number,
id_casa : Number
});
this.Preggral = new Schema({
id_preggral : Number,
descripcion_gral : String,
id_casa : Number,
id_mision : Number
});
this.Respuestasgral = new Schema({
id_respuestasgral : Number,
texto_resp_gral : String,
f_v_gral : Boolean,
id_preggral : Number
});
/*
Ejemplo de inserccinnn de datos
db.preguntashc.insert({id_preghc : 0, descripcion_hc : "A los shumies les gustan las manzanas", id_misinnn : 0, id_casa : 0});
db.respuestashc.insert({id_respuestashc : 0, texto_resp_hc : "Tienes raznnn, a los shumies ls gustan las manzanas", id_misinnn : 0, id_casa : 0});
db.preguntasgral.insert({id_preggral : 0, descripcion_gral : "Mozart compositor alemdb.respuestasgral.insert({id_respuestasgral : 0, texto_resp_gral : "Cierto... Mozart es alem*/
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
this.Publicacion = new Schema({
id_publicacion : Number,
fecha_publicacion : {type : Date, default : Date.now},
texto_publicacion : String,
id_alumnos : Number
});
/*
db.publicacion.insert({
fecha_publicacion : new Date(), id_publicacion : 0, texto_publicacion : 'Hola mundo de ninos', no_arias : 1, id_alumno : 0
});
*/
this.Notificaciones = new Schema({
id_notificacion : Number,
texto_notificacion : String,
id_alumnos: Number,
id_publicacion : Number
});
/*
db.notificaciones.insert({
id_notificacion : 0, texto_notificacion : 'tal persona publico', id_alumnos : 0, id_publicacion : 0
});
*/
this.Rol = new Schema({
//Moderador social, experimentos, admin
id_rol : Number,
nombre : String,
});
//contiene el test de ingreso alas casas
this.Test = new Schema({
id_alumno : Number,
});
this.Arias = new Schema({
id_arias : Number,
num_arias : Number,
//alumnos : [Alumnos]
});
}
module.exports = CoayoloDAO;
/*
1.- AP sombrero
2.- AP registro
3.- AP avatar
4.-
*/
| VUH-Tec/cuayolo-db | CoayoloDAO.js | JavaScript | bsd-3-clause | 5,441 |
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the <copyright holder> nor the names of its contributors may
* be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.
*/
package nom.bdezonia.zorbage.type.integer.int4;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test; import nom.bdezonia.zorbage.algebra.G;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;
import nom.bdezonia.zorbage.storage.array.ArrayStorageBit;
import nom.bdezonia.zorbage.storage.array.ArrayStorageSignedInt8;
/**
*
* @author Barry DeZonia
*
*/
public class TestUnsignedInt4 {
private void testStorageMethods(IndexedDataSource<UnsignedInt4Member> data) {
UnsignedInt4Member in = new UnsignedInt4Member();
UnsignedInt4Member out = new UnsignedInt4Member();
in.setV(0);
for (long i = 0; i < data.size(); i++) {
data.set(i, in);
data.get(i, out);
assertEquals(0, out.v);
}
for (long i = 0; i < data.size(); i++) {
in.setV((int)i);
data.set(i, in);
out.setV(in.v-1);
data.get(i, out);
assertEquals(in.v, out.v);
}
in.setV(0);
for (long i = 0; i < data.size(); i++) {
data.set(i, in);
data.get(i, out);
assertEquals(0, out.v);
}
for (long i = data.size()-1; i >= 0; i--) {
in.setV((int)i);
data.set(i, in);
out.setV(in.v-1);
data.get(i, out);
assertEquals(in.v, out.v);
}
in.setV(0);
for (long i = data.size()-1; i >= 0; i--) {
data.set(i, in);
data.get(i, out);
assertEquals(0, out.v);
}
for (long i = data.size()-1; i >= 0; i--) {
in.setV((int)i);
data.set(i, in);
out.setV(in.v-1);
data.get(i, out);
assertEquals(in.v, out.v);
}
}
@Test
public void testStorage() {
testStorageMethods(new ArrayStorageBit<UnsignedInt4Member>(G.UINT4.construct(), 6000));
testStorageMethods(new ArrayStorageSignedInt8<UnsignedInt4Member>(G.UINT4.construct(), 6000));
}
@Test
public void testMathematicalMethods() {
UnsignedInt4Member a = G.UINT4.construct();
UnsignedInt4Member b = G.UINT4.construct();
UnsignedInt4Member c = G.UINT4.construct();
for (int i = 0; i < 16; i++) {
a.setV(i);
for (int j = 0; j < 16; j++) {
b.setV(j);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.abs().call(a, c);
assertEquals(a.v,c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.add().call(a, b, c);
assertEquals((i+j) & 0xf, (int)c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.assign().call(a, c);
assertEquals(a.v,c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.bitAnd().call(a, b, c);
assertEquals((i & j)&0xf, c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.bitOr().call(a, b, c);
assertEquals((i | j)&0xf, c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.bitShiftLeft().call(j, a, c);
assertEquals((i << (j%4))&0xf, c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.bitShiftRight().call(j, a, c);
assertEquals((i >> j)&0xf, c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.bitShiftRightFillZero().call(j, a, c);
assertEquals((i >>> j)&0xf, c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.bitXor().call(a, b, c);
assertEquals((i ^ j)&0xf, c.v);
int expected;
if (i > j) expected = 1;
else if (i < j) expected = -1;
else expected = 0;
assertEquals(expected,(int) G.UINT4.compare().call(a, b));
UnsignedInt4Member v = G.UINT4.construct();
assertEquals(0, v.v);
v = G.UINT4.construct(Integer.toString((i+j) & 0xf));
assertEquals(((i+j) & 0xf), v.v);
v = G.UINT4.construct(a);
assertEquals(i,v.v);
if (j != 0) {
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.div().call(a, b, c);
assertEquals((i / j), c.v);
}
// TODO: gcd()
// TODO: lcm()
assertEquals((i&1) == 0, G.UINT4.isEven().call(a));
assertEquals((i&1) == 1, G.UINT4.isOdd().call(a));
assertEquals(i==j, G.UINT4.isEqual().call(a, b));
assertEquals(i!=j, G.UINT4.isNotEqual().call(a, b));
assertEquals(i<j, G.UINT4.isLess().call(a, b));
assertEquals(i<=j, G.UINT4.isLessEqual().call(a, b));
assertEquals(i>j, G.UINT4.isGreater().call(a, b));
assertEquals(i>=j, G.UINT4.isGreaterEqual().call(a, b));
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.max().call(a, b, c);
assertEquals(Math.max(i, j), c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.min().call(a, b, c);
assertEquals(Math.min(i, j), c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.maxBound().call(c);
assertEquals(0xf, c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.minBound().call(c);
assertEquals(0, c.v);
if (j != 0) {
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.mod().call(a, b, c);
assertEquals(i%j, c.v);
}
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.multiply().call(a, b, c);
assertEquals((i*j) & 0xf,c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.norm().call(a, c);
assertEquals(i, c.v);
double p;
if (i == 0 && j == 0) {
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
try {
G.UINT4.pow().call(a, b, c);
fail();
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
else {
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.pow().call(a, b, c);
p = Math.pow(i, j);
if (0 <= p && p <= Math.pow(2, 51))
assertEquals(((long)p) & 0xf, c.v);
}
if (i == 0 && j == 0) {
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
try {
G.UINT4.power().call(j, a, c);
fail();
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
else {
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.power().call(j, a, c);
p = Math.pow(i, j);
if (0 <= p && p <= Math.pow(2, 51))
assertEquals(((long)p) & 0xf, c.v);
}
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(a, c);
expected = (a.v == 0) ? 0xf : a.v-1;
assertEquals(expected, c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.succ().call(a, c);
expected = (a.v == 0xf) ? 0 : a.v+1;
assertEquals(expected, c.v);
// TODO: random()
if (i < 0) expected = -1;
else if (i > 0) expected = 1;
else expected = 0;
assertEquals(expected, (int) G.UINT4.signum().call(a));
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.subtract().call(a, b, c);
assertEquals((i-j) & 0x0f, c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.unity().call(c);
assertEquals(1, c.v);
c.set(a);
G.UINT4.pred().call(c, c);
G.UINT4.pred().call(c, c);
G.UINT4.zero().call(c);
assertEquals(0, c.v);
}
}
}
@Test
public void rollover() {
UnsignedInt4Member num = G.UINT4.construct();
for (int offset : new int[] {0, 16, 32, 48, 64, 80, -16, -32, -48,-64, -80}) {
for (int i = 0; i < 16; i++) {
num.setV(offset + i);
assertEquals(i, num.v);
}
}
}
}
| bdezonia/zorbage | src/test/java/nom/bdezonia/zorbage/type/integer/int4/TestUnsignedInt4.java | Java | bsd-3-clause | 9,478 |
#!/usr/bin/env python
# Authors: Thomas Cannon <tcannon@viaforensics.com>
# Seyton Bradford <sbradford@viaforensics.com>
# Cedric Halbronn <cedric.halbronn@sogeti.com>
# TAGS: Android, Device, Decryption, Crespo, Bruteforce
#
# Parses the header for the encrypted userdata partition
# Decrypts the master key found in the footer using a supplied password
# Bruteforces the pin number using the header
#
# --
# Revision 0.1 (released by Thomas)
# ------------
# Written for Nexus S (crespo) running Android 4.0.4
# Header is located in file userdata_footer on the efs partition
#
# --
# Revision 0.3 (shipped with Santoku Alpha 0.3)
# ------------
# Added support for more than 4-digit PINs
# Speed improvements
#
# --
# Revision 0.4 (released by Cedric)
# ------------
# Adapted to support HTC One running Android 4.2.2
# Header is located in "extra" partition located in mmcblk0p27
# Note: changed name from bruteforce_stdcrypto.py to bruteforce.py
# --
#
from fde import *
def bruteforce_pin(encrypted_partition, encrypted_key, salt, maxdigits):
# load the header data for testing the password
#data = open(headerFile, 'rb').read(32)
#skip: "This is an encrypted device:)"
fd = open(encrypted_partition, 'rb')
fd.read(32)
data = fd.read(32)
fd.close()
print 'Trying to Bruteforce Password... please wait'
# try all possible 4 to maxdigits digit PINs, returns value immediately when found
for j in itertools.product(xrange(10),repeat=maxdigits):
# decrypt password
passwdTry = ''.join(str(elem) for elem in j)
#print 'Trying: ' + passwdTry
# -- In case you prefer printing every 100
try:
if (int(passwdTry) % 100) == 0:
print 'Trying passwords from %d to %d' %(int(passwdTry),int(passwdTry)+100)
except:
pass
# make the decryption key from the password
decrypted_key = get_decrypted_key(encrypted_key, salt, passwdTry)
# try to decrypt the frist 32 bytes of the header data (we don't need the iv)
# We do not use the ESSIV as IV generator
# Decrypting with the incorrect IV causes the first block of plaintext to be
# corrupt but subsequent plaintext blocks will be correct.
# http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher-block_chaining_.28CBC.29
decData = decrypt_data(decrypted_key, "", data)
# has the test worked?
if decData[16:32] == "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0":
return passwdTry, decrypted_key, decData
return None
def do_job(header_file, encrypted_partition, outfile, maxpin_digits):
assert path.isfile(header_file), "Header file '%s' not found." % header_file
assert path.isfile(encrypted_partition), "Encrypted partition '%s' not found." % encrypted_partition
# Parse header
encrypted_key, salt = parse_header(header_file)
for n in xrange(4, maxpin_digits+1):
result = bruteforce_pin(encrypted_partition, encrypted_key, salt, n)
if result:
passwdTry, decrypted_key, decData = result
print "Decrypted data:"
hexdump(decData)
print 'Found PIN!: ' + passwdTry
if outfile:
print "Saving decrypted master key to '%s'" % outfile
open(outfile, 'wb').write(decrypted_key)
break
print "Done."
def main():
parser = argparse.ArgumentParser(description='FDE for Android')
parser.add_argument('encrypted_partition', help='The first sector of the encrypted /data partition')
parser.add_argument('header_file', help='The header file containing the encrypted key')
parser.add_argument('-d', '--maxpin_digits', help='max PIN digits. Default is 4', default=4, type=int)
parser.add_argument('-o', '--output_keyfile', help='The filename to save the decrypted master key. Default does not save it', default=None)
args = parser.parse_args()
header_file = args.header_file
encrypted_partition = args.encrypted_partition
outfile = args.output_keyfile
maxpin_digits = args.maxpin_digits
do_job(header_file, encrypted_partition, outfile, maxpin_digits)
if __name__ == "__main__":
main()
| sogeti-esec-lab/android-fde | pydroidfde/bruteforce.py | Python | bsd-3-clause | 4,064 |
<?php defined('SYSPATH') or die('No direct script access.');
/**
*
*/
class Controller_Auth extends Controller
{
public function action_index()
{
if ($this->request->post('username')
&& $this->request->post('password')
&& Auth::instance()->login($this->request->post('username'), $this->request->post('password')))
{
$this->redirect('first');
}
$this->response->body(View::factory('login'));
}
public function action_logout()
{
Auth::instance()->logout();
$this->redirect('auth');
}
public function action_signin()
{
$user = ORM::factory('User');
$user->username = 'Konro1';
$user->email = 'yuriy.myrosh@lemberg.co.uk';
$user->password = '123456';
$user->save();
$user->add('roles',ORM::factory('Role', array('name' => 'login')));
$user->save();
}
}
?> | Konro1/kohana | application/classes/Controller/Auth.php | PHP | bsd-3-clause | 837 |
<?php
/**
* File to execute the doctrine command.
*/
require_once "bootstrap.php";
return \Doctrine\Orm\Tools\Console\ConsoleRunner::createHelperSet($entityManager);
| jsikora/fitnessclub | cli-config.php | PHP | bsd-3-clause | 172 |
# http://matpalm.com/blog/2012/12/27/dead_simple_pymc/
from pylab import * # for close()
import spacepy.plot as spp # for the styles
import numpy as np
import pymc as pm
| balarsen/pymc_learning | Learning/simple_normal_model.py | Python | bsd-3-clause | 175 |
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\Publication */
$this->title = Yii::t('app', 'Update {modelClass}: ', [
'modelClass' => 'Publication',
]) . ' ' . $model->id_publ;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Publications'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id_publ, 'url' => ['view', 'id' => $model->id_publ]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="publication-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| GreenIceTeam/greenice | backend/views/publication/update.php | PHP | bsd-3-clause | 649 |
namespace AjScript.Expressions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AjScript.Language;
using Microsoft.VisualBasic.CompilerServices;
public class CompareExpression : BinaryExpression
{
private Func<object, object, bool, object> function;
private ComparisonOperator operation;
public CompareExpression(ComparisonOperator operation, IExpression left, IExpression right)
: base(left, right)
{
this.operation = operation;
switch (operation)
{
case ComparisonOperator.NonStrictEqual:
this.function = NonStrictEqual;
break;
case ComparisonOperator.NonStrictNotEqual:
this.function = NonStrictNotEqual;
break;
case ComparisonOperator.Equal:
this.function = Operators.CompareObjectEqual;
break;
case ComparisonOperator.NotEqual:
this.function = Operators.CompareObjectNotEqual;
break;
case ComparisonOperator.Less:
this.function = Operators.CompareObjectLess;
break;
case ComparisonOperator.LessEqual:
this.function = Operators.CompareObjectLessEqual;
break;
case ComparisonOperator.Greater:
this.function = Operators.CompareObjectGreater;
break;
case ComparisonOperator.GreaterEqual:
this.function = Operators.CompareObjectGreaterEqual;
break;
default:
throw new ArgumentException("Invalid operator");
}
}
public ComparisonOperator Operation { get { return this.operation; } }
public override object Apply(object leftValue, object rightValue)
{
return this.function(leftValue, rightValue, false);
}
private static object NonStrictEqual(object left, object right, bool txtcompare)
{
if (left == null && right is Undefined)
return true;
if (left is Undefined && right == null)
return true;
return left == right;
}
private static object NonStrictNotEqual(object left, object right, bool txtcompare)
{
if (left == null && right is Undefined)
return false;
if (left is Undefined && right == null)
return false;
return left != right;
}
}
}
| ajlopez/AjScript | src/AjScript/Expressions/CompareExpression.cs | C# | bsd-3-clause | 2,830 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/simple_web_view_dialog.h"
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "base/message_loop.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/chromeos/login/captive_portal_window_proxy.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/content_settings/content_setting_bubble_model_delegate.h"
#include "chrome/browser/ui/toolbar/toolbar_model.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/location_bar/location_icon_view.h"
#include "chrome/browser/ui/views/page_info_bubble_view.h"
#include "chrome/browser/ui/views/reload_button.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/web_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "grit/theme_resources_standard.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/theme_provider.h"
#include "ui/views/background.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
using content::WebContents;
using views::GridLayout;
namespace {
const int kLocationBarHeight = 35;
// Margin between screen edge and SimpleWebViewDialog border.
const int kExternalMargin = 50;
// Margin between WebView and SimpleWebViewDialog border.
const int kInnerMargin = 2;
class ToolbarRowView : public views::View {
public:
ToolbarRowView() {
set_background(views::Background::CreateSolidBackground(
SkColorSetRGB(0xbe, 0xbe, 0xbe)));
}
virtual ~ToolbarRowView() {}
void Init(views::View* back,
views::View* forward,
views::View* reload,
views::View* location_bar) {
GridLayout* layout = new GridLayout(this);
SetLayoutManager(layout);
// Back button.
views::ColumnSet* column_set = layout->AddColumnSet(0);
column_set->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing);
// Forward button.
column_set->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing);
// Reload button.
column_set->AddColumn(GridLayout::CENTER, GridLayout::CENTER, 0,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing);
// Location bar.
column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 1,
GridLayout::FIXED, kLocationBarHeight, 0);
column_set->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing);
layout->StartRow(0, 0);
layout->AddView(back);
layout->AddView(forward);
layout->AddView(reload);
layout->AddView(location_bar);
}
private:
DISALLOW_COPY_AND_ASSIGN(ToolbarRowView);
};
} // namespace
namespace chromeos {
// Stub implementation of ContentSettingBubbleModelDelegate.
class StubBubbleModelDelegate : public ContentSettingBubbleModelDelegate {
public:
StubBubbleModelDelegate() {}
virtual ~StubBubbleModelDelegate() {}
// ContentSettingBubbleModelDelegate implementation:
virtual void ShowCollectedCookiesDialog(
TabContentsWrapper* contents) OVERRIDE {
}
virtual void ShowContentSettingsPage(ContentSettingsType type) OVERRIDE {
}
private:
DISALLOW_COPY_AND_ASSIGN(StubBubbleModelDelegate);
};
// SimpleWebViewDialog class ---------------------------------------------------
SimpleWebViewDialog::SimpleWebViewDialog(Profile* profile)
: profile_(profile),
back_(NULL),
forward_(NULL),
reload_(NULL),
location_bar_(NULL),
web_view_(NULL),
bubble_model_delegate_(new StubBubbleModelDelegate) {
command_updater_.reset(new CommandUpdater(this));
command_updater_->UpdateCommandEnabled(IDC_BACK, true);
command_updater_->UpdateCommandEnabled(IDC_FORWARD, true);
command_updater_->UpdateCommandEnabled(IDC_STOP, true);
command_updater_->UpdateCommandEnabled(IDC_RELOAD, true);
command_updater_->UpdateCommandEnabled(IDC_RELOAD_IGNORING_CACHE, true);
}
SimpleWebViewDialog::~SimpleWebViewDialog() {
if (web_view_container_.get()) {
// WebView can't be deleted immediately, because it could be on the stack.
web_view_->web_contents()->SetDelegate(NULL);
MessageLoop::current()->DeleteSoon(
FROM_HERE, web_view_container_.release());
}
}
void SimpleWebViewDialog::StartLoad(const GURL& url) {
web_view_container_.reset(new views::WebView(profile_));
web_view_ = web_view_container_.get();
web_view_->GetWebContents()->SetDelegate(this);
web_view_->LoadInitialURL(url);
}
void SimpleWebViewDialog::Init() {
set_background(views::Background::CreateSolidBackground(SK_ColorWHITE));
// Back/Forward buttons.
back_ = new views::ImageButton(this);
back_->set_triggerable_event_flags(ui::EF_LEFT_MOUSE_BUTTON |
ui::EF_MIDDLE_MOUSE_BUTTON);
back_->set_tag(IDC_BACK);
back_->SetImageAlignment(views::ImageButton::ALIGN_RIGHT,
views::ImageButton::ALIGN_TOP);
back_->SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_BACK));
back_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_BACK));
back_->set_id(VIEW_ID_BACK_BUTTON);
forward_ = new views::ImageButton(this);
forward_->set_triggerable_event_flags(ui::EF_LEFT_MOUSE_BUTTON |
ui::EF_MIDDLE_MOUSE_BUTTON);
forward_->set_tag(IDC_FORWARD);
forward_->SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_FORWARD));
forward_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_FORWARD));
forward_->set_id(VIEW_ID_FORWARD_BUTTON);
toolbar_model_.reset(new ToolbarModel(this));
// Location bar.
location_bar_ = new LocationBarView(profile_,
command_updater_.get(),
toolbar_model_.get(),
this,
LocationBarView::POPUP);
// Reload button.
reload_ = new ReloadButton(location_bar_, command_updater_.get());
reload_->set_triggerable_event_flags(ui::EF_LEFT_MOUSE_BUTTON |
ui::EF_MIDDLE_MOUSE_BUTTON);
reload_->set_tag(IDC_RELOAD);
reload_->SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_RELOAD));
reload_->SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_RELOAD));
reload_->set_id(VIEW_ID_RELOAD_BUTTON);
LoadImages();
// Use separate view to setup custom background.
ToolbarRowView* toolbar_row = new ToolbarRowView;
toolbar_row->Init(back_, forward_, reload_, location_bar_);
// Layout.
GridLayout* layout = new GridLayout(this);
SetLayoutManager(layout);
views::ColumnSet* column_set = layout->AddColumnSet(0);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::FIXED, 0, 0);
column_set = layout->AddColumnSet(1);
column_set->AddPaddingColumn(0, kInnerMargin);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::FIXED, 0, 0);
column_set->AddPaddingColumn(0, kInnerMargin);
// Setup layout rows.
layout->StartRow(0, 0);
layout->AddView(toolbar_row);
layout->AddPaddingRow(0, kInnerMargin);
layout->StartRow(1, 1);
layout->AddView(web_view_container_.release());
layout->AddPaddingRow(0, kInnerMargin);
location_bar_->Init();
UpdateReload(web_view_->web_contents()->IsLoading(), true);
Layout();
}
views::View* SimpleWebViewDialog::GetContentsView() {
return this;
}
views::View* SimpleWebViewDialog::GetInitiallyFocusedView() {
return web_view_;
}
void SimpleWebViewDialog::ButtonPressed(views::Button* sender,
const views::Event& event) {
command_updater_->ExecuteCommand(sender->tag());
}
void SimpleWebViewDialog::NavigationStateChanged(
const WebContents* source, unsigned changed_flags) {
if (location_bar_) {
location_bar_->Update(NULL);
UpdateButtons();
}
}
void SimpleWebViewDialog::LoadingStateChanged(WebContents* source) {
bool is_loading = source->IsLoading();
UpdateReload(is_loading, false);
command_updater_->UpdateCommandEnabled(IDC_STOP, is_loading);
}
TabContentsWrapper* SimpleWebViewDialog::GetTabContentsWrapper() const {
return NULL;
}
InstantController* SimpleWebViewDialog::GetInstant() {
return NULL;
}
views::Widget* SimpleWebViewDialog::CreateViewsBubble(
views::BubbleDelegateView* bubble_delegate) {
return views::BubbleDelegateView::CreateBubble(bubble_delegate);
}
ContentSettingBubbleModelDelegate*
SimpleWebViewDialog::GetContentSettingBubbleModelDelegate() {
return bubble_model_delegate_.get();
}
void SimpleWebViewDialog::ShowPageInfo(content::WebContents* web_contents,
const GURL& url,
const content::SSLStatus& ssl,
bool show_history) {
PageInfoBubbleView* page_info_bubble =
new PageInfoBubbleView(
location_bar_->location_icon_view(),
location_bar_->profile(),
url, ssl, true);
page_info_bubble->set_parent_window(
ash::Shell::GetInstance()->GetContainer(
ash::internal::kShellWindowId_LockSystemModalContainer));
CreateViewsBubble(page_info_bubble);
page_info_bubble->Show();
}
PageActionImageView* SimpleWebViewDialog::CreatePageActionImageView(
LocationBarView* owner,
ExtensionAction* action) {
// Notreached because SimpleWebViewDialog uses
// LocationBarView::POPUP type, and it doesn't create
// PageActionImageViews.
NOTREACHED();
return NULL;
}
void SimpleWebViewDialog::OnInputInProgress(bool in_progress) {
}
content::WebContents* SimpleWebViewDialog::GetActiveWebContents() const {
return web_view_->web_contents();
}
void SimpleWebViewDialog::ExecuteCommandWithDisposition(
int id,
WindowOpenDisposition) {
WebContents* web_contents = web_view_->web_contents();
switch (id) {
case IDC_BACK:
if (web_contents->GetController().CanGoBack()) {
location_bar_->Revert();
web_contents->GetController().GoBack();
}
break;
case IDC_FORWARD:
if (web_contents->GetController().CanGoForward()) {
location_bar_->Revert();
web_contents->GetController().GoForward();
}
break;
case IDC_STOP:
web_contents->Stop();
break;
case IDC_RELOAD:
// Always reload ignoring cache.
case IDC_RELOAD_IGNORING_CACHE:
web_contents->GetController().ReloadIgnoringCache(true);
break;
default:
NOTREACHED();
}
}
void SimpleWebViewDialog::LoadImages() {
ui::ThemeProvider* tp = GetThemeProvider();
back_->SetImage(views::CustomButton::BS_NORMAL, tp->GetBitmapNamed(IDR_BACK));
back_->SetImage(views::CustomButton::BS_HOT, tp->GetBitmapNamed(IDR_BACK_H));
back_->SetImage(views::CustomButton::BS_PUSHED,
tp->GetBitmapNamed(IDR_BACK_P));
back_->SetImage(views::CustomButton::BS_DISABLED,
tp->GetBitmapNamed(IDR_BACK_D));
forward_->SetImage(views::CustomButton::BS_NORMAL,
tp->GetBitmapNamed(IDR_FORWARD));
forward_->SetImage(views::CustomButton::BS_HOT,
tp->GetBitmapNamed(IDR_FORWARD_H));
forward_->SetImage(views::CustomButton::BS_PUSHED,
tp->GetBitmapNamed(IDR_FORWARD_P));
forward_->SetImage(views::CustomButton::BS_DISABLED,
tp->GetBitmapNamed(IDR_FORWARD_D));
reload_->SetImage(views::CustomButton::BS_NORMAL,
tp->GetBitmapNamed(IDR_RELOAD));
reload_->SetImage(views::CustomButton::BS_HOT,
tp->GetBitmapNamed(IDR_RELOAD_H));
reload_->SetImage(views::CustomButton::BS_PUSHED,
tp->GetBitmapNamed(IDR_RELOAD_P));
reload_->SetToggledImage(views::CustomButton::BS_NORMAL,
tp->GetBitmapNamed(IDR_STOP));
reload_->SetToggledImage(views::CustomButton::BS_HOT,
tp->GetBitmapNamed(IDR_STOP_H));
reload_->SetToggledImage(views::CustomButton::BS_PUSHED,
tp->GetBitmapNamed(IDR_STOP_P));
reload_->SetToggledImage(views::CustomButton::BS_DISABLED,
tp->GetBitmapNamed(IDR_STOP_D));
}
void SimpleWebViewDialog::UpdateButtons() {
const content::NavigationController& navigation_controller =
web_view_->web_contents()->GetController();
back_->SetEnabled(navigation_controller.CanGoBack());
forward_->SetEnabled(navigation_controller.CanGoForward());
}
void SimpleWebViewDialog::UpdateReload(bool is_loading, bool force) {
if (reload_) {
reload_->ChangeMode(
is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD,
force);
}
}
} // namespace chromeos
| robclark/chromium | chrome/browser/chromeos/login/simple_web_view_dialog.cc | C++ | bsd-3-clause | 13,454 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\TipsClass */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="tips-class-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => 100]) ?>
<?= $form->field($model, 'created_at')->textInput() ?>
<?= $form->field($model, 'updated_at')->textInput(['maxlength' => 10]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| lemayi/chinatravel | backend/views/tips-class/_form.php | PHP | bsd-3-clause | 690 |
var classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d =
[
[ "Function2D", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a5d1f29ecd5a972b2b774b34c0c73567f", null ],
[ "getHeight", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a0967402a3ebb011faa4ea231857687ea", null ],
[ "getWidth", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a43117cf81c33211a41e0f67f6e51f6ae", null ],
[ "value", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a41ea396f31047c219a41fbc34ce83d9d", null ],
[ "function", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a96c4a66aa532e87fd212e36ec5e66800", null ],
[ "fxi", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a2369979613653a0c43ac90f18acb204b", null ],
[ "width", "classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.html#a54cb3873835476e031f94914e6fa1291", null ]
]; | DweebsUnited/CodeMonkey | resources/hemesh/ref/html/classwblut_1_1geom_1_1_w_b___iso_values2_d_1_1_function2_d.js | JavaScript | bsd-3-clause | 949 |
# Copyright (C) 2010 Google 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the Google name nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Abstract base class of Port-specific entry points for the layout tests
test infrastructure (the Port and Driver classes)."""
import cgi
import difflib
import errno
import itertools
import json
import logging
import os
import operator
import optparse
import re
import sys
try:
from collections import OrderedDict
except ImportError:
# Needed for Python < 2.7
from webkitpy.thirdparty.ordered_dict import OrderedDict
from webkitpy.common import find_files
from webkitpy.common import read_checksum_from_png
from webkitpy.common.memoized import memoized
from webkitpy.common.system import path
from webkitpy.common.system.executive import ScriptError
from webkitpy.common.system.path import cygpath
from webkitpy.common.system.systemhost import SystemHost
from webkitpy.common.webkit_finder import WebKitFinder
from webkitpy.layout_tests.layout_package.bot_test_expectations import BotTestExpectationsFactory
from webkitpy.layout_tests.models import test_run_results
from webkitpy.layout_tests.models.test_configuration import TestConfiguration
from webkitpy.layout_tests.port import config as port_config
from webkitpy.layout_tests.port import driver
from webkitpy.layout_tests.port import server_process
from webkitpy.layout_tests.port.factory import PortFactory
from webkitpy.layout_tests.servers import apache_http
from webkitpy.layout_tests.servers import pywebsocket
from webkitpy.layout_tests.servers import wptserve
_log = logging.getLogger(__name__)
# FIXME: This class should merge with WebKitPort now that Chromium behaves mostly like other webkit ports.
class Port(object):
"""Abstract class for Port-specific hooks for the layout_test package."""
# Subclasses override this. This should indicate the basic implementation
# part of the port name, e.g., 'mac', 'win', 'gtk'; there is probably (?)
# one unique value per class.
# FIXME: We should probably rename this to something like 'implementation_name'.
port_name = None
# Test names resemble unix relative paths, and use '/' as a directory separator.
TEST_PATH_SEPARATOR = '/'
ALL_BUILD_TYPES = ('debug', 'release')
CONTENT_SHELL_NAME = 'content_shell'
# True if the port as aac and mp3 codecs built in.
PORT_HAS_AUDIO_CODECS_BUILT_IN = False
ALL_SYSTEMS = (
# FIXME: We treat Retina (High-DPI) devices as if they are running
# a different operating system version. This isn't accurate, but will work until
# we need to test and support baselines across multiple O/S versions.
('retina', 'x86'),
('mac10.9', 'x86'),
('mac10.10', 'x86'),
('mac10.11', 'x86'),
('win7', 'x86'),
('win10', 'x86'),
('precise', 'x86_64'),
('trusty', 'x86_64'),
# FIXME: Technically this should be 'arm', but adding a third architecture type breaks TestConfigurationConverter.
# If we need this to be 'arm' in the future, then we first have to fix TestConfigurationConverter.
('icecreamsandwich', 'x86'),
)
CONFIGURATION_SPECIFIER_MACROS = {
'mac': ['retina', 'mac10.9', 'mac10.10', 'mac10.11'],
'win': ['win7', 'win10'],
'linux': ['precise', 'trusty'],
'android': ['icecreamsandwich'],
}
DEFAULT_BUILD_DIRECTORIES = ('out',)
# overridden in subclasses.
FALLBACK_PATHS = {}
SUPPORTED_VERSIONS = []
# URL to the build requirements page.
BUILD_REQUIREMENTS_URL = ''
@classmethod
def latest_platform_fallback_path(cls):
return cls.FALLBACK_PATHS[cls.SUPPORTED_VERSIONS[-1]]
@classmethod
def _static_build_path(cls, filesystem, build_directory, chromium_base, target, comps):
if build_directory:
return filesystem.join(build_directory, target, *comps)
hits = []
for directory in cls.DEFAULT_BUILD_DIRECTORIES:
base_dir = filesystem.join(chromium_base, directory, target)
path = filesystem.join(base_dir, *comps)
if filesystem.exists(path):
hits.append((filesystem.mtime(path), path))
if hits:
hits.sort(reverse=True)
return hits[0][1] # Return the newest file found.
# We have to default to something, so pick the last one.
return filesystem.join(base_dir, *comps)
@classmethod
def determine_full_port_name(cls, host, options, port_name):
"""Return a fully-specified port name that can be used to construct objects."""
# Subclasses will usually override this.
assert port_name.startswith(cls.port_name)
return port_name
def __init__(self, host, port_name, options=None, **kwargs):
# This value may be different from cls.port_name by having version modifiers
# and other fields appended to it (for example, 'qt-arm' or 'mac-wk2').
self._name = port_name
# These are default values that should be overridden in a subclasses.
self._version = ''
self._architecture = 'x86'
# FIXME: Ideally we'd have a package-wide way to get a
# well-formed options object that had all of the necessary
# options defined on it.
self._options = options or optparse.Values()
self.host = host
self._executive = host.executive
self._filesystem = host.filesystem
self._webkit_finder = WebKitFinder(host.filesystem)
self._config = port_config.Config(self._executive, self._filesystem, self.port_name)
self._helper = None
self._http_server = None
self._websocket_server = None
self._is_wpt_enabled = hasattr(options, 'enable_wptserve') and options.enable_wptserve
self._wpt_server = None
self._image_differ = None
self._server_process_constructor = server_process.ServerProcess # overridable for testing
self._http_lock = None # FIXME: Why does this live on the port object?
self._dump_reader = None
# Python's Popen has a bug that causes any pipes opened to a
# process that can't be executed to be leaked. Since this
# code is specifically designed to tolerate exec failures
# to gracefully handle cases where wdiff is not installed,
# the bug results in a massive file descriptor leak. As a
# workaround, if an exec failure is ever experienced for
# wdiff, assume it's not available. This will leak one
# file descriptor but that's better than leaking each time
# wdiff would be run.
#
# http://mail.python.org/pipermail/python-list/
# 2008-August/505753.html
# http://bugs.python.org/issue3210
self._wdiff_available = None
# FIXME: prettypatch.py knows this path, why is it copied here?
self._pretty_patch_path = self.path_from_webkit_base("Tools", "Scripts", "webkitruby", "PrettyPatch", "prettify.rb")
self._pretty_patch_available = None
if not hasattr(options, 'configuration') or not options.configuration:
self.set_option_default('configuration', self.default_configuration())
if not hasattr(options, 'target') or not options.target:
self.set_option_default('target', self._options.configuration)
self._test_configuration = None
self._reftest_list = {}
self._results_directory = None
self._virtual_test_suites = None
def __str__(self):
return "Port{name=%s, version=%s, architecture=%s, test_configuration=%s}" % (self._name, self._version, self._architecture, self._test_configuration)
def buildbot_archives_baselines(self):
return True
def additional_driver_flag(self):
if self.driver_name() == self.CONTENT_SHELL_NAME:
return ['--run-layout-test']
return []
def supports_per_test_timeout(self):
return False
def default_pixel_tests(self):
return True
def default_smoke_test_only(self):
return False
def default_timeout_ms(self):
timeout_ms = 6 * 1000
if self.get_option('configuration') == 'Debug':
# Debug is usually 2x-3x slower than Release.
return 3 * timeout_ms
return timeout_ms
def driver_stop_timeout(self):
""" Returns the amount of time in seconds to wait before killing the process in driver.stop()."""
# We want to wait for at least 3 seconds, but if we are really slow, we want to be slow on cleanup as
# well (for things like ASAN, Valgrind, etc.)
return 3.0 * float(self.get_option('time_out_ms', '0')) / self.default_timeout_ms()
def wdiff_available(self):
if self._wdiff_available is None:
self._wdiff_available = self.check_wdiff(logging=False)
return self._wdiff_available
def pretty_patch_available(self):
if self._pretty_patch_available is None:
self._pretty_patch_available = self.check_pretty_patch(logging=False)
return self._pretty_patch_available
def default_batch_size(self):
"""Return the default batch size to use for this port."""
if self.get_option('enable_sanitizer'):
# ASAN/MSAN/TSAN use more memory than regular content_shell. Their
# memory usage may also grow over time, up to a certain point.
# Relaunching the driver periodically helps keep it under control.
return 40
# The default is infinte batch size.
return None
def default_child_processes(self):
"""Return the number of child processes to use for this port."""
return self._executive.cpu_count()
def max_drivers_per_process(self):
"""The maximum number of drivers a child process can use for this port."""
return 2
def default_max_locked_shards(self):
"""Return the number of "locked" shards to run in parallel (like the http tests)."""
max_locked_shards = int(self.default_child_processes()) / 4
if not max_locked_shards:
return 1
return max_locked_shards
def baseline_path(self):
"""Return the absolute path to the directory to store new baselines in for this port."""
# FIXME: remove once all callers are calling either baseline_version_dir() or baseline_platform_dir()
return self.baseline_version_dir()
def baseline_platform_dir(self):
"""Return the absolute path to the default (version-independent) platform-specific results."""
return self._filesystem.join(self.layout_tests_dir(), 'platform', self.port_name)
def baseline_version_dir(self):
"""Return the absolute path to the platform-and-version-specific results."""
baseline_search_paths = self.baseline_search_path()
return baseline_search_paths[0]
def virtual_baseline_search_path(self, test_name):
suite = self.lookup_virtual_suite(test_name)
if not suite:
return None
return [self._filesystem.join(path, suite.name) for path in self.default_baseline_search_path()]
def baseline_search_path(self):
return self.get_option('additional_platform_directory', []) + self._compare_baseline() + self.default_baseline_search_path()
def default_baseline_search_path(self):
"""Return a list of absolute paths to directories to search under for
baselines. The directories are searched in order."""
return map(self._webkit_baseline_path, self.FALLBACK_PATHS[self.version()])
@memoized
def _compare_baseline(self):
factory = PortFactory(self.host)
target_port = self.get_option('compare_port')
if target_port:
return factory.get(target_port).default_baseline_search_path()
return []
def _check_file_exists(self, path_to_file, file_description,
override_step=None, logging=True):
"""Verify the file is present where expected or log an error.
Args:
file_name: The (human friendly) name or description of the file
you're looking for (e.g., "HTTP Server"). Used for error logging.
override_step: An optional string to be logged if the check fails.
logging: Whether or not log the error messages."""
if not self._filesystem.exists(path_to_file):
if logging:
_log.error('Unable to find %s' % file_description)
_log.error(' at %s' % path_to_file)
if override_step:
_log.error(' %s' % override_step)
_log.error('')
return False
return True
def check_build(self, needs_http, printer):
result = True
dump_render_tree_binary_path = self._path_to_driver()
result = self._check_file_exists(dump_render_tree_binary_path,
'test driver') and result
if not result and self.get_option('build'):
result = self._check_driver_build_up_to_date(
self.get_option('configuration'))
else:
_log.error('')
helper_path = self._path_to_helper()
if helper_path:
result = self._check_file_exists(helper_path,
'layout test helper') and result
if self.get_option('pixel_tests'):
result = self.check_image_diff(
'To override, invoke with --no-pixel-tests') and result
# It's okay if pretty patch and wdiff aren't available, but we will at least log messages.
self._pretty_patch_available = self.check_pretty_patch()
self._wdiff_available = self.check_wdiff()
if self._dump_reader:
result = self._dump_reader.check_is_functional() and result
if needs_http:
result = self.check_httpd() and result
return test_run_results.OK_EXIT_STATUS if result else test_run_results.UNEXPECTED_ERROR_EXIT_STATUS
def _check_driver(self):
driver_path = self._path_to_driver()
if not self._filesystem.exists(driver_path):
_log.error("%s was not found at %s" % (self.driver_name(), driver_path))
return False
return True
def _check_port_build(self):
# Ports can override this method to do additional checks.
return True
def check_sys_deps(self, needs_http):
"""If the port needs to do some runtime checks to ensure that the
tests can be run successfully, it should override this routine.
This step can be skipped with --nocheck-sys-deps.
Returns whether the system is properly configured."""
cmd = [self._path_to_driver(), '--check-layout-test-sys-deps']
local_error = ScriptError()
def error_handler(script_error):
local_error.exit_code = script_error.exit_code
output = self._executive.run_command(cmd, error_handler=error_handler)
if local_error.exit_code:
_log.error('System dependencies check failed.')
_log.error('To override, invoke with --nocheck-sys-deps')
_log.error('')
_log.error(output)
if self.BUILD_REQUIREMENTS_URL is not '':
_log.error('')
_log.error('For complete build requirements, please see:')
_log.error(self.BUILD_REQUIREMENTS_URL)
return test_run_results.SYS_DEPS_EXIT_STATUS
return test_run_results.OK_EXIT_STATUS
def check_image_diff(self, override_step=None, logging=True):
"""This routine is used to check whether image_diff binary exists."""
image_diff_path = self._path_to_image_diff()
if not self._filesystem.exists(image_diff_path):
_log.error("image_diff was not found at %s" % image_diff_path)
return False
return True
def check_pretty_patch(self, logging=True):
"""Checks whether we can use the PrettyPatch ruby script."""
try:
_ = self._executive.run_command(['ruby', '--version'])
except OSError, e:
if e.errno in [errno.ENOENT, errno.EACCES, errno.ECHILD]:
if logging:
_log.warning("Ruby is not installed; can't generate pretty patches.")
_log.warning('')
return False
if not self._filesystem.exists(self._pretty_patch_path):
if logging:
_log.warning("Unable to find %s; can't generate pretty patches." % self._pretty_patch_path)
_log.warning('')
return False
return True
def check_wdiff(self, logging=True):
if not self._path_to_wdiff():
# Don't need to log here since this is the port choosing not to use wdiff.
return False
try:
_ = self._executive.run_command([self._path_to_wdiff(), '--help'])
except OSError:
if logging:
message = self._wdiff_missing_message()
if message:
for line in message.splitlines():
_log.warning(' ' + line)
_log.warning('')
return False
return True
def _wdiff_missing_message(self):
return 'wdiff is not installed; please install it to generate word-by-word diffs.'
def check_httpd(self):
httpd_path = self.path_to_apache()
if httpd_path:
try:
server_name = self._filesystem.basename(httpd_path)
env = self.setup_environ_for_server(server_name)
if self._executive.run_command([httpd_path, "-v"], env=env, return_exit_code=True) != 0:
_log.error("httpd seems broken. Cannot run http tests.")
return False
return True
except OSError:
pass
_log.error("No httpd found. Cannot run http tests.")
return False
def do_text_results_differ(self, expected_text, actual_text):
return expected_text != actual_text
def do_audio_results_differ(self, expected_audio, actual_audio):
return expected_audio != actual_audio
def diff_image(self, expected_contents, actual_contents):
"""Compare two images and return a tuple of an image diff, and an error string.
If an error occurs (like image_diff isn't found, or crashes, we log an error and return True (for a diff).
"""
# If only one of them exists, return that one.
if not actual_contents and not expected_contents:
return (None, None)
if not actual_contents:
return (expected_contents, None)
if not expected_contents:
return (actual_contents, None)
tempdir = self._filesystem.mkdtemp()
expected_filename = self._filesystem.join(str(tempdir), "expected.png")
self._filesystem.write_binary_file(expected_filename, expected_contents)
actual_filename = self._filesystem.join(str(tempdir), "actual.png")
self._filesystem.write_binary_file(actual_filename, actual_contents)
diff_filename = self._filesystem.join(str(tempdir), "diff.png")
# image_diff needs native win paths as arguments, so we need to convert them if running under cygwin.
native_expected_filename = self._convert_path(expected_filename)
native_actual_filename = self._convert_path(actual_filename)
native_diff_filename = self._convert_path(diff_filename)
executable = self._path_to_image_diff()
# Note that although we are handed 'old', 'new', image_diff wants 'new', 'old'.
comand = [executable, '--diff', native_actual_filename, native_expected_filename, native_diff_filename]
result = None
err_str = None
try:
exit_code = self._executive.run_command(comand, return_exit_code=True)
if exit_code == 0:
# The images are the same.
result = None
elif exit_code == 1:
result = self._filesystem.read_binary_file(native_diff_filename)
else:
err_str = "Image diff returned an exit code of %s. See http://crbug.com/278596" % exit_code
except OSError, e:
err_str = 'error running image diff: %s' % str(e)
finally:
self._filesystem.rmtree(str(tempdir))
return (result, err_str or None)
def diff_text(self, expected_text, actual_text, expected_filename, actual_filename):
"""Returns a string containing the diff of the two text strings
in 'unified diff' format."""
# The filenames show up in the diff output, make sure they're
# raw bytes and not unicode, so that they don't trigger join()
# trying to decode the input.
def to_raw_bytes(string_value):
if isinstance(string_value, unicode):
return string_value.encode('utf-8')
return string_value
expected_filename = to_raw_bytes(expected_filename)
actual_filename = to_raw_bytes(actual_filename)
diff = difflib.unified_diff(expected_text.splitlines(True),
actual_text.splitlines(True),
expected_filename,
actual_filename)
# The diff generated by the difflib is incorrect if one of the files
# does not have a newline at the end of the file and it is present in
# the diff. Relevant Python issue: http://bugs.python.org/issue2142
def diff_fixup(diff):
for line in diff:
yield line
if not line.endswith('\n'):
yield '\n\ No newline at end of file\n'
return ''.join(diff_fixup(diff))
def driver_name(self):
if self.get_option('driver_name'):
return self.get_option('driver_name')
return self.CONTENT_SHELL_NAME
def expected_baselines_by_extension(self, test_name):
"""Returns a dict mapping baseline suffix to relative path for each baseline in
a test. For reftests, it returns ".==" or ".!=" instead of the suffix."""
# FIXME: The name similarity between this and expected_baselines() below, is unfortunate.
# We should probably rename them both.
baseline_dict = {}
reference_files = self.reference_files(test_name)
if reference_files:
# FIXME: How should this handle more than one type of reftest?
baseline_dict['.' + reference_files[0][0]] = self.relative_test_filename(reference_files[0][1])
for extension in self.baseline_extensions():
path = self.expected_filename(test_name, extension, return_default=False)
baseline_dict[extension] = self.relative_test_filename(path) if path else path
return baseline_dict
def baseline_extensions(self):
"""Returns a tuple of all of the non-reftest baseline extensions we use. The extensions include the leading '.'."""
return ('.wav', '.txt', '.png')
def expected_baselines(self, test_name, suffix, all_baselines=False):
"""Given a test name, finds where the baseline results are located.
Args:
test_name: name of test file (usually a relative path under LayoutTests/)
suffix: file suffix of the expected results, including dot; e.g.
'.txt' or '.png'. This should not be None, but may be an empty
string.
all_baselines: If True, return an ordered list of all baseline paths
for the given platform. If False, return only the first one.
Returns
a list of ( platform_dir, results_filename ), where
platform_dir - abs path to the top of the results tree (or test
tree)
results_filename - relative path from top of tree to the results
file
(port.join() of the two gives you the full path to the file,
unless None was returned.)
Return values will be in the format appropriate for the current
platform (e.g., "\\" for path separators on Windows). If the results
file is not found, then None will be returned for the directory,
but the expected relative pathname will still be returned.
This routine is generic but lives here since it is used in
conjunction with the other baseline and filename routines that are
platform specific.
"""
baseline_filename = self._filesystem.splitext(test_name)[0] + '-expected' + suffix
baseline_search_path = self.baseline_search_path()
baselines = []
for platform_dir in baseline_search_path:
if self._filesystem.exists(self._filesystem.join(platform_dir, baseline_filename)):
baselines.append((platform_dir, baseline_filename))
if not all_baselines and baselines:
return baselines
# If it wasn't found in a platform directory, return the expected
# result in the test directory, even if no such file actually exists.
platform_dir = self.layout_tests_dir()
if self._filesystem.exists(self._filesystem.join(platform_dir, baseline_filename)):
baselines.append((platform_dir, baseline_filename))
if baselines:
return baselines
return [(None, baseline_filename)]
def expected_filename(self, test_name, suffix, return_default=True):
"""Given a test name, returns an absolute path to its expected results.
If no expected results are found in any of the searched directories,
the directory in which the test itself is located will be returned.
The return value is in the format appropriate for the platform
(e.g., "\\" for path separators on windows).
Args:
test_name: name of test file (usually a relative path under LayoutTests/)
suffix: file suffix of the expected results, including dot; e.g. '.txt'
or '.png'. This should not be None, but may be an empty string.
platform: the most-specific directory name to use to build the
search list of directories, e.g., 'win', or
'chromium-cg-mac-leopard' (we follow the WebKit format)
return_default: if True, returns the path to the generic expectation if nothing
else is found; if False, returns None.
This routine is generic but is implemented here to live alongside
the other baseline and filename manipulation routines.
"""
# FIXME: The [0] here is very mysterious, as is the destructured return.
platform_dir, baseline_filename = self.expected_baselines(test_name, suffix)[0]
if platform_dir:
return self._filesystem.join(platform_dir, baseline_filename)
actual_test_name = self.lookup_virtual_test_base(test_name)
if actual_test_name:
return self.expected_filename(actual_test_name, suffix)
if return_default:
return self._filesystem.join(self.layout_tests_dir(), baseline_filename)
return None
def expected_checksum(self, test_name):
"""Returns the checksum of the image we expect the test to produce, or None if it is a text-only test."""
png_path = self.expected_filename(test_name, '.png')
if self._filesystem.exists(png_path):
with self._filesystem.open_binary_file_for_reading(png_path) as filehandle:
return read_checksum_from_png.read_checksum(filehandle)
return None
def expected_image(self, test_name):
"""Returns the image we expect the test to produce."""
baseline_path = self.expected_filename(test_name, '.png')
if not self._filesystem.exists(baseline_path):
return None
return self._filesystem.read_binary_file(baseline_path)
def expected_audio(self, test_name):
baseline_path = self.expected_filename(test_name, '.wav')
if not self._filesystem.exists(baseline_path):
return None
return self._filesystem.read_binary_file(baseline_path)
def expected_text(self, test_name):
"""Returns the text output we expect the test to produce, or None
if we don't expect there to be any text output.
End-of-line characters are normalized to '\n'."""
# FIXME: DRT output is actually utf-8, but since we don't decode the
# output from DRT (instead treating it as a binary string), we read the
# baselines as a binary string, too.
baseline_path = self.expected_filename(test_name, '.txt')
if not self._filesystem.exists(baseline_path):
return None
text = self._filesystem.read_binary_file(baseline_path)
return text.replace("\r\n", "\n")
def _get_reftest_list(self, test_name):
dirname = self._filesystem.join(self.layout_tests_dir(), self._filesystem.dirname(test_name))
if dirname not in self._reftest_list:
self._reftest_list[dirname] = Port._parse_reftest_list(self._filesystem, dirname)
return self._reftest_list[dirname]
@staticmethod
def _parse_reftest_list(filesystem, test_dirpath):
reftest_list_path = filesystem.join(test_dirpath, 'reftest.list')
if not filesystem.isfile(reftest_list_path):
return None
reftest_list_file = filesystem.read_text_file(reftest_list_path)
parsed_list = {}
for line in reftest_list_file.split('\n'):
line = re.sub('#.+$', '', line)
split_line = line.split()
if len(split_line) == 4:
# FIXME: Probably one of mozilla's extensions in the reftest.list format. Do we need to support this?
_log.warning("unsupported reftest.list line '%s' in %s" % (line, reftest_list_path))
continue
if len(split_line) < 3:
continue
expectation_type, test_file, ref_file = split_line
parsed_list.setdefault(filesystem.join(test_dirpath, test_file), []).append(
(expectation_type, filesystem.join(test_dirpath, ref_file)))
return parsed_list
def reference_files(self, test_name):
"""Return a list of expectation (== or !=) and filename pairs"""
reftest_list = self._get_reftest_list(test_name)
if not reftest_list:
reftest_list = []
for expectation, prefix in (('==', ''), ('!=', '-mismatch')):
for extension in Port._supported_file_extensions:
path = self.expected_filename(test_name, prefix + extension)
if self._filesystem.exists(path):
reftest_list.append((expectation, path))
return reftest_list
return reftest_list.get(self._filesystem.join(self.layout_tests_dir(), test_name), []) # pylint: disable=E1103
def tests(self, paths):
"""Return the list of tests found matching paths."""
tests = self._real_tests(paths)
suites = self.virtual_test_suites()
if paths:
tests.extend(self._virtual_tests_matching_paths(paths, suites))
else:
tests.extend(self._all_virtual_tests(suites))
return tests
def _real_tests(self, paths):
# When collecting test cases, skip these directories
skipped_directories = set(['.svn', '_svn', 'platform', 'resources', 'support', 'script-tests', 'reference', 'reftest'])
files = find_files.find(self._filesystem, self.layout_tests_dir(), paths,
skipped_directories, Port.is_test_file, self.test_key)
return [self.relative_test_filename(f) for f in files]
# When collecting test cases, we include any file with these extensions.
_supported_file_extensions = set(['.html', '.xml', '.xhtml', '.xht', '.pl',
'.htm', '.php', '.svg', '.mht', '.pdf'])
@staticmethod
# If any changes are made here be sure to update the isUsedInReftest method in old-run-webkit-tests as well.
def is_reference_html_file(filesystem, dirname, filename):
if filename.startswith('ref-') or filename.startswith('notref-'):
return True
filename_wihout_ext, unused = filesystem.splitext(filename)
for suffix in ['-expected', '-expected-mismatch', '-ref', '-notref']:
if filename_wihout_ext.endswith(suffix):
return True
return False
@staticmethod
def _has_supported_extension(filesystem, filename):
"""Return true if filename is one of the file extensions we want to run a test on."""
extension = filesystem.splitext(filename)[1]
return extension in Port._supported_file_extensions
@staticmethod
def is_test_file(filesystem, dirname, filename):
return Port._has_supported_extension(filesystem, filename) and not Port.is_reference_html_file(filesystem, dirname, filename)
ALL_TEST_TYPES = ['audio', 'harness', 'pixel', 'ref', 'text', 'unknown']
def test_type(self, test_name):
fs = self._filesystem
if fs.exists(self.expected_filename(test_name, '.png')):
return 'pixel'
if fs.exists(self.expected_filename(test_name, '.wav')):
return 'audio'
if self.reference_files(test_name):
return 'ref'
txt = self.expected_text(test_name)
if txt:
if 'layer at (0,0) size 800x600' in txt:
return 'pixel'
for line in txt.splitlines():
if line.startswith('FAIL') or line.startswith('TIMEOUT') or line.startswith('PASS'):
return 'harness'
return 'text'
return 'unknown'
def test_key(self, test_name):
"""Turns a test name into a list with two sublists, the natural key of the
dirname, and the natural key of the basename.
This can be used when sorting paths so that files in a directory.
directory are kept together rather than being mixed in with files in
subdirectories."""
dirname, basename = self.split_test(test_name)
return (self._natural_sort_key(dirname + self.TEST_PATH_SEPARATOR), self._natural_sort_key(basename))
def _natural_sort_key(self, string_to_split):
""" Turns a string into a list of string and number chunks, i.e. "z23a" -> ["z", 23, "a"]
This can be used to implement "natural sort" order. See:
http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
http://nedbatchelder.com/blog/200712.html#e20071211T054956
"""
def tryint(val):
try:
return int(val)
except ValueError:
return val
return [tryint(chunk) for chunk in re.split('(\d+)', string_to_split)]
def test_dirs(self):
"""Returns the list of top-level test directories."""
layout_tests_dir = self.layout_tests_dir()
return filter(lambda x: self._filesystem.isdir(self._filesystem.join(layout_tests_dir, x)),
self._filesystem.listdir(layout_tests_dir))
@memoized
def test_isfile(self, test_name):
"""Return True if the test name refers to a directory of tests."""
# Used by test_expectations.py to apply rules to whole directories.
if self._filesystem.isfile(self.abspath_for_test(test_name)):
return True
base = self.lookup_virtual_test_base(test_name)
return base and self._filesystem.isfile(self.abspath_for_test(base))
@memoized
def test_isdir(self, test_name):
"""Return True if the test name refers to a directory of tests."""
# Used by test_expectations.py to apply rules to whole directories.
if self._filesystem.isdir(self.abspath_for_test(test_name)):
return True
base = self.lookup_virtual_test_base(test_name)
return base and self._filesystem.isdir(self.abspath_for_test(base))
@memoized
def test_exists(self, test_name):
"""Return True if the test name refers to an existing test or baseline."""
# Used by test_expectations.py to determine if an entry refers to a
# valid test and by printing.py to determine if baselines exist.
return self.test_isfile(test_name) or self.test_isdir(test_name)
def split_test(self, test_name):
"""Splits a test name into the 'directory' part and the 'basename' part."""
index = test_name.rfind(self.TEST_PATH_SEPARATOR)
if index < 1:
return ('', test_name)
return (test_name[0:index], test_name[index:])
def normalize_test_name(self, test_name):
"""Returns a normalized version of the test name or test directory."""
if test_name.endswith('/'):
return test_name
if self.test_isdir(test_name):
return test_name + '/'
return test_name
def driver_cmd_line(self):
"""Prints the DRT command line that will be used."""
driver = self.create_driver(0)
return driver.cmd_line(self.get_option('pixel_tests'), [])
def update_baseline(self, baseline_path, data):
"""Updates the baseline for a test.
Args:
baseline_path: the actual path to use for baseline, not the path to
the test. This function is used to update either generic or
platform-specific baselines, but we can't infer which here.
data: contents of the baseline.
"""
self._filesystem.write_binary_file(baseline_path, data)
# FIXME: update callers to create a finder and call it instead of these next five routines (which should be protected).
def webkit_base(self):
return self._webkit_finder.webkit_base()
def path_from_webkit_base(self, *comps):
return self._webkit_finder.path_from_webkit_base(*comps)
def path_from_chromium_base(self, *comps):
return self._webkit_finder.path_from_chromium_base(*comps)
def path_to_script(self, script_name):
return self._webkit_finder.path_to_script(script_name)
def layout_tests_dir(self):
return self._webkit_finder.layout_tests_dir()
def perf_tests_dir(self):
return self._webkit_finder.perf_tests_dir()
def skipped_layout_tests(self, test_list):
"""Returns tests skipped outside of the TestExpectations files."""
return set(self._skipped_tests_for_unsupported_features(test_list))
def _tests_from_skipped_file_contents(self, skipped_file_contents):
tests_to_skip = []
for line in skipped_file_contents.split('\n'):
line = line.strip()
line = line.rstrip('/') # Best to normalize directory names to not include the trailing slash.
if line.startswith('#') or not len(line):
continue
tests_to_skip.append(line)
return tests_to_skip
def _expectations_from_skipped_files(self, skipped_file_paths):
tests_to_skip = []
for search_path in skipped_file_paths:
filename = self._filesystem.join(self._webkit_baseline_path(search_path), "Skipped")
if not self._filesystem.exists(filename):
_log.debug("Skipped does not exist: %s" % filename)
continue
_log.debug("Using Skipped file: %s" % filename)
skipped_file_contents = self._filesystem.read_text_file(filename)
tests_to_skip.extend(self._tests_from_skipped_file_contents(skipped_file_contents))
return tests_to_skip
@memoized
def skipped_perf_tests(self):
return self._expectations_from_skipped_files([self.perf_tests_dir()])
def skips_perf_test(self, test_name):
for test_or_category in self.skipped_perf_tests():
if test_or_category == test_name:
return True
category = self._filesystem.join(self.perf_tests_dir(), test_or_category)
if self._filesystem.isdir(category) and test_name.startswith(test_or_category):
return True
return False
def is_chromium(self):
return True
def name(self):
"""Returns a name that uniquely identifies this particular type of port
(e.g., "mac-snowleopard" or "linux-trusty" and can be passed
to factory.get() to instantiate the port."""
return self._name
def operating_system(self):
# Subclasses should override this default implementation.
return 'mac'
def version(self):
"""Returns a string indicating the version of a given platform, e.g.
'leopard' or 'win7'.
This is used to help identify the exact port when parsing test
expectations, determining search paths, and logging information."""
return self._version
def architecture(self):
return self._architecture
def get_option(self, name, default_value=None):
return getattr(self._options, name, default_value)
def set_option_default(self, name, default_value):
return self._options.ensure_value(name, default_value)
@memoized
def path_to_generic_test_expectations_file(self):
return self._filesystem.join(self.layout_tests_dir(), 'TestExpectations')
def relative_test_filename(self, filename):
"""Returns a test_name a relative unix-style path for a filename under the LayoutTests
directory. Ports may legitimately return abspaths here if no relpath makes sense."""
# Ports that run on windows need to override this method to deal with
# filenames with backslashes in them.
if filename.startswith(self.layout_tests_dir()):
return self.host.filesystem.relpath(filename, self.layout_tests_dir())
else:
return self.host.filesystem.abspath(filename)
@memoized
def abspath_for_test(self, test_name):
"""Returns the full path to the file for a given test name. This is the
inverse of relative_test_filename()."""
return self._filesystem.join(self.layout_tests_dir(), test_name)
def results_directory(self):
"""Absolute path to the place to store the test results (uses --results-directory)."""
if not self._results_directory:
option_val = self.get_option('results_directory') or self.default_results_directory()
self._results_directory = self._filesystem.abspath(option_val)
return self._results_directory
def bot_test_times_path(self):
return self._build_path('webkit_test_times', 'bot_times_ms.json')
def perf_results_directory(self):
return self._build_path()
def inspector_build_directory(self):
return self._build_path('resources', 'inspector')
def default_results_directory(self):
"""Absolute path to the default place to store the test results."""
try:
return self.path_from_chromium_base('out', self.get_option('configuration'), 'layout-test-results')
except AssertionError:
return self._build_path('layout-test-results')
def setup_test_run(self):
"""Perform port-specific work at the beginning of a test run."""
# Delete the disk cache if any to ensure a clean test run.
dump_render_tree_binary_path = self._path_to_driver()
cachedir = self._filesystem.dirname(dump_render_tree_binary_path)
cachedir = self._filesystem.join(cachedir, "cache")
if self._filesystem.exists(cachedir):
self._filesystem.rmtree(cachedir)
if self._dump_reader:
self._filesystem.maybe_make_directory(self._dump_reader.crash_dumps_directory())
def num_workers(self, requested_num_workers):
"""Returns the number of available workers (possibly less than the number requested)."""
return requested_num_workers
def clean_up_test_run(self):
"""Perform port-specific work at the end of a test run."""
if self._image_differ:
self._image_differ.stop()
self._image_differ = None
# FIXME: os.environ access should be moved to onto a common/system class to be more easily mockable.
def _value_or_default_from_environ(self, name, default=None):
if name in os.environ:
return os.environ[name]
return default
def _copy_value_from_environ_if_set(self, clean_env, name):
if name in os.environ:
clean_env[name] = os.environ[name]
def setup_environ_for_server(self, server_name=None):
# We intentionally copy only a subset of os.environ when
# launching subprocesses to ensure consistent test results.
clean_env = {
'LOCAL_RESOURCE_ROOT': self.layout_tests_dir(), # FIXME: Is this used?
}
variables_to_copy = [
'WEBKIT_TESTFONTS', # FIXME: Is this still used?
'WEBKITOUTPUTDIR', # FIXME: Is this still used?
'CHROME_DEVEL_SANDBOX',
'CHROME_IPC_LOGGING',
'ASAN_OPTIONS',
'TSAN_OPTIONS',
'MSAN_OPTIONS',
'LSAN_OPTIONS',
'UBSAN_OPTIONS',
'VALGRIND_LIB',
'VALGRIND_LIB_INNER',
]
if self.host.platform.is_linux() or self.host.platform.is_freebsd():
variables_to_copy += [
'XAUTHORITY',
'HOME',
'LANG',
'LD_LIBRARY_PATH',
'DBUS_SESSION_BUS_ADDRESS',
'XDG_DATA_DIRS',
]
clean_env['DISPLAY'] = self._value_or_default_from_environ('DISPLAY', ':1')
if self.host.platform.is_mac():
clean_env['DYLD_LIBRARY_PATH'] = self._build_path()
variables_to_copy += [
'HOME',
]
if self.host.platform.is_win():
variables_to_copy += [
'PATH',
'GYP_DEFINES', # Required to locate win sdk.
]
if self.host.platform.is_cygwin():
variables_to_copy += [
'HOMEDRIVE',
'HOMEPATH',
'_NT_SYMBOL_PATH',
]
for variable in variables_to_copy:
self._copy_value_from_environ_if_set(clean_env, variable)
for string_variable in self.get_option('additional_env_var', []):
[name, value] = string_variable.split('=', 1)
clean_env[name] = value
return clean_env
def show_results_html_file(self, results_filename):
"""This routine should display the HTML file pointed at by
results_filename in a users' browser."""
return self.host.user.open_url(path.abspath_to_uri(self.host.platform, results_filename))
def create_driver(self, worker_number, no_timeout=False):
"""Return a newly created Driver subclass for starting/stopping the test driver."""
return self._driver_class()(self, worker_number, pixel_tests=self.get_option('pixel_tests'), no_timeout=no_timeout)
def start_helper(self):
"""If a port needs to reconfigure graphics settings or do other
things to ensure a known test configuration, it should override this
method."""
helper_path = self._path_to_helper()
if helper_path:
_log.debug("Starting layout helper %s" % helper_path)
# Note: Not thread safe: http://bugs.python.org/issue2320
self._helper = self._executive.popen([helper_path],
stdin=self._executive.PIPE, stdout=self._executive.PIPE, stderr=None)
is_ready = self._helper.stdout.readline()
if not is_ready.startswith('ready'):
_log.error("layout_test_helper failed to be ready")
def requires_http_server(self):
"""Does the port require an HTTP server for running tests? This could
be the case when the tests aren't run on the host platform."""
return False
def start_http_server(self, additional_dirs, number_of_drivers):
"""Start a web server. Raise an error if it can't start or is already running.
Ports can stub this out if they don't need a web server to be running."""
assert not self._http_server, 'Already running an http server.'
server = apache_http.ApacheHTTP(self, self.results_directory(),
additional_dirs=additional_dirs,
number_of_servers=(number_of_drivers * 4))
server.start()
self._http_server = server
def start_websocket_server(self):
"""Start a web server. Raise an error if it can't start or is already running.
Ports can stub this out if they don't need a websocket server to be running."""
assert not self._websocket_server, 'Already running a websocket server.'
server = pywebsocket.PyWebSocket(self, self.results_directory())
server.start()
self._websocket_server = server
def is_wpt_enabled(self):
"""Used as feature flag for WPT Serve feature."""
return self._is_wpt_enabled
def is_wpt_test(self, test):
"""Whether this test is part of a web-platform-tests which require wptserve servers."""
return "web-platform-tests" in test
def start_wptserve(self):
"""Start a WPT web server. Raise an error if it can't start or is already running.
Ports can stub this out if they don't need a WPT web server to be running."""
assert not self._wpt_server, 'Already running an http server.'
assert self.is_wpt_enabled(), 'Cannot start server if WPT is not enabled.'
# We currently don't support any output mechanism for the WPT server.
server = wptserve.WPTServe(self, self.results_directory())
server.start()
self._wpt_server = server
def stop_wptserve(self):
"""Shut down the WPT server if it is running. Do nothing if it isn't."""
if self._wpt_server:
self._wpt_server.stop()
self._wpt_server = None
def http_server_supports_ipv6(self):
# Apache < 2.4 on win32 does not support IPv6, nor does cygwin apache.
if self.host.platform.is_cygwin() or self.host.platform.is_win():
return False
return True
def stop_helper(self):
"""Shut down the test helper if it is running. Do nothing if
it isn't, or it isn't available. If a port overrides start_helper()
it must override this routine as well."""
if self._helper:
_log.debug("Stopping layout test helper")
try:
self._helper.stdin.write("x\n")
self._helper.stdin.close()
self._helper.wait()
except IOError, e:
pass
finally:
self._helper = None
def stop_http_server(self):
"""Shut down the http server if it is running. Do nothing if it isn't."""
if self._http_server:
self._http_server.stop()
self._http_server = None
def stop_websocket_server(self):
"""Shut down the websocket server if it is running. Do nothing if it isn't."""
if self._websocket_server:
self._websocket_server.stop()
self._websocket_server = None
#
# TEST EXPECTATION-RELATED METHODS
#
def test_configuration(self):
"""Returns the current TestConfiguration for the port."""
if not self._test_configuration:
self._test_configuration = TestConfiguration(self._version, self._architecture, self._options.configuration.lower())
return self._test_configuration
# FIXME: Belongs on a Platform object.
@memoized
def all_test_configurations(self):
"""Returns a list of TestConfiguration instances, representing all available
test configurations for this port."""
return self._generate_all_test_configurations()
# FIXME: Belongs on a Platform object.
def configuration_specifier_macros(self):
"""Ports may provide a way to abbreviate configuration specifiers to conveniently
refer to them as one term or alias specific values to more generic ones. For example:
(vista, win7) -> win # Abbreviate all Windows versions into one namesake.
(precise, trusty) -> linux # Change specific name of Linux distro to a more generic term.
Returns a dictionary, each key representing a macro term ('win', for example),
and value being a list of valid configuration specifiers (such as ['vista', 'win7'])."""
return self.CONFIGURATION_SPECIFIER_MACROS
def _generate_all_test_configurations(self):
"""Returns a sequence of the TestConfigurations the port supports."""
# By default, we assume we want to test every graphics type in
# every configuration on every system.
test_configurations = []
for version, architecture in self.ALL_SYSTEMS:
for build_type in self.ALL_BUILD_TYPES:
test_configurations.append(TestConfiguration(version, architecture, build_type))
return test_configurations
def warn_if_bug_missing_in_test_expectations(self):
return True
def _port_specific_expectations_files(self):
paths = []
paths.append(self._filesystem.join(self.layout_tests_dir(), 'NeverFixTests'))
paths.append(self._filesystem.join(self.layout_tests_dir(), 'StaleTestExpectations'))
paths.append(self._filesystem.join(self.layout_tests_dir(), 'SlowTests'))
if self._is_wpt_enabled:
paths.append(self._filesystem.join(self.layout_tests_dir(), 'WPTServeExpectations'))
return paths
def _flag_specific_expectations_files(self):
return [self._filesystem.join(self.layout_tests_dir(), 'FlagExpectations', flag.lstrip('-'))
for flag in self.get_option('additional_driver_flag', [])]
def expectations_dict(self):
"""Returns an OrderedDict of name -> expectations strings.
The names are expected to be (but not required to be) paths in the filesystem.
If the name is a path, the file can be considered updatable for things like rebaselining,
so don't use names that are paths if they're not paths.
Generally speaking the ordering should be files in the filesystem in cascade order
(TestExpectations followed by Skipped, if the port honors both formats),
then any built-in expectations (e.g., from compile-time exclusions), then --additional-expectations options."""
# FIXME: rename this to test_expectations() once all the callers are updated to know about the ordered dict.
expectations = OrderedDict()
for path in self.expectations_files():
if self._filesystem.exists(path):
expectations[path] = self._filesystem.read_text_file(path)
for path in self.get_option('additional_expectations', []):
expanded_path = self._filesystem.expanduser(path)
if self._filesystem.exists(expanded_path):
_log.debug("reading additional_expectations from path '%s'" % path)
expectations[path] = self._filesystem.read_text_file(expanded_path)
else:
_log.warning("additional_expectations path '%s' does not exist" % path)
return expectations
def bot_expectations(self):
if not self.get_option('ignore_flaky_tests'):
return {}
full_port_name = self.determine_full_port_name(self.host, self._options, self.port_name)
builder_category = self.get_option('ignore_builder_category', 'layout')
factory = BotTestExpectationsFactory()
# FIXME: This only grabs release builder's flakiness data. If we're running debug,
# when we should grab the debug builder's data.
expectations = factory.expectations_for_port(full_port_name, builder_category)
if not expectations:
return {}
ignore_mode = self.get_option('ignore_flaky_tests')
if ignore_mode == 'very-flaky' or ignore_mode == 'maybe-flaky':
return expectations.flakes_by_path(ignore_mode == 'very-flaky')
if ignore_mode == 'unexpected':
return expectations.unexpected_results_by_path()
_log.warning("Unexpected ignore mode: '%s'." % ignore_mode)
return {}
def expectations_files(self):
return ([self.path_to_generic_test_expectations_file()] +
self._port_specific_expectations_files() +
self._flag_specific_expectations_files())
def repository_path(self):
"""Returns the repository path for the chromium code base."""
return self.path_from_chromium_base('build')
_WDIFF_DEL = '##WDIFF_DEL##'
_WDIFF_ADD = '##WDIFF_ADD##'
_WDIFF_END = '##WDIFF_END##'
def _format_wdiff_output_as_html(self, wdiff):
wdiff = cgi.escape(wdiff)
wdiff = wdiff.replace(self._WDIFF_DEL, "<span class=del>")
wdiff = wdiff.replace(self._WDIFF_ADD, "<span class=add>")
wdiff = wdiff.replace(self._WDIFF_END, "</span>")
html = "<head><style>.del { background: #faa; } "
html += ".add { background: #afa; }</style></head>"
html += "<pre>%s</pre>" % wdiff
return html
def _wdiff_command(self, actual_filename, expected_filename):
executable = self._path_to_wdiff()
return [executable,
"--start-delete=%s" % self._WDIFF_DEL,
"--end-delete=%s" % self._WDIFF_END,
"--start-insert=%s" % self._WDIFF_ADD,
"--end-insert=%s" % self._WDIFF_END,
actual_filename,
expected_filename]
@staticmethod
def _handle_wdiff_error(script_error):
# Exit 1 means the files differed, any other exit code is an error.
if script_error.exit_code != 1:
raise script_error
def _run_wdiff(self, actual_filename, expected_filename):
"""Runs wdiff and may throw exceptions.
This is mostly a hook for unit testing."""
# Diffs are treated as binary as they may include multiple files
# with conflicting encodings. Thus we do not decode the output.
command = self._wdiff_command(actual_filename, expected_filename)
wdiff = self._executive.run_command(command, decode_output=False,
error_handler=self._handle_wdiff_error)
return self._format_wdiff_output_as_html(wdiff)
_wdiff_error_html = "Failed to run wdiff, see error log."
def wdiff_text(self, actual_filename, expected_filename):
"""Returns a string of HTML indicating the word-level diff of the
contents of the two filenames. Returns an empty string if word-level
diffing isn't available."""
if not self.wdiff_available():
return ""
try:
# It's possible to raise a ScriptError we pass wdiff invalid paths.
return self._run_wdiff(actual_filename, expected_filename)
except OSError as e:
if e.errno in [errno.ENOENT, errno.EACCES, errno.ECHILD]:
# Silently ignore cases where wdiff is missing.
self._wdiff_available = False
return ""
raise
except ScriptError as e:
_log.error("Failed to run wdiff: %s" % e)
self._wdiff_available = False
return self._wdiff_error_html
# This is a class variable so we can test error output easily.
_pretty_patch_error_html = "Failed to run PrettyPatch, see error log."
def pretty_patch_text(self, diff_path):
if self._pretty_patch_available is None:
self._pretty_patch_available = self.check_pretty_patch(logging=False)
if not self._pretty_patch_available:
return self._pretty_patch_error_html
command = ("ruby", "-I", self._filesystem.dirname(self._pretty_patch_path),
self._pretty_patch_path, diff_path)
try:
# Diffs are treated as binary (we pass decode_output=False) as they
# may contain multiple files of conflicting encodings.
return self._executive.run_command(command, decode_output=False)
except OSError, e:
# If the system is missing ruby log the error and stop trying.
self._pretty_patch_available = False
_log.error("Failed to run PrettyPatch (%s): %s" % (command, e))
return self._pretty_patch_error_html
except ScriptError, e:
# If ruby failed to run for some reason, log the command
# output and stop trying.
self._pretty_patch_available = False
_log.error("Failed to run PrettyPatch (%s):\n%s" % (command, e.message_with_output()))
return self._pretty_patch_error_html
def default_configuration(self):
return self._config.default_configuration()
def clobber_old_port_specific_results(self):
pass
# FIXME: This does not belong on the port object.
@memoized
def path_to_apache(self):
"""Returns the full path to the apache binary.
This is needed only by ports that use the apache_http_server module."""
raise NotImplementedError('Port.path_to_apache')
def path_to_apache_config_file(self):
"""Returns the full path to the apache configuration file.
If the WEBKIT_HTTP_SERVER_CONF_PATH environment variable is set, its
contents will be used instead.
This is needed only by ports that use the apache_http_server module."""
config_file_from_env = os.environ.get('WEBKIT_HTTP_SERVER_CONF_PATH')
if config_file_from_env:
if not self._filesystem.exists(config_file_from_env):
raise IOError('%s was not found on the system' % config_file_from_env)
return config_file_from_env
config_file_name = self._apache_config_file_name_for_platform()
return self._filesystem.join(self.layout_tests_dir(), 'http', 'conf', config_file_name)
#
# PROTECTED ROUTINES
#
# The routines below should only be called by routines in this class
# or any of its subclasses.
#
def _apache_version(self):
config = self._executive.run_command([self.path_to_apache(), '-v'])
return re.sub(r'(?:.|\n)*Server version: Apache/(\d+\.\d+)(?:.|\n)*', r'\1', config)
def _apache_config_file_name_for_platform(self):
if self.host.platform.is_cygwin():
return 'cygwin-httpd.conf' # CYGWIN is the only platform to still use Apache 1.3.
if self.host.platform.is_linux():
distribution = self.host.platform.linux_distribution()
custom_configuration_distributions = ['arch', 'debian', 'redhat']
if distribution in custom_configuration_distributions:
return "%s-httpd-%s.conf" % (distribution, self._apache_version())
return 'apache2-httpd-' + self._apache_version() + '.conf'
def _path_to_driver(self, target=None):
"""Returns the full path to the test driver."""
return self._build_path(target, self.driver_name())
def _path_to_webcore_library(self):
"""Returns the full path to a built copy of WebCore."""
return None
def _path_to_helper(self):
"""Returns the full path to the layout_test_helper binary, which
is used to help configure the system for the test run, or None
if no helper is needed.
This is likely only used by start/stop_helper()."""
return None
def _path_to_image_diff(self):
"""Returns the full path to the image_diff binary, or None if it is not available.
This is likely used only by diff_image()"""
return self._build_path('image_diff')
@memoized
def _path_to_wdiff(self):
"""Returns the full path to the wdiff binary, or None if it is not available.
This is likely used only by wdiff_text()"""
for path in ("/usr/bin/wdiff", "/usr/bin/dwdiff"):
if self._filesystem.exists(path):
return path
return None
def _webkit_baseline_path(self, platform):
"""Return the full path to the top of the baseline tree for a
given platform."""
return self._filesystem.join(self.layout_tests_dir(), 'platform', platform)
def _driver_class(self):
"""Returns the port's driver implementation."""
return driver.Driver
def output_contains_sanitizer_messages(self, output):
if not output:
return None
if 'AddressSanitizer' in output:
return 'AddressSanitizer'
if 'MemorySanitizer' in output:
return 'MemorySanitizer'
return None
def _get_crash_log(self, name, pid, stdout, stderr, newer_than):
if self.output_contains_sanitizer_messages(stderr):
# Running the symbolizer script can take a lot of memory, so we need to
# serialize access to it across all the concurrently running drivers.
llvm_symbolizer_path = self.path_from_chromium_base(
'third_party', 'llvm-build', 'Release+Asserts', 'bin', 'llvm-symbolizer')
if self._filesystem.exists(llvm_symbolizer_path):
env = os.environ.copy()
env['LLVM_SYMBOLIZER_PATH'] = llvm_symbolizer_path
else:
env = None
sanitizer_filter_path = self.path_from_chromium_base('tools', 'valgrind', 'asan', 'asan_symbolize.py')
sanitizer_strip_path_prefix = 'Release/../../'
if self._filesystem.exists(sanitizer_filter_path):
stderr = self._executive.run_command(
['flock', sys.executable, sanitizer_filter_path, sanitizer_strip_path_prefix], input=stderr, decode_output=False, env=env)
name_str = name or '<unknown process name>'
pid_str = str(pid or '<unknown>')
# We require stdout and stderr to be bytestrings, not character strings.
if stdout:
assert isinstance(stdout, str)
stdout_lines = stdout.decode('utf8', 'replace').splitlines()
else:
stdout_lines = [u'<empty>']
if stderr:
assert isinstance(stderr, str)
stderr_lines = stderr.decode('utf8', 'replace').splitlines()
else:
stderr_lines = [u'<empty>']
return (stderr, 'crash log for %s (pid %s):\n%s\n%s\n' % (name_str, pid_str,
'\n'.join(('STDOUT: ' + l) for l in stdout_lines),
'\n'.join(('STDERR: ' + l) for l in stderr_lines)))
def look_for_new_crash_logs(self, crashed_processes, start_time):
pass
def look_for_new_samples(self, unresponsive_processes, start_time):
pass
def sample_process(self, name, pid):
pass
def physical_test_suites(self):
return [
# For example, to turn on force-compositing-mode in the svg/ directory:
# PhysicalTestSuite('svg', ['--force-compositing-mode']),
PhysicalTestSuite('fast/text', ["--enable-direct-write", "--enable-font-antialiasing"]),
]
def virtual_test_suites(self):
if self._virtual_test_suites is None:
path_to_virtual_test_suites = self._filesystem.join(self.layout_tests_dir(), 'VirtualTestSuites')
assert self._filesystem.exists(path_to_virtual_test_suites), 'LayoutTests/VirtualTestSuites not found'
try:
test_suite_json = json.loads(self._filesystem.read_text_file(path_to_virtual_test_suites))
self._virtual_test_suites = [VirtualTestSuite(**d) for d in test_suite_json]
except ValueError as e:
raise ValueError("LayoutTests/VirtualTestSuites is not a valid JSON file: %s" % str(e))
return self._virtual_test_suites
def _all_virtual_tests(self, suites):
tests = []
for suite in suites:
self._populate_virtual_suite(suite)
tests.extend(suite.tests.keys())
return tests
def _virtual_tests_matching_paths(self, paths, suites):
tests = []
for suite in suites:
if any(p.startswith(suite.name) for p in paths):
self._populate_virtual_suite(suite)
for test in suite.tests:
if any(test.startswith(p) for p in paths):
tests.append(test)
return tests
def _populate_virtual_suite(self, suite):
if not suite.tests:
base_tests = self._real_tests([suite.base])
suite.tests = {}
for test in base_tests:
suite.tests[test.replace(suite.base, suite.name, 1)] = test
def is_virtual_test(self, test_name):
return bool(self.lookup_virtual_suite(test_name))
def lookup_virtual_suite(self, test_name):
for suite in self.virtual_test_suites():
if test_name.startswith(suite.name):
return suite
return None
def lookup_virtual_test_base(self, test_name):
suite = self.lookup_virtual_suite(test_name)
if not suite:
return None
return test_name.replace(suite.name, suite.base, 1)
def lookup_virtual_test_args(self, test_name):
for suite in self.virtual_test_suites():
if test_name.startswith(suite.name):
return suite.args
return []
def lookup_virtual_reference_args(self, test_name):
for suite in self.virtual_test_suites():
if test_name.startswith(suite.name):
return suite.reference_args
return []
def lookup_physical_test_args(self, test_name):
for suite in self.physical_test_suites():
if test_name.startswith(suite.name):
return suite.args
return []
def lookup_physical_reference_args(self, test_name):
for suite in self.physical_test_suites():
if test_name.startswith(suite.name):
return suite.reference_args
return []
def should_run_as_pixel_test(self, test_input):
if not self._options.pixel_tests:
return False
if self._options.pixel_test_directories:
return any(test_input.test_name.startswith(directory) for directory in self._options.pixel_test_directories)
# TODO(burnik): Make sure this is the right way to do it.
if self.is_wpt_enabled() and self.is_wpt_test(test_input.test_name):
return False
return True
def _modules_to_search_for_symbols(self):
path = self._path_to_webcore_library()
if path:
return [path]
return []
def _symbols_string(self):
symbols = ''
for path_to_module in self._modules_to_search_for_symbols():
try:
symbols += self._executive.run_command(['nm', path_to_module], error_handler=self._executive.ignore_error)
except OSError, e:
_log.warn("Failed to run nm: %s. Can't determine supported features correctly." % e)
return symbols
# Ports which use compile-time feature detection should define this method and return
# a dictionary mapping from symbol substrings to possibly disabled test directories.
# When the symbol substrings are not matched, the directories will be skipped.
# If ports don't ever enable certain features, then those directories can just be
# in the Skipped list instead of compile-time-checked here.
def _missing_symbol_to_skipped_tests(self):
if self.PORT_HAS_AUDIO_CODECS_BUILT_IN:
return {}
else:
return {
"ff_mp3_decoder": ["webaudio/codec-tests/mp3"],
"ff_aac_decoder": ["webaudio/codec-tests/aac"],
}
def _has_test_in_directories(self, directory_lists, test_list):
if not test_list:
return False
directories = itertools.chain.from_iterable(directory_lists)
for directory, test in itertools.product(directories, test_list):
if test.startswith(directory):
return True
return False
def _skipped_tests_for_unsupported_features(self, test_list):
# Only check the symbols of there are tests in the test_list that might get skipped.
# This is a performance optimization to avoid the calling nm.
# Runtime feature detection not supported, fallback to static detection:
# Disable any tests for symbols missing from the executable or libraries.
if self._has_test_in_directories(self._missing_symbol_to_skipped_tests().values(), test_list):
symbols_string = self._symbols_string()
if symbols_string is not None:
return reduce(operator.add, [directories for symbol_substring, directories in self._missing_symbol_to_skipped_tests().items() if symbol_substring not in symbols_string], [])
return []
def _convert_path(self, path):
"""Handles filename conversion for subprocess command line args."""
# See note above in diff_image() for why we need this.
if sys.platform == 'cygwin':
return cygpath(path)
return path
def _build_path(self, *comps):
return self._build_path_with_target(self._options.target, *comps)
def _build_path_with_target(self, target, *comps):
# Note that we don't do the option caching that the
# base class does, because finding the right directory is relatively
# fast.
target = target or self.get_option('target')
return self._static_build_path(self._filesystem, self.get_option('build_directory'),
self.path_from_chromium_base(), target, comps)
def _check_driver_build_up_to_date(self, target):
# We should probably get rid of this check altogether as it has
# outlived its usefulness in a GN-based world, but for the moment
# we will just check things if they are using the standard
# Debug or Release target directories.
if target not in ('Debug', 'Release'):
return True
try:
debug_path = self._path_to_driver('Debug')
release_path = self._path_to_driver('Release')
debug_mtime = self._filesystem.mtime(debug_path)
release_mtime = self._filesystem.mtime(release_path)
if (debug_mtime > release_mtime and target == 'Release' or
release_mtime > debug_mtime and target == 'Debug'):
most_recent_binary = 'Release' if target == 'Debug' else 'Debug'
_log.warning('You are running the %s binary. However the %s binary appears to be more recent. '
'Please pass --%s.', target, most_recent_binary, most_recent_binary.lower())
_log.warning('')
# This will fail if we don't have both a debug and release binary.
# That's fine because, in this case, we must already be running the
# most up-to-date one.
except OSError:
pass
return True
def _chromium_baseline_path(self, platform):
if platform is None:
platform = self.name()
return self.path_from_webkit_base('LayoutTests', 'platform', platform)
class VirtualTestSuite(object):
def __init__(self, prefix=None, base=None, args=None, references_use_default_args=False):
assert base
assert args
assert prefix.find('/') == -1, "Virtual test suites prefixes cannot contain /'s: %s" % prefix
self.name = 'virtual/' + prefix + '/' + base
self.base = base
self.args = args
self.reference_args = [] if references_use_default_args else args
self.tests = {}
def __repr__(self):
return "VirtualTestSuite('%s', '%s', %s, %s)" % (self.name, self.base, self.args, self.reference_args)
class PhysicalTestSuite(object):
def __init__(self, base, args, reference_args=None):
self.name = base
self.base = base
self.args = args
self.reference_args = args if reference_args is None else reference_args
self.tests = set()
def __repr__(self):
return "PhysicalTestSuite('%s', '%s', %s, %s)" % (self.name, self.base, self.args, self.reference_args)
| was4444/chromium.src | third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base.py | Python | bsd-3-clause | 78,408 |
# Delegation tree
#
# Targets
# / \
# a f
# / \
# b e
# / \
# c d
#
# No terminating delegations.
#
# Roles should be evaluated in the order:
# Targets > a > b > c > d > e > f
from fixtures.builder import FixtureBuilder
def build():
FixtureBuilder('TUFTestFixture3LevelDelegation')\
.publish(with_client=True)\
.create_target('targets.txt')\
.delegate('a', ['*.txt'])\
.create_target('a.txt', signing_role='a')\
.delegate('b', ['*.txt'], parent='a') \
.create_target('b.txt', signing_role='b') \
.delegate('c', ['*.txt'], parent='b') \
.create_target('c.txt', signing_role='c') \
.delegate('d', ['*.txt'], parent='b') \
.create_target('d.txt', signing_role='d') \
.delegate('e', ['*.txt'], parent='a') \
.create_target('e.txt', signing_role='e') \
.delegate('f', ['*.txt']) \
.create_target('f.txt', signing_role='f') \
.publish()
| theupdateframework/go-tuf | client/testdata/php-tuf-fixtures/TUFTestFixture3LevelDelegation/__init__.py | Python | bsd-3-clause | 1,041 |
package org.marswars.commands;
/**
*
* @author bradmiller
*/
public class UnwindRR extends CommandBase {
boolean isFinished = false;
public UnwindRR() {
// Use requires() here to declare subsystem dependencies
requires(drive);
setRunWhenDisabled(true);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
isFinished = !drive.unwindRR();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return isFinished;
}
// Called once after isFinished returns true
protected void end() {
isFinished = false;
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| FRC-Team-4143/AerialAssist | src/org/marswars/commands/UnwindRR.java | Java | bsd-3-clause | 961 |
package com.impossibl.stencil.engine.internal;
import java.io.Serializable;
import com.impossibl.stencil.api.Template;
import com.impossibl.stencil.engine.parsing.StencilParser.TemplateContext;
public class TemplateImpl implements Template, Serializable {
private static final long serialVersionUID = -4977880299063133293L;
private String path;
private TemplateContext context;
public TemplateImpl(String path, TemplateContext context) {
this.path = path;
this.context = context;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public TemplateContext getContext() {
return context;
}
public void setContext(TemplateContext context) {
this.context = context;
}
}
| impossibl/stencil | engine/src/main/java/com/impossibl/stencil/engine/internal/TemplateImpl.java | Java | bsd-3-clause | 781 |
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.application.util;
import gov.nih.nci.caarray.domain.file.CaArrayFileSet;
import java.io.IOException;
import java.util.Set;
/**
* Splits a large CaArrayFileSet into smaller manageable chunks.
*
* @author kkanchinadam
*/
public interface CaArrayFileSetSplitter {
/**
* Accepts a (potentially) large file set and creates a set of smaller file sets, with the appropriate
* CaArrayFile parent/child relationships between SDRF files.
*
* <p>This method is null safe. Null input results in null output.
*
* @param largeFileSet the input files to be split
* @return collection of files
* @throws IOException if temporary file management fails during the split
*/
Set<CaArrayFileSet> split(CaArrayFileSet largeFileSet) throws IOException;
}
| NCIP/caarray | software/caarray-ejb.jar/src/main/java/gov/nih/nci/caarray/application/util/CaArrayFileSetSplitter.java | Java | bsd-3-clause | 1,175 |
package net.minidev.ovh.api.hosting.web.database.dump;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* List of dump types
*/
public enum OvhDateEnum {
@JsonProperty("daily.1")
daily_1("daily.1"),
now("now"),
@JsonProperty("weekly.1")
weekly_1("weekly.1");
final String value;
OvhDateEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
| UrielCh/ovh-java-sdk | ovh-java-sdk-hostingweb/src/main/java/net/minidev/ovh/api/hosting/web/database/dump/OvhDateEnum.java | Java | bsd-3-clause | 401 |
<?php defined('SYSPATH') or die('No direct access allowed.');
$lang = array
(
'requires_mcrypt' => 'Käyttääksesi Encrypt-kirjastoa, mcrypt tulee olla kytkettynä PHP-asennukessasi.',
'no_encryption_key' => 'Käyttääksesi Encrypt-kirjastoa, tulee salausavain olla määriteltynä asetuksissa.'
);
| WebArchivCZ/WA-Admin | system/i18n/fi_FI/encrypt.php | PHP | bsd-3-clause | 306 |
<?php
namespace SanAuth\Model;
use Zend\Authentication\Storage;
use Zend\Session\Container;
class MyAuthStorage extends Storage\Session
{
protected $container;
public function getContainer(){
if(!$this->container){
$this->container = new Container('MTakip');
}
return $this->container;
}
public function setRememberMe($rememberMe = 0, $time = 1209600)
{
if ($rememberMe == 1) {
$this->session->getManager()->rememberMe($time);
}
}
public function forgetMe()
{
$this->session->getManager()->forgetMe();
}
public function getRole(){
return $this->getContainer()->role;
}
public function setRole($role){
$this->getContainer()->role = $role;
}
public function getFirma(){
return $this->getContainer()->firma;
}
public function setFirma($firma){
$this->getContainer()->firma = $firma;
}
} | fkaynakli/MukellefTakip | module/SanAuth/src/SanAuth/Model/MyAuthStorage.php | PHP | bsd-3-clause | 981 |
import liblo
import time
from liblo import make_method
target = liblo.Address(12002)
class SerialOsc(liblo.Server):
def __init__(self, *args, **kwargs):
liblo.Server.__init__(self, *args, **kwargs)
self.devices = []
@make_method('/serialosc/device', 'ssi')
def list_device(self, path, args):
print path, args
id_, type_, port = args
print port
device = liblo.Address(port)
liblo.send(device, '/sys/prefix', 'monome')
liblo.send(device, '/sys/host', 'localhost')
liblo.send(device, '/sys/port', self.port)
self.devices.append(device)
@make_method('/monome/grid/key', 'iii')
def button(self, path, args):
(x, y, b) = args
print x, y
for d in self.devices:
liblo.send(d, '/monome/grid/led/set', x, y, b)
@make_method(None, None)
def fallback(self, path, args):
print path, args
s = SerialOsc()
liblo.send(target, '/serialosc/list', 'localhost', s.port)
while True:
s.recv(100)
| litghost/etherdream_toys | monome_test.py | Python | bsd-3-clause | 1,048 |
from django.db import models
from django.contrib.postgres.fields import ArrayField
from localflavor.us.us_states import US_STATES
from django.core.urlresolvers import reverse
from django.utils.text import slugify
from common.models import TimestampedModel
import uuid
STATE_NATL_CHOICES = (('US', 'National'),) + US_STATES
STATE_NATL_LOOKUP = dict(STATE_NATL_CHOICES)
class Category(TimestampedModel):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=70, editable=False)
parent = models.ForeignKey("self", related_name="children", null=True, blank=True)
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['parent__name', 'name']
unique_together = ("name", "parent")
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
@property
def path(self):
return self._calculate_pathname(False)
@property
def slugged_path(self):
return self._calculate_pathname(True)
def _calculate_pathname(self, slugged):
name = self.slug if slugged else self.name
if self.parent:
parent_name = str(self.parent.slug) if slugged else str(self.parent.name)
return "{parent_name}/{name}".format(name=name, parent_name=parent_name)
else:
return "{name}".format(name=name)
def get_absolute_url(self):
kwargs = {'category': self.parent.slug if self.parent else self.slug}
if self.parent:
kwargs['subcategory'] = self.slug
return reverse('datasets-by-category', kwargs=kwargs)
def __str__(self):
return self.path
class Dataset(TimestampedModel):
uuid = models.UUIDField(default=uuid.uuid4, editable=False)
# General
title = models.TextField()
url = models.URLField(blank=True, null=True, max_length=500)
description = models.TextField(blank=True)
group_name = models.CharField(db_index=True, max_length=150,
help_text="Name of group administering dataset.")
categories = models.ManyToManyField("Category")
tags = ArrayField(models.CharField(max_length=50), blank=True, default=[],
help_text="Tags, separated by commas.")
# Location
states = ArrayField(models.CharField(choices=STATE_NATL_CHOICES, max_length=2), default=[],
help_text="List of state abbreviations: NC, CA, PA, etc. Use 'US' for a national dataset")
division_names = ArrayField(models.CharField(max_length=150), default=[],
help_text='Describes one or more geographic divisions such as a city or county.')
# Resource Information
resource_location = models.TextField(blank=True,
help_text='Describes where in a resource to find the dataset.')
updated = models.NullBooleanField(help_text="Does this resource get updated?")
frequency = models.CharField(blank=True, max_length=50,
help_text="How often this resource is updated.")
sectors = ArrayField(models.CharField(max_length=40), blank=True, default=[],
help_text="Sectors responsible for the data resource, such as \
'Private' or 'Government' or 'Non-Profit', separated by commas.")
# Data Properties
mappable = models.NullBooleanField(help_text="Can the information be put on a map, i.e. a crime map?")
population_data = models.NullBooleanField(help_text="Does this dataset include population data?")
formats = ArrayField(models.CharField(max_length=40), blank=True, default=[],
help_text="Enter formats, separated by commas")
data_range = models.CharField(blank=True, max_length=100,
help_text="Human-readable description of the time period covered in the data.")
# Availability
internet_available = models.NullBooleanField(help_text="Is this dataset available online?")
access_type = models.CharField(db_index=True, blank=True, max_length=50,
help_text="Description of how data can be accessed, and if it is machine readable.")
# Associated Information
associated_legislation = models.TextField(blank=True)
associated_grant = models.TextField(blank=True,
help_text="Name of associated grant that funds the dataset, if available.")
class Meta:
get_latest_by = 'created_at'
verbose_name = "Dataset"
verbose_name_plural = "Datasets"
ordering = ['states', '-updated_at', 'url']
def states_expanded(self):
return (STATE_NATL_LOOKUP[s] for s in self.states)
def get_states_display(self):
return ", ".join(self.states_expanded())
def get_states_abbr_display(self):
return ", ".join(self.states)
def get_division_names_display(self):
return ", ".join(self.division_names)
def get_absolute_url(self):
return reverse('dataset-detail', args=[str(self.uuid)])
def __str__(self):
return "{states} ({sectors}): {title}".format(states=self.get_states_display(),
title=self.title,
sectors=",".join(self.sectors))
| sunlightlabs/hall-of-justice | cjdata/models.py | Python | bsd-3-clause | 5,438 |
<?php
/**
* This is the model class for table "competidor".
*
* The followings are the available columns in table 'competidor':
* @property integer $id
* @property string $nombre
*
* The followings are the available model relations:
* @property Cliente[] $clientes
*/
class Competidor extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'competidor';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('nombre', 'required'),
array('nombre', 'length', 'max'=>45),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, nombre', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'clientes' => array(self::MANY_MANY, 'Cliente', 'cliente_competidor(competidor_id, cliente_id)'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'nombre' => 'Nombre',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('nombre',$this->nombre,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Competidor the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
| marceloepuyao/dashboard | protected/models/Competidor.php | PHP | bsd-3-clause | 2,593 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\search\ProductoSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="producto-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id_producto') ?>
<?= $form->field($model, 'nombre') ?>
<?= $form->field($model, 'foto') ?>
<?= $form->field($model, 'descipcion') ?>
<?= $form->field($model, 'id_categoria') ?>
<?php // echo $form->field($model, 'status') ?>
<?php // echo $form->field($model, 'id_empresa') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| sburgos/easydelivery | modules/admin/views/producto/_search.php | PHP | bsd-3-clause | 891 |
/*
* $Id: Boolean.java,v 1.19 2007/08/27 11:18:20 agoubard Exp $
*
* Copyright 2003-2007 Orange Nederland Breedband B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.types.standard;
import org.xins.common.types.Type;
import org.xins.common.types.TypeValueException;
import org.xins.common.MandatoryArgumentChecker;
/**
* Standard type <em>_boolean</em>.
*
* @version $Revision: 1.19 $ $Date: 2007/08/27 11:18:20 $
* @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a>
*
* @since XINS 1.0.0
*/
public final class Boolean extends Type {
/**
* The only instance of this class. This field is never <code>null</code>.
*/
public static final Boolean SINGLETON = new org.xins.common.types.standard.Boolean();
/**
* Constructs a new <code>Boolean</code>.
* This constructor is private, the field {@link #SINGLETON} should be
* used.
*/
private Boolean() {
super("_boolean", java.lang.Boolean.class);
}
/**
* Converts the specified non-<code>null</code> string value to a
* <code>boolean</code>.
*
* @param string
* the string to convert, cannot be <code>null</code>.
*
* @return
* the <code>boolean</code> value.
*
* @throws IllegalArgumentException
* if <code>string == null</code>.
*
* @throws TypeValueException
* if the specified string does not represent a valid value for this
* type.
*/
public static boolean fromStringForRequired(String string)
throws IllegalArgumentException, TypeValueException {
if ("true".equals(string)) {
return true;
} else if ("false".equals(string)) {
return false;
} else if (string == null) {
throw new IllegalArgumentException("string == null");
} else {
throw new TypeValueException(SINGLETON, string);
}
}
/**
* Converts the specified string value to a <code>java.lang.Boolean</code>
* value.
*
* @param string
* the string to convert, can be <code>null</code>.
*
* @return
* the {@link java.lang.Boolean}, or <code>null</code> if
* <code>string == null</code>.
*
* @throws TypeValueException
* if the specified string does not represent a valid value for this
* type.
*/
public static java.lang.Boolean fromStringForOptional(String string)
throws TypeValueException {
if ("true".equals(string)) {
return java.lang.Boolean.TRUE;
} else if ("false".equals(string)) {
return java.lang.Boolean.FALSE;
} else if (string == null) {
return null;
} else {
throw new TypeValueException(SINGLETON, string);
}
}
/**
* Converts the specified <code>Boolean</code> to a string.
*
* @param value
* the value to convert, can be <code>null</code>.
*
* @return
* the textual representation of the value, or <code>null</code> if and
* only if <code>value == null</code>.
*/
public static String toString(java.lang.Boolean value) {
if (value == null) {
return null;
} else {
return toString(value.booleanValue());
}
}
/**
* Converts the specified <code>boolean</code> to a string.
*
* @param value
* the value to convert.
*
* @return
* the textual representation of the value, never <code>null</code>.
*/
public static String toString(boolean value) {
return value ? "true" : "false";
}
@Override
protected void checkValueImpl(String string) throws TypeValueException {
if (! ("true".equals(string) || "false".equals(string))) {
throw new TypeValueException(this, string, "Expected either \"true\" or \"false\".");
}
}
@Override
protected Object fromStringImpl(String string) {
return "true".equals(string) ? java.lang.Boolean.TRUE
: java.lang.Boolean.FALSE;
}
@Override
public String toString(Object value)
throws IllegalArgumentException, ClassCastException, TypeValueException {
MandatoryArgumentChecker.check("value", value);
java.lang.Boolean b = (java.lang.Boolean) value;
return b.toString();
}
@Override
public String getDescription() {
return "A boolean, either 'true' or 'false'.";
}
}
| znerd/xins | src/java/org/xins/common/types/standard/Boolean.java | Java | bsd-3-clause | 4,415 |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"fmt"
"go/token"
"go/types"
"strings"
)
type goGen struct {
*printer
fset *token.FileSet
pkg *types.Package
err ErrorList
}
func (g *goGen) errorf(format string, args ...interface{}) {
g.err = append(g.err, fmt.Errorf(format, args...))
}
const goPreamble = `// Package go_%s is an autogenerated binder stub for package %s.
// gobind -lang=go %s
//
// File is generated by gobind. Do not edit.
package go_%s
import (
"golang.org/x/mobile/bind/seq"
%q
)
`
func (g *goGen) genPreamble() {
n := g.pkg.Name()
g.Printf(goPreamble, n, n, g.pkg.Path(), n, g.pkg.Path())
}
func (g *goGen) genFuncBody(o *types.Func, selectorLHS string) {
sig := o.Type().(*types.Signature)
params := sig.Params()
for i := 0; i < params.Len(); i++ {
p := params.At(i)
g.genRead("param_"+paramName(params, i), "in", p.Type())
}
res := sig.Results()
if res.Len() > 2 || res.Len() == 2 && !isErrorType(res.At(1).Type()) {
g.errorf("functions and methods must return either zero or one values, and optionally an error")
return
}
returnsValue := false
returnsError := false
if res.Len() == 1 {
if isErrorType(res.At(0).Type()) {
returnsError = true
g.Printf("err := ")
} else {
returnsValue = true
g.Printf("res := ")
}
} else if res.Len() == 2 {
returnsValue = true
returnsError = true
g.Printf("res, err := ")
}
g.Printf("%s.%s(", selectorLHS, o.Name())
for i := 0; i < params.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("param_%s", paramName(params, i))
}
g.Printf(")\n")
if returnsValue {
g.genWrite("res", "out", res.At(0).Type())
}
if returnsError {
g.genWrite("err", "out", res.At(res.Len()-1).Type())
}
}
func (g *goGen) genWrite(valName, seqName string, T types.Type) {
if isErrorType(T) {
g.Printf("if %s == nil {\n", valName)
g.Printf(" %s.WriteString(\"\");\n", seqName)
g.Printf("} else {\n")
g.Printf(" %s.WriteString(%s.Error());\n", seqName, valName)
g.Printf("}\n")
return
}
switch T := T.(type) {
case *types.Pointer:
// TODO(crawshaw): test *int
// TODO(crawshaw): test **Generator
switch T := T.Elem().(type) {
case *types.Named:
obj := T.Obj()
if obj.Pkg() != g.pkg {
g.errorf("type %s not defined in package %s", T, g.pkg)
return
}
g.Printf("%s.WriteGoRef(%s)\n", seqName, valName)
default:
g.errorf("unsupported type %s", T)
}
case *types.Named:
switch u := T.Underlying().(type) {
case *types.Interface, *types.Pointer:
g.Printf("%s.WriteGoRef(%s)\n", seqName, valName)
default:
g.errorf("unsupported, direct named type %s: %s", T, u)
}
default:
g.Printf("%s.Write%s(%s);\n", seqName, seqType(T), valName)
}
}
func (g *goGen) genFunc(o *types.Func) {
g.Printf("func proxy_%s(out, in *seq.Buffer) {\n", o.Name())
g.Indent()
g.genFuncBody(o, g.pkg.Name())
g.Outdent()
g.Printf("}\n\n")
}
func (g *goGen) genStruct(obj *types.TypeName, T *types.Struct) {
fields := exportedFields(T)
methods := exportedMethodSet(types.NewPointer(obj.Type()))
g.Printf("const (\n")
g.Indent()
g.Printf("proxy%s_Descriptor = \"go.%s.%s\"\n", obj.Name(), g.pkg.Name(), obj.Name())
for i, f := range fields {
g.Printf("proxy%s_%s_Get_Code = 0x%x0f\n", obj.Name(), f.Name(), i)
g.Printf("proxy%s_%s_Set_Code = 0x%x1f\n", obj.Name(), f.Name(), i)
}
for i, m := range methods {
g.Printf("proxy%s_%s_Code = 0x%x0c\n", obj.Name(), m.Name(), i)
}
g.Outdent()
g.Printf(")\n\n")
g.Printf("type proxy%s seq.Ref\n\n", obj.Name())
for _, f := range fields {
g.Printf("func proxy%s_%s_Set(out, in *seq.Buffer) {\n", obj.Name(), f.Name())
g.Indent()
g.Printf("ref := in.ReadRef()\n")
g.genRead("v", "in", f.Type())
g.Printf("ref.Get().(*%s.%s).%s = v\n", g.pkg.Name(), obj.Name(), f.Name())
g.Outdent()
g.Printf("}\n\n")
g.Printf("func proxy%s_%s_Get(out, in *seq.Buffer) {\n", obj.Name(), f.Name())
g.Indent()
g.Printf("ref := in.ReadRef()\n")
g.Printf("v := ref.Get().(*%s.%s).%s\n", g.pkg.Name(), obj.Name(), f.Name())
g.genWrite("v", "out", f.Type())
g.Outdent()
g.Printf("}\n\n")
}
for _, m := range methods {
g.Printf("func proxy%s_%s(out, in *seq.Buffer) {\n", obj.Name(), m.Name())
g.Indent()
g.Printf("ref := in.ReadRef()\n")
g.Printf("v := ref.Get().(*%s.%s)\n", g.pkg.Name(), obj.Name())
g.genFuncBody(m, "v")
g.Outdent()
g.Printf("}\n\n")
}
g.Printf("func init() {\n")
g.Indent()
for _, f := range fields {
n := f.Name()
g.Printf("seq.Register(proxy%s_Descriptor, proxy%s_%s_Set_Code, proxy%s_%s_Set)\n", obj.Name(), obj.Name(), n, obj.Name(), n)
g.Printf("seq.Register(proxy%s_Descriptor, proxy%s_%s_Get_Code, proxy%s_%s_Get)\n", obj.Name(), obj.Name(), n, obj.Name(), n)
}
for _, m := range methods {
n := m.Name()
g.Printf("seq.Register(proxy%s_Descriptor, proxy%s_%s_Code, proxy%s_%s)\n", obj.Name(), obj.Name(), n, obj.Name(), n)
}
g.Outdent()
g.Printf("}\n\n")
}
func (g *goGen) genInterface(obj *types.TypeName) {
iface := obj.Type().(*types.Named).Underlying().(*types.Interface)
ifaceDesc := fmt.Sprintf("go.%s.%s", g.pkg.Name(), obj.Name())
summary := makeIfaceSummary(iface)
// Descriptor and code for interface methods.
g.Printf("const (\n")
g.Indent()
g.Printf("proxy%s_Descriptor = %q\n", obj.Name(), ifaceDesc)
for i, m := range summary.callable {
g.Printf("proxy%s_%s_Code = 0x%x0a\n", obj.Name(), m.Name(), i+1)
}
g.Outdent()
g.Printf(")\n\n")
// Define the entry points.
for _, m := range summary.callable {
g.Printf("func proxy%s_%s(out, in *seq.Buffer) {\n", obj.Name(), m.Name())
g.Indent()
g.Printf("ref := in.ReadRef()\n")
g.Printf("v := ref.Get().(%s.%s)\n", g.pkg.Name(), obj.Name())
g.genFuncBody(m, "v")
g.Outdent()
g.Printf("}\n\n")
}
// Register the method entry points.
if len(summary.callable) > 0 {
g.Printf("func init() {\n")
g.Indent()
for _, m := range summary.callable {
g.Printf("seq.Register(proxy%s_Descriptor, proxy%s_%s_Code, proxy%s_%s)\n",
obj.Name(), obj.Name(), m.Name(), obj.Name(), m.Name())
}
g.Outdent()
g.Printf("}\n\n")
}
// Define a proxy interface.
if !summary.implementable {
// The interface defines an unexported method or a method that
// uses an unexported type. We cannot generate a proxy object
// for such a type.
return
}
g.Printf("type proxy%s seq.Ref\n\n", obj.Name())
for i := 0; i < iface.NumMethods(); i++ {
m := iface.Method(i)
sig := m.Type().(*types.Signature)
params := sig.Params()
res := sig.Results()
if res.Len() > 2 ||
(res.Len() == 2 && !isErrorType(res.At(1).Type())) {
g.errorf("functions and methods must return either zero or one value, and optionally an error: %s.%s", obj.Name(), m.Name())
continue
}
g.Printf("func (p *proxy%s) %s(", obj.Name(), m.Name())
for i := 0; i < params.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("%s %s", paramName(params, i), g.typeString(params.At(i).Type()))
}
g.Printf(") ")
if res.Len() == 1 {
g.Printf(g.typeString(res.At(0).Type()))
} else if res.Len() == 2 {
g.Printf("(%s, error)", g.typeString(res.At(0).Type()))
}
g.Printf(" {\n")
g.Indent()
g.Printf("in := new(seq.Buffer)\n")
for i := 0; i < params.Len(); i++ {
g.genWrite(paramName(params, i), "in", params.At(i).Type())
}
if res.Len() == 0 {
g.Printf("seq.Transact((*seq.Ref)(p), %q, proxy%s_%s_Code, in)\n", ifaceDesc, obj.Name(), m.Name())
} else {
g.Printf("out := seq.Transact((*seq.Ref)(p), %q, proxy%s_%s_Code, in)\n", ifaceDesc, obj.Name(), m.Name())
var rvs []string
for i := 0; i < res.Len(); i++ {
rv := fmt.Sprintf("res_%d", i)
g.genRead(rv, "out", res.At(i).Type())
rvs = append(rvs, rv)
}
g.Printf("return %s\n", strings.Join(rvs, ","))
}
g.Outdent()
g.Printf("}\n\n")
}
}
func (g *goGen) genRead(valName, seqName string, typ types.Type) {
if isErrorType(typ) {
g.Printf("%s := %s.ReadError()\n", valName, seqName)
return
}
switch t := typ.(type) {
case *types.Pointer:
switch u := t.Elem().(type) {
case *types.Named:
o := u.Obj()
if o.Pkg() != g.pkg {
g.errorf("type %s not defined in package %s", u, g.pkg)
return
}
g.Printf("// Must be a Go object\n")
g.Printf("%s_ref := %s.ReadRef()\n", valName, seqName)
g.Printf("%s_ref_get := %s_ref.Get()\n", valName, valName)
g.Printf("var %s *%s.%s\n", valName, g.pkg.Name(), o.Name())
g.Printf("if %s_ref_get == nil {\n", valName)
g.Printf(" %s = nil\n", valName)
g.Printf("} else {\n")
g.Printf(" %s = %s_ref_get.(*%s.%s)\n", valName, valName, g.pkg.Name(), o.Name())
g.Printf("}\n")
default:
g.errorf("unsupported type %s", t)
}
case *types.Named:
switch t.Underlying().(type) {
case *types.Interface, *types.Pointer:
hasProxy := true
if iface, ok := t.Underlying().(*types.Interface); ok {
hasProxy = makeIfaceSummary(iface).implementable
}
o := t.Obj()
if o.Pkg() != g.pkg {
g.errorf("type %s not defined in package %s", t, g.pkg)
return
}
g.Printf("var %s %s\n", valName, g.typeString(t))
g.Printf("%s_ref := %s.ReadRef()\n", valName, seqName)
g.Printf("if %s_ref.Num < 0 { // go object \n", valName)
g.Printf(" %s = %s_ref.Get().(%s.%s)\n", valName, valName, g.pkg.Name(), o.Name())
g.Printf("} else if %s_ref.Num == 0 { // nil object \n", valName)
g.Printf(" %s = nil\n", valName)
if hasProxy {
g.Printf("} else { // foreign object \n")
g.Printf(" %s = (*proxy%s)(%s_ref)\n", valName, o.Name(), valName)
}
g.Printf("}\n")
}
default:
g.Printf("%s := %s.Read%s()\n", valName, seqName, seqType(t))
}
}
func (g *goGen) typeString(typ types.Type) string {
pkg := g.pkg
switch t := typ.(type) {
case *types.Named:
obj := t.Obj()
if obj.Pkg() == nil { // e.g. error type is *types.Named.
return types.TypeString(typ, types.RelativeTo(pkg))
}
if obj.Pkg() != g.pkg {
g.errorf("type %s not defined in package %s", t, g.pkg)
}
switch t.Underlying().(type) {
case *types.Interface, *types.Struct:
return fmt.Sprintf("%s.%s", pkg.Name(), types.TypeString(typ, types.RelativeTo(pkg)))
default:
g.errorf("unsupported named type %s / %T", t, t)
}
case *types.Pointer:
switch t := t.Elem().(type) {
case *types.Named:
return fmt.Sprintf("*%s", g.typeString(t))
default:
g.errorf("not yet supported, pointer type %s / %T", t, t)
}
default:
return types.TypeString(typ, types.RelativeTo(pkg))
}
return ""
}
func (g *goGen) gen() error {
g.genPreamble()
var funcs []string
scope := g.pkg.Scope()
names := scope.Names()
for _, name := range names {
obj := scope.Lookup(name)
if !obj.Exported() {
continue
}
switch obj := obj.(type) {
// TODO(crawshaw): case *types.Var:
case *types.Func:
// TODO(crawshaw): functions that are not implementable from
// another language may still be callable.
if isCallable(obj) {
g.genFunc(obj)
funcs = append(funcs, obj.Name())
}
case *types.TypeName:
named := obj.Type().(*types.Named)
switch T := named.Underlying().(type) {
case *types.Struct:
g.genStruct(obj, T)
case *types.Interface:
g.genInterface(obj)
}
case *types.Const:
default:
g.errorf("not yet supported, name for %v / %T", obj, obj)
continue
}
}
if len(funcs) > 0 {
g.Printf("func init() {\n")
g.Indent()
for i, name := range funcs {
g.Printf("seq.Register(%q, %d, proxy_%s)\n", g.pkg.Name(), i+1, name)
}
g.Outdent()
g.Printf("}\n")
}
if len(g.err) > 0 {
return g.err
}
return nil
}
| xing/gomobile | bind/gengo.go | GO | bsd-3-clause | 11,730 |
#pragma once
namespace Ra {
namespace Core {
namespace _internalIterator {
template <class T>
struct _reversed {
T& t;
explicit _reversed( T& _t ) : t( _t ) {}
};
template <class T>
struct _creversed {
const T& t;
explicit _creversed( const T& _t ) : t( _t ) {}
};
} // namespace _internalIterator
// Provide reverse iterators for range loops and std::containers:
// \code for (auto x: reversed(c)) ; \endcode
// source: https://stackoverflow.com/a/21510185
template <class T>
_internalIterator::_reversed<T> reversed( T& t ) {
return _internalIterator::_reversed<T>( t );
}
template <class T>
_internalIterator::_reversed<T const> reversed( T const& t ) {
return _internalIterator::_reversed<T const>( t );
}
} // namespace Core
} // namespace Ra
namespace std {
template <class T>
auto begin( Ra::Core::_internalIterator::_reversed<T>& r ) -> decltype( r.t.rbegin() ) {
return r.t.rbegin();
}
template <class T>
auto end( Ra::Core::_internalIterator::_reversed<T>& r ) -> decltype( r.t.rend() ) {
return r.t.rend();
}
template <class T>
auto begin( Ra::Core::_internalIterator::_creversed<T> const& cr ) -> decltype( cr.t.rbegin() ) {
return cr.t.rbegin();
}
template <class T>
auto end( Ra::Core::_internalIterator::_creversed<T> const& cr ) -> decltype( cr.t.rend() ) {
return cr.t.rend();
}
} // namespace std
| Zouch/Radium-Engine | src/Core/Containers/Iterators.hpp | C++ | bsd-3-clause | 1,360 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package ioutil implements some I/O utility functions.
package ioutil
import (
"bytes"
"io"
"os"
"sort"
)
// readAll reads from r until an error or EOF and returns the data it read
// from the internal buffer allocated with a specified capacity.
func readAll(r io.Reader, capacity int64) ([]byte, os.Error) {
buf := bytes.NewBuffer(make([]byte, 0, capacity))
_, err := buf.ReadFrom(r)
return buf.Bytes(), err
}
// ReadAll reads from r until an error or EOF and returns the data it read.
func ReadAll(r io.Reader) ([]byte, os.Error) {
return readAll(r, bytes.MinRead)
}
// ReadFile reads the file named by filename and returns the contents.
func ReadFile(filename string) ([]byte, os.Error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
// It's a good but not certain bet that FileInfo will tell us exactly how much to
// read, so let's try it but be prepared for the answer to be wrong.
fi, err := f.Stat()
var n int64
if err == nil && fi.Size < 2e9 { // Don't preallocate a huge buffer, just in case.
n = fi.Size
}
// As initial capacity for readAll, use n + a little extra in case Size is zero,
// and to avoid another allocation after Read has filled the buffer. The readAll
// call will read into its allocated internal buffer cheaply. If the size was
// wrong, we'll either waste some space off the end or reallocate as needed, but
// in the overwhelmingly common case we'll get it just right.
return readAll(f, n+bytes.MinRead)
}
// WriteFile writes data to a file named by filename.
// If the file does not exist, WriteFile creates it with permissions perm;
// otherwise WriteFile truncates it before writing.
func WriteFile(filename string, data []byte, perm uint32) os.Error {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
n, err := f.Write(data)
f.Close()
if err == nil && n < len(data) {
err = io.ErrShortWrite
}
return err
}
// A dirList implements sort.Interface.
type fileInfoList []*os.FileInfo
func (f fileInfoList) Len() int { return len(f) }
func (f fileInfoList) Less(i, j int) bool { return f[i].Name < f[j].Name }
func (f fileInfoList) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
// ReadDir reads the directory named by dirname and returns
// a list of sorted directory entries.
func ReadDir(dirname string) ([]*os.FileInfo, os.Error) {
f, err := os.Open(dirname)
if err != nil {
return nil, err
}
list, err := f.Readdir(-1)
f.Close()
if err != nil {
return nil, err
}
fi := make(fileInfoList, len(list))
for i := range list {
fi[i] = &list[i]
}
sort.Sort(fi)
return fi, nil
}
type nopCloser struct {
io.Reader
}
func (nopCloser) Close() os.Error { return nil }
// NopCloser returns a ReadCloser with a no-op Close method wrapping
// the provided Reader r.
func NopCloser(r io.Reader) io.ReadCloser {
return nopCloser{r}
}
type devNull int
func (devNull) Write(p []byte) (int, os.Error) {
return len(p), nil
}
// Discard is an io.Writer on which all Write calls succeed
// without doing anything.
var Discard io.Writer = devNull(0)
| SDpower/golang | src/pkg/io/ioutil/ioutil.go | GO | bsd-3-clause | 3,297 |
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2010-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_GEOMETRIES_ADAPTED_BOOST_POLYGON_POLYGON_HPP
#define BOOST_GEOMETRY_GEOMETRIES_ADAPTED_BOOST_POLYGON_POLYGON_HPP
// Adapts Geometries from Boost.Polygon for usage in Boost.Geometry
// pdalboost::polygon::polygon_with_holes_data -> pdalboost::geometry::polygon
#include <boost/polygon/polygon.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/core/ring_type.hpp>
#include <boost/geometry/core/exterior_ring.hpp>
#include <boost/geometry/core/interior_rings.hpp>
#include <boost/geometry/geometries/adapted/boost_polygon/ring_proxy.hpp>
#include <boost/geometry/geometries/adapted/boost_polygon/hole_iterator.hpp>
#include <boost/geometry/geometries/adapted/boost_polygon/holes_proxy.hpp>
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace geometry
{
#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS
namespace traits
{
template <typename CoordinateType>
struct tag<pdalboost::polygon::polygon_with_holes_data<CoordinateType> >
{
typedef polygon_tag type;
};
template <typename CoordinateType>
struct ring_const_type<pdalboost::polygon::polygon_with_holes_data<CoordinateType> >
{
typedef adapt::bp::ring_proxy<pdalboost::polygon::polygon_with_holes_data<CoordinateType> const> type;
};
template <typename CoordinateType>
struct ring_mutable_type<pdalboost::polygon::polygon_with_holes_data<CoordinateType> >
{
typedef adapt::bp::ring_proxy<pdalboost::polygon::polygon_with_holes_data<CoordinateType> > type;
};
template <typename CoordinateType>
struct interior_const_type<pdalboost::polygon::polygon_with_holes_data<CoordinateType> >
{
typedef adapt::bp::holes_proxy<pdalboost::polygon::polygon_with_holes_data<CoordinateType> const> type;
};
template <typename CoordinateType>
struct interior_mutable_type<pdalboost::polygon::polygon_with_holes_data<CoordinateType> >
{
typedef adapt::bp::holes_proxy<pdalboost::polygon::polygon_with_holes_data<CoordinateType> > type;
};
template <typename CoordinateType>
struct exterior_ring<pdalboost::polygon::polygon_with_holes_data<CoordinateType> >
{
typedef pdalboost::polygon::polygon_with_holes_data<CoordinateType> polygon_type;
typedef adapt::bp::ring_proxy<polygon_type> proxy;
typedef adapt::bp::ring_proxy<polygon_type const> const_proxy;
static inline proxy get(polygon_type& p)
{
return proxy(p);
}
static inline const_proxy get(polygon_type const& p)
{
return const_proxy(p);
}
};
template <typename CoordinateType>
struct interior_rings<pdalboost::polygon::polygon_with_holes_data<CoordinateType> >
{
typedef pdalboost::polygon::polygon_with_holes_data<CoordinateType> polygon_type;
typedef adapt::bp::holes_proxy<polygon_type> proxy;
typedef adapt::bp::holes_proxy<polygon_type const> const_proxy;
static inline proxy get(polygon_type& p)
{
return proxy(p);
}
static inline const_proxy get(polygon_type const& p)
{
return const_proxy(p);
}
};
} // namespace traits
#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS
}} // namespace pdalboost::geometry
#endif // BOOST_GEOMETRY_GEOMETRIES_ADAPTED_BOOST_POLYGON_POLYGON_HPP
| verma/PDAL | boost/boost/geometry/geometries/adapted/boost_polygon/polygon.hpp | C++ | bsd-3-clause | 3,504 |
// *****************************************************************************
//
// © Component Factory Pty Ltd 2017. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to licence terms.
//
// Version 4.6.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Ribbon
{
internal class KryptonRibbonGroupDomainUpDownDesigner : ComponentDesigner, IKryptonDesignObject
{
#region Instance Fields
private IDesignerHost _designerHost;
private IComponentChangeService _changeService;
private KryptonRibbonGroupDomainUpDown _ribbonDomainUpDown;
private DesignerVerbCollection _verbs;
private DesignerVerb _toggleHelpersVerb;
private DesignerVerb _moveFirstVerb;
private DesignerVerb _movePrevVerb;
private DesignerVerb _moveNextVerb;
private DesignerVerb _moveLastVerb;
private DesignerVerb _deleteDomainUpDownVerb;
private ContextMenuStrip _cms;
private ToolStripMenuItem _toggleHelpersMenu;
private ToolStripMenuItem _visibleMenu;
private ToolStripMenuItem _moveFirstMenu;
private ToolStripMenuItem _movePreviousMenu;
private ToolStripMenuItem _moveNextMenu;
private ToolStripMenuItem _moveLastMenu;
private ToolStripMenuItem _deleteDomainUpDownMenu;
private bool _visible;
private bool _enabled;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the KryptonRibbonGroupDomainUpDownDesigner class.
/// </summary>
public KryptonRibbonGroupDomainUpDownDesigner()
{
}
#endregion
#region Public
/// <summary>
/// Initializes the designer with the specified component.
/// </summary>
/// <param name="component">The IComponent to associate the designer with.</param>
public override void Initialize(IComponent component)
{
Debug.Assert(component != null);
// Validate the parameter reference
if (component == null) throw new ArgumentNullException("component");
// Let base class do standard stuff
base.Initialize(component);
// Cast to correct type
_ribbonDomainUpDown = (KryptonRibbonGroupDomainUpDown)component;
_ribbonDomainUpDown.DomainUpDownDesigner = this;
// Update designer properties with actual starting values
Visible = _ribbonDomainUpDown.Visible;
Enabled = _ribbonDomainUpDown.Enabled;
// Update visible/enabled to always be showing/enabled at design time
_ribbonDomainUpDown.Visible = true;
_ribbonDomainUpDown.Enabled = true;
// Tell the embedded domain up-down control it is in design mode
_ribbonDomainUpDown.DomainUpDown.InRibbonDesignMode = true;
// Hook into events
_ribbonDomainUpDown.DesignTimeContextMenu += new MouseEventHandler(OnContextMenu);
// Get access to the services
_designerHost = (IDesignerHost)GetService(typeof(IDesignerHost));
_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
// We need to know when we are being removed/changed
_changeService.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged);
}
/// <summary>
/// Gets the design-time verbs supported by the component that is associated with the designer.
/// </summary>
public override DesignerVerbCollection Verbs
{
get
{
UpdateVerbStatus();
return _verbs;
}
}
/// <summary>
/// Gets and sets if the object is enabled.
/// </summary>
public bool DesignEnabled
{
get { return Enabled; }
set { Enabled = value; }
}
/// <summary>
/// Gets and sets if the object is visible.
/// </summary>
public bool DesignVisible
{
get { return Visible; }
set { Visible = value; }
}
#endregion
#region Protected
/// <summary>
/// Releases all resources used by the component.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
// Unhook from events
_ribbonDomainUpDown.DesignTimeContextMenu -= new MouseEventHandler(OnContextMenu);
_changeService.ComponentChanged -= new ComponentChangedEventHandler(OnComponentChanged);
}
}
finally
{
// Must let base class do standard stuff
base.Dispose(disposing);
}
}
/// <summary>
/// Adjusts the set of properties the component exposes through a TypeDescriptor.
/// </summary>
/// <param name="properties">An IDictionary containing the properties for the class of the component.</param>
protected override void PreFilterProperties(IDictionary properties)
{
base.PreFilterProperties(properties);
// Setup the array of properties we override
Attribute[] attributes = new Attribute[0];
string[] strArray = new string[] { "Visible", "Enabled" };
// Adjust our list of properties
for (int i = 0; i < strArray.Length; i++)
{
PropertyDescriptor descrip = (PropertyDescriptor)properties[strArray[i]];
if (descrip != null)
properties[strArray[i]] = TypeDescriptor.CreateProperty(typeof(KryptonRibbonGroupDomainUpDownDesigner), descrip, attributes);
}
}
#endregion
#region Internal
internal bool Visible
{
get { return _visible; }
set { _visible = value; }
}
internal bool Enabled
{
get { return _enabled; }
set { _enabled = value; }
}
#endregion
#region Implementation
private void ResetVisible()
{
Visible = true;
}
private bool ShouldSerializeVisible()
{
return !Visible;
}
private void ResetEnabled()
{
Enabled = true;
}
private bool ShouldSerializeEnabled()
{
return !Enabled;
}
private void UpdateVerbStatus()
{
// Create verbs first time around
if (_verbs == null)
{
_verbs = new DesignerVerbCollection();
_toggleHelpersVerb = new DesignerVerb("Toggle Helpers", new EventHandler(OnToggleHelpers));
_moveFirstVerb = new DesignerVerb("Move DomainUpDown First", new EventHandler(OnMoveFirst));
_movePrevVerb = new DesignerVerb("Move DomainUpDown Previous", new EventHandler(OnMovePrevious));
_moveNextVerb = new DesignerVerb("Move DomainUpDown Next", new EventHandler(OnMoveNext));
_moveLastVerb = new DesignerVerb("Move DomainUpDown Last", new EventHandler(OnMoveLast));
_deleteDomainUpDownVerb = new DesignerVerb("Delete DomainUpDown", new EventHandler(OnDeleteDomainUpDown));
_verbs.AddRange(new DesignerVerb[] { _toggleHelpersVerb, _moveFirstVerb, _movePrevVerb,
_moveNextVerb, _moveLastVerb, _deleteDomainUpDownVerb });
}
bool moveFirst = false;
bool movePrev = false;
bool moveNext = false;
bool moveLast = false;
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
{
TypedRestrictCollection<KryptonRibbonGroupItem> items = ParentItems;
moveFirst = (items.IndexOf(_ribbonDomainUpDown) > 0);
movePrev = (items.IndexOf(_ribbonDomainUpDown) > 0);
moveNext = (items.IndexOf(_ribbonDomainUpDown) < (items.Count - 1));
moveLast = (items.IndexOf(_ribbonDomainUpDown) < (items.Count - 1));
}
_moveFirstVerb.Enabled = moveFirst;
_movePrevVerb.Enabled = movePrev;
_moveNextVerb.Enabled = moveNext;
_moveLastVerb.Enabled = moveLast;
}
private void OnToggleHelpers(object sender, EventArgs e)
{
// Invert the current toggle helper mode
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
_ribbonDomainUpDown.Ribbon.InDesignHelperMode = !_ribbonDomainUpDown.Ribbon.InDesignHelperMode;
}
private void OnMoveFirst(object sender, EventArgs e)
{
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
{
// Get access to the parent collection of items
TypedRestrictCollection<KryptonRibbonGroupItem> items = ParentItems;
// Use a transaction to support undo/redo actions
DesignerTransaction transaction = _designerHost.CreateTransaction("KryptonRibbonGroupDomainUpDown MoveFirst");
try
{
// Get access to the Items property
MemberDescriptor propertyItems = TypeDescriptor.GetProperties(_ribbonDomainUpDown.RibbonContainer)["Items"];
RaiseComponentChanging(propertyItems);
// Move position of the numeric up-down
items.Remove(_ribbonDomainUpDown);
items.Insert(0, _ribbonDomainUpDown);
UpdateVerbStatus();
RaiseComponentChanged(propertyItems, null, null);
}
finally
{
// If we managed to create the transaction, then do it
if (transaction != null)
transaction.Commit();
}
}
}
private void OnMovePrevious(object sender, EventArgs e)
{
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
{
// Get access to the parent collection of items
TypedRestrictCollection<KryptonRibbonGroupItem> items = ParentItems;
// Use a transaction to support undo/redo actions
DesignerTransaction transaction = _designerHost.CreateTransaction("KryptonRibbonGroupDomainUpDown MovePrevious");
try
{
// Get access to the Items property
MemberDescriptor propertyItems = TypeDescriptor.GetProperties(_ribbonDomainUpDown.RibbonContainer)["Items"];
RaiseComponentChanging(propertyItems);
// Move position of the numeric up-down
int index = items.IndexOf(_ribbonDomainUpDown) - 1;
index = Math.Max(index, 0);
items.Remove(_ribbonDomainUpDown);
items.Insert(index, _ribbonDomainUpDown);
UpdateVerbStatus();
RaiseComponentChanged(propertyItems, null, null);
}
finally
{
// If we managed to create the transaction, then do it
if (transaction != null)
transaction.Commit();
}
}
}
private void OnMoveNext(object sender, EventArgs e)
{
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
{
// Get access to the parent collection of items
TypedRestrictCollection<KryptonRibbonGroupItem> items = ParentItems;
// Use a transaction to support undo/redo actions
DesignerTransaction transaction = _designerHost.CreateTransaction("KryptonRibbonGroupDomainUpDown MoveNext");
try
{
// Get access to the Items property
MemberDescriptor propertyItems = TypeDescriptor.GetProperties(_ribbonDomainUpDown.RibbonContainer)["Items"];
RaiseComponentChanging(propertyItems);
// Move position of the numeric up-down
int index = items.IndexOf(_ribbonDomainUpDown) + 1;
index = Math.Min(index, items.Count - 1);
items.Remove(_ribbonDomainUpDown);
items.Insert(index, _ribbonDomainUpDown);
UpdateVerbStatus();
RaiseComponentChanged(propertyItems, null, null);
}
finally
{
// If we managed to create the transaction, then do it
if (transaction != null)
transaction.Commit();
}
}
}
private void OnMoveLast(object sender, EventArgs e)
{
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
{
// Get access to the parent collection of items
TypedRestrictCollection<KryptonRibbonGroupItem> items = ParentItems;
// Use a transaction to support undo/redo actions
DesignerTransaction transaction = _designerHost.CreateTransaction("KryptonRibbonGroupDomainUpDown MoveLast");
try
{
// Get access to the Items property
MemberDescriptor propertyItems = TypeDescriptor.GetProperties(_ribbonDomainUpDown.RibbonContainer)["Items"];
RaiseComponentChanging(propertyItems);
// Move position of the numeric up-down
items.Remove(_ribbonDomainUpDown);
items.Insert(items.Count, _ribbonDomainUpDown);
UpdateVerbStatus();
RaiseComponentChanged(propertyItems, null, null);
}
finally
{
// If we managed to create the transaction, then do it
if (transaction != null)
transaction.Commit();
}
}
}
private void OnDeleteDomainUpDown(object sender, EventArgs e)
{
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
{
// Get access to the parent collection of items
TypedRestrictCollection<KryptonRibbonGroupItem> items = ParentItems;
// Use a transaction to support undo/redo actions
DesignerTransaction transaction = _designerHost.CreateTransaction("KryptonRibbonGroupDomainUpDown DeleteDomainUpDown");
try
{
// Get access to the Items property
MemberDescriptor propertyItems = TypeDescriptor.GetProperties(_ribbonDomainUpDown.RibbonContainer)["Items"];
RaiseComponentChanging(null);
RaiseComponentChanging(propertyItems);
// Remove the numeric up-down from the group
items.Remove(_ribbonDomainUpDown);
// Get designer to destroy it
_designerHost.DestroyComponent(_ribbonDomainUpDown);
RaiseComponentChanged(propertyItems, null, null);
RaiseComponentChanged(null, null, null);
}
finally
{
// If we managed to create the transaction, then do it
if (transaction != null)
transaction.Commit();
}
}
}
private void OnEnabled(object sender, EventArgs e)
{
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
{
PropertyDescriptor propertyEnabled = TypeDescriptor.GetProperties(_ribbonDomainUpDown)["Enabled"];
bool oldValue = (bool)propertyEnabled.GetValue(_ribbonDomainUpDown);
bool newValue = !oldValue;
_changeService.OnComponentChanged(_ribbonDomainUpDown, null, oldValue, newValue);
propertyEnabled.SetValue(_ribbonDomainUpDown, newValue);
}
}
private void OnVisible(object sender, EventArgs e)
{
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
{
PropertyDescriptor propertyVisible = TypeDescriptor.GetProperties(_ribbonDomainUpDown)["Visible"];
bool oldValue = (bool)propertyVisible.GetValue(_ribbonDomainUpDown);
bool newValue = !oldValue;
_changeService.OnComponentChanged(_ribbonDomainUpDown, null, oldValue, newValue);
propertyVisible.SetValue(_ribbonDomainUpDown, newValue);
}
}
private void OnComponentChanged(object sender, ComponentChangedEventArgs e)
{
UpdateVerbStatus();
}
private void OnContextMenu(object sender, MouseEventArgs e)
{
if ((_ribbonDomainUpDown != null) && (_ribbonDomainUpDown.Ribbon != null))
{
// Create the menu strip the first time around
if (_cms == null)
{
_cms = new ContextMenuStrip();
_toggleHelpersMenu = new ToolStripMenuItem("Design Helpers", null, new EventHandler(OnToggleHelpers));
_visibleMenu = new ToolStripMenuItem("Visible", null, new EventHandler(OnVisible));
_moveFirstMenu = new ToolStripMenuItem("Move DomainUpDown First", Properties.Resources.MoveFirst, new EventHandler(OnMoveFirst));
_movePreviousMenu = new ToolStripMenuItem("Move DomainUpDown Previous", Properties.Resources.MovePrevious, new EventHandler(OnMovePrevious));
_moveNextMenu = new ToolStripMenuItem("Move DomainUpDown Next", Properties.Resources.MoveNext, new EventHandler(OnMoveNext));
_moveLastMenu = new ToolStripMenuItem("Move DomainUpDown Last", Properties.Resources.MoveLast, new EventHandler(OnMoveLast));
_deleteDomainUpDownMenu = new ToolStripMenuItem("Delete DomainUpDown", Properties.Resources.delete2, new EventHandler(OnDeleteDomainUpDown));
_cms.Items.AddRange(new ToolStripItem[] { _toggleHelpersMenu, new ToolStripSeparator(),
_visibleMenu, new ToolStripSeparator(),
_moveFirstMenu, _movePreviousMenu, _moveNextMenu, _moveLastMenu, new ToolStripSeparator(),
_deleteDomainUpDownMenu });
}
// Update verbs to work out correct enable states
UpdateVerbStatus();
// Update menu items state from versb
_toggleHelpersMenu.Checked = _ribbonDomainUpDown.Ribbon.InDesignHelperMode;
_visibleMenu.Checked = Visible;
_moveFirstMenu.Enabled = _moveFirstVerb.Enabled;
_movePreviousMenu.Enabled = _movePrevVerb.Enabled;
_moveNextMenu.Enabled = _moveNextVerb.Enabled;
_moveLastMenu.Enabled = _moveLastVerb.Enabled;
// Show the context menu
if (CommonHelper.ValidContextMenuStrip(_cms))
{
Point screenPt = _ribbonDomainUpDown.Ribbon.ViewRectangleToPoint(_ribbonDomainUpDown.DomainUpDownView);
VisualPopupManager.Singleton.ShowContextMenuStrip(_cms, screenPt);
}
}
}
private TypedRestrictCollection<KryptonRibbonGroupItem> ParentItems
{
get
{
if (_ribbonDomainUpDown.RibbonContainer is KryptonRibbonGroupTriple)
{
KryptonRibbonGroupTriple triple = (KryptonRibbonGroupTriple)_ribbonDomainUpDown.RibbonContainer;
return triple.Items;
}
else if (_ribbonDomainUpDown.RibbonContainer is KryptonRibbonGroupLines)
{
KryptonRibbonGroupLines lines = (KryptonRibbonGroupLines)_ribbonDomainUpDown.RibbonContainer;
return lines.Items;
}
else
{
// Should never happen!
Debug.Assert(false);
return null;
}
}
}
#endregion
}
}
| ComponentFactory/Krypton | Source/Krypton Components/ComponentFactory.Krypton.Ribbon/Ribbon/KryptonRibbonGroupDomainUpDownDesigner.cs | C# | bsd-3-clause | 21,816 |
$(document).ready(function() {
Drupal.dupe.clearDOB();
});
Drupal.dupe = {};
Drupal.dupe.clearDOB = function() {
y = $("#edit-profile-dob-year").val();
var years = '';
var d = new Date();
var max_year = d.getFullYear() - 18;
for (i = 1900; i <= max_year; i++) years += '<option value="' + i + '">' + i + '</option>';
$("#edit-profile-dob-year").html(years);
if (y > max_year) y = max_year;
$("#edit-profile-dob-year").val(y);
}
Drupal.dupe.stepOne = function() {
$("#user-register div fieldset:eq(0)").show();
$("#user-register div fieldset:eq(1)").show();
$("#user-register div fieldset:eq(2)").show();
$("#edit-submit").val("Continue");
};
Drupal.dupe.stepTwo = function() {
//$("#user-register div fieldset:eq(2)").slideDown();
};
Drupal.dupe.cancel = function() {
window.location = '';
}
Drupal.dupe.clearErrors = function() {
$("#user-register div fieldset input").removeClass('error');
};
Drupal.dupe.dupeUserYes = function() {
$("#user-register").append('<input type="hidden" name="i_am_dupe" value="1">');
$("#user-register").submit();
};
Drupal.dupe.dupeUserNo = function() {
$("#user-register").append('<input type="hidden" name="i_am_dupe" value="0">');
$("#user-register").submit();
};
| NCIP/edct-collector | collector-CMS/sites/all/modules/custom/dupe/dupe.js | JavaScript | bsd-3-clause | 1,290 |
package org.basex.io.out;
import java.io.*;
import org.basex.data.*;
import org.basex.io.*;
/**
* This class allows a blockwise output of the database table.
*
* @author BaseX Team 2005-22, BSD License
* @author Christian Gruen
* @author Tim Petrowsky
*/
public final class TableOutput extends OutputStream {
/** Buffer. */
private final byte[] buffer = new byte[IO.BLOCKSIZE];
/** The underlying output stream. */
private final OutputStream os;
/** Meta data. */
private final MetaData meta;
/** Current filename. */
private final String file;
/** Current buffer position. */
private int pos;
/** Number of pages. */
private int pages;
/**
* Initializes the output.
* The database suffix will be added to all filenames.
* @param md meta data
* @param fn the file to be written to
* @throws IOException I/O exception
*/
public TableOutput(final MetaData md, final String fn) throws IOException {
os = md.dbFile(fn).outputStream();
meta = md;
file = fn;
}
@Override
public void write(final int b) throws IOException {
if(pos == IO.BLOCKSIZE) writeBuffer();
buffer[pos++] = (byte) b;
}
/**
* Writes a page to disk.
* @throws IOException I/O exception
*/
private void writeBuffer() throws IOException {
os.write(buffer);
pages++;
pos = 0;
}
@Override
public void close() throws IOException {
// write last entries, or single empty page, to disk
final boolean empty = pages == 0 && pos == 0;
if(pos > 0 || empty) writeBuffer();
os.close();
// create table info file
try(DataOutput out = new DataOutput(meta.dbFile(file + 'i'))) {
// total number of pages
out.writeNum(pages);
// number of used pages (0: empty table; MAX: no mapping)
out.writeNum(empty ? 0 : Integer.MAX_VALUE);
}
}
}
| BaseXdb/basex | basex-core/src/main/java/org/basex/io/out/TableOutput.java | Java | bsd-3-clause | 1,856 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/test/test_context_support.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
namespace cc {
TestContextSupport::TestContextSupport()
: out_of_order_callbacks_(false), weak_ptr_factory_(this) {}
TestContextSupport::~TestContextSupport() {}
void TestContextSupport::SignalSyncPoint(uint32 sync_point,
const base::Closure& callback) {
sync_point_callbacks_.push_back(callback);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&TestContextSupport::CallAllSyncPointCallbacks,
weak_ptr_factory_.GetWeakPtr()));
}
void TestContextSupport::SignalSyncToken(const gpu::SyncToken& sync_token,
const base::Closure& callback) {
sync_point_callbacks_.push_back(callback);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&TestContextSupport::CallAllSyncPointCallbacks,
weak_ptr_factory_.GetWeakPtr()));
}
void TestContextSupport::SignalQuery(uint32 query,
const base::Closure& callback) {
sync_point_callbacks_.push_back(callback);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&TestContextSupport::CallAllSyncPointCallbacks,
weak_ptr_factory_.GetWeakPtr()));
}
void TestContextSupport::SetSurfaceVisible(bool visible) {
if (!set_visible_callback_.is_null()) {
set_visible_callback_.Run(visible);
}
}
void TestContextSupport::SetAggressivelyFreeResources(
bool aggressively_free_resources) {
}
void TestContextSupport::CallAllSyncPointCallbacks() {
size_t size = sync_point_callbacks_.size();
if (out_of_order_callbacks_) {
for (size_t i = size; i > 0; --i) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, sync_point_callbacks_[i - 1]);
}
} else {
for (size_t i = 0; i < size; ++i) {
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
sync_point_callbacks_[i]);
}
}
sync_point_callbacks_.clear();
}
void TestContextSupport::SetSurfaceVisibleCallback(
const SurfaceVisibleCallback& set_visible_callback) {
set_visible_callback_ = set_visible_callback;
}
void TestContextSupport::SetScheduleOverlayPlaneCallback(
const ScheduleOverlayPlaneCallback& schedule_overlay_plane_callback) {
schedule_overlay_plane_callback_ = schedule_overlay_plane_callback;
}
void TestContextSupport::Swap() {
}
uint32 TestContextSupport::InsertFutureSyncPointCHROMIUM() {
NOTIMPLEMENTED();
return 0;
}
void TestContextSupport::RetireSyncPointCHROMIUM(uint32 sync_point) {
NOTIMPLEMENTED();
}
void TestContextSupport::PartialSwapBuffers(const gfx::Rect& sub_buffer) {
}
void TestContextSupport::ScheduleOverlayPlane(
int plane_z_order,
gfx::OverlayTransform plane_transform,
unsigned overlay_texture_id,
const gfx::Rect& display_bounds,
const gfx::RectF& uv_rect) {
if (!schedule_overlay_plane_callback_.is_null()) {
schedule_overlay_plane_callback_.Run(plane_z_order,
plane_transform,
overlay_texture_id,
display_bounds,
uv_rect);
}
}
uint64_t TestContextSupport::ShareGroupTracingGUID() const {
NOTIMPLEMENTED();
return 0;
}
} // namespace cc
| Bysmyyr/chromium-crosswalk | cc/test/test_context_support.cc | C++ | bsd-3-clause | 3,741 |
// Copyright 2015-present 650 Industries. All rights reserved.
package host.exp.exponent.kernel.services.sensors;
import android.content.Context;
import android.hardware.Sensor;
public class GyroscopeKernelService extends SubscribableSensorKernelService {
public GyroscopeKernelService(Context context) {
super(context);
}
@Override
int getSensorType() {
return Sensor.TYPE_GYROSCOPE;
}
}
| exponent/exponent | android/expoview/src/main/java/host/exp/exponent/kernel/services/sensors/GyroscopeKernelService.java | Java | bsd-3-clause | 411 |
# -*- coding: utf-8 -*-
import sys
def main():
sys.exit(42)
def test_is_compiled():
global __cached__, __file__
try:
source = __cached__ or __file__
except NameError:
source = __file__
assert source.endswith('.pyc')
def test_extras():
from extension_dist.test_ext import get_the_answer
assert get_the_answer() == 42
def test_no_extras():
try:
import extension_dist # noqa
except ImportError:
pass
else:
assert False, "extra was insatlled when it shouldn't have been"
| dairiki/humpty | tests/dist1/dist1.py | Python | bsd-3-clause | 558 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Ldap;
use Traversable;
use Zend\Stdlib\ErrorHandler;
class Ldap
{
const SEARCH_SCOPE_SUB = 1;
const SEARCH_SCOPE_ONE = 2;
const SEARCH_SCOPE_BASE = 3;
const ACCTNAME_FORM_DN = 1;
const ACCTNAME_FORM_USERNAME = 2;
const ACCTNAME_FORM_BACKSLASH = 3;
const ACCTNAME_FORM_PRINCIPAL = 4;
/**
* String used with ldap_connect for error handling purposes.
*
* @var string
*/
private $connectString;
/**
* The options used in connecting, binding, etc.
*
* @var array
*/
protected $options = null;
/**
* The raw LDAP extension resource.
*
* @var resource
*/
protected $resource = null;
/**
* FALSE if no user is bound to the LDAP resource
* NULL if there has been an anonymous bind
* username of the currently bound user
*
* @var bool|null|string
*/
protected $boundUser = false;
/**
* Caches the RootDse
*
* @var Node\RootDse
*/
protected $rootDse = null;
/**
* Caches the schema
*
* @var Node\Schema
*/
protected $schema = null;
/**
* Constructor.
*
* @param array|Traversable $options Options used in connecting, binding, etc.
* @throws Exception\LdapException
*/
public function __construct($options = array())
{
if (!extension_loaded('ldap')) {
throw new Exception\LdapException(null, 'LDAP extension not loaded',
Exception\LdapException::LDAP_X_EXTENSION_NOT_LOADED);
}
$this->setOptions($options);
}
/**
* Destructor.
*
* @return void
*/
public function __destruct()
{
$this->disconnect();
}
/**
* @return resource The raw LDAP extension resource.
*/
public function getResource()
{
if (!is_resource($this->resource) || $this->boundUser === false) {
$this->bind();
}
return $this->resource;
}
/**
* Return the LDAP error number of the last LDAP command
*
* @return int
*/
public function getLastErrorCode()
{
ErrorHandler::start(E_WARNING);
$ret = ldap_get_option($this->resource, LDAP_OPT_ERROR_NUMBER, $err);
ErrorHandler::stop();
if ($ret === true) {
if ($err <= -1 && $err >= -17) {
/* For some reason draft-ietf-ldapext-ldap-c-api-xx.txt error
* codes in OpenLDAP are negative values from -1 to -17.
*/
$err = Exception\LdapException::LDAP_SERVER_DOWN + (-$err - 1);
}
return $err;
}
return 0;
}
/**
* Return the LDAP error message of the last LDAP command
*
* @param int $errorCode
* @param array $errorMessages
* @return string
*/
public function getLastError(&$errorCode = null, array &$errorMessages = null)
{
$errorCode = $this->getLastErrorCode();
$errorMessages = array();
/* The various error retrieval functions can return
* different things so we just try to collect what we
* can and eliminate dupes.
*/
ErrorHandler::start(E_WARNING);
$estr1 = ldap_error($this->resource);
ErrorHandler::stop();
if ($errorCode !== 0 && $estr1 === 'Success') {
ErrorHandler::start(E_WARNING);
$estr1 = ldap_err2str($errorCode);
ErrorHandler::stop();
}
if (!empty($estr1)) {
$errorMessages[] = $estr1;
}
ErrorHandler::start(E_WARNING);
ldap_get_option($this->resource, LDAP_OPT_ERROR_STRING, $estr2);
ErrorHandler::stop();
if (!empty($estr2) && !in_array($estr2, $errorMessages)) {
$errorMessages[] = $estr2;
}
$message = '';
if ($errorCode > 0) {
$message = '0x' . dechex($errorCode) . ' ';
}
if (count($errorMessages) > 0) {
$message .= '(' . implode('; ', $errorMessages) . ')';
} else {
$message .= '(no error message from LDAP)';
}
return $message;
}
/**
* Get the currently bound user
*
* FALSE if no user is bound to the LDAP resource
* NULL if there has been an anonymous bind
* username of the currently bound user
*
* @return bool|null|string
*/
public function getBoundUser()
{
return $this->boundUser;
}
/**
* Sets the options used in connecting, binding, etc.
*
* Valid option keys:
* host
* port
* useSsl
* username
* password
* bindRequiresDn
* baseDn
* accountCanonicalForm
* accountDomainName
* accountDomainNameShort
* accountFilterFormat
* allowEmptyPassword
* useStartTls
* optReferrals
* tryUsernameSplit
* networkTimeout
*
* @param array|Traversable $options Options used in connecting, binding, etc.
* @return Ldap Provides a fluent interface
* @throws Exception\LdapException
*/
public function setOptions($options)
{
if ($options instanceof Traversable) {
$options = iterator_to_array($options);
}
$permittedOptions = array(
'host' => null,
'port' => 0,
'useSsl' => false,
'username' => null,
'password' => null,
'bindRequiresDn' => false,
'baseDn' => null,
'accountCanonicalForm' => null,
'accountDomainName' => null,
'accountDomainNameShort' => null,
'accountFilterFormat' => null,
'allowEmptyPassword' => false,
'useStartTls' => false,
'optReferrals' => false,
'tryUsernameSplit' => true,
'networkTimeout' => null,
);
foreach ($permittedOptions as $key => $val) {
if (array_key_exists($key, $options)) {
$val = $options[$key];
unset($options[$key]);
/* Enforce typing. This eliminates issues like Zend\Config\Reader\Ini
* returning '1' as a string (ZF-3163).
*/
switch ($key) {
case 'port':
case 'accountCanonicalForm':
case 'networkTimeout':
$permittedOptions[$key] = (int) $val;
break;
case 'useSsl':
case 'bindRequiresDn':
case 'allowEmptyPassword':
case 'useStartTls':
case 'optReferrals':
case 'tryUsernameSplit':
$permittedOptions[$key] = ($val === true
|| $val === '1'
|| strcasecmp($val, 'true') == 0);
break;
default:
$permittedOptions[$key] = trim($val);
break;
}
}
}
if (count($options) > 0) {
$key = key($options);
throw new Exception\LdapException(null, "Unknown Zend\\Ldap\\Ldap option: $key");
}
$this->options = $permittedOptions;
return $this;
}
/**
* @return array The current options.
*/
public function getOptions()
{
return $this->options;
}
/**
* @return string The hostname of the LDAP server being used to
* authenticate accounts
*/
protected function getHost()
{
return $this->options['host'];
}
/**
* @return int The port of the LDAP server or 0 to indicate that no port
* value is set
*/
protected function getPort()
{
return $this->options['port'];
}
/**
* @return bool The default SSL / TLS encrypted transport control
*/
protected function getUseSsl()
{
return $this->options['useSsl'];
}
/**
* @return string The default acctname for binding
*/
protected function getUsername()
{
return $this->options['username'];
}
/**
* @return string The default password for binding
*/
protected function getPassword()
{
return $this->options['password'];
}
/**
* @return bool Bind requires DN
*/
protected function getBindRequiresDn()
{
return $this->options['bindRequiresDn'];
}
/**
* Gets the base DN under which objects of interest are located
*
* @return string
*/
public function getBaseDn()
{
return $this->options['baseDn'];
}
/**
* @return int Either ACCTNAME_FORM_BACKSLASH, ACCTNAME_FORM_PRINCIPAL or
* ACCTNAME_FORM_USERNAME indicating the form usernames should be canonicalized to.
*/
protected function getAccountCanonicalForm()
{
/* Account names should always be qualified with a domain. In some scenarios
* using non-qualified account names can lead to security vulnerabilities. If
* no account canonical form is specified, we guess based in what domain
* names have been supplied.
*/
$accountCanonicalForm = $this->options['accountCanonicalForm'];
if (!$accountCanonicalForm) {
$accountDomainName = $this->getAccountDomainName();
$accountDomainNameShort = $this->getAccountDomainNameShort();
if ($accountDomainNameShort) {
$accountCanonicalForm = self::ACCTNAME_FORM_BACKSLASH;
} else {
if ($accountDomainName) {
$accountCanonicalForm = self::ACCTNAME_FORM_PRINCIPAL;
} else {
$accountCanonicalForm = self::ACCTNAME_FORM_USERNAME;
}
}
}
return $accountCanonicalForm;
}
/**
* @return string The account domain name
*/
protected function getAccountDomainName()
{
return $this->options['accountDomainName'];
}
/**
* @return string The short account domain name
*/
protected function getAccountDomainNameShort()
{
return $this->options['accountDomainNameShort'];
}
/**
* @return string A format string for building an LDAP search filter to match
* an account
*/
protected function getAccountFilterFormat()
{
return $this->options['accountFilterFormat'];
}
/**
* @return bool Allow empty passwords
*/
protected function getAllowEmptyPassword()
{
return $this->options['allowEmptyPassword'];
}
/**
* @return bool The default SSL / TLS encrypted transport control
*/
protected function getUseStartTls()
{
return $this->options['useStartTls'];
}
/**
* @return bool Opt. Referrals
*/
protected function getOptReferrals()
{
return $this->options['optReferrals'];
}
/**
* @return bool Try splitting the username into username and domain
*/
protected function getTryUsernameSplit()
{
return $this->options['tryUsernameSplit'];
}
/**
* @return int The value for network timeout when connect to the LDAP server.
*/
protected function getNetworkTimeout()
{
return $this->options['networkTimeout'];
}
/**
* @param string $acctname
* @return string The LDAP search filter for matching directory accounts
*/
protected function getAccountFilter($acctname)
{
$dname = '';
$aname = '';
$this->splitName($acctname, $dname, $aname);
$accountFilterFormat = $this->getAccountFilterFormat();
$aname = Filter\AbstractFilter::escapeValue($aname);
if ($accountFilterFormat) {
return sprintf($accountFilterFormat, $aname);
}
if (!$this->getBindRequiresDn()) {
// is there a better way to detect this?
return sprintf("(&(objectClass=user)(sAMAccountName=%s))", $aname);
}
return sprintf("(&(objectClass=posixAccount)(uid=%s))", $aname);
}
/**
* @param string $name The name to split
* @param string $dname The resulting domain name (this is an out parameter)
* @param string $aname The resulting account name (this is an out parameter)
* @return void
*/
protected function splitName($name, &$dname, &$aname)
{
$dname = null;
$aname = $name;
if (!$this->getTryUsernameSplit()) {
return;
}
$pos = strpos($name, '@');
if ($pos) {
$dname = substr($name, $pos + 1);
$aname = substr($name, 0, $pos);
} else {
$pos = strpos($name, '\\');
if ($pos) {
$dname = substr($name, 0, $pos);
$aname = substr($name, $pos + 1);
}
}
}
/**
* @param string $acctname The name of the account
* @return string The DN of the specified account
* @throws Exception\LdapException
*/
protected function getAccountDn($acctname)
{
if (Dn::checkDn($acctname)) {
return $acctname;
}
$acctname = $this->getCanonicalAccountName($acctname, self::ACCTNAME_FORM_USERNAME);
$acct = $this->getAccount($acctname, array('dn'));
return $acct['dn'];
}
/**
* @param string $dname The domain name to check
* @return bool
*/
protected function isPossibleAuthority($dname)
{
if ($dname === null) {
return true;
}
$accountDomainName = $this->getAccountDomainName();
$accountDomainNameShort = $this->getAccountDomainNameShort();
if ($accountDomainName === null && $accountDomainNameShort === null) {
return true;
}
if (strcasecmp($dname, $accountDomainName) == 0) {
return true;
}
if (strcasecmp($dname, $accountDomainNameShort) == 0) {
return true;
}
return false;
}
/**
* @param string $acctname The name to canonicalize
* @param int $form The desired form of canonicalization
* @return string The canonicalized name in the desired form
* @throws Exception\LdapException
*/
public function getCanonicalAccountName($acctname, $form = 0)
{
$dname = '';
$uname = '';
$this->splitName($acctname, $dname, $uname);
if (!$this->isPossibleAuthority($dname)) {
throw new Exception\LdapException(null,
"Binding domain is not an authority for user: $acctname",
Exception\LdapException::LDAP_X_DOMAIN_MISMATCH);
}
if (!$uname) {
throw new Exception\LdapException(null, "Invalid account name syntax: $acctname");
}
if (function_exists('mb_strtolower')) {
$uname = mb_strtolower($uname, 'UTF-8');
} else {
$uname = strtolower($uname);
}
if ($form === 0) {
$form = $this->getAccountCanonicalForm();
}
switch ($form) {
case self::ACCTNAME_FORM_DN:
return $this->getAccountDn($acctname);
case self::ACCTNAME_FORM_USERNAME:
return $uname;
case self::ACCTNAME_FORM_BACKSLASH:
$accountDomainNameShort = $this->getAccountDomainNameShort();
if (!$accountDomainNameShort) {
throw new Exception\LdapException(null, 'Option required: accountDomainNameShort');
}
return "$accountDomainNameShort\\$uname";
case self::ACCTNAME_FORM_PRINCIPAL:
$accountDomainName = $this->getAccountDomainName();
if (!$accountDomainName) {
throw new Exception\LdapException(null, 'Option required: accountDomainName');
}
return "$uname@$accountDomainName";
default:
throw new Exception\LdapException(null, "Unknown canonical name form: $form");
}
}
/**
* @param string $acctname
* @param array $attrs An array of names of desired attributes
* @return array An array of the attributes representing the account
* @throws Exception\LdapException
*/
protected function getAccount($acctname, array $attrs = null)
{
$baseDn = $this->getBaseDn();
if (!$baseDn) {
throw new Exception\LdapException(null, 'Base DN not set');
}
$accountFilter = $this->getAccountFilter($acctname);
if (!$accountFilter) {
throw new Exception\LdapException(null, 'Invalid account filter');
}
if (!is_resource($this->getResource())) {
$this->bind();
}
$accounts = $this->search($accountFilter, $baseDn, self::SEARCH_SCOPE_SUB, $attrs);
$count = $accounts->count();
if ($count === 1) {
$acct = $accounts->getFirst();
$accounts->close();
return $acct;
} else {
if ($count === 0) {
$code = Exception\LdapException::LDAP_NO_SUCH_OBJECT;
$str = "No object found for: $accountFilter";
} else {
$code = Exception\LdapException::LDAP_OPERATIONS_ERROR;
$str = "Unexpected result count ($count) for: $accountFilter";
}
}
$accounts->close();
throw new Exception\LdapException($this, $str, $code);
}
/**
* @return Ldap Provides a fluent interface
*/
public function disconnect()
{
if (is_resource($this->resource)) {
ErrorHandler::start(E_WARNING);
ldap_unbind($this->resource);
ErrorHandler::stop();
}
$this->resource = null;
$this->boundUser = false;
return $this;
}
/**
* To connect using SSL it seems the client tries to verify the server
* certificate by default. One way to disable this behavior is to set
* 'TLS_REQCERT never' in OpenLDAP's ldap.conf and restarting Apache. Or,
* if you really care about the server's cert you can put a cert on the
* web server.
*
* @param string $host The hostname of the LDAP server to connect to
* @param int $port The port number of the LDAP server to connect to
* @param bool $useSsl Use SSL
* @param bool $useStartTls Use STARTTLS
* @param int $networkTimeout The value for network timeout when connect to the LDAP server.
* @return Ldap Provides a fluent interface
* @throws Exception\LdapException
*/
public function connect($host = null, $port = null, $useSsl = null, $useStartTls = null, $networkTimeout = null)
{
if ($host === null) {
$host = $this->getHost();
}
if ($port === null) {
$port = $this->getPort();
} else {
$port = (int) $port;
}
if ($useSsl === null) {
$useSsl = $this->getUseSsl();
} else {
$useSsl = (bool) $useSsl;
}
if ($useStartTls === null) {
$useStartTls = $this->getUseStartTls();
} else {
$useStartTls = (bool) $useStartTls;
}
if ($networkTimeout === null) {
$networkTimeout = $this->getNetworkTimeout();
} else {
$networkTimeout = (int) $networkTimeout;
}
if (!$host) {
throw new Exception\LdapException(null, 'A host parameter is required');
}
$useUri = false;
/* Because ldap_connect doesn't really try to connect, any connect error
* will actually occur during the ldap_bind call. Therefore, we save the
* connect string here for reporting it in error handling in bind().
*/
$hosts = array();
if (preg_match_all('~ldap(?:i|s)?://~', $host, $hosts, PREG_SET_ORDER) > 0) {
$this->connectString = $host;
$useUri = true;
$useSsl = false;
} else {
if ($useSsl) {
$this->connectString = 'ldaps://' . $host;
$useUri = true;
} else {
$this->connectString = 'ldap://' . $host;
}
if ($port) {
$this->connectString .= ':' . $port;
}
}
$this->disconnect();
/* Only OpenLDAP 2.2 + supports URLs so if SSL is not requested, just
* use the old form.
*/
ErrorHandler::start();
$resource = ($useUri) ? ldap_connect($this->connectString) : ldap_connect($host, $port);
ErrorHandler::stop();
if (is_resource($resource) === true) {
$this->resource = $resource;
$this->boundUser = false;
$optReferrals = ($this->getOptReferrals()) ? 1 : 0;
ErrorHandler::start(E_WARNING);
if (ldap_set_option($resource, LDAP_OPT_PROTOCOL_VERSION, 3)
&& ldap_set_option($resource, LDAP_OPT_REFERRALS, $optReferrals)
) {
if ($networkTimeout) {
ldap_set_option($resource, LDAP_OPT_NETWORK_TIMEOUT, $networkTimeout);
}
if ($useSsl || !$useStartTls || ldap_start_tls($resource)) {
ErrorHandler::stop();
return $this;
}
}
ErrorHandler::stop();
$zle = new Exception\LdapException($this, "$host:$port");
$this->disconnect();
throw $zle;
}
throw new Exception\LdapException(null, "Failed to connect to LDAP server: $host:$port");
}
/**
* @param string $username The username for authenticating the bind
* @param string $password The password for authenticating the bind
* @return Ldap Provides a fluent interface
* @throws Exception\LdapException
*/
public function bind($username = null, $password = null)
{
$moreCreds = true;
if ($username === null) {
$username = $this->getUsername();
$password = $this->getPassword();
$moreCreds = false;
}
if (empty($username)) {
/* Perform anonymous bind
*/
$username = null;
$password = null;
} else {
/* Check to make sure the username is in DN form.
*/
if (!Dn::checkDn($username)) {
if ($this->getBindRequiresDn()) {
/* moreCreds stops an infinite loop if getUsername does not
* return a DN and the bind requires it
*/
if ($moreCreds) {
try {
$username = $this->getAccountDn($username);
} catch (Exception\LdapException $zle) {
switch ($zle->getCode()) {
case Exception\LdapException::LDAP_NO_SUCH_OBJECT:
case Exception\LdapException::LDAP_X_DOMAIN_MISMATCH:
case Exception\LdapException::LDAP_X_EXTENSION_NOT_LOADED:
throw $zle;
}
throw new Exception\LdapException(null,
'Failed to retrieve DN for account: ' . $username .
' [' . $zle->getMessage() . ']',
Exception\LdapException::LDAP_OPERATIONS_ERROR);
}
} else {
throw new Exception\LdapException(null, 'Binding requires username in DN form');
}
} else {
$username = $this->getCanonicalAccountName(
$username,
$this->getAccountCanonicalForm()
);
}
}
}
if (!is_resource($this->resource)) {
$this->connect();
}
if ($username !== null && $password === '' && $this->getAllowEmptyPassword() !== true) {
$zle = new Exception\LdapException(null,
'Empty password not allowed - see allowEmptyPassword option.');
} else {
ErrorHandler::start(E_WARNING);
$bind = ldap_bind($this->resource, $username, $password);
ErrorHandler::stop();
if ($bind) {
$this->boundUser = $username;
return $this;
}
$message = ($username === null) ? $this->connectString : $username;
switch ($this->getLastErrorCode()) {
case Exception\LdapException::LDAP_SERVER_DOWN:
/* If the error is related to establishing a connection rather than binding,
* the connect string is more informative than the username.
*/
$message = $this->connectString;
}
$zle = new Exception\LdapException($this, $message);
}
$this->disconnect();
throw $zle;
}
/**
* A global LDAP search routine for finding information.
*
* Options can be either passed as single parameters according to the
* method signature or as an array with one or more of the following keys
* - filter
* - baseDn
* - scope
* - attributes
* - sort
* - collectionClass
* - sizelimit
* - timelimit
*
* @param string|Filter\AbstractFilter|array $filter
* @param string|Dn|null $basedn
* @param int $scope
* @param array $attributes
* @param string|null $sort
* @param string|null $collectionClass
* @param int $sizelimit
* @param int $timelimit
* @return Collection
* @throws Exception\LdapException
*/
public function search($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB, array $attributes = array(),
$sort = null, $collectionClass = null, $sizelimit = 0, $timelimit = 0
)
{
if (is_array($filter)) {
$options = array_change_key_case($filter, CASE_LOWER);
foreach ($options as $key => $value) {
switch ($key) {
case 'filter':
case 'basedn':
case 'scope':
case 'sort':
$$key = $value;
break;
case 'attributes':
if (is_array($value)) {
$attributes = $value;
}
break;
case 'collectionclass':
$collectionClass = $value;
break;
case 'sizelimit':
case 'timelimit':
$$key = (int) $value;
break;
}
}
}
if ($basedn === null) {
$basedn = $this->getBaseDn();
} elseif ($basedn instanceof Dn) {
$basedn = $basedn->toString();
}
if ($filter instanceof Filter\AbstractFilter) {
$filter = $filter->toString();
}
$resource = $this->getResource();
ErrorHandler::start(E_WARNING);
switch ($scope) {
case self::SEARCH_SCOPE_ONE:
$search = ldap_list($resource, $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
break;
case self::SEARCH_SCOPE_BASE:
$search = ldap_read($resource, $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
break;
case self::SEARCH_SCOPE_SUB:
default:
$search = ldap_search($resource, $basedn, $filter, $attributes, 0, $sizelimit, $timelimit);
break;
}
ErrorHandler::stop();
if ($search === false) {
throw new Exception\LdapException($this, 'searching: ' . $filter);
}
if ($sort !== null && is_string($sort)) {
ErrorHandler::start(E_WARNING);
$isSorted = ldap_sort($resource, $search, $sort);
ErrorHandler::stop();
if ($isSorted === false) {
throw new Exception\LdapException($this, 'sorting: ' . $sort);
}
}
$iterator = new Collection\DefaultIterator($this, $search);
return $this->createCollection($iterator, $collectionClass);
}
/**
* Extension point for collection creation
*
* @param Collection\DefaultIterator $iterator
* @param string|null $collectionClass
* @return Collection
* @throws Exception\LdapException
*/
protected function createCollection(Collection\DefaultIterator $iterator, $collectionClass)
{
if ($collectionClass === null) {
return new Collection($iterator);
} else {
$collectionClass = (string) $collectionClass;
if (!class_exists($collectionClass)) {
throw new Exception\LdapException(null,
"Class '$collectionClass' can not be found");
}
if (!is_subclass_of($collectionClass, 'Zend\Ldap\Collection')) {
throw new Exception\LdapException(null,
"Class '$collectionClass' must subclass 'Zend\\Ldap\\Collection'");
}
return new $collectionClass($iterator);
}
}
/**
* Count items found by given filter.
*
* @param string|Filter\AbstractFilter $filter
* @param string|Dn|null $basedn
* @param int $scope
* @return int
* @throws Exception\LdapException
*/
public function count($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB)
{
try {
$result = $this->search($filter, $basedn, $scope, array('dn'), null);
} catch (Exception\LdapException $e) {
if ($e->getCode() === Exception\LdapException::LDAP_NO_SUCH_OBJECT) {
return 0;
}
throw $e;
}
return $result->count();
}
/**
* Count children for a given DN.
*
* @param string|Dn $dn
* @return int
* @throws Exception\LdapException
*/
public function countChildren($dn)
{
return $this->count('(objectClass=*)', $dn, self::SEARCH_SCOPE_ONE);
}
/**
* Check if a given DN exists.
*
* @param string|Dn $dn
* @return bool
* @throws Exception\LdapException
*/
public function exists($dn)
{
return ($this->count('(objectClass=*)', $dn, self::SEARCH_SCOPE_BASE) == 1);
}
/**
* Search LDAP registry for entries matching filter and optional attributes
*
* Options can be either passed as single parameters according to the
* method signature or as an array with one or more of the following keys
* - filter
* - baseDn
* - scope
* - attributes
* - sort
* - reverseSort
* - sizelimit
* - timelimit
*
* @param string|Filter\AbstractFilter|array $filter
* @param string|Dn|null $basedn
* @param int $scope
* @param array $attributes
* @param string|null $sort
* @param bool $reverseSort
* @param int $sizelimit
* @param int $timelimit
* @return array
* @throws Exception\LdapException
*/
public function searchEntries($filter, $basedn = null, $scope = self::SEARCH_SCOPE_SUB,
array $attributes = array(), $sort = null, $reverseSort = false, $sizelimit = 0,
$timelimit = 0)
{
if (is_array($filter)) {
$filter = array_change_key_case($filter, CASE_LOWER);
if (isset($filter['collectionclass'])) {
unset($filter['collectionclass']);
}
if (isset($filter['reversesort'])) {
$reverseSort = $filter['reversesort'];
unset($filter['reversesort']);
}
}
$result = $this->search($filter, $basedn, $scope, $attributes, $sort, null, $sizelimit, $timelimit);
$items = $result->toArray();
if ((bool) $reverseSort === true) {
$items = array_reverse($items, false);
}
return $items;
}
/**
* Get LDAP entry by DN
*
* @param string|Dn $dn
* @param array $attributes
* @param bool $throwOnNotFound
* @return array
* @throws null|Exception\LdapException
*/
public function getEntry($dn, array $attributes = array(), $throwOnNotFound = false)
{
try {
$result = $this->search(
"(objectClass=*)", $dn, self::SEARCH_SCOPE_BASE,
$attributes, null
);
return $result->getFirst();
} catch (Exception\LdapException $e) {
if ($throwOnNotFound !== false) {
throw $e;
}
}
return null;
}
/**
* Prepares an ldap data entry array for insert/update operation
*
* @param array $entry
* @throws Exception\InvalidArgumentException
* @return void
*/
public static function prepareLdapEntryArray(array &$entry)
{
if (array_key_exists('dn', $entry)) {
unset($entry['dn']);
}
foreach ($entry as $key => $value) {
if (is_array($value)) {
foreach ($value as $i => $v) {
if ($v === null) {
unset($value[$i]);
} elseif (!is_scalar($v)) {
throw new Exception\InvalidArgumentException('Only scalar values allowed in LDAP data');
} else {
$v = (string) $v;
if (strlen($v) == 0) {
unset($value[$i]);
} else {
$value[$i] = $v;
}
}
}
$entry[$key] = array_values($value);
} else {
if ($value === null) {
$entry[$key] = array();
} elseif (!is_scalar($value)) {
throw new Exception\InvalidArgumentException('Only scalar values allowed in LDAP data');
} else {
$value = (string) $value;
if (strlen($value) == 0) {
$entry[$key] = array();
} else {
$entry[$key] = array($value);
}
}
}
}
$entry = array_change_key_case($entry, CASE_LOWER);
}
/**
* Add new information to the LDAP repository
*
* @param string|Dn $dn
* @param array $entry
* @return Ldap Provides a fluid interface
* @throws Exception\LdapException
*/
public function add($dn, array $entry)
{
if (!($dn instanceof Dn)) {
$dn = Dn::factory($dn, null);
}
static::prepareLdapEntryArray($entry);
foreach ($entry as $key => $value) {
if (is_array($value) && count($value) === 0) {
unset($entry[$key]);
}
}
$rdnParts = $dn->getRdn(Dn::ATTR_CASEFOLD_LOWER);
foreach ($rdnParts as $key => $value) {
$value = Dn::unescapeValue($value);
if (!array_key_exists($key, $entry)) {
$entry[$key] = array($value);
} elseif (!in_array($value, $entry[$key])) {
$entry[$key] = array_merge(array($value), $entry[$key]);
}
}
$adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory',
'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated');
foreach ($adAttributes as $attr) {
if (array_key_exists($attr, $entry)) {
unset($entry[$attr]);
}
}
$resource = $this->getResource();
ErrorHandler::start(E_WARNING);
$isAdded = ldap_add($resource, $dn->toString(), $entry);
ErrorHandler::stop();
if ($isAdded === false) {
throw new Exception\LdapException($this, 'adding: ' . $dn->toString());
}
return $this;
}
/**
* Update LDAP registry
*
* @param string|Dn $dn
* @param array $entry
* @return Ldap Provides a fluid interface
* @throws Exception\LdapException
*/
public function update($dn, array $entry)
{
if (!($dn instanceof Dn)) {
$dn = Dn::factory($dn, null);
}
static::prepareLdapEntryArray($entry);
$rdnParts = $dn->getRdn(Dn::ATTR_CASEFOLD_LOWER);
foreach ($rdnParts as $key => $value) {
$value = Dn::unescapeValue($value);
if (array_key_exists($key, $entry) && !in_array($value, $entry[$key])) {
$entry[$key] = array_merge(array($value), $entry[$key]);
}
}
$adAttributes = array('distinguishedname', 'instancetype', 'name', 'objectcategory',
'objectguid', 'usnchanged', 'usncreated', 'whenchanged', 'whencreated');
foreach ($adAttributes as $attr) {
if (array_key_exists($attr, $entry)) {
unset($entry[$attr]);
}
}
if (count($entry) > 0) {
$resource = $this->getResource();
ErrorHandler::start(E_WARNING);
$isModified = ldap_modify($resource, $dn->toString(), $entry);
ErrorHandler::stop();
if ($isModified === false) {
throw new Exception\LdapException($this, 'updating: ' . $dn->toString());
}
}
return $this;
}
/**
* Note entry to LDAP registry.
*
* Internally decides if entry will be updated to added by calling
* {@link exists()}.
*
* @param string|Dn $dn
* @param array $entry
* @return Ldap Provides a fluid interface
* @throws Exception\LdapException
*/
public function save($dn, array $entry)
{
if ($dn instanceof Dn) {
$dn = $dn->toString();
}
if ($this->exists($dn)) {
$this->update($dn, $entry);
} else {
$this->add($dn, $entry);
}
return $this;
}
/**
* Delete an LDAP entry
*
* @param string|Dn $dn
* @param bool $recursively
* @return Ldap Provides a fluid interface
* @throws Exception\LdapException
*/
public function delete($dn, $recursively = false)
{
if ($dn instanceof Dn) {
$dn = $dn->toString();
}
if ($recursively === true) {
if ($this->countChildren($dn) > 0) {
$children = $this->getChildrenDns($dn);
foreach ($children as $c) {
$this->delete($c, true);
}
}
}
$resource = $this->getResource();
ErrorHandler::start(E_WARNING);
$isDeleted = ldap_delete($resource, $dn);
ErrorHandler::stop();
if ($isDeleted === false) {
throw new Exception\LdapException($this, 'deleting: ' . $dn);
}
return $this;
}
/**
* Retrieve the immediate children DNs of the given $parentDn
*
* This method is used in recursive methods like {@see delete()}
* or {@see copy()}
*
* @param string|Dn $parentDn
* @throws Exception\LdapException
* @return array of DNs
*/
protected function getChildrenDns($parentDn)
{
if ($parentDn instanceof Dn) {
$parentDn = $parentDn->toString();
}
$children = array();
$resource = $this->getResource();
ErrorHandler::start(E_WARNING);
$search = ldap_list($resource, $parentDn, '(objectClass=*)', array('dn'));
for (
$entry = ldap_first_entry($resource, $search);
$entry !== false;
$entry = ldap_next_entry($resource, $entry)
) {
$childDn = ldap_get_dn($resource, $entry);
if ($childDn === false) {
ErrorHandler::stop();
throw new Exception\LdapException($this, 'getting dn');
}
$children[] = $childDn;
}
ldap_free_result($search);
ErrorHandler::stop();
return $children;
}
/**
* Moves a LDAP entry from one DN to another subtree.
*
* @param string|Dn $from
* @param string|Dn $to
* @param bool $recursively
* @param bool $alwaysEmulate
* @return Ldap Provides a fluid interface
* @throws Exception\LdapException
*/
public function moveToSubtree($from, $to, $recursively = false, $alwaysEmulate = false)
{
if ($from instanceof Dn) {
$orgDnParts = $from->toArray();
} else {
$orgDnParts = Dn::explodeDn($from);
}
if ($to instanceof Dn) {
$newParentDnParts = $to->toArray();
} else {
$newParentDnParts = Dn::explodeDn($to);
}
$newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts);
$newDn = Dn::fromArray($newDnParts);
return $this->rename($from, $newDn, $recursively, $alwaysEmulate);
}
/**
* Moves a LDAP entry from one DN to another DN.
*
* This is an alias for {@link rename()}
*
* @param string|Dn $from
* @param string|Dn $to
* @param bool $recursively
* @param bool $alwaysEmulate
* @return Ldap Provides a fluid interface
* @throws Exception\LdapException
*/
public function move($from, $to, $recursively = false, $alwaysEmulate = false)
{
return $this->rename($from, $to, $recursively, $alwaysEmulate);
}
/**
* Renames a LDAP entry from one DN to another DN.
*
* This method implicitly moves the entry to another location within the tree.
*
* @param string|Dn $from
* @param string|Dn $to
* @param bool $recursively
* @param bool $alwaysEmulate
* @return Ldap Provides a fluid interface
* @throws Exception\LdapException
*/
public function rename($from, $to, $recursively = false, $alwaysEmulate = false)
{
$emulate = (bool) $alwaysEmulate;
if (!function_exists('ldap_rename')) {
$emulate = true;
} elseif ($recursively) {
$emulate = true;
}
if ($emulate === false) {
if ($from instanceof Dn) {
$from = $from->toString();
}
if ($to instanceof Dn) {
$newDnParts = $to->toArray();
} else {
$newDnParts = Dn::explodeDn($to);
}
$newRdn = Dn::implodeRdn(array_shift($newDnParts));
$newParent = Dn::implodeDn($newDnParts);
$resource = $this->getResource();
ErrorHandler::start(E_WARNING);
$isOK = ldap_rename($resource, $from, $newRdn, $newParent, true);
ErrorHandler::stop();
if ($isOK === false) {
throw new Exception\LdapException($this, 'renaming ' . $from . ' to ' . $to);
} elseif (!$this->exists($to)) {
$emulate = true;
}
}
if ($emulate) {
$this->copy($from, $to, $recursively);
$this->delete($from, $recursively);
}
return $this;
}
/**
* Copies a LDAP entry from one DN to another subtree.
*
* @param string|Dn $from
* @param string|Dn $to
* @param bool $recursively
* @return Ldap Provides a fluid interface
* @throws Exception\LdapException
*/
public function copyToSubtree($from, $to, $recursively = false)
{
if ($from instanceof Dn) {
$orgDnParts = $from->toArray();
} else {
$orgDnParts = Dn::explodeDn($from);
}
if ($to instanceof Dn) {
$newParentDnParts = $to->toArray();
} else {
$newParentDnParts = Dn::explodeDn($to);
}
$newDnParts = array_merge(array(array_shift($orgDnParts)), $newParentDnParts);
$newDn = Dn::fromArray($newDnParts);
return $this->copy($from, $newDn, $recursively);
}
/**
* Copies a LDAP entry from one DN to another DN.
*
* @param string|Dn $from
* @param string|Dn $to
* @param bool $recursively
* @return Ldap Provides a fluid interface
* @throws Exception\LdapException
*/
public function copy($from, $to, $recursively = false)
{
$entry = $this->getEntry($from, array(), true);
if ($to instanceof Dn) {
$toDnParts = $to->toArray();
} else {
$toDnParts = Dn::explodeDn($to);
}
$this->add($to, $entry);
if ($recursively === true && $this->countChildren($from) > 0) {
$children = $this->getChildrenDns($from);
foreach ($children as $c) {
$cDnParts = Dn::explodeDn($c);
$newChildParts = array_merge(array(array_shift($cDnParts)), $toDnParts);
$newChild = Dn::implodeDn($newChildParts);
$this->copy($c, $newChild, true);
}
}
return $this;
}
/**
* Returns the specified DN as a Zend\Ldap\Node
*
* @param string|Dn $dn
* @return Node|null
* @throws Exception\LdapException
*/
public function getNode($dn)
{
return Node::fromLdap($dn, $this);
}
/**
* Returns the base node as a Zend\Ldap\Node
*
* @return Node
* @throws Exception\LdapException
*/
public function getBaseNode()
{
return $this->getNode($this->getBaseDn(), $this);
}
/**
* Returns the RootDse
*
* @return Node\RootDse
* @throws Exception\LdapException
*/
public function getRootDse()
{
if ($this->rootDse === null) {
$this->rootDse = Node\RootDse::create($this);
}
return $this->rootDse;
}
/**
* Returns the schema
*
* @return Node\Schema
* @throws Exception\LdapException
*/
public function getSchema()
{
if ($this->schema === null) {
$this->schema = Node\Schema::create($this);
}
return $this->schema;
}
}
| snallam/writewell_sprint2 | vendor/zendframework/zendframework/library/Zend/Ldap/Ldap.php | PHP | bsd-3-clause | 48,260 |
<?php
/**
* Created by PhpStorm.
* User: wumahoo
* Date: 2016/9/2 0002
* Time: 下午 4:40
*/
$this->title=Yii::t('shop','Community Shop');
?>
<h1>社区小店建设中...</h1>
| wumahoo/ying | frontend/views/shop/index.php | PHP | bsd-3-clause | 185 |
#ifndef __SIMPLE_FIPU_HPP__
#define __SIMPLE_FIPU_HPP__
#include "promote_traits.hpp"
struct mult_opcode {};
struct div_opcode {};
struct add_opcode {};
struct sub_opcode {};
struct Mult
{
template<typename T1, typename T2>
struct NBits
{
enum {
Magnitude = T1::Magnitude + T2::Magnitude,
Fractional = T1::Fractional + T2::Fractional,
Total = Magnitude + Fractional
};
};
template<typename T1, typename T2>
struct result
{
typedef Q< NBits<T1,T2>::Magnitude,
NBits<T1,T2>::Fractional > type;
};
template<class T1, class T2>
__forceinline static typename result<T1, T2>::type apply(const T1& roLeft, const T2& roRight)
{
typedef result<T1,T2>::type result_type;
result_type res;
res.m_CompFast = static_cast<typename result_type::MagnType>(roLeft.m_CompFast) *
static_cast<typename result_type::MagnType>(roRight.m_CompFast);
#ifdef FIXED_DEBUG_MODE
res.typeStr = "(" + roLeft.typeStr + " * " + roRight.typeStr + ")";
res.valueStr = "(" + roLeft.valueStr + " * " + roRight.valueStr + " [" + boost::lexical_cast<std::string>(res.m_Magn) + "," + boost::lexical_cast<std::string>(res.m_Frac) + "] )";
res.floatStr = "(" + roLeft.floatStr + " * " + roRight.floatStr + " [" + boost::lexical_cast<std::string>((float)res) + "] )";
res.floatValue = roLeft.floatValue * roRight.floatValue;
res.cumulativeEpsilon = (double)roLeft * roRight.cumulativeEpsilon +
(double)roRight * roLeft.cumulativeEpsilon +
roLeft.cumulativeEpsilon * roRight.cumulativeEpsilon;
;
#endif //FIXED_DEBUG_MODE
return res;
}
};
struct Div
{
template<typename T1, typename T2>
struct instance
{
typedef typename promote_traits<T1, T2>::promote_type value_type;
template<typename OutT>
__forceinline static value_type apply(const T1& roLeft, const T2& roRight)
{
value_type res;
// ????
return res;
}
};
template<typename T>
struct instance<T,T>
{
typedef T value_type;
template<typename OutT>
__forceinline static OutT apply(const T& roLeft, const T& roRight)
{
value_type res;
BOOST_ASSERT(roRight.m_CompExact != 0);
if (roRight.m_CompExact == 0)
res.m_CompFast = BitMask<value_type::NBits>::value;
else
res.m_CompFast = static_cast<typename OutT::MagnType>(roLeft.m_CompFast / roRight.m_CompFast);
return res;
}
};
};
struct Add
{
template<typename T1, typename T2>
struct instance
{
typedef typename promote_traits<T1, T2>::promote_type value_type;
template<typename OutT>
__forceinline static value_type apply(const T1& roLeft, const T2& roRight)
{
value_type res;
// ????
return res;
}
};
template<typename T>
struct instance<T,T>
{
typedef T value_type;
template<typename OutT>
__forceinline static value_type apply(const T& roLeft, const T& roRight)
{
value_type res;
res.m_CompFast = roLeft.m_CompFast + roRight.m_CompFast;
return res;
}
};
};
struct Sub
{
template<typename T1, typename T2>
struct instance
{
typedef typename promote_traits<T1, T2>::promote_type value_type;
template<typename OutT>
__forceinline static value_type apply(const T1& roLeft, const T2& roRight)
{
value_type res;
// ????
return res;
}
};
template<typename T>
struct instance<T,T>
{
typedef T value_type;
template<typename OutT>
__forceinline static value_type apply(const T& roLeft, const T& roRight)
{
value_type res;
res.m_CompFast = roLeft.m_CompFast - roRight.m_CompFast;
return res;
}
};
};
#endif //__SIMPLE_FIPU_HPP__ | graveljp/fixed | fixed/SimpleFiPU.hpp | C++ | bsd-3-clause | 4,339 |
$().ready(function() {
$("a[rel^='prettyPhoto']").prettyPhoto();
}); | Freecer/freecer.net | themes/bootlance/js/js.js | JavaScript | bsd-3-clause | 73 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/common/aw_switches.h"
namespace switches {
const char kDisableRecordDocumentWorkaround[] =
"disable-record-document-workaround";
} // namespace switches
| chromium2014/src | android_webview/common/aw_switches.cc | C++ | bsd-3-clause | 353 |
namespace Zinc.WebService.ServiceUtil
{
/// <summary>
/// Describes the type of .NET type contained in the service description file.
/// </summary>
public enum TypeofType
{
/// <summary>
/// Service interface.
/// </summary>
Interface = 0,
/// <summary>
/// Client class, which implements service interface.
/// </summary>
ClientClass = 1,
/// <summary>
/// User type, used to transport data.
/// </summary>
UserType = 2,
}
}
| filipetoscano/Zinc | src/Zinc.WebServices.SvcUtil/TypeofType.cs | C# | bsd-3-clause | 551 |