text stringlengths 2 1.04M | meta dict |
|---|---|
const Rails = window.Rails
const _ = window._
import { Controller } from "@hotwired/stimulus"
// This controller has 3 related functions
// - Keep a users session alive
// Keep the user's session alive if they are 'active' (there are keypresses,
// clicks or resize events on the same page) by sending a throttled ajax
// request to reset the session window which will prevent their session
// expiring and throwing them out when they are for example writing a long
// letter (which they would otherwise not finish before their session expires)
// - Auto logging-out a user after a period of inactivity
// Check after a period of intactivity to see if their session has expired.
// If it has then refresh the page which will redirect them to the login page.
// - Signalling to other open tabs when the user's session has expired or they
// have manually logged out - so that all tabs go to the login page at around
// the same time.
//
// Goals:
// - Performance and code clarity more important than having an accurate session
// window - if it is extended for a minute or two that is OK.
// - The server should always be the judge of whether the session has timed out
// - Query the server as little as possible - partly for performance and partly
// to avoid noise in the server logs
// - Keep event handler activity minimal to preserve CPU cycles - ie use
// throttle or debounce
//
// Possible enhancements:
// - After a period of inactivity, show a dialog asking if user wants to extend
// the session - this would involve starting a separate timer and displaying
// the countdown
//
// Scenarios to test:
// - Keypresses, clicks and window resizing - any of these should reset session
// and thus the user remains logged in as long as one of these events ocurrs
// within sessionTimeoutSeconds
// - User closes lid on laptop overnight and reopens in the morning - what is
// expected?
// - Network disconnected - what do we do?
// - user gets withing 10 seconds of session timeout and starts typing - session
// window shoud be reset
// - user has > 1 tab open and logs out of one - ideally it should log out of
// other tabs before too long. We do by setting a localStorage value to signal
// to other tabs
//
// Known issues:
// - user sitting on register page will keep polling checkAlivePath
// - if a user becomes active on a page within throttlePeriodSeconds of
// sessionTimeoutSeconds then there is no currently opportunity for
// throttledRegisterUserActivity to reset kick in a trump
// checkForSessionExpiryTimeout - so the session will log out. We might need
// an extra step before calling checkForSessionExpiry - a final chance to
// check if the user was
// active
// - Not quite sure if putting the data attribute config settings in the body
// tag is the right thing to do - perhaps should be in a config .js.erb
export default class extends Controller {
checkForSessionExpiryTimeout = null
userActivityDetected = false
checkAlivePath = null
keepAlivePath = null
loginPath = null
throttledRegisterUserActivity = null
sessionTimeoutSeconds = 0
defaultSessionTimeoutSeconds = 20 * 60 // 20 mins
throttlePeriodSeconds = 0
defaultThrottlePeriodSeconds = 20
initialize() {
this.throttlePeriodSeconds = parseInt(this.data.get("register-user-activity-after") || this.defaultThrottlePeriodSeconds)
this.sessionTimeoutSeconds = parseInt(this.data.get("timeout") || this.defaultSessionTimeoutSeconds)
this.sessionTimeoutSeconds += 10 // To allow for network roundtrips etc
this.checkAlivePath = this.data.get("check-alive-path")
this.loginPath = this.data.get("login-path")
this.keepAlivePath = this.data.get("keep-alive-path")
this.logSettings()
// Throttle the user activity callback because we only need to know about user activity
// only very occasionally, so that we can periodically tell there server the user was active.
// Here, even if there are hundreds of events (click, keypress etc) within throttlePeriodSeconds,
// our function is only called at most once in that period, when throttlePeriodSeconds has
// passed (since trailing = true). This suits is as we want to avoid making any call to the
// server unless the user has been on the page for at least throttlePeriodSeconds.
// See https://lodash.com/docs/#trottle
this.throttledRegisterUserActivity = _.throttle(
this.registerUserActivity.bind(this),
this.throttlePeriodSeconds * 1000,
{ "leading": false, "trailing": true }
)
}
connect() {
if (this.onLoginPage) {
this.log("connect: onLoginPage - skipping session time")
} else {
this.addHandlersToMonitorUserActivity()
this.resetCheckForSessionExpiryTimeout(this.sessionTimeoutSeconds)
}
}
disconnect() {
if (!this.onLoginPage) {
this.removeUserActivityHandlers()
clearTimeout(this.checkForSessionExpiryTimeout)
}
}
sendLogoutMessageToAnyOpenTabs() {
window.localStorage.setItem("logout-event", "logout" + Math.random())
}
// Debounced event handler for key/click/resize
// If we come in there then the user has interacted with the page
// within throttlePeriodSeconds
registerUserActivity() {
this.sendRequestToKeepSessionAlive()
this.resetCheckForSessionExpiryTimeout(this.sessionTimeoutSeconds)
}
// Timeout handler for checking if the sesison has expired
resetCheckForSessionExpiryTimeout(intervalSeconds) {
this.log(`resetting session expiry timeout ${intervalSeconds}`)
clearTimeout(this.checkForSessionExpiryTimeout)
this.checkForSessionExpiryTimeout = setTimeout(
this.checkForSessionExpiry.bind(this),
intervalSeconds * 1000
)
}
// Here we really expect the session to have expired. In case it hasn't
// we reset the timeout to check again. We could reset the timeout to be
// sessionTimeoutSeconds, but if when we checked for expiry we had only just
// missed it, we will end up staying on this page (assuming the user is
// inactive) for nearly twice as long as we need to. So we set the timeout
// to be throttlePeriodSeconds * 2, which gives time for the
// throttledRegisterUserActivity handler to reset the session again if it
// fires.
checkForSessionExpiry() {
this.sendRequestToTestForSessionExpiry()
this.resetCheckForSessionExpiryTimeout(this.throttlePeriodSeconds * 2)
}
sendRequestToKeepSessionAlive() {
this.ajaxGet(this.keepAlivePath)
}
sendRequestToTestForSessionExpiry() {
this.log("checking for session expiry")
this.ajaxGet(this.checkAlivePath)
}
ajaxGet(path) {
Rails.ajax({
type: "GET",
url: path,
dataType: "text",
error: this.reloadPageIfAjaxRequestWasUnauthorised.bind(this)
})
}
reloadPageIfAjaxRequestWasUnauthorised(responseText, status, xhr) {
if (xhr.status == 401) {
window.location.reload()
this.sendLogoutMessageToAnyOpenTabs()
}
}
addHandlersToMonitorUserActivity() {
document.addEventListener("click", this.throttledRegisterUserActivity.bind(this))
document.addEventListener("keydown", this.throttledRegisterUserActivity.bind(this))
window.addEventListener("resize", this.throttledRegisterUserActivity.bind(this))
window.addEventListener("storage", this.storageChange.bind(this))
}
removeUserActivityHandlers() {
document.removeEventListener("click", this.throttledRegisterUserActivity.bind(this))
document.removeEventListener("keydown", this.throttledRegisterUserActivity.bind(this))
window.removeEventListener("resize", this.throttledRegisterUserActivity.bind(this))
window.removeEventListener("storage", this.storageChange.bind(this))
}
logSettings() {
if (this.debug) {
this.log(`keepAlivePath ${this.keepAlivePath}`)
this.log(`checkAlivePath ${this.checkAlivePath}`)
this.log(`loginPath ${this.loginPath}`)
this.log(`sessionTimeoutSeconds ${this.sessionTimeoutSeconds}`)
this.log(`throttlePeriodSeconds ${this.throttlePeriodSeconds}`)
}
}
log(msg) {
if (this.debug) {
console.log(msg)
}
}
// An event handler to watch for changes in the value of the local storage item called
// 'logged_in'. We use localStorage as a cross-tab communication protocol: when the user has
// logged out of one tab, this mechanism is used to signal to any other logged-in tabs that they
// should log themselves out.
// This applies in 2 circumstances:
// - the user has clicked the "Log Out" link in the navbar - the sendLogoutMessageToAnyOpenTabs()
// action defined above is called
// - our tab has timed out due to inactivity; other open tabs may not timeout for another few
// minutes (depending on the polling frequency etc) so we give them a nudge.
storageChange(event) {
if(event.key == "logout-event") {
setTimeout(this.sendRequestToTestForSessionExpiry.bind(this), 2000)
}
}
get onLoginPage() {
return window.location.pathname == this.loginPath
}
// If you add data-session-debug=1 then logging will be enabled
// This is evaluated each time we can add debugging into a running page
get debug() {
return this.data.get("debug") === "true"
}
}
| {
"content_hash": "f40f69c33dbf8332b2446f69d4a0d0b2",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 125,
"avg_line_length": 41.7972972972973,
"alnum_prop": 0.7318676581528182,
"repo_name": "airslie/renalware-core",
"id": "873e41a075b41d4d7a7e2f7dc7e28549d57decfd",
"size": "9280",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "app/javascript/renalware/controllers/session_controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9251"
},
{
"name": "Dockerfile",
"bytes": "4123"
},
{
"name": "Gherkin",
"bytes": "114740"
},
{
"name": "HTML",
"bytes": "36757"
},
{
"name": "JavaScript",
"bytes": "1330952"
},
{
"name": "PLpgSQL",
"bytes": "790250"
},
{
"name": "Procfile",
"bytes": "287"
},
{
"name": "Rich Text Format",
"bytes": "629"
},
{
"name": "Ruby",
"bytes": "4090100"
},
{
"name": "SCSS",
"bytes": "145750"
},
{
"name": "Shell",
"bytes": "11142"
},
{
"name": "Slim",
"bytes": "758115"
}
],
"symlink_target": ""
} |
package com.dozenx.game.engine.ui.toolbar.view;
import cola.machine.game.myblocks.engine.Constants;
import cola.machine.game.myblocks.model.ui.html.Document;
import cola.machine.game.myblocks.model.ui.html.HtmlObject;
import cola.machine.game.myblocks.registry.CoreRegistry;
import com.dozenx.game.engine.Role.controller.LivingThingManager;
import com.dozenx.game.engine.item.bean.ItemBean;
import com.dozenx.game.engine.ui.inventory.control.BagController;
import com.dozenx.game.engine.ui.inventory.view.IconView;
import com.dozenx.game.engine.ui.inventory.view.SlotPanel;
/**
* Created by luying on 17/2/5.
*/
public class ToolBarView extends SlotPanel {
public ToolBarView(int numSlotsX, int numSlotsY) {
super( numSlotsX, numSlotsY);
this.setPosition(HtmlObject.POSITION_ABSOLUTE);
this.setTop(Constants.WINDOW_HEIGHT-40);
this.setLeft(0);
CoreRegistry.put(ToolBarView.class,this);
for(int i=0;i<10;i++){
this.slot[i].index=25+i;
}
}
public void keyDown(int num){
for(int i=0;i<10;i++){
this.slot[i].setBorderWidth(1);
}
this.slot[num-1].setBorderWidth(5);
Document.needUpdate=true;
if(this.slot[num-1].getIconView()!=null) {
LivingThingManager livingThingManager = CoreRegistry.get(LivingThingManager.class);
livingThingManager.addHandEquipStart(this.slot[num-1].getIconView().getItemBean());
}else{
LivingThingManager livingThingManager = CoreRegistry.get(LivingThingManager.class);
livingThingManager.addHandEquipStart(null);
}
//LogUtil.println("hello");
/* switch (num){
case 1:
ItemSlotView icon = this.getIconInSlot(num);
}*/
}
/* public ItemSlotView getIconInSlot(int num){
ItemSlotView itemSlot=slot[num];
if(itemSlot.getIconView()!=null && itemSlot.getIconView().getItemDefinition()!=null){
}
}*/
public void reload(BagController bagController){
ItemBean[] itemBeanList=bagController.getItemBeanList(1);
for(int i=25;i<=34;i++){
if(itemBeanList[i]!=null && itemBeanList[i].getItemDefinition()!=null) {
slot[i-25].setIconView(new IconView(itemBeanList[i]));
}else{
slot[i-25].setIconView(null);
}
}
}
}
| {
"content_hash": "fa5eaa381e4bf439099b925e17d426eb",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 95,
"avg_line_length": 31.81578947368421,
"alnum_prop": 0.6509511993382961,
"repo_name": "ColaMachine/MyBlock",
"id": "f78e118b9ba12373e5e8bd256c8056818be3e538",
"size": "2418",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/dozenx/game/engine/ui/toolbar/view/ToolBarView.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "86"
},
{
"name": "GLSL",
"bytes": "72019"
},
{
"name": "HTML",
"bytes": "10204"
},
{
"name": "Java",
"bytes": "6785515"
},
{
"name": "Lex",
"bytes": "4243"
},
{
"name": "TeX",
"bytes": "19738"
}
],
"symlink_target": ""
} |
<?php
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getViewHelperConfig()
{
return array(
'factories' => array(
// the array key here is the name you will call the view helper by in your view scripts
'ajaxLink' => function($sm) {
$locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager
return new View\Helper\AjaxLink($locator->get('Request'));
},
),
);
}
}
| {
"content_hash": "754bee355dbae1e11ca94ffd89efde4b",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 136,
"avg_line_length": 28.23404255319149,
"alnum_prop": 0.549359457422758,
"repo_name": "HaroldVillacorte/lhprod",
"id": "4abe6a9651df7b36472e4751c6766e62c4a611eb",
"size": "1636",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Application/Module.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1981"
},
{
"name": "JavaScript",
"bytes": "3377"
},
{
"name": "PHP",
"bytes": "70353"
}
],
"symlink_target": ""
} |
module.exports = require('./choo-devtools.js')
| {
"content_hash": "473bbc200b9eb519a1783d64bd1383f8",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 46,
"avg_line_length": 47,
"alnum_prop": 0.723404255319149,
"repo_name": "michalczaplinski/choo-devtools",
"id": "80a5e2b453e0e584da77d653915b899f1f13d065",
"size": "47",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "794"
},
{
"name": "HTML",
"bytes": "444"
},
{
"name": "JavaScript",
"bytes": "5826"
},
{
"name": "Makefile",
"bytes": "316"
}
],
"symlink_target": ""
} |
/*
* This file is part of the swblocks-baselib library.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define UTF_TEST_MODULE utf_baselib_async
#include <utests/baselib/UtfMain.h>
#include "TestAsyncCB.h"
#include "TestAsyncV2.h"
| {
"content_hash": "d14a0bc9951d7e6cdeac5aeae381d29e",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 75,
"avg_line_length": 35.666666666666664,
"alnum_prop": 0.7436582109479306,
"repo_name": "lazar-ivanov/swblocks-baselib",
"id": "f794b50e64b40f733a9d9cc76bf6910aabcc59b2",
"size": "749",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/utests/utf_baselib_async/UtfBaselibAsyncMain.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "12349"
},
{
"name": "C",
"bytes": "19443"
},
{
"name": "C++",
"bytes": "4773626"
},
{
"name": "Java",
"bytes": "14653"
},
{
"name": "Makefile",
"bytes": "49877"
},
{
"name": "Objective-C",
"bytes": "4113"
},
{
"name": "Python",
"bytes": "33854"
}
],
"symlink_target": ""
} |
package org.apache.phoenix.iterate;
import java.text.Format;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.hadoop.hbase.client.Consistency;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.filter.PageFilter;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.io.TimeRange;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.compile.GroupByCompiler.GroupBy;
import org.apache.phoenix.compile.OrderByCompiler.OrderBy;
import org.apache.phoenix.compile.ScanRanges;
import org.apache.phoenix.compile.StatementContext;
import org.apache.phoenix.coprocessor.BaseScannerRegionObserver;
import org.apache.phoenix.filter.BooleanExpressionFilter;
import org.apache.phoenix.parse.HintNode;
import org.apache.phoenix.parse.HintNode.Hint;
import org.apache.phoenix.query.KeyRange;
import org.apache.phoenix.query.KeyRange.Bound;
import org.apache.phoenix.schema.RowKeySchema;
import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.TableRef;
import org.apache.phoenix.schema.types.PDataType;
import org.apache.phoenix.schema.types.PInteger;
import org.apache.phoenix.util.ScanUtil;
import org.apache.phoenix.util.StringUtil;
import com.google.common.collect.Iterators;
public abstract class ExplainTable {
private static final List<KeyRange> EVERYTHING = Collections.singletonList(KeyRange.EVERYTHING_RANGE);
protected final StatementContext context;
protected final TableRef tableRef;
protected final GroupBy groupBy;
protected final OrderBy orderBy;
protected final HintNode hint;
protected final Integer limit;
public ExplainTable(StatementContext context, TableRef table) {
this(context,table,GroupBy.EMPTY_GROUP_BY, OrderBy.EMPTY_ORDER_BY, HintNode.EMPTY_HINT_NODE, null);
}
public ExplainTable(StatementContext context, TableRef table, GroupBy groupBy, OrderBy orderBy, HintNode hintNode, Integer limit) {
this.context = context;
this.tableRef = table;
this.groupBy = groupBy;
this.orderBy = orderBy;
this.hint = hintNode;
this.limit = limit;
}
private boolean explainSkipScan(StringBuilder buf) {
ScanRanges scanRanges = context.getScanRanges();
if (scanRanges.isPointLookup()) {
int keyCount = scanRanges.getPointLookupCount();
buf.append("POINT LOOKUP ON " + keyCount + " KEY" + (keyCount > 1 ? "S " : " "));
} else if (scanRanges.useSkipScanFilter()) {
buf.append("SKIP SCAN ");
int count = 1;
boolean hasRanges = false;
int nSlots = scanRanges.getBoundSlotCount();
for (int i = 0; i < nSlots; i++) {
List<KeyRange> ranges = scanRanges.getRanges().get(i);
count *= ranges.size();
for (KeyRange range : ranges) {
hasRanges |= !range.isSingleKey();
}
}
buf.append("ON ");
buf.append(count);
buf.append(hasRanges ? " RANGE" : " KEY");
buf.append(count > 1 ? "S " : " ");
} else {
buf.append("RANGE SCAN ");
}
return scanRanges.useSkipScanFilter();
}
protected void explain(String prefix, List<String> planSteps) {
StringBuilder buf = new StringBuilder(prefix);
ScanRanges scanRanges = context.getScanRanges();
Scan scan = context.getScan();
if (scan.getConsistency() != Consistency.STRONG){
buf.append("TIMELINE-CONSISTENCY ");
}
if (hint.hasHint(Hint.SMALL)) {
buf.append("SMALL ");
}
if (OrderBy.REV_ROW_KEY_ORDER_BY.equals(orderBy)) {
buf.append("REVERSE ");
}
if (scanRanges.isEverything()) {
buf.append("FULL SCAN ");
} else {
explainSkipScan(buf);
}
buf.append("OVER " + tableRef.getTable().getPhysicalName().getString());
if (!scanRanges.isPointLookup()) {
appendKeyRanges(buf);
}
planSteps.add(buf.toString());
if (context.getScan() != null && tableRef.getTable().getRowTimestampColPos() != -1) {
TimeRange range = context.getScan().getTimeRange();
planSteps.add(" ROW TIMESTAMP FILTER [" + range.getMin() + ", " + range.getMax() + ")");
}
Iterator<Filter> filterIterator = ScanUtil.getFilterIterator(scan);
if (filterIterator.hasNext()) {
PageFilter pageFilter = null;
FirstKeyOnlyFilter firstKeyOnlyFilter = null;
BooleanExpressionFilter whereFilter = null;
do {
Filter filter = filterIterator.next();
if (filter instanceof FirstKeyOnlyFilter) {
firstKeyOnlyFilter = (FirstKeyOnlyFilter)filter;
} else if (filter instanceof PageFilter) {
pageFilter = (PageFilter)filter;
} else if (filter instanceof BooleanExpressionFilter) {
whereFilter = (BooleanExpressionFilter)filter;
}
} while (filterIterator.hasNext());
if (whereFilter != null) {
planSteps.add(" SERVER FILTER BY " + (firstKeyOnlyFilter == null ? "" : "FIRST KEY ONLY AND ") + whereFilter.toString());
} else if (firstKeyOnlyFilter != null) {
planSteps.add(" SERVER FILTER BY FIRST KEY ONLY");
}
if (!orderBy.getOrderByExpressions().isEmpty() && groupBy.isEmpty()) { // with GROUP BY, sort happens client-side
planSteps.add(" SERVER" + (limit == null ? "" : " TOP " + limit + " ROW" + (limit == 1 ? "" : "S"))
+ " SORTED BY " + orderBy.getOrderByExpressions().toString());
} else if (pageFilter != null) {
planSteps.add(" SERVER " + pageFilter.getPageSize() + " ROW LIMIT");
}
}
Integer groupByLimit = null;
byte[] groupByLimitBytes = scan.getAttribute(BaseScannerRegionObserver.GROUP_BY_LIMIT);
if (groupByLimitBytes != null) {
groupByLimit = (Integer) PInteger.INSTANCE.toObject(groupByLimitBytes);
}
groupBy.explain(planSteps, groupByLimit);
if (scan.getAttribute(BaseScannerRegionObserver.SPECIFIC_ARRAY_INDEX) != null) {
planSteps.add(" SERVER ARRAY ELEMENT PROJECTION");
}
}
private void appendPKColumnValue(StringBuilder buf, byte[] range, Boolean isNull, int slotIndex) {
if (Boolean.TRUE.equals(isNull)) {
buf.append("null");
return;
}
if (Boolean.FALSE.equals(isNull)) {
buf.append("not null");
return;
}
if (range.length == 0) {
buf.append('*');
return;
}
ScanRanges scanRanges = context.getScanRanges();
PDataType type = scanRanges.getSchema().getField(slotIndex).getDataType();
SortOrder sortOrder = tableRef.getTable().getPKColumns().get(slotIndex).getSortOrder();
if (sortOrder == SortOrder.DESC) {
buf.append('~');
ImmutableBytesWritable ptr = new ImmutableBytesWritable(range);
type.coerceBytes(ptr, type, sortOrder, SortOrder.getDefault());
range = ptr.get();
}
Format formatter = context.getConnection().getFormatter(type);
buf.append(type.toStringLiteral(range, formatter));
}
private static class RowKeyValueIterator implements Iterator<byte[]> {
private final RowKeySchema schema;
private ImmutableBytesWritable ptr = new ImmutableBytesWritable();
private int position = 0;
private final int maxOffset;
private byte[] nextValue;
public RowKeyValueIterator(RowKeySchema schema, byte[] rowKey) {
this.schema = schema;
this.maxOffset = schema.iterator(rowKey, ptr);
iterate();
}
private void iterate() {
if (schema.next(ptr, position++, maxOffset) == null) {
nextValue = null;
} else {
nextValue = ptr.copyBytes();
}
}
@Override
public boolean hasNext() {
return nextValue != null;
}
@Override
public byte[] next() {
if (nextValue == null) {
throw new NoSuchElementException();
}
byte[] value = nextValue;
iterate();
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private void appendScanRow(StringBuilder buf, Bound bound) {
ScanRanges scanRanges = context.getScanRanges();
// TODO: review this and potentially intersect the scan ranges
// with the minMaxRange in ScanRanges to prevent having to do all this.
KeyRange minMaxRange = scanRanges.getMinMaxRange();
Iterator<byte[]> minMaxIterator = Iterators.emptyIterator();
if (minMaxRange != KeyRange.EVERYTHING_RANGE) {
RowKeySchema schema = tableRef.getTable().getRowKeySchema();
if (!minMaxRange.isUnbound(bound)) {
minMaxIterator = new RowKeyValueIterator(schema, minMaxRange.getRange(bound));
}
}
boolean forceSkipScan = this.hint.hasHint(Hint.SKIP_SCAN);
int nRanges = forceSkipScan ? scanRanges.getRanges().size() : scanRanges.getBoundSlotCount();
for (int i = 0, minPos = 0; minPos < nRanges || minMaxIterator.hasNext(); i++) {
List<KeyRange> ranges = minPos >= nRanges ? EVERYTHING : scanRanges.getRanges().get(minPos++);
KeyRange range = bound == Bound.LOWER ? ranges.get(0) : ranges.get(ranges.size()-1);
byte[] b = range.getRange(bound);
Boolean isNull = KeyRange.IS_NULL_RANGE == range ? Boolean.TRUE : KeyRange.IS_NOT_NULL_RANGE == range ? Boolean.FALSE : null;
if (minMaxIterator.hasNext()) {
byte[] bMinMax = minMaxIterator.next();
int cmp = Bytes.compareTo(bMinMax, b) * (bound == Bound.LOWER ? 1 : -1);
if (cmp > 0) {
minPos = nRanges;
b = bMinMax;
isNull = null;
} else if (cmp < 0) {
minMaxIterator = Iterators.emptyIterator();
}
}
appendPKColumnValue(buf, b, isNull, i);
buf.append(',');
}
}
private void appendKeyRanges(StringBuilder buf) {
ScanRanges scanRanges = context.getScanRanges();
if (scanRanges.isDegenerate() || scanRanges.isEverything()) {
return;
}
buf.append(" [");
StringBuilder buf1 = new StringBuilder();
appendScanRow(buf1, Bound.LOWER);
buf.append(buf1);
buf.setCharAt(buf.length()-1, ']');
StringBuilder buf2 = new StringBuilder();
appendScanRow(buf2, Bound.UPPER);
if (!StringUtil.equals(buf1, buf2)) {
buf.append( " - [");
buf.append(buf2);
}
buf.setCharAt(buf.length()-1, ']');
}
}
| {
"content_hash": "addbdc268360bb15125e1f9615cf3151",
"timestamp": "",
"source": "github",
"line_count": 277,
"max_line_length": 140,
"avg_line_length": 41.768953068592054,
"alnum_prop": 0.5997407087294728,
"repo_name": "rvaleti/phoenix",
"id": "1fa4526cb37fc08c9a710756fef3da4aaa9964cf",
"size": "12371",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "phoenix-core/src/main/java/org/apache/phoenix/iterate/ExplainTable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GAP",
"bytes": "45024"
},
{
"name": "HTML",
"bytes": "18969"
},
{
"name": "Java",
"bytes": "12006360"
},
{
"name": "JavaScript",
"bytes": "203766"
},
{
"name": "Protocol Buffer",
"bytes": "13795"
},
{
"name": "Python",
"bytes": "83417"
},
{
"name": "Scala",
"bytes": "52875"
},
{
"name": "Shell",
"bytes": "62142"
}
],
"symlink_target": ""
} |
#include <errno.h>
#include <limits.h>
#include <algorithm>
#include "io_interface.h"
#include "associative_cache.h"
#include "dirty_page_flusher.h"
#include "safs_exception.h"
#include "memory_manager.h"
namespace safs
{
const long default_init_cache_size = 128 * 1024 * 1024;
template<class T>
void page_cell<T>::set_pages(char *pages[], int num, int node_id)
{
assert(num <= CELL_SIZE);
page_id_t pg_id;
for (int i = 0; i < num; i++) {
buf[i] = T(pg_id, pages[i], node_id);
}
idx = 0;
num_pages = num;
for (int i = 0; i < num; i++) {
maps[i] = i;
}
}
template<class T>
void page_cell<T>::rebuild_map()
{
int j = 0;
for (int i = 0; i < CELL_SIZE; i++) {
if (buf[i].get_data())
maps[j++] = i;
}
assert(j == num_pages);
}
template<class T>
void page_cell<T>::add_pages(char *pages[], int num, int node_id)
{
int num_added = 0;
assert(num_pages == get_num_used_pages());
assert(num + num_pages <= CELL_SIZE);
page_id_t pg_id;
for (int i = 0; i < CELL_SIZE && num_added < num; i++) {
if (buf[i].get_data() == NULL)
buf[i] = T(pg_id, pages[num_added++], node_id);
}
num_pages += num;
rebuild_map();
}
template<class T>
void page_cell<T>::inject_pages(T pages[], int npages)
{
int num_copied = 0;
for (int i = 0; i < CELL_SIZE && num_copied < npages; i++) {
if (buf[i].get_data() == NULL) {
buf[i] = pages[num_copied++];
}
}
assert(num_copied == npages);
num_pages += num_copied;
rebuild_map();
}
template<class T>
void page_cell<T>::steal_pages(T pages[], int &npages)
{
int num_copied = 0;
for (int i = 0; i < CELL_SIZE && num_copied < npages; i++) {
if (buf[i].get_data()) {
// We have to make sure the page isn't being referenced.
// TODO busy wait.
while (buf[i].get_ref() > 0) {}
pages[num_copied++] = buf[i];
buf[i] = T();
}
}
npages = num_copied;
num_pages -= num_copied;
if (num_pages > 0)
rebuild_map();
else
memset(maps, 0, sizeof(maps));
}
template<class T>
void page_cell<T>::sanity_check() const
{
assert(params.get_SA_min_cell_size() <= num_pages);
int num_used_pages = 0;
for (int i = 0; i < CELL_SIZE; i++)
if (buf[i].get_data())
num_used_pages++;
assert(num_used_pages == num_pages);
int prev_map = -1;
for (int i = 0; i < num_pages; i++) {
int map = maps[i];
if (prev_map >= 0)
assert(map > prev_map);
assert(buf[map].get_data());
prev_map = map;
}
}
template<class T>
int page_cell<T>::get_num_used_pages() const
{
int num = 0;
for (int i = 0; i < CELL_SIZE; i++)
if (buf[i].get_data())
num++;
return num;
}
void hash_cell::init(associative_cache *cache, long hash, bool get_pages) {
this->hash = hash;
assert(hash < INT_MAX);
this->table = cache;
if (get_pages) {
char *pages[CELL_SIZE];
if (!table->get_manager()->get_free_pages(params.get_SA_min_cell_size(),
pages, cache))
throw oom_exception();
buf.set_pages(pages, params.get_SA_min_cell_size(), table->get_node_id());
}
num_accesses = 0;
num_evictions = 0;
}
void hash_cell::sanity_check()
{
_lock.lock();
buf.sanity_check();
assert(!is_referenced());
_lock.unlock();
}
void hash_cell::add_pages(char *pages[], int num)
{
buf.add_pages(pages, num, table->get_node_id());
}
int hash_cell::add_pages_to_min(char *pages[], int num)
{
int num_required = CELL_MIN_NUM_PAGES - buf.get_num_pages();
if (num_required > 0) {
num_required = min(num_required, num);
buf.add_pages(pages, num_required, table->get_node_id());
return num_required;
}
else
return 0;
}
void hash_cell::merge(hash_cell *cell)
{
_lock.lock();
cell->_lock.lock();
assert(cell->get_num_pages() + this->get_num_pages() <= CELL_SIZE);
thread_safe_page pages[CELL_SIZE];
int npages = CELL_SIZE;
// TODO there may be busy wait in this method.
cell->buf.steal_pages(pages, npages);
buf.inject_pages(pages, npages);
cell->_lock.unlock();
_lock.unlock();
}
/**
* rehash the pages in the current cell to the expanded cell.
*/
void hash_cell::rehash(hash_cell *expanded)
{
_lock.lock();
expanded->_lock.lock();
thread_safe_page *exchanged_pages_pointers[CELL_SIZE];
int num_exchanges = 0;
for (unsigned int i = 0; i < buf.get_num_pages(); i++) {
thread_safe_page *pg = buf.get_page(i);
page_id_t pg_id(pg->get_file_id(), pg->get_offset());
int hash1 = table->hash1_locked(pg_id);
/*
* It's possible that a page is in a wrong cell.
* It's likely because the page is added to the cell
* right when `level' is increased.
* But the case is rare, so we can just simple ignore
* the case. It doesn't affect the correctness of
* the implementation. The only penalty is that
* we might get a cache miss.
* Since the page is in a wrong cell, it won't be
* accessed any more, so we should shorten the time
* it gets evicted by setting its hit to 1.
*/
if (hash1 != expanded->hash) {
pg->set_hits(1);
continue;
}
/*
* if the two hash values don't match,
* it means the page is mapped to the expanded cell.
* we exchange the pages in the two cells.
*/
if (this->hash != hash1) {
/*
* we have to make sure no other threads are using them
* before we can exchange them.
* If the pages are in use, skip them.
*/
if (pg->get_ref())
continue;
exchanged_pages_pointers[num_exchanges++] = pg;
// We can't steal pages while iterating them.
}
}
if (num_exchanges > 0) {
// We can only steal pages here.
thread_safe_page exchanged_pages[CELL_SIZE];
for (int i = 0; i < num_exchanges; i++) {
exchanged_pages[i] = *exchanged_pages_pointers[i];
buf.steal_page(exchanged_pages_pointers[i], false);
*exchanged_pages_pointers[i] = thread_safe_page();
}
buf.rebuild_map();
expanded->buf.inject_pages(exchanged_pages, num_exchanges);
}
// Move empty pages to the expanded cell if it doesn't have enough pages.
int num_required = params.get_SA_min_cell_size() - expanded->buf.get_num_pages();
int num_empty = 0;
if (num_required > 0) {
thread_safe_page *empty_pages_pointers[num_required];
thread_safe_page *empty_pages = new thread_safe_page[params.get_SA_min_cell_size()];
for (unsigned int i = 0; i < buf.get_num_pages()
&& num_empty < num_required; i++) {
thread_safe_page *pg = buf.get_page(i);
if (!pg->initialized())
empty_pages_pointers[num_empty++] = pg;
}
for (int i = 0; i < num_empty; i++) {
// For the same reason, we can't steal pages
// while iterating them.
empty_pages[i] = *empty_pages_pointers[i];
buf.steal_page(empty_pages_pointers[i], false);
*empty_pages_pointers[i] = thread_safe_page();
}
buf.rebuild_map();
expanded->buf.inject_pages(empty_pages, num_empty);
delete [] empty_pages;
}
expanded->_lock.unlock();
_lock.unlock();
}
void hash_cell::steal_pages(char *pages[], int &npages)
{
int num_stolen = 0;
while (num_stolen < npages) {
thread_safe_page *pg = get_empty_page();
if (pg == NULL)
break;
assert(!pg->is_dirty());
pages[num_stolen++] = (char *) pg->get_data();
*pg = thread_safe_page();
buf.steal_page(pg, false);
}
buf.rebuild_map();
npages = num_stolen;
}
void hash_cell::rebalance(hash_cell *cell)
{
// TODO
}
page *hash_cell::search(const page_id_t &pg_id)
{
_lock.lock();
page *ret = NULL;
for (unsigned int i = 0; i < buf.get_num_pages(); i++) {
if (buf.get_page(i)->get_offset() == pg_id.get_offset()
&& buf.get_page(i)->get_file_id() == pg_id.get_file_id()) {
ret = buf.get_page(i);
break;
}
}
if (ret)
ret->inc_ref();
_lock.unlock();
return ret;
}
/**
* search for a page with the offset.
* If the page doesn't exist, return an empty page.
*/
page *hash_cell::search(const page_id_t &pg_id, page_id_t &old_id)
{
thread_safe_page *ret = NULL;
_lock.lock();
num_accesses++;
for (unsigned int i = 0; i < buf.get_num_pages(); i++) {
if (buf.get_page(i)->get_offset() == pg_id.get_offset()
&& buf.get_page(i)->get_file_id() == pg_id.get_file_id()) {
ret = buf.get_page(i);
break;
}
}
if (ret == NULL) {
num_evictions++;
ret = get_empty_page();
if (ret == NULL) {
_lock.unlock();
return NULL;
}
// We need to clear flags here.
ret->set_data_ready(false);
assert(!ret->is_io_pending());
// We don't clear the prepare writeback flag because this flag
// indicates that the page is in the queue for writing back, so
// the flusher doesn't need to add another request to flush the
// page. The flag will be cleared after it is removed from the queue.
if (ret->is_dirty() && !ret->is_old_dirty()) {
ret->set_dirty(false);
ret->set_old_dirty(true);
}
off_t old_off = ret->get_offset();
file_id_t old_file_id = ret->get_file_id();
if (old_off == -1) {
old_off = PAGE_INVALID_OFFSET;
assert(old_file_id == INVALID_FILE_ID);
}
old_id = page_id_t(old_file_id, old_off);
/*
* I have to change the offset in the spinlock,
* to make sure when the spinlock is unlocked,
* the page can be seen by others even though
* it might not have data ready.
*/
ret->set_id(pg_id);
#ifdef USE_SHADOW_PAGE
shadow_page shadow_pg = shadow.search(off);
/*
* if the page has been seen before,
* we should set the hits info.
*/
if (shadow_pg.is_valid())
ret->set_hits(shadow_pg.get_hits());
#endif
}
else
policy.access_page(ret, buf);
/* it's possible that the data in the page isn't ready */
ret->inc_ref();
if (ret->get_hits() == 0xff) {
buf.scale_down_hits();
#ifdef USE_SHADOW_PAGE
shadow.scale_down_hits();
#endif
}
ret->hit();
_lock.unlock();
#ifdef DEBUG
if (enable_debug && ret->is_old_dirty())
print_cell();
#endif
return ret;
}
void hash_cell::print_cell()
{
_lock.lock();
printf("cell %ld: in queue: %d\n", get_hash(), is_in_queue());
for (unsigned int i = 0; i < buf.get_num_pages(); i++) {
thread_safe_page *p = buf.get_page(i);
printf("cell %ld: p%lx, hits: %d, score: %d, ref: %d, r: %d, p: %d, d: %d, od: %d, w: %d\n",
get_hash(), p->get_offset(), p->get_hits(), p->get_flush_score(),
p->get_ref(), p->data_ready(), p->is_io_pending(), p->is_dirty(),
p->is_old_dirty(), p->is_prepare_writeback());
}
_lock.unlock();
}
/* this function has to be called with lock held */
thread_safe_page *hash_cell::get_empty_page()
{
thread_safe_page *ret = policy.evict_page(buf);
if (ret == NULL) {
#ifdef DEBUG
printf("all pages in the cell were all referenced\n");
#endif
return NULL;
}
/* we record the hit info of the page in the shadow cell. */
#ifdef USE_SHADOW_PAGE
if (ret->get_hits() > 0)
shadow.add(shadow_page(*ret));
#endif
return ret;
}
/*
* the end of the vector points to the pages
* that are most recently accessed.
*/
thread_safe_page *LRU_eviction_policy::evict_page(
page_cell<thread_safe_page> &buf)
{
int pos;
if (pos_vec.size() < buf.get_num_pages()) {
pos = pos_vec.size();
}
else {
/* evict the first page */
pos = pos_vec[0];
pos_vec.erase(pos_vec.begin());
}
thread_safe_page *ret = buf.get_page(pos);
while (ret->get_ref()) {}
pos_vec.push_back(pos);
ret->set_data_ready(false);
return ret;
}
void LRU_eviction_policy::access_page(thread_safe_page *pg,
page_cell<thread_safe_page> &buf)
{
/* move the page to the end of the pos vector. */
int pos = buf.get_idx(pg);
for (std::vector<int>::iterator it = pos_vec.begin();
it != pos_vec.end(); it++) {
if (*it == pos) {
pos_vec.erase(it);
break;
}
}
pos_vec.push_back(pos);
}
thread_safe_page *LFU_eviction_policy::evict_page(
page_cell<thread_safe_page> &buf)
{
thread_safe_page *ret = NULL;
int min_hits = 0x7fffffff;
do {
unsigned int num_io_pending = 0;
for (unsigned int i = 0; i < buf.get_num_pages(); i++) {
thread_safe_page *pg = buf.get_page(i);
if (pg->get_ref()) {
if (pg->is_io_pending())
num_io_pending++;
continue;
}
/*
* refcnt only increases within the lock of the cell,
* so if the page's refcnt is 0 above,
* it'll be always 0 within the lock.
*/
if (min_hits > pg->get_hits()) {
min_hits = pg->get_hits();
ret = pg;
}
/*
* if a page hasn't been accessed before,
* it's a completely new page, just use it.
*/
if (min_hits == 0)
break;
}
if (num_io_pending == buf.get_num_pages()) {
printf("all pages are at io pending\n");
// TODO do something...
// maybe we should use pthread_wait
}
/* it happens when all pages in the cell is used currently. */
} while (ret == NULL);
ret->set_data_ready(false);
ret->reset_hits();
return ret;
}
thread_safe_page *FIFO_eviction_policy::evict_page(
page_cell<thread_safe_page> &buf)
{
thread_safe_page *ret = buf.get_empty_page();
/*
* This happens a lot if we actually read pages from the disk.
* So basically, we shouldn't use this eviction policy for SSDs
* or magnetic hard drive..
*/
while (ret->get_ref()) {
ret = buf.get_empty_page();
}
ret->set_data_ready(false);
return ret;
}
struct page_score
{
thread_safe_page *pg;
int score;
};
struct comp_flush_score {
bool operator() (const page_score &pg1, const page_score &pg2) {
return pg1.score < pg2.score;
}
} flush_score_comparator;
void gclock_eviction_policy::assign_flush_scores(page_cell<thread_safe_page> &buf)
{
const int num_pages = buf.get_num_pages();
page_score pages[num_pages];
int head = clock_head % num_pages;
int num_avail_pages = 0;
for (int i = 0; i < num_pages; i++) {
thread_safe_page *pg = buf.get_page(i);
if (pg->is_valid()) {
int score = pg->get_hits() * num_pages + (i - head + num_pages) % num_pages;
pg->set_flush_score(score);
pages[num_avail_pages].pg = pg;
pages[num_avail_pages].score = score;
num_avail_pages++;
}
}
// We need to normalize the flush score.
std::sort(pages, pages + num_avail_pages, flush_score_comparator);
for (int i = 0; i < num_avail_pages; i++) {
pages[i].pg->set_flush_score(i);
}
}
thread_safe_page *gclock_eviction_policy::evict_page(
page_cell<thread_safe_page> &buf)
{
thread_safe_page *ret = NULL;
unsigned int num_referenced = 0;
unsigned int num_dirty = 0;
bool avoid_dirty = true;
do {
thread_safe_page *pg = buf.get_page(clock_head % buf.get_num_pages());
if (num_dirty + num_referenced >= buf.get_num_pages()) {
num_dirty = 0;
num_referenced = 0;
avoid_dirty = false;
}
clock_head++;
if (pg->get_ref()) {
num_referenced++;
/*
* If all pages in the cell are referenced, we should
* return NULL to notify the invoker.
*/
if (num_referenced >= buf.get_num_pages())
return NULL;
continue;
}
if (avoid_dirty && pg->is_dirty()) {
num_dirty++;
continue;
}
if (pg->get_hits() == 0) {
ret = pg;
break;
}
pg->set_hits(pg->get_hits() - 1);
} while (ret == NULL);
ret->set_data_ready(false);
#if 0
assign_flush_scores(buf);
#endif
return ret;
}
/**
* This method runs over all pages and finds the pages that are most likely
* to be evicted. But we only return pages that have certain flags and/or
* don't have certain pages.
*/
int gclock_eviction_policy::predict_evicted_pages(
page_cell<thread_safe_page> &buf, int num_pages, int set_flags,
int clear_flags, std::map<off_t, thread_safe_page *> &pages)
{
// We are just predicting. We don't actually evict any pages.
// So we need to make a copy of the hits of each page.
short hits[CELL_SIZE];
for (int i = 0; i < (int) buf.get_num_pages(); i++) {
hits[i] = buf.get_page(i)->get_hits();
}
assign_flush_scores(buf);
// The number of pages that are most likely to be evicted.
int num_most_likely = 0;
// The function returns when we get the expected number of pages
// or we get pages
while (true) {
for (int i = 0; i < (int) buf.get_num_pages(); i++) {
int idx = (i + clock_head) % buf.get_num_pages();
short *hit = &hits[idx];
// The page is already in the page map.
if (*hit < 0)
continue;
else if (*hit == 0) {
*hit = -1;
thread_safe_page *p = buf.get_page(idx);
if (p->test_flags(set_flags) && !p->test_flags(clear_flags)) {
pages.insert(std::pair<off_t, thread_safe_page *>(
p->get_offset(), p));
if ((int) pages.size() == num_pages)
return pages.size();
}
num_most_likely++;
}
else {
(*hit)--;
}
/*
* We have got all pages that are most likely to be evicted.
* Let's just return whatever we have.
*/
if (num_most_likely >= MAX_NUM_WRITEBACK)
return pages.size();
}
}
}
thread_safe_page *clock_eviction_policy::evict_page(
page_cell<thread_safe_page> &buf)
{
thread_safe_page *ret = NULL;
unsigned int num_referenced = 0;
unsigned int num_dirty = 0;
bool avoid_dirty = true;
do {
thread_safe_page *pg = buf.get_page(clock_head % buf.get_num_pages());
if (num_dirty + num_referenced >= buf.get_num_pages()) {
num_dirty = 0;
num_referenced = 0;
avoid_dirty = false;
}
if (pg->get_ref()) {
num_referenced++;
if (num_referenced >= buf.get_num_pages())
return NULL;
clock_head++;
continue;
}
if (avoid_dirty && pg->is_dirty()) {
num_dirty++;
clock_head++;
continue;
}
if (pg->get_hits() == 0) {
ret = pg;
break;
}
pg->reset_hits();
clock_head++;
} while (ret == NULL);
ret->set_data_ready(false);
ret->reset_hits();
return ret;
}
associative_cache::~associative_cache()
{
for (unsigned int i = 0; i < cells_table.size(); i++)
if (cells_table[i])
hash_cell::destroy_array(cells_table[i], init_ncells);
manager->unregister_cache(this);
memory_manager::destroy(manager);
}
bool associative_cache::shrink(int npages, char *pages[])
{
if (flags.set_flag(TABLE_EXPANDING)) {
/*
* if the flag has been set before,
* it means another thread is expanding the table,
*/
return false;
}
/* starting from this point, only one thred can be here. */
int pg_idx = 0;
int orig_ncells = get_num_cells();
while (pg_idx < npages) {
// The cell table isn't in the stage of splitting.
if (split == 0) {
hash_cell *cell = get_cell(expand_cell_idx);
while (height >= params.get_SA_min_cell_size()) {
int num = max(0, cell->get_num_pages() - height);
num = min(npages - pg_idx, num);
if (num > 0) {
cell->steal_pages(&pages[pg_idx], num);
pg_idx += num;
}
if (expand_cell_idx <= 0) {
height--;
expand_cell_idx = orig_ncells;
}
expand_cell_idx--;
cell = get_cell(expand_cell_idx);
}
if (pg_idx == npages) {
cache_npages.dec(npages);
flags.clear_flag(TABLE_EXPANDING);
return true;
}
}
/* From here, we shrink the cell table. */
// When the thread is within in the while loop, other threads can
// hardly access the cells in the table.
if (level == 0)
break;
int num_half = (1 << level) * init_ncells / 2;
table_lock.write_lock();
if (split == 0) {
split = num_half - 1;
level--;
}
table_lock.write_unlock();
while (split > 0) {
hash_cell *high_cell = get_cell(split + num_half);
hash_cell *cell = get_cell(split);
// At this point, the high cell and the low cell together
// should have no more than CELL_MIN_NUM_PAGES pages.
cell->merge(high_cell);
table_lock.write_lock();
split--;
table_lock.write_unlock();
}
int orig_narrays = (1 << level);
// It's impossible to access the arrays after `narrays' now.
int narrays = orig_narrays / 2;
for (int i = narrays; i < orig_narrays; i++) {
hash_cell::destroy_array(cells_table[i], init_ncells);
cells_table[i] = NULL;
}
}
flags.clear_flag(TABLE_EXPANDING);
cache_npages.dec(npages);
return true;
}
/**
* This method increases the cache size by `npages'.
*/
int associative_cache::expand(int npages)
{
if (flags.set_flag(TABLE_EXPANDING)) {
/*
* if the flag has been set before,
* it means another thread is expanding the table,
*/
return 0;
}
/* starting from this point, only one thred can be here. */
char *pages[npages];
if (!manager->get_free_pages(npages, pages, this)) {
flags.clear_flag(TABLE_EXPANDING);
fprintf(stderr, "expand: can't allocate %d pages\n", npages);
return 0;
}
int pg_idx = 0;
bool expand_over = false;
while (pg_idx < npages && !expand_over) {
// The cell table isn't in the stage of splitting.
if (split == 0) {
int orig_ncells = get_num_cells();
/* We first try to add pages to the existing cells. */
hash_cell *cell = get_cell(expand_cell_idx);
while (height <= CELL_SIZE && pg_idx < npages) {
int num_missing;
assert(pages[pg_idx]);
// We should skip the cells with more than `height'.
if (cell->get_num_pages() >= height)
goto next_cell;
num_missing = height - cell->get_num_pages();
num_missing = min(num_missing, npages - pg_idx);
cell->add_pages(&pages[pg_idx], num_missing);
pg_idx += num_missing;
next_cell:
expand_cell_idx++;
if (expand_cell_idx >= (unsigned) orig_ncells) {
expand_cell_idx = 0;
height++;
}
cell = get_cell(expand_cell_idx);
}
if (pg_idx == npages) {
cache_npages.inc(npages);
flags.clear_flag(TABLE_EXPANDING);
return npages;
}
/* We have to expand the cell table in order to add more pages. */
/* Double the size of the cell table. */
/* create cells and put them in a temporary table. */
std::vector<hash_cell *> table;
int orig_narrays = (1 << level);
for (int i = orig_narrays; i < orig_narrays * 2; i++) {
hash_cell *cells = hash_cell::create_array(node_id, init_ncells);
printf("create %d cells: %p\n", init_ncells, cells);
for (int j = 0; j < init_ncells; j++) {
cells[j].init(this, i * init_ncells + j, false);
}
table.push_back(cells);
}
/*
* here we need to hold the lock because other threads
* might be accessing the table. by using the write lock,
* we notify others the table has been changed.
*/
table_lock.write_lock();
for (unsigned int i = 0; i < table.size(); i++) {
cells_table[orig_narrays + i] = table[i];
}
table_lock.write_unlock();
}
height = params.get_SA_min_cell_size() + 1;
// When the thread is within in the while loop, other threads
// can hardly access the cells in the table.
int num_half = (1 << level) * init_ncells;
while (split < num_half) {
hash_cell *expanded_cell = get_cell(split + num_half);
hash_cell *cell = get_cell(split);
cell->rehash(expanded_cell);
/*
* After rehashing, there is no guarantee that two cells will have
* the same number of pages. We need to either add empty pages to
* the cell without enough pages or rebalance the two cells.
*/
/* Add pages to the cell without enough pages. */
int num_required = max(expanded_cell->get_num_pages()
- params.get_SA_min_cell_size(), 0);
num_required += max(cell->get_num_pages() - params.get_SA_min_cell_size(), 0);
if (num_required <= npages - pg_idx) {
/*
* Actually only one cell requires more pages, the other
* one will just take 0 pages.
*/
pg_idx += cell->add_pages_to_min(&pages[pg_idx],
npages - pg_idx);
pg_idx += expanded_cell->add_pages_to_min(&pages[pg_idx],
npages - pg_idx);
}
if (expanded_cell->get_num_pages() < params.get_SA_min_cell_size()
|| cell->get_num_pages() < params.get_SA_min_cell_size()) {
// If we failed to split a cell, we should merge the two half
cell->merge(expanded_cell);
expand_over = true;
fprintf(stderr, "A cell can't have enough pages, merge back\n");
break;
}
table_lock.write_lock();
split++;
table_lock.write_unlock();
}
table_lock.write_lock();
if (split == num_half) {
split = 0;
level++;
}
table_lock.write_unlock();
}
if (pg_idx < npages)
manager->free_pages(npages - pg_idx, &pages[pg_idx]);
flags.clear_flag(TABLE_EXPANDING);
cache_npages.inc(npages);
return npages - pg_idx;
}
page *associative_cache::search(const page_id_t &pg_id, page_id_t &old_id) {
/*
* search might change the structure of the cell,
* and cause the cell table to expand.
* Thus, the page might not be placed in the cell
* we found before. Therefore, we need to research
* for the cell.
*/
do {
page *p = get_cell_offset(pg_id)->search(pg_id, old_id);
#ifdef DEBUG
if (p->is_old_dirty())
num_dirty_pages.dec(1);
#endif
return p;
} while (true);
}
page *associative_cache::search(const page_id_t &pg_id)
{
do {
return get_cell_offset(pg_id)->search(pg_id);
} while (true);
}
int associative_cache::get_num_used_pages() const
{
unsigned long count;
int npages = 0;
do {
table_lock.read_lock(count);
int ncells = get_num_cells();
for (int i = 0; i < ncells; i++) {
npages += get_cell(i)->get_num_pages();
}
} while (!table_lock.read_unlock(count));
return npages;
}
void associative_cache::sanity_check() const
{
unsigned long count;
do {
table_lock.read_lock(count);
int ncells = get_num_cells();
for (int i = 0; i < ncells; i++) {
hash_cell *cell = get_cell(i);
cell->sanity_check();
}
} while (!table_lock.read_unlock(count));
}
associative_cache::associative_cache(long cache_size, long max_cache_size,
int node_id, int offset_factor, int _max_num_pending_flush,
bool expandable): max_num_pending_flush(_max_num_pending_flush)
{
this->offset_factor = offset_factor;
pthread_mutex_init(&init_mutex, NULL);
#ifdef DEBUG
printf("associative cache is created on node %d, cache size: %ld, min cell size: %d\n",
node_id, cache_size, params.get_SA_min_cell_size());
#endif
this->node_id = node_id;
level = 0;
split = 0;
height = params.get_SA_min_cell_size();
expand_cell_idx = 0;
this->expandable = expandable;
this->manager = memory_manager::create(max_cache_size, node_id);
manager->register_cache(this);
long init_cache_size = default_init_cache_size;
if (init_cache_size > cache_size
// If the cache isn't expandable, let's just use the maximal
// cache size at the beginning.
|| !expandable)
init_cache_size = cache_size;
int min_cell_size = params.get_SA_min_cell_size();
if (init_cache_size < min_cell_size * PAGE_SIZE)
init_cache_size = min_cell_size * PAGE_SIZE;
int npages = init_cache_size / PAGE_SIZE;
init_ncells = npages / min_cell_size;
hash_cell *cells = hash_cell::create_array(node_id, init_ncells);
int max_npages = manager->get_max_size() / PAGE_SIZE;
try {
for (int i = 0; i < init_ncells; i++)
cells[i].init(this, i, true);
} catch (oom_exception e) {
fprintf(stderr,
"out of memory: max npages: %d, init npages: %d\n",
max_npages, npages);
throw e;
}
cells_table.push_back(cells);
int max_ncells = max_npages / min_cell_size;
for (int i = 1; i < max_ncells / init_ncells; i++)
cells_table.push_back(NULL);
if (expandable && cache_size > init_cache_size)
expand((cache_size - init_cache_size) / PAGE_SIZE);
}
/**
* This defines an interface for implementing the policy of selecting
* dirty pages for flushing.
*/
class select_dirty_pages_policy
{
public:
// It select a specified number of pages from the page set.
virtual int select(hash_cell *cell, int num_pages,
std::map<off_t, thread_safe_page *> &pages) = 0;
};
/**
* The policy selects dirty pages that are most likely to be evicted
* by the eviction policy.
*/
class eviction_select_dirty_pages_policy: public select_dirty_pages_policy
{
public:
int select(hash_cell *cell, int num_pages,
std::map<off_t, thread_safe_page *> &pages) {
char set_flags = 0;
char clear_flags = 0;
page_set_flag(set_flags, DIRTY_BIT, true);
page_set_flag(clear_flags, IO_PENDING_BIT, true);
page_set_flag(clear_flags, PREPARE_WRITEBACK, true);
cell->predict_evicted_pages(num_pages, set_flags, clear_flags, pages);
return pages.size();
}
};
/**
* This policy simply selects some dirty pages in a page set.
*/
class default_select_dirty_pages_policy: public select_dirty_pages_policy
{
public:
int select(hash_cell *cell, int num_pages,
std::map<off_t, thread_safe_page *> &pages) {
char set_flags = 0;
char clear_flags = 0;
page_set_flag(set_flags, DIRTY_BIT, true);
page_set_flag(clear_flags, IO_PENDING_BIT, true);
page_set_flag(clear_flags, PREPARE_WRITEBACK, true);
cell->get_pages(num_pages, set_flags, clear_flags, pages);
return pages.size();
}
};
class associative_flusher;
class flush_io: public io_interface
{
io_interface::ptr underlying;
pthread_key_t underlying_key;
associative_cache *cache;
associative_flusher *flusher;
io_interface *get_per_thread_io() {
io_interface *io = (io_interface *) pthread_getspecific(underlying_key);
if (io == NULL) {
thread *curr = thread::get_curr_thread();
assert(curr);
io = underlying->clone(curr);
pthread_setspecific(underlying_key, io);
}
return io;
}
public:
flush_io(io_interface::ptr underlying, associative_cache *cache,
associative_flusher *flusher): io_interface(NULL,
underlying->get_header()) {
this->underlying = underlying;
this->cache = cache;
this->flusher = flusher;
pthread_key_create(&underlying_key, NULL);
}
virtual int get_file_id() const {
throw unsupported_exception("get_file_id");
}
virtual void notify_completion(io_request *reqs[], int num);
virtual void access(io_request *requests, int num, io_status *status = NULL) {
get_per_thread_io()->access(requests, num, status);
}
virtual void flush_requests() {
get_per_thread_io()->flush_requests();
}
virtual int wait4complete(int num) {
throw unsupported_exception("wait4complete");
}
virtual void cleanup() {
throw unsupported_exception("cleanup");
}
};
class associative_flusher: public dirty_page_flusher
{
// For the case of NUMA cache, cache and local_cache are different.
page_cache *cache;
associative_cache *local_cache;
int node_id;
std::unique_ptr<flush_io> io;
std::unique_ptr<select_dirty_pages_policy> policy;
public:
thread_safe_FIFO_queue<hash_cell *> dirty_cells;
associative_flusher(page_cache *cache, associative_cache *local_cache,
io_interface::ptr io, int node_id): dirty_cells(
std::string("dirty_cells-") + itoa(io->get_node_id()),
io->get_node_id(), local_cache->get_num_cells()) {
this->node_id = node_id;
this->cache = cache;
this->local_cache = local_cache;
if (this->cache == NULL)
this->cache = local_cache;
this->io = std::unique_ptr<flush_io>(new flush_io(io, local_cache, this));
policy = std::unique_ptr<select_dirty_pages_policy>(new eviction_select_dirty_pages_policy());
}
int get_node_id() const {
return node_id;
}
void run();
void flush_dirty_pages(thread_safe_page *pages[], int num,
io_interface &io);
int flush_dirty_pages(page_filter *filter, int max_num);
int flush_cell(hash_cell *cell, io_request *req_array, int req_array_size);
};
void flush_io::notify_completion(io_request *reqs[], int num)
{
hash_cell *dirty_cells[num];
int num_dirty_cells = 0;
int num_flushes = 0;
for (int i = 0; i < num; i++) {
// If the request is discarded by the I/O thread, we need to
// check the page set where it is located.
// If the page set isn't in the queue of dirty page sets,
// we need to check if the page set contains pages that
// we should flush.
if (reqs[i]->is_discarded()) {
page_id_t pg_id(reqs[i]->get_file_id(), reqs[i]->get_offset());
hash_cell *cell = cache->get_cell_offset(pg_id);
#ifdef DEBUG
assert(cell->contain(reqs[i]->get_page(0)));
#endif
if (cell->is_in_queue())
continue;
// Try to add more flushes only when there aren't many pending
// flush requests.
if (cache->num_pending_flush.get() < cache->max_num_pending_flush) {
io_request req_array[NUM_WRITEBACK_DIRTY_PAGES];
int ret = flusher->flush_cell(cell, req_array,
NUM_WRITEBACK_DIRTY_PAGES);
if (ret > 0) {
this->access(req_array, ret);
num_flushes += ret;
}
// If we get what we ask for, maybe there are more dirty pages
// we can flush. Add the dirty cell back in the queue.
if (ret == NUM_WRITEBACK_DIRTY_PAGES && !cell->set_in_queue(true))
dirty_cells[num_dirty_cells++] = cell;
}
else
// Let's add the cell for later examination.
dirty_cells[num_dirty_cells++] = cell;
continue;
}
assert(reqs[i]->get_num_bufs());
if (reqs[i]->get_num_bufs() == 1) {
thread_safe_page *p = (thread_safe_page *) reqs[i]->get_page(0);
p->lock();
assert(p->is_dirty());
p->set_dirty(false);
p->set_io_pending(false);
BOOST_VERIFY(p->reset_reqs() == NULL);
p->unlock();
p->dec_ref();
}
else {
off_t off = reqs[i]->get_offset();
for (int j = 0; j < reqs[i]->get_num_bufs(); j++) {
thread_safe_page *p = reqs[i]->get_page(j);
assert(p);
p->lock();
assert(p->is_dirty());
p->set_dirty(false);
p->set_io_pending(false);
BOOST_VERIFY(p->reset_reqs() == NULL);
p->unlock();
p->dec_ref();
assert(p->get_ref() >= 0);
off += PAGE_SIZE;
}
}
delete reqs[i]->get_extension();
}
if (num_dirty_cells > 0)
flusher->dirty_cells.add(dirty_cells, num_dirty_cells);
if (num_flushes > 0)
cache->num_pending_flush.inc(num_flushes);
cache->num_pending_flush.dec(num);
#ifdef DEBUG
cache->num_dirty_pages.dec(num);
int orig = cache->num_pending_flush.get();
#endif
if (cache->num_pending_flush.get() < cache->max_num_pending_flush) {
flusher->run();
}
#ifdef DEBUG
if (enable_debug)
printf("node %d: %d orig, %d pending, %d dirty cells, %d dirty pages\n",
get_node_id(), orig, cache->num_pending_flush.get(),
flusher->dirty_cells.get_num_entries(),
cache->num_dirty_pages.get());
#endif
}
void merge_pages2req(io_request &req, page_cache *cache);
int associative_flusher::flush_cell(hash_cell *cell,
io_request *req_array, int req_array_size)
{
std::map<off_t, thread_safe_page *> dirty_pages;
policy->select(cell, NUM_WRITEBACK_DIRTY_PAGES, dirty_pages);
int num_init_reqs = 0;
for (std::map<off_t, thread_safe_page *>::const_iterator it
= dirty_pages.begin(); it != dirty_pages.end(); it++) {
thread_safe_page *p = it->second;
p->lock();
assert(!p->is_old_dirty());
assert(p->data_ready());
assert(num_init_reqs < req_array_size);
// Here we flush dirty pages with normal requests.
#if 0
if (!p->is_io_pending() && !p->is_prepare_writeback()
// The page may have been cleaned.
&& p->is_dirty()) {
// TODO global_cached_io may delete the extension.
// I'll fix it later.
if (!req_array[num_init_reqs].is_extended_req()) {
io_request tmp(true);
req_array[num_init_reqs] = tmp;
}
req_array[num_init_reqs].init(p->get_offset(), WRITE, io,
get_node_id(), NULL, cache, NULL);
req_array[num_init_reqs].add_page(p);
req_array[num_init_reqs].set_high_prio(true);
p->set_io_pending(true);
p->unlock();
merge_pages2req(req_array[num_init_reqs], cache);
num_init_reqs++;
}
else {
p->unlock();
p->dec_ref();
}
#endif
// The code blow flush dirty pages with low-priority requests.
if (!p->is_io_pending() && !p->is_prepare_writeback()
// The page may have been cleaned.
&& p->is_dirty()) {
data_loc_t loc(p->get_file_id(), p->get_offset());
new (req_array + num_init_reqs) io_request(
new io_req_extension(), loc, WRITE, io.get(), get_node_id());
req_array[num_init_reqs].set_priv(cache);
req_array[num_init_reqs].add_page(p);
req_array[num_init_reqs].set_high_prio(false);
#ifdef STATISTICS
req_array[num_init_reqs].set_timestamp();
#endif
num_init_reqs++;
p->set_prepare_writeback(true);
}
// When a page is put in the queue for writing back,
// the queue of the IO thread doesn't own the page, which
// means that the page can be evicted.
p->unlock();
p->dec_ref();
}
return num_init_reqs;
}
/**
* This will run until we get enough pending flushes.
*/
void associative_flusher::run()
{
const int FETCH_BUF_SIZE = 32;
// We can't get more requests than the number of pages in a cell.
io_request req_array[NUM_WRITEBACK_DIRTY_PAGES];
int tot_flushes = 0;
while (dirty_cells.get_num_entries() > 0) {
hash_cell *cells[FETCH_BUF_SIZE];
hash_cell *tmp[FETCH_BUF_SIZE];
int num_dirty_cells = 0;
int num_fetches = dirty_cells.fetch(cells, FETCH_BUF_SIZE);
int num_flushes = 0;
for (int i = 0; i < num_fetches; i++) {
int ret = flush_cell(cells[i], req_array,
NUM_WRITEBACK_DIRTY_PAGES);
if (ret > 0) {
io->access(req_array, ret);
num_flushes += ret;
}
// If we get what we ask for, maybe there are more dirty pages
// we can flush. Add the dirty cell back in the queue.
if (ret == NUM_WRITEBACK_DIRTY_PAGES)
tmp[num_dirty_cells++] = cells[i];
else {
// We can clear the in_queue flag now.
// The cell won't be added to the queue for flush until its dirty pages
// have been written back successfully.
// A cell is added to the queue only when the number of dirty pages
// that aren't being written back is larger than a threshold.
cells[i]->set_in_queue(false);
}
}
dirty_cells.add(tmp, num_dirty_cells);
local_cache->num_pending_flush.inc(num_flushes);
tot_flushes += num_flushes;
// If we have flushed enough pages, we can stop now.
if (local_cache->num_pending_flush.get()
> local_cache->max_num_pending_flush) {
break;
}
}
io->flush_requests();
}
void associative_cache::create_flusher(io_interface::ptr io,
page_cache *global_cache)
{
pthread_mutex_lock(&init_mutex);
if (_flusher == NULL && io
// The IO instance should be on the same node or we don't know
// in which node the cache is.
&& (io->get_node_id() == node_id || node_id == -1)) {
_flusher = std::unique_ptr<dirty_page_flusher>(
new associative_flusher(global_cache, this, io, node_id));
}
pthread_mutex_unlock(&init_mutex);
}
void associative_cache::mark_dirty_pages(thread_safe_page *pages[], int num,
io_interface &io)
{
#ifdef DEBUG
num_dirty_pages.inc(num);
#endif
if (_flusher)
_flusher->flush_dirty_pages(pages, num, io);
}
void associative_cache::init(io_interface::ptr underlying)
{
create_flusher(underlying, this);
}
hash_cell *associative_cache::get_prev_cell(hash_cell *cell) {
long index = cell->get_hash();
// The first cell in the hash table.
if (index == 0)
return NULL;
// The cell is in the middle of a cell array.
if (index % init_ncells)
return cell - 1;
else {
unsigned i;
for (i = 0; i < cells_table.size(); i++) {
if (cell == cells_table[i]) {
assert(i > 0);
// return the last cell in the previous cell array.
return (cells_table[i - 1] + init_ncells - 1);
}
}
// we shouldn't reach here if the cell exists in the table.
return NULL;
}
}
hash_cell *associative_cache::get_next_cell(hash_cell *cell)
{
long index = cell->get_hash();
// If it's not the last cell in the cell array.
if (index % init_ncells != init_ncells - 1)
return cell + 1;
else {
unsigned i;
hash_cell *first = cell + 1 - init_ncells;
for (i = 0; i < cells_table.size(); i++) {
if (first == cells_table[i]) {
if (i == cells_table.size() - 1)
return NULL;
else
return cells_table[i + 1];
}
}
// We shouldn't reach here.
return NULL;
}
}
int hash_cell::num_pages(char set_flags, char clear_flags)
{
int num = 0;
_lock.lock();
for (unsigned int i = 0; i < buf.get_num_pages(); i++) {
thread_safe_page *p = buf.get_page(i);
if (p->test_flags(set_flags) && !p->test_flags(clear_flags))
num++;
}
_lock.unlock();
return num;
}
void hash_cell::predict_evicted_pages(int num_pages, char set_flags,
char clear_flags, std::map<off_t, thread_safe_page *> &pages)
{
_lock.lock();
policy.predict_evicted_pages(buf, num_pages, set_flags,
clear_flags, pages);
bool print = false;
for (std::map<off_t, thread_safe_page *>::iterator it = pages.begin();
it != pages.end(); it++) {
it->second->inc_ref();
if (it->second->get_flush_score() >= MAX_NUM_WRITEBACK)
print = true;
}
_lock.unlock();
if (print) {
for (std::map<off_t, thread_safe_page *>::iterator it = pages.begin();
it != pages.end(); it++) {
printf("flush page %lx\n", it->second->get_offset());
}
print_cell();
}
}
void hash_cell::get_pages(int num_pages, char set_flags, char clear_flags,
std::map<off_t, thread_safe_page *> &pages)
{
_lock.lock();
for (int i = 0; i < (int) buf.get_num_pages(); i++) {
thread_safe_page *p = buf.get_page(i);
if (p->test_flags(set_flags) && !p->test_flags(clear_flags)) {
p->inc_ref();
pages.insert(std::pair<off_t, thread_safe_page *>(
p->get_offset(), p));
}
}
_lock.unlock();
}
void associative_flusher::flush_dirty_pages(thread_safe_page *pages[],
int num, io_interface &io)
{
if (!params.is_use_flusher()) {
return;
}
hash_cell *cells[num];
int num_queued_cells = 0;
int num_flushes = 0;
for (int i = 0; i < num; i++) {
page_id_t pg_id(pages[i]->get_file_id(), pages[i]->get_offset());
hash_cell *cell = local_cache->get_cell_offset(pg_id);
char dirty_flag = 0;
char skip_flags = 0;
page_set_flag(dirty_flag, DIRTY_BIT, true);
// We should skip pages in IO pending or in a writeback queue.
page_set_flag(skip_flags, IO_PENDING_BIT, true);
page_set_flag(skip_flags, PREPARE_WRITEBACK, true);
/*
* We only count the number of dirty pages without IO pending.
* If a page is dirty but has IO pending, it means the page
* is being written back, so we don't need to do anything with it.
*/
int n = cell->num_pages(dirty_flag, skip_flags);
if (n > DIRTY_PAGES_THRESHOLD) {
if (local_cache->num_pending_flush.get()
> local_cache->max_num_pending_flush) {
if (!cell->set_in_queue(true))
cells[num_queued_cells++] = cell;
}
else {
io_request req_array[NUM_WRITEBACK_DIRTY_PAGES];
int ret = flush_cell(cell, req_array,
NUM_WRITEBACK_DIRTY_PAGES);
io.access(req_array, ret);
num_flushes += ret;
// If it has the required number of dirty pages to flush,
// it may have more to be flushed.
if (ret == NUM_WRITEBACK_DIRTY_PAGES && n - ret > 6)
if (!cell->set_in_queue(true))
cells[num_queued_cells++] = cell;
}
}
}
if (num_flushes > 0)
local_cache->num_pending_flush.inc(num_flushes);
if (num_queued_cells > 0) {
// TODO currently, there is only one flush thread. Adding dirty cells
// requires to grab a spin lock. It may not work well on a NUMA machine.
int ret = dirty_cells.add(cells, num_queued_cells);
if (ret < num_queued_cells) {
printf("only queue %d in %d dirty cells\n", ret, num_queued_cells);
}
}
#ifdef DEBUG
if (enable_debug)
printf("node %d: %d flushes, %d pending, %d dirty cells, %d dirty pages\n",
get_node_id(), num_flushes, local_cache->num_pending_flush.get(),
dirty_cells.get_num_entries(), local_cache->num_dirty_pages.get());
#endif
}
int associative_flusher::flush_dirty_pages(page_filter *filter, int max_num)
{
if (!params.is_use_flusher())
return 0;
int num_flushes = 0;
while (num_flushes < max_num) {
int num_cells = (max_num - num_flushes) / NUM_WRITEBACK_DIRTY_PAGES;
if (num_cells == 0)
num_cells = 1;
hash_cell *cells[num_cells];
hash_cell *queue_cells[num_cells];
int num_queued_cells = 0;
int num_fetched_cells = dirty_cells.fetch(cells, num_cells);
if (num_fetched_cells == 0)
return num_flushes;
io_request req_array[NUM_WRITEBACK_DIRTY_PAGES];
for (int i = 0; i < num_fetched_cells; i++) {
int ret = flush_cell(cells[i], req_array, NUM_WRITEBACK_DIRTY_PAGES);
io->access(req_array, ret);
num_flushes += ret;
if (ret == NUM_WRITEBACK_DIRTY_PAGES)
queue_cells[num_queued_cells++] = cells[i];
else
cells[i]->set_in_queue(false);
}
dirty_cells.add(queue_cells, num_queued_cells);
}
io->flush_requests();
int pending = local_cache->num_pending_flush.inc(num_flushes);
local_cache->recorded_max_num_pending.add(pending);
local_cache->avg_num_pending.add(pending);
return num_flushes;
}
int associative_cache::get_num_dirty_pages() const
{
int num = 0;
for (int i = 0; i < get_num_cells(); i++) {
hash_cell *cell = get_cell(i);
char set_flag = 0;
page_set_flag(set_flag, DIRTY_BIT, true);
int n = cell->num_pages(set_flag, 0);
num += n;
}
#ifdef DEBUG
if (num != num_dirty_pages.get())
printf("the counted dirty pages: %d, there are actually %d dirty pages\n",
num_dirty_pages.get(), num);
#endif
return num;
}
int associative_cache::flush_dirty_pages(page_filter *filter, int max_num)
{
if (_flusher)
return _flusher->flush_dirty_pages(filter, max_num);
else
return 0;
}
}
| {
"content_hash": "8d6b55e51b29353fad8e792b3d5804b3",
"timestamp": "",
"source": "github",
"line_count": 1604,
"max_line_length": 96,
"avg_line_length": 27.66770573566085,
"alnum_prop": 0.6344892854728588,
"repo_name": "icoming/FlashX",
"id": "b83df6cdd8fe46dd8ad7b982c025d249fb754d14",
"size": "45093",
"binary": false,
"copies": "2",
"ref": "refs/heads/release",
"path": "libsafs/associative_cache.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3624"
},
{
"name": "C++",
"bytes": "3071995"
},
{
"name": "CMake",
"bytes": "11969"
},
{
"name": "Makefile",
"bytes": "38090"
},
{
"name": "Perl",
"bytes": "15060"
},
{
"name": "R",
"bytes": "195963"
},
{
"name": "Shell",
"bytes": "11908"
}
],
"symlink_target": ""
} |
import {EventEmitter} from '../../../src/facade/async';
import {NgZone} from '@angular/core/src/zone/ng_zone';
export {EventEmitter, Observable} from '../../../src/facade/async';
/**
* Message Bus is a low level API used to communicate between the UI and the background.
* Communication is based on a channel abstraction. Messages published in a
* given channel to one MessageBusSink are received on the same channel
* by the corresponding MessageBusSource.
*/
export abstract class MessageBus implements MessageBusSource, MessageBusSink {
/**
* Sets up a new channel on the MessageBus.
* MUST be called before calling from or to on the channel.
* If runInZone is true then the source will emit events inside the angular zone
* and the sink will buffer messages and send only once the zone exits.
* if runInZone is false then the source will emit events inside the global zone
* and the sink will send messages immediately.
*/
abstract initChannel(channel: string, runInZone?: boolean): void;
/**
* Assigns this bus to the given zone.
* Any callbacks attached to channels where runInZone was set to true on initialization
* will be executed in the given zone.
*/
abstract attachToZone(zone: NgZone): void;
/**
* Returns an {@link EventEmitter} that emits every time a message
* is received on the given channel.
*/
abstract from(channel: string): EventEmitter<any>;
/**
* Returns an {@link EventEmitter} for the given channel
* To publish methods to that channel just call next (or add in dart) on the returned emitter
*/
abstract to(channel: string): EventEmitter<any>;
}
export interface MessageBusSource {
/**
* Sets up a new channel on the MessageBusSource.
* MUST be called before calling from on the channel.
* If runInZone is true then the source will emit events inside the angular zone.
* if runInZone is false then the source will emit events inside the global zone.
*/
initChannel(channel: string, runInZone: boolean): void;
/**
* Assigns this source to the given zone.
* Any channels which are initialized with runInZone set to true will emit events that will be
* executed within the given zone.
*/
attachToZone(zone: NgZone): void;
/**
* Returns an {@link EventEmitter} that emits every time a message
* is received on the given channel.
*/
from(channel: string): EventEmitter<any>;
}
export interface MessageBusSink {
/**
* Sets up a new channel on the MessageBusSink.
* MUST be called before calling to on the channel.
* If runInZone is true the sink will buffer messages and send only once the zone exits.
* if runInZone is false the sink will send messages immediatly.
*/
initChannel(channel: string, runInZone: boolean): void;
/**
* Assigns this sink to the given zone.
* Any channels which are initialized with runInZone set to true will wait for the given zone
* to exit before sending messages.
*/
attachToZone(zone: NgZone): void;
/**
* Returns an {@link EventEmitter} for the given channel
* To publish methods to that channel just call next (or add in dart) on the returned emitter
*/
to(channel: string): EventEmitter<any>;
}
| {
"content_hash": "739f4a647a13a072dd971d8f5bf8c24a",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 96,
"avg_line_length": 37.13793103448276,
"alnum_prop": 0.7168059424326834,
"repo_name": "tyleranton/angular",
"id": "410b55d0acf74643e53372cb998b7db8451d774f",
"size": "3231",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "modules/@angular/platform-browser/src/web_workers/shared/message_bus.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "62741"
},
{
"name": "Dart",
"bytes": "585504"
},
{
"name": "HTML",
"bytes": "57434"
},
{
"name": "JavaScript",
"bytes": "73355"
},
{
"name": "Protocol Buffer",
"bytes": "3373"
},
{
"name": "Python",
"bytes": "3535"
},
{
"name": "Shell",
"bytes": "20666"
},
{
"name": "TypeScript",
"bytes": "3007138"
}
],
"symlink_target": ""
} |
package org.apache.accumulo.core.client.mapreduce;
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.security.tokens.AuthenticationToken;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.util.format.DefaultFormatter;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
/**
* This class allows MapReduce jobs to use multiple Accumulo tables as the source of data. This
* {@link org.apache.hadoop.mapreduce.InputFormat} provides keys and values of type {@link Key} and
* {@link Value} to the Map function.
*
* The user must specify the following via static configurator methods:
*
* <ul>
* <li>{@link AccumuloMultiTableInputFormat#setConnectorInfo(Job, String, AuthenticationToken)}
* <li>{@link AccumuloMultiTableInputFormat#setConnectorInfo(Job, String, String)}
* <li>{@link AccumuloMultiTableInputFormat#setScanAuthorizations(Job, Authorizations)}
* <li>{@link AccumuloMultiTableInputFormat#setInputTableConfigs(Job, Map)}
* </ul>
*
* Other static methods are optional.
*
* @deprecated since 2.0.0; Use org.apache.accumulo.hadoop.mapreduce instead from the
* accumulo-hadoop-mapreduce.jar
*/
@Deprecated
public class AccumuloMultiTableInputFormat extends AbstractInputFormat<Key,Value> {
/**
* Sets the {@link InputTableConfig} objects on the given Hadoop configuration
*
* @param job
* the Hadoop job instance to be configured
* @param configs
* the table query configs to be set on the configuration.
* @since 1.6.0
*/
public static void setInputTableConfigs(Job job, Map<String,InputTableConfig> configs) {
requireNonNull(configs);
org.apache.accumulo.core.clientImpl.mapreduce.lib.InputConfigurator.setInputTableConfigs(CLASS,
job.getConfiguration(), configs);
}
@Override
public RecordReader<Key,Value> createRecordReader(InputSplit inputSplit,
TaskAttemptContext context) throws IOException, InterruptedException {
log.setLevel(getLogLevel(context));
return new AbstractRecordReader<Key,Value>() {
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (scannerIterator.hasNext()) {
++numKeysRead;
Map.Entry<Key,Value> entry = scannerIterator.next();
currentK = currentKey = entry.getKey();
currentV = entry.getValue();
if (log.isTraceEnabled())
log.trace("Processing key/value pair: " + DefaultFormatter.formatEntry(entry, true));
return true;
}
return false;
}
@Override
protected List<IteratorSetting> contextIterators(TaskAttemptContext context,
String tableName) {
return getInputTableConfig(context, tableName).getIterators();
}
};
}
}
| {
"content_hash": "b7ea8ffa4ea83e183644f1f883cff7a4",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 99,
"avg_line_length": 37.95238095238095,
"alnum_prop": 0.7330614805520702,
"repo_name": "keith-turner/accumulo",
"id": "a6986bbbb5e3d967529125e02ab8a84671f0a397",
"size": "3995",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/apache/accumulo/core/client/mapreduce/AccumuloMultiTableInputFormat.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2465"
},
{
"name": "C++",
"bytes": "37312"
},
{
"name": "CSS",
"bytes": "6443"
},
{
"name": "FreeMarker",
"bytes": "57422"
},
{
"name": "HTML",
"bytes": "5454"
},
{
"name": "Java",
"bytes": "18457738"
},
{
"name": "JavaScript",
"bytes": "71755"
},
{
"name": "Makefile",
"bytes": "2872"
},
{
"name": "Python",
"bytes": "7344"
},
{
"name": "Shell",
"bytes": "61899"
},
{
"name": "Thrift",
"bytes": "40724"
}
],
"symlink_target": ""
} |
namespace WcfServiceHost
{
using ReturnSubstringFromString;
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
public class Program
{
public static void Main()
{
var url = "http://127.0.0.1:9876";
var behavior = new ServiceMetadataBehavior();
ServiceHost host = new ServiceHost(typeof(StringCounter), new Uri(url));
host.Description.Behaviors.Add(behavior);
host.Open();
Console.WriteLine("Service working on {0}", url);
Console.ReadKey();
host.Close();
}
}
}
| {
"content_hash": "ef5927854c965efc46a0ed3c5bbc2e22",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 84,
"avg_line_length": 23.035714285714285,
"alnum_prop": 0.5813953488372093,
"repo_name": "juvemar/WebApi-Cloud-Wcf",
"id": "8a8101a750a31479d1f3f73ba45aaada073a6b60",
"size": "647",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "05. Wcf/WcfServiceHost/Program.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "334"
},
{
"name": "C#",
"bytes": "146355"
},
{
"name": "HTML",
"bytes": "5069"
},
{
"name": "Pascal",
"bytes": "14667"
},
{
"name": "PowerShell",
"bytes": "112313"
}
],
"symlink_target": ""
} |
use warnings;
use strict;
package qbasic;
use parent '_c_base';
1;
| {
"content_hash": "6deda3a48498f85eef6eaaf1b9f4eee8",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 21,
"avg_line_length": 9.857142857142858,
"alnum_prop": 0.6956521739130435,
"repo_name": "pragma-/pbot",
"id": "f33373ba86218d1c62048eb9bf8af0c1d5dd0676",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "applets/pbot-vm/guest/lib/Languages/qbasic.pm",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "64006"
},
{
"name": "CSS",
"bytes": "1203"
},
{
"name": "Perl",
"bytes": "1781484"
},
{
"name": "Python",
"bytes": "135729"
},
{
"name": "Raku",
"bytes": "11126"
},
{
"name": "Shell",
"bytes": "2006"
}
],
"symlink_target": ""
} |
package com.intellij.javaee;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.xml.Html5SchemaProvider;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
/**
* @author Eugene.Kudelevsky
*/
@Singleton
public class DefaultHtmlDoctypeInitialConfigurator
{
@Inject
public DefaultHtmlDoctypeInitialConfigurator(ProjectManager projectManager)
{
PropertiesComponent propertiesComponent = PropertiesComponent.getInstance();
if(!propertiesComponent.getBoolean("DefaultHtmlDoctype.MigrateToHtml5", false))
{
propertiesComponent.setValue("DefaultHtmlDoctype.MigrateToHtml5", Boolean.TRUE.toString());
ExternalResourceManagerEx.getInstanceEx().setDefaultHtmlDoctype(Html5SchemaProvider.getHtml5SchemaLocation(), projectManager.getDefaultProject());
}
}
}
| {
"content_hash": "50daa56890fba7b12bb9cbc34ef31be6",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 149,
"avg_line_length": 32.73076923076923,
"alnum_prop": 0.8284371327849589,
"repo_name": "consulo/consulo-xml",
"id": "b6afb7660f035d3b1ec7cd5df960f985da816fd1",
"size": "851",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xml-impl/src/main/java/com/intellij/javaee/DefaultHtmlDoctypeInitialConfigurator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "18021"
},
{
"name": "HTML",
"bytes": "13636"
},
{
"name": "Java",
"bytes": "4181256"
},
{
"name": "Lex",
"bytes": "21779"
},
{
"name": "Makefile",
"bytes": "353"
},
{
"name": "Ruby",
"bytes": "1217"
},
{
"name": "Shell",
"bytes": "973"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<doc>
<assembly>
<name>Nokia.Graphics.Imaging.Managed</name>
</assembly>
<members>
<member name="T:Nokia.Graphics.Imaging.CustomEffectBase">
<summary>
Base class for custom user-defined effects.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.#ctor(Nokia.Graphics.Imaging.IImageProvider,System.Boolean)">
<summary>
EffectBase constructor.
</summary>
<param name="source">
<see cref="T:Nokia.Graphics.Imaging.IImageProvider" /> to use as source.</param>
<param name="isInplace">If true, the sourcePixels and targetPixels parameters to OnProcess will refer to the same array. This can be more efficient, but may restrict the effect (writing a pixel means the original source pixel is discarded). If false, different buffers are used. The default value is false.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.Dispose">
<summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.Dispose(System.Boolean)">
<summary>
Dispose the object.
</summary>
<param name="disposing">True if this is a call to Dispose(), or false if called by the finalizer.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.FromColor(Windows.UI.Color)">
<summary>
Encode a <see cref="T:Windows.UI.Color" /> into an unsigned integer.
</summary>
<param name="color">The color to encode.</param>
<returns>An unsigned integer representing the color.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.GetBitmapAsync(Nokia.Graphics.Imaging.Bitmap,Nokia.Graphics.Imaging.OutputOption)">
<summary>Create a Bitmap with the contents of the image provider.</summary>
<param name="bitmap">An input bitmap to fill. If null, a bitmap will be created and returned.</param>
<param name="outputOption">Specifies how to adjust if the source image has different aspect ratio from the bitmap passed into this method.</param>
<returns>An async result with the bitmap.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.GetInfoAsync">
<summary>Asynchronously get information about this image provider.</summary>
<returns>An async result with an ImageProviderInfo containing the information.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.Lock(Nokia.Graphics.Imaging.RenderRequest)">
<summary>Lock the image provider for the purpose of rendering.</summary>
<param name="renderRequest">The render request to lock with.</param>
<returns>True if the RenderRequest owns the lock. False if the lock was already taken.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.OnLoadAsync">
<summary>
Called when the effect should load/prepare for rendering.
</summary>
<returns>
An async action representing the work.
</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.OnProcess(Nokia.Graphics.Imaging.PixelRegion,Nokia.Graphics.Imaging.PixelRegion)">
<summary>
Called when the effect is asked to process a rectangular area of the image.
</summary>
<param name="sourcePixelRegion">The region of source pixels to read.</param>
<param name="targetPixelRegion">The region of target pixels to write.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.PreloadAsync">
<summary>Perform any loading (expensive operations typically involving I/O) needed to render or get info from this image provider.</summary>
<returns>An async action, which completes when the loading is done.</returns>
</member>
<member name="P:Nokia.Graphics.Imaging.CustomEffectBase.Source">
<summary>
The <see cref="T:Nokia.Graphics.Imaging.IImageProvider" /> that will be used as source.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomEffectBase.ToColor(System.UInt32)">
<summary>
Return a <see cref="T:Windows.UI.Color" /> from an unsigned integer.
</summary>
<param name="uintColor">The unsigned integer to convert.</param>
<returns>Returns a color instance.</returns>
</member>
<member name="T:Nokia.Graphics.Imaging.CustomFilterBase">
<summary>
Base class for user-defined custom filters with support for block based processing.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomFilterBase.#ctor(Nokia.Graphics.Imaging.Margins,System.Boolean,System.Collections.Generic.IEnumerable{Nokia.Graphics.Imaging.ColorMode})">
<summary>
CustomFilterBase constructor.
</summary>
<param name="blockMargins">Size of the margins around the pixel block that will be needed when processing the. Setting non-zero margins means that the sourcePixelRegion provided in the call to
<see cref="M:Nokia.Graphics.Imaging.CustomFilterBase.OnProcess(Nokia.Graphics.Imaging.PixelRegion,Nokia.Graphics.Imaging.PixelRegion)" /> will be larger than the targetPixelRegion.</param>
<param name="wrapBorders">If set true and block margins are non-zero, when processing a block at the edge of an image, the pixel data in the margin will still be taken from inside the image. If false, the pixels in the margin will be transparent black.</param>
<param name="supportedColorModes">The color modes that the implementation supports. Valid values are <see cref="F:Nokia.Graphics.Imaging.ColorMode.Bgra8888" /> and <see cref="F:Nokia.Graphics.Imaging.ColorMode.Ayuv4444" />.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomFilterBase.Dispose">
<summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomFilterBase.Dispose(System.Boolean)">
<summary>
Dispose the object.
</summary>
<param name="disposing">True if this is a call to Dispose(), or false if called by the finalizer.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomFilterBase.OnPrepareAsync">
<summary>
Called when the filter should load/prepare for rendering.
</summary>
<returns>
An async action representing the work.
</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomFilterBase.OnProcess(Nokia.Graphics.Imaging.PixelRegion,Nokia.Graphics.Imaging.PixelRegion)">
<summary>
Called when the filter is asked to process a rectangular area of the image.
</summary>
<param name="sourcePixelRegion">The region of source pixels to read.</param>
<param name="targetPixelRegion">The region of target pixels to write.</param>
</member>
<member name="T:Nokia.Graphics.Imaging.CustomImageSourceBase">
<summary>
Managed base class for custom image sources.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.#ctor(Windows.Foundation.Size)">
<summary>
CustomImageSourceBase constructor.
</summary>
<param name="size">Inherent size of the image.</param>
</member>
<member name="P:Nokia.Graphics.Imaging.CustomImageSourceBase.CanSetSize">
<summary>Indicates whether the <see cref="P:Nokia.Graphics.Imaging.IImageSize.Size" /> property can be set.</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.Dispose">
<summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.Dispose(System.Boolean)">
<summary>
Dispose the object.
</summary>
<param name="disposing">True if this is a call to Dispose(), or false if called by the finalizer.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.FromColor(Windows.UI.Color)">
<summary>
Encode a <see cref="T:Windows.UI.Color" /> into an uint.
</summary>
<param name="color">The color to encode.</param>
<returns>An uint.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.GetBitmapAsync(Nokia.Graphics.Imaging.Bitmap,Nokia.Graphics.Imaging.OutputOption)">
<summary>Create a Bitmap with the contents of the image provider.</summary>
<param name="bitmap">An input bitmap to fill. If null, a bitmap will be created and returned.</param>
<param name="outputOption">Specifies how to adjust if the source image has different aspect ratio from the bitmap passed into this method.</param>
<returns>An async result with the bitmap.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.GetInfoAsync">
<summary>Asynchronously get information about this image provider.</summary>
<returns>An async result with an ImageProviderInfo containing the information.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.Invalidate">
<summary>
Requests a reloading of the image source during the next load or render operation.
Note: Calling invalidate during a load or render operation will have no effect.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.Lock(Nokia.Graphics.Imaging.RenderRequest)">
<summary>Lock the image provider for the purpose of rendering.</summary>
<param name="renderRequest">The render request to lock with.</param>
<returns>True if the RenderRequest owns the lock. False if the lock was already taken.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.OnLoadAsync">
<summary>
Called when the image source should load/prepare for rendering.
</summary>
<returns>
An async action representing the work.
</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.OnProcess(Nokia.Graphics.Imaging.PixelRegion)">
<summary>
Called when the image source is asked to generate a rectangular area of the image.
</summary>
<param name="pixelRegion">The region of pixels to process.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.CustomImageSourceBase.PreloadAsync">
<summary>Perform any loading (expensive operations typically involving I/O) needed to render or get info from this image provider.</summary>
<returns>An async action, which completes when the loading is done.</returns>
</member>
<member name="P:Nokia.Graphics.Imaging.CustomImageSourceBase.Size">
<summary>The inherent size of the image.</summary>
</member>
<member name="T:Nokia.Graphics.Imaging.ImageProviderExtensions">
<summary>
Extension methods for IImageProvider.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.ImageProviderExtensions.GetBitmapAsync(Nokia.Graphics.Imaging.IImageProvider,System.Windows.Media.Imaging.WriteableBitmap,Nokia.Graphics.Imaging.OutputOption)">
<summary>
Create a WriteableBitmap with the contents of the image provider.
</summary>
<param name="imageProvider">The extended <see cref="T:Nokia.Graphics.Imaging.IImageProvider" />.</param>
<param name="writeableBitmap">An input <see cref="T:System.Windows.Media.Imaging.WriteableBitmap" /> to fill. </param>
<param name="outputOption">Specifies how to adjust if the source image has different aspect ratio from the bitmap passed into this method.</param>
<returns>
An async result with the bitmap.
</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.ImageProviderExtensions.Then``1(Nokia.Graphics.Imaging.IImageProvider,``0)">
<summary>
Enables a fluid way of chaining multiple IImageProviders and IImageConsumers.
</summary>
<param name="provider">The image provider.</param>
<param name="consumer">The image consumer.</param>
<typeparam name="TImageConsumer">The extended image consumer.</typeparam>
<returns>The consumer that was passed in.</returns>
</member>
<member name="T:Nokia.Graphics.Imaging.PixelRegion">
<summary>
Represents a region of pixels within a pixel array, and contains metrics and helper methods for traversing them.
</summary>
</member>
<member name="P:Nokia.Graphics.Imaging.PixelRegion.Bounds">
<summary>
The bounds of the region within the image to be processed.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.PixelRegion.ForEachRow(Nokia.Graphics.Imaging.PixelRegion,Nokia.Graphics.Imaging.PixelRegion.ProcessRowWithSourceAction)">
<summary>
Run the user-supplied action per row within the <see cref="P:Nokia.Graphics.Imaging.PixelRegion.Bounds" />, also tracking a source PixelRegion having margins that will be read from.
</summary>
<param name="sourcePixelRegion">A source PixelRegion that will be read from. It is assumed to have non-zero margins.</param>
<param name="rowAction">A user-provided action which when called is expected to process one row of pixels.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.PixelRegion.ForEachRow(Nokia.Graphics.Imaging.PixelRegion.ProcessRowAction)">
<summary>
Run the user-supplied action per row within the <see cref="P:Nokia.Graphics.Imaging.PixelRegion.Bounds" />.
</summary>
<param name="rowAction">A user-provided action which when called is expected to process one row of pixels.</param>
</member>
<member name="P:Nokia.Graphics.Imaging.PixelRegion.ImagePixels">
<summary>
The array of image pixels of size Pitch * ImageSize.Height.
</summary>
</member>
<member name="P:Nokia.Graphics.Imaging.PixelRegion.ImageSize">
<summary>
The size of the image in <see cref="P:Nokia.Graphics.Imaging.PixelRegion.ImagePixels" />.
</summary>
</member>
<member name="P:Nokia.Graphics.Imaging.PixelRegion.Pitch">
<summary>
The index distance between rows in <see cref="P:Nokia.Graphics.Imaging.PixelRegion.ImagePixels" />.
</summary>
</member>
<member name="P:Nokia.Graphics.Imaging.PixelRegion.StartIndex">
<summary>
The index within <see cref="P:Nokia.Graphics.Imaging.PixelRegion.ImagePixels" /> of the first pixel to process, based on <see cref="P:Nokia.Graphics.Imaging.PixelRegion.Bounds" />.
</summary>
</member>
<member name="T:Nokia.Graphics.Imaging.PixelRegion.ProcessRowAction">
<summary>
A user-supplied action which can be used with <see cref="M:Nokia.Graphics.Imaging.PixelRegion.ForEachRow(Nokia.Graphics.Imaging.PixelRegion.ProcessRowAction)" />.
</summary>
<param name="startIndex">The index within <see cref="P:Nokia.Graphics.Imaging.PixelRegion.ImagePixels" /> of the first pixel to process on this row.</param>
<param name="width">The number of pixels to process on this row.</param>
<param name="startPosition">For reference, this is the position of the first pixel in this row, within the entire image.</param>
</member>
<member name="T:Nokia.Graphics.Imaging.PixelRegion.ProcessRowWithSourceAction">
<summary>
A user-supplied action which can be used with <see cref="M:Nokia.Graphics.Imaging.PixelRegion.ForEachRow(Nokia.Graphics.Imaging.PixelRegion,Nokia.Graphics.Imaging.PixelRegion.ProcessRowWithSourceAction)" />, where a source PixelRegion with non-zero margins is taken into account.
</summary>
<param name="sourceStartIndex">The index within the source <see cref="P:Nokia.Graphics.Imaging.PixelRegion.ImagePixels" /> of the first pixel to process on this row.</param>
<param name="targetStartIndex">The index within <see cref="P:Nokia.Graphics.Imaging.PixelRegion.ImagePixels" /> of the first pixel to process on this row.</param>
<param name="width">The number of target pixels to write on this row.</param>
<param name="startPosition">For reference, this is the position of the first pixel in this row, within the entire image. Margins are not included.</param>
</member>
<member name="T:Nokia.Graphics.Imaging.StreamImageSource">
<summary>
An image source implementing <see cref="T:Nokia.Graphics.Imaging.IImageProvider" />, reading its data from a <see cref="P:Nokia.Graphics.Imaging.StreamImageSource.Stream" />.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.StreamImageSource.#ctor(System.IO.Stream,Nokia.Graphics.Imaging.ImageFormat)">
<summary>
StreamImageSource constructor.
</summary>
<param name="stream">The stream to read and use as an image source.</param>
<param name="imageFormat">The format of the image. If not specified, autodetects.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.StreamImageSource.Dispose">
<summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.StreamImageSource.GetBitmapAsync(Nokia.Graphics.Imaging.Bitmap,Nokia.Graphics.Imaging.OutputOption)">
<summary>Create a Bitmap with the contents of the image provider.</summary>
<param name="bitmap">An input bitmap to fill. If null, a bitmap will be created and returned.</param>
<param name="outputOption">Specifies how to adjust if the source image has different aspect ratio from the bitmap passed into this method.</param>
<returns>An async result with the bitmap.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.StreamImageSource.GetInfoAsync">
<summary>Asynchronously get information about this image provider.</summary>
<returns>An async result with an ImageProviderInfo containing the information.</returns>
</member>
<member name="P:Nokia.Graphics.Imaging.StreamImageSource.ImageFormat">
<summary>
The format of the compressed image data.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.StreamImageSource.Lock(Nokia.Graphics.Imaging.RenderRequest)">
<summary>Lock the image provider for the purpose of rendering.</summary>
<param name="renderRequest">The render request to lock with.</param>
<returns>True if the RenderRequest owns the lock. False if the lock was already taken.</returns>
</member>
<member name="M:Nokia.Graphics.Imaging.StreamImageSource.PreloadAsync">
<summary>Perform any loading (expensive operations typically involving I/O) needed to render or get info from this image provider.</summary>
<returns>An async action, which completes when the loading is done.</returns>
</member>
<member name="P:Nokia.Graphics.Imaging.StreamImageSource.Stream">
<summary>
The stream containing compressed image data.
</summary>
</member>
<member name="T:Nokia.Graphics.Imaging.WriteableBitmapRenderer">
<summary>
Renders an image source to a writeable bitmap.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.WriteableBitmapRenderer.#ctor">
<summary>
Creates a new writeable bitmap renderer.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.WriteableBitmapRenderer.#ctor(Nokia.Graphics.Imaging.IImageProvider)">
<summary>
Creates a new writeable bitmap renderer.
</summary>
<param name="source">The image source that will be rendered.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.WriteableBitmapRenderer.#ctor(Nokia.Graphics.Imaging.IImageProvider,System.Windows.Media.Imaging.WriteableBitmap,Nokia.Graphics.Imaging.OutputOption)">
<summary>
Creates a new writeable bitmap renderer.
</summary>
<param name="source">The image source that will be rendered.</param>
<param name="writeableBitmap">The <see cref="P:Nokia.Graphics.Imaging.WriteableBitmapRenderer.WriteableBitmap" /> that will be rendered to.</param>
<param name="outputOption">Controls how the image is rendered.</param>
</member>
<member name="M:Nokia.Graphics.Imaging.WriteableBitmapRenderer.Dispose">
<summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
</member>
<member name="P:Nokia.Graphics.Imaging.WriteableBitmapRenderer.OutputOption">
<summary>
Output option for desired behavior when source and target aspect ratio differ.
</summary>
</member>
<member name="M:Nokia.Graphics.Imaging.WriteableBitmapRenderer.RenderAsync">
<summary>
Asynchronous render of image.
</summary>
<returns>An IAsyncAction representing the render operation.</returns>
</member>
<member name="P:Nokia.Graphics.Imaging.WriteableBitmapRenderer.Source">
<summary>
The IImageProvider that will be rendered.
</summary>
</member>
<member name="P:Nokia.Graphics.Imaging.WriteableBitmapRenderer.WriteableBitmap">
<summary>
The <see cref="P:Nokia.Graphics.Imaging.WriteableBitmapRenderer.WriteableBitmap" /> that will be rendered to.
</summary>
</member>
<member name="T:Nokia.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions">
<summary>
Provides extension methods for operating on Windows Runtime buffers (Windows.Storage.Streams.IBuffer).
</summary>
</member>
<member name="M:Nokia.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.AsBuffer(System.Int32[])">
<summary>
Wrap an array of <see cref="T:System.Int32" /> in an <see cref="T:Windows.Storage.Streams.IBuffer" />.
</summary>
<param name="data">The array to wrap.</param>
<returns>An <see cref="T:Windows.Storage.Streams.IBuffer" /> representing the data.</returns>
</member>
<member name="M:Nokia.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.AsBuffer(System.UInt32[])">
<summary>
Wrap an array of <see cref="T:System.UInt32" /> in an <see cref="T:Windows.Storage.Streams.IBuffer" />.
</summary>
<param name="data">The array to wrap.</param>
<returns>An <see cref="T:Windows.Storage.Streams.IBuffer" /> representing the data.</returns>
</member>
<member name="T:Nokia.InteropServices.WindowsRuntime.WriteableBitmapExtensions">
<summary>
Extension methods for <see cref="T:System.Windows.Media.Imaging.WriteableBitmap" /></summary>
</member>
<member name="M:Nokia.InteropServices.WindowsRuntime.WriteableBitmapExtensions.AsBitmap(System.Windows.Media.Imaging.WriteableBitmap,Windows.Foundation.Rect)">
<summary>
Creates an <see cref="T:Nokia.Graphics.Imaging.IReadableBitmap" /> wrapping the pixel data of a <see cref="T:System.Windows.Media.Imaging.WriteableBitmap" />, without copying it.
</summary>
<param name="writeableBitmap">The <see cref="T:System.Windows.Media.Imaging.WriteableBitmap" />.</param>
<param name="cropArea">The area of the <see cref="T:System.Windows.Media.Imaging.WriteableBitmap" /> to wrap as a <see cref="T:Nokia.Graphics.Imaging.Bitmap" />. By default the entire <see cref="T:System.Windows.Media.Imaging.WriteableBitmap" /> is used.</param>
<returns>A <see cref="T:Nokia.Graphics.Imaging.Bitmap" /> wrapping the pixel data of <paramref name="writeableBitmap" />.</returns>
</member>
</members>
</doc> | {
"content_hash": "905862c59fec8a745d55b14bba1fe377",
"timestamp": "",
"source": "github",
"line_count": 401,
"max_line_length": 320,
"avg_line_length": 61.089775561097255,
"alnum_prop": 0.7014736498346736,
"repo_name": "dut09/RGBDVideoStreams",
"id": "40340a5d318d25bfc705505df8ecf756d625e373",
"size": "24499",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "RGBDVideoStreams/packages/NokiaImagingSDK.1.2.115/lib/wp8/Nokia.Graphics.Imaging.Managed.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "937544"
},
{
"name": "C#",
"bytes": "134172"
},
{
"name": "C++",
"bytes": "3338356"
},
{
"name": "Objective-C",
"bytes": "5343"
}
],
"symlink_target": ""
} |
/**
* This module contains some common helpers shared between middlewares
*/
'use strict'
const mime = require('mime')
const parseRange = require('range-parser')
const log = require('../logger').create('web-server')
function createServeFile (fs, directory, config) {
const cache = Object.create(null)
return function (filepath, rangeHeader, response, transform, content, doNotCache) {
let responseData
function convertForRangeRequest () {
const range = parseRange(responseData.length, rangeHeader)
if (range === -2) {
return 200 // malformed header string
} else if (range === -1) {
responseData = Buffer.alloc(0) // unsatisfiable range
return 416
} else if (range.type === 'bytes') {
responseData = Buffer.from(responseData)
if (range.length === 1) {
const { start, end } = range[0]
response.setHeader('Content-Range', `bytes ${start}-${end}/${responseData.length}`)
response.setHeader('Accept-Ranges', 'bytes')
response.setHeader('Content-Length', end - start + 1)
responseData = responseData.slice(start, end + 1)
return 206
} else {
responseData = Buffer.alloc(0) // Multiple ranges are not supported. Maybe future?
return 416
}
}
return 200 // All other states, ignore
}
if (directory) {
filepath = directory + filepath
}
if (!content && cache[filepath]) {
content = cache[filepath]
}
if (config && config.customHeaders && config.customHeaders.length > 0) {
config.customHeaders.forEach((header) => {
const regex = new RegExp(header.match)
if (regex.test(filepath)) {
log.debug(`setting header: ${header.name} for: ${filepath}`)
response.setHeader(header.name, header.value)
}
})
}
if (content && !doNotCache) {
log.debug(`serving (cached): ${filepath}`)
response.setHeader('Content-Type', mime.getType(filepath, 'text/plain'))
responseData = (transform && transform(content)) || content
response.writeHead(rangeHeader ? convertForRangeRequest() : 200)
return response.end(responseData)
}
return fs.readFile(filepath, function (error, data) {
if (error) {
return serve404(response, filepath)
}
if (!doNotCache) {
cache[filepath] = data.toString()
}
log.debug('serving: ' + filepath)
response.setHeader('Content-Type', mime.getType(filepath, 'text/plain'))
responseData = (transform && transform(data.toString())) || data
response.writeHead(rangeHeader ? convertForRangeRequest() : 200)
return response.end(responseData)
})
}
}
function serve404 (response, path) {
log.warn(`404: ${path}`)
response.writeHead(404)
return response.end('NOT FOUND')
}
function setNoCacheHeaders (response) {
response.setHeader('Cache-Control', 'no-cache')
response.setHeader('Pragma', 'no-cache')
response.setHeader('Expires', (new Date(0)).toUTCString())
}
function setHeavyCacheHeaders (response) {
response.setHeader('Cache-Control', 'public, max-age=31536000')
}
// PUBLIC API
exports.createServeFile = createServeFile
exports.setNoCacheHeaders = setNoCacheHeaders
exports.setHeavyCacheHeaders = setHeavyCacheHeaders
exports.serve404 = serve404
| {
"content_hash": "f4e79055e125ac5a2820dc1ce858c6a7",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 93,
"avg_line_length": 32.03809523809524,
"alnum_prop": 0.6459571938168847,
"repo_name": "maksimr/karma",
"id": "3c84fbc9d1d193475079b928f4cff43cc43a0d87",
"size": "3364",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "lib/middleware/common.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "2358"
},
{
"name": "Cucumber",
"bytes": "22662"
},
{
"name": "HTML",
"bytes": "6256"
},
{
"name": "JavaScript",
"bytes": "427328"
},
{
"name": "LiveScript",
"bytes": "1650"
},
{
"name": "Shell",
"bytes": "2562"
}
],
"symlink_target": ""
} |
package org.apereo.cas.logout;
import java.net.URL;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apereo.cas.authentication.principal.WebApplicationService;
/**
* Define a logout request for a service accessed by a user.
*
* @author Jerome Leleu
* @since 4.0.0
*/
public class DefaultLogoutRequest implements LogoutRequest {
/** Generated serialVersionUID. */
private static final long serialVersionUID = -6411421298859045022L;
/** The service ticket id. */
private final String ticketId;
/** The service. */
private final WebApplicationService service;
/** The status of the logout request. */
private LogoutRequestStatus status = LogoutRequestStatus.NOT_ATTEMPTED;
private final URL logoutUrl;
/**
* Build a logout request from ticket identifier and service.
* Default status is {@link LogoutRequestStatus#NOT_ATTEMPTED}.
*
* @param ticketId the service ticket id.
* @param service the service.
* @param logoutUrl the logout url
*/
public DefaultLogoutRequest(final String ticketId, final WebApplicationService service, final URL logoutUrl) {
this.ticketId = ticketId;
this.service = service;
this.logoutUrl = logoutUrl;
}
@Override
public LogoutRequestStatus getStatus() {
return this.status;
}
@Override
public void setStatus(final LogoutRequestStatus status) {
this.status = status;
}
@Override
public String getTicketId() {
return this.ticketId;
}
@Override
public WebApplicationService getService() {
return this.service;
}
@Override
public URL getLogoutUrl() {
return this.logoutUrl;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("ticketId", this.ticketId)
.append("service", this.service)
.append("status", this.status)
.toString();
}
}
| {
"content_hash": "8cc5fc7af6f55ccdbb54fe6c98346732",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 114,
"avg_line_length": 26.142857142857142,
"alnum_prop": 0.6592151018380527,
"repo_name": "pmarasse/cas",
"id": "0f2ec1075d552eabd1c4da2c8495ae352a7de29f",
"size": "2013",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/cas-server-core-logout/src/main/java/org/apereo/cas/logout/DefaultLogoutRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "275885"
},
{
"name": "Groovy",
"bytes": "4583"
},
{
"name": "HTML",
"bytes": "250640"
},
{
"name": "Java",
"bytes": "6569782"
},
{
"name": "JavaScript",
"bytes": "204340"
},
{
"name": "Shell",
"bytes": "14980"
}
],
"symlink_target": ""
} |
#ifndef ELEMDDLUDREXTERNALSECURITY_H
#define ELEMDDLUDREXTERNALSECURITY_H
/* -*-C++-*-
******************************************************************************
*
* File: ElemDDLUdrExternalSecurity.h
* Description: class for UDR External Security (parse node) elements in
* DDL statements
*
*
* Created: 01/20/2012
* Language: C++
*
*
******************************************************************************
*/
#include "ComSmallDefs.h"
#include "ElemDDLNode.h"
class ElemDDLUdrExternalSecurity : public ElemDDLNode
{
public:
// default constructor
ElemDDLUdrExternalSecurity(ComRoutineExternalSecurity theExternalSecurity);
// virtual destructor
virtual ~ElemDDLUdrExternalSecurity(void);
// cast
virtual ElemDDLUdrExternalSecurity * castToElemDDLUdrExternalSecurity(void);
// accessor
inline const ComRoutineExternalSecurity getExternalSecurity(void) const
{
return externalSecurity_;
}
//
// methods for tracing
//
virtual NATraceList getDetailInfo() const;
virtual const NAString getText() const;
private:
ComRoutineExternalSecurity externalSecurity_;
}; // class ElemDDLUdrExternalSecurity
#endif /* ELEMDDLUDREXTERNALSECURITY_H */
| {
"content_hash": "08514e32eac2238ed621ab2bde8d545b",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 78,
"avg_line_length": 22.285714285714285,
"alnum_prop": 0.6354166666666666,
"repo_name": "robertamarton/incubator-trafodion",
"id": "19e2a19e16dac0f09f056719348356961d539db5",
"size": "2250",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "core/sql/parser/ElemDDLUdrExternalSecurity.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "18915"
},
{
"name": "Batchfile",
"bytes": "26831"
},
{
"name": "C",
"bytes": "19172682"
},
{
"name": "C++",
"bytes": "67721539"
},
{
"name": "CSS",
"bytes": "99092"
},
{
"name": "Groff",
"bytes": "46673"
},
{
"name": "HTML",
"bytes": "4618"
},
{
"name": "Inno Setup",
"bytes": "8471"
},
{
"name": "Java",
"bytes": "11660303"
},
{
"name": "JavaScript",
"bytes": "883279"
},
{
"name": "LLVM",
"bytes": "42881"
},
{
"name": "Makefile",
"bytes": "312193"
},
{
"name": "Objective-C",
"bytes": "561563"
},
{
"name": "PHP",
"bytes": "413443"
},
{
"name": "PLpgSQL",
"bytes": "201494"
},
{
"name": "Perl",
"bytes": "549850"
},
{
"name": "Protocol Buffer",
"bytes": "117046"
},
{
"name": "Python",
"bytes": "187052"
},
{
"name": "QMake",
"bytes": "3622"
},
{
"name": "Ruby",
"bytes": "8053"
},
{
"name": "SQLPL",
"bytes": "60330"
},
{
"name": "Shell",
"bytes": "1938530"
},
{
"name": "Tcl",
"bytes": "2763"
},
{
"name": "XSLT",
"bytes": "6100"
},
{
"name": "Yacc",
"bytes": "1347672"
}
],
"symlink_target": ""
} |
package net.glowstone.generator.populators.overworld;
import net.glowstone.generator.decorators.overworld.DoublePlantDecorator.DoublePlantDecoration;
import net.glowstone.generator.decorators.overworld.MushroomDecorator;
import net.glowstone.generator.decorators.overworld.TreeDecorator.TreeDecoration;
import net.glowstone.generator.objects.trees.RedwoodTree;
import net.glowstone.generator.objects.trees.TallRedwoodTree;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
public class TaigaPopulator extends BiomePopulator {
private static final Biome[] BIOMES = {Biome.TAIGA, Biome.TAIGA_HILLS, Biome.TAIGA_MOUNTAINS,
Biome.SNOWY_TAIGA,
Biome.SNOWY_TAIGA_HILLS, Biome.SNOWY_TAIGA_MOUNTAINS};
private static final DoublePlantDecoration[] DOUBLE_PLANTS = {
new DoublePlantDecoration(Material.LARGE_FERN, 1)};
private static final TreeDecoration[] TREES = {new TreeDecoration(RedwoodTree::new, 2),
new TreeDecoration(TallRedwoodTree::new, 1)};
protected final MushroomDecorator taigaBrownMushroomDecorator = new MushroomDecorator(
Material.BROWN_MUSHROOM);
protected final MushroomDecorator taigaRedMushroomDecorator = new MushroomDecorator(
Material.RED_MUSHROOM);
/**
* Creates a populator specialized for Taiga, Taiga Hills and Taiga Mountains, and their Snowy variants.
*/
public TaigaPopulator() {
doublePlantDecorator.setAmount(7);
doublePlantDecorator.setDoublePlants(DOUBLE_PLANTS);
treeDecorator.setAmount(10);
treeDecorator.setTrees(TREES);
tallGrassDecorator.setFernDensity(0.8D);
deadBushDecorator.setAmount(1);
taigaBrownMushroomDecorator.setAmount(1);
taigaBrownMushroomDecorator.setUseFixedHeightRange();
taigaBrownMushroomDecorator.setDensity(0.25D);
taigaRedMushroomDecorator.setAmount(1);
taigaRedMushroomDecorator.setDensity(0.125D);
}
@Override
public Collection<Biome> getBiomes() {
return Collections.unmodifiableList(Arrays.asList(BIOMES));
}
@Override
public void populateOnGround(World world, Random random, Chunk chunk) {
super.populateOnGround(world, random, chunk);
taigaBrownMushroomDecorator.populate(world, random, chunk);
taigaRedMushroomDecorator.populate(world, random, chunk);
}
}
| {
"content_hash": "d429b58aac24e3dbc40a1364008472df",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 108,
"avg_line_length": 41.39344262295082,
"alnum_prop": 0.7556435643564356,
"repo_name": "GlowstonePlusPlus/GlowstonePlusPlus",
"id": "eda97156e4fb0b64418b51d8c7070357c62b6508",
"size": "2525",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/main/java/net/glowstone/generator/populators/overworld/TaigaPopulator.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2325722"
},
{
"name": "Python",
"bytes": "1031"
},
{
"name": "Ruby",
"bytes": "335"
},
{
"name": "Shell",
"bytes": "2214"
}
],
"symlink_target": ""
} |
package blade.migrate.liferay70;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import blade.migrate.api.Problem;
public class ConvertProcessPropertiesTest {
final File file = new File("projects/knowledge-base-portlet-6.2.x/docroot/WEB-INF/src/portal.properties");
ConvertProcessProperties component;
@Before
public void beforeTest() {
assertTrue(file.exists());
component = new ConvertProcessProperties();
component.addPropertiesToSearch(component._properties);
}
@Test
public void convertProcessPropertiesTest() throws Exception {
List<Problem> problems = component.analyzeFile(file);
assertNotNull(problems);
assertEquals(1, problems.size());
}
@Test
public void convertProcessPropertiesTest2() throws Exception {
List<Problem> problems = component.analyzeFile(file);
problems = component.analyzeFile(file);
assertNotNull(problems);
assertEquals(1, problems.size());
}
}
| {
"content_hash": "41cad82bb3a035cd44a8c68a179caaae",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 107,
"avg_line_length": 26.047619047619047,
"alnum_prop": 0.7787934186471663,
"repo_name": "dnebinger/blade.tools",
"id": "0f421b6b6b8630beb6db2c08a258fceb79084ea7",
"size": "1094",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "blade.migrate.liferay70/test/blade/migrate/liferay70/ConvertProcessPropertiesTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22523"
},
{
"name": "CSS",
"bytes": "9902"
},
{
"name": "HTML",
"bytes": "13101"
},
{
"name": "Java",
"bytes": "7451179"
},
{
"name": "JavaScript",
"bytes": "121459"
},
{
"name": "Perl",
"bytes": "9844"
},
{
"name": "Python",
"bytes": "3299"
},
{
"name": "Shell",
"bytes": "11036"
},
{
"name": "XSLT",
"bytes": "224454"
}
],
"symlink_target": ""
} |
namespace Google.Cloud.Dialogflow.Cx.V3.Snippets
{
// [START dialogflow_v3_generated_Versions_CreateVersion_async]
using Google.Cloud.Dialogflow.Cx.V3;
using Google.LongRunning;
using System.Threading.Tasks;
public sealed partial class GeneratedVersionsClientSnippets
{
/// <summary>Snippet for CreateVersionAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task CreateVersionRequestObjectAsync()
{
// Create client
VersionsClient versionsClient = await VersionsClient.CreateAsync();
// Initialize request argument(s)
CreateVersionRequest request = new CreateVersionRequest
{
ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"),
Version = new Version(),
};
// Make the request
Operation<Version, CreateVersionOperationMetadata> response = await versionsClient.CreateVersionAsync(request);
// Poll until the returned long-running operation is complete
Operation<Version, CreateVersionOperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Version result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Version, CreateVersionOperationMetadata> retrievedResponse = await versionsClient.PollOnceCreateVersionAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Version retrievedResult = retrievedResponse.Result;
}
}
}
// [END dialogflow_v3_generated_Versions_CreateVersion_async]
}
| {
"content_hash": "e0018b153faa8d16d18e56b8c0a0c9aa",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 146,
"avg_line_length": 48.04347826086956,
"alnum_prop": 0.6606334841628959,
"repo_name": "jskeet/google-cloud-dotnet",
"id": "60438bab49a77e7c7eb069e42089706f50e1df59",
"size": "2832",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "apis/Google.Cloud.Dialogflow.Cx.V3/Google.Cloud.Dialogflow.Cx.V3.GeneratedSnippets/VersionsClient.CreateVersionRequestObjectAsyncSnippet.g.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "767"
},
{
"name": "C#",
"bytes": "268415427"
},
{
"name": "CSS",
"bytes": "1346"
},
{
"name": "Dockerfile",
"bytes": "3173"
},
{
"name": "HTML",
"bytes": "3823"
},
{
"name": "JavaScript",
"bytes": "226"
},
{
"name": "PowerShell",
"bytes": "3303"
},
{
"name": "Python",
"bytes": "2744"
},
{
"name": "Shell",
"bytes": "65260"
},
{
"name": "sed",
"bytes": "1030"
}
],
"symlink_target": ""
} |
package org.apache.activemq.artemis.core.journal.impl;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQBuffers;
import org.apache.activemq.artemis.api.core.ActiveMQExceptionType;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.core.io.IOCallback;
import org.apache.activemq.artemis.core.io.SequentialFile;
import org.apache.activemq.artemis.core.io.SequentialFileFactory;
import org.apache.activemq.artemis.core.journal.EncodingSupport;
import org.apache.activemq.artemis.core.journal.IOCompletion;
import org.apache.activemq.artemis.core.journal.JournalLoadInformation;
import org.apache.activemq.artemis.core.journal.LoaderCallback;
import org.apache.activemq.artemis.core.persistence.Persister;
import org.apache.activemq.artemis.core.journal.PreparedTransactionInfo;
import org.apache.activemq.artemis.core.journal.RecordInfo;
import org.apache.activemq.artemis.core.journal.TestableJournal;
import org.apache.activemq.artemis.core.journal.TransactionFailureCallback;
import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalAddRecord;
import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalAddRecordTX;
import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalCompleteRecordTX;
import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalCompleteRecordTX.TX_RECORD_TYPE;
import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalDeleteRecord;
import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalDeleteRecordTX;
import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalInternalRecord;
import org.apache.activemq.artemis.core.journal.impl.dataformat.JournalRollbackRecordTX;
import org.apache.activemq.artemis.journal.ActiveMQJournalBundle;
import org.apache.activemq.artemis.journal.ActiveMQJournalLogger;
import org.apache.activemq.artemis.utils.ActiveMQThreadFactory;
import org.apache.activemq.artemis.utils.ConcurrentHashSet;
import org.apache.activemq.artemis.utils.DataConstants;
import org.apache.activemq.artemis.utils.ExecutorFactory;
import org.apache.activemq.artemis.utils.OrderedExecutorFactory;
import org.apache.activemq.artemis.utils.SimpleFuture;
import org.jboss.logging.Logger;
/**
* <p>A circular log implementation.</p>
* <p>Look at {@link JournalImpl#load(LoaderCallback)} for the file layout
*/
public class JournalImpl extends JournalBase implements TestableJournal, JournalRecordProvider {
// Constants -----------------------------------------------------
public static final int FORMAT_VERSION = 2;
private static final int[] COMPATIBLE_VERSIONS = new int[]{1};
// Static --------------------------------------------------------
private static final Logger logger = Logger.getLogger(JournalImpl.class);
// The sizes of primitive types
public static final int MIN_FILE_SIZE = 1024;
// FileID(Long) + JournalVersion + UserVersion
public static final int SIZE_HEADER = DataConstants.SIZE_LONG + DataConstants.SIZE_INT + DataConstants.SIZE_INT;
private static final int BASIC_SIZE = DataConstants.SIZE_BYTE + DataConstants.SIZE_INT + DataConstants.SIZE_INT;
public static final int SIZE_ADD_RECORD = JournalImpl.BASIC_SIZE + DataConstants.SIZE_LONG +
DataConstants.SIZE_BYTE +
DataConstants.SIZE_INT /* + record.length */;
// Record markers - they must be all unique
public static final byte ADD_RECORD = 11;
public static final byte UPDATE_RECORD = 12;
public static final int SIZE_ADD_RECORD_TX = JournalImpl.BASIC_SIZE + DataConstants.SIZE_LONG +
DataConstants.SIZE_BYTE +
DataConstants.SIZE_LONG +
DataConstants.SIZE_INT /* + record.length */;
public static final byte ADD_RECORD_TX = 13;
public static final byte UPDATE_RECORD_TX = 14;
public static final int SIZE_DELETE_RECORD_TX = JournalImpl.BASIC_SIZE + DataConstants.SIZE_LONG +
DataConstants.SIZE_LONG +
DataConstants.SIZE_INT /* + record.length */;
public static final byte DELETE_RECORD_TX = 15;
public static final int SIZE_DELETE_RECORD = JournalImpl.BASIC_SIZE + DataConstants.SIZE_LONG;
public static final byte DELETE_RECORD = 16;
public static final int SIZE_COMPLETE_TRANSACTION_RECORD = JournalImpl.BASIC_SIZE + DataConstants.SIZE_LONG +
DataConstants.SIZE_INT;
public static final int SIZE_PREPARE_RECORD = JournalImpl.SIZE_COMPLETE_TRANSACTION_RECORD + DataConstants.SIZE_INT;
public static final byte PREPARE_RECORD = 17;
public static final int SIZE_COMMIT_RECORD = JournalImpl.SIZE_COMPLETE_TRANSACTION_RECORD;
public static final byte COMMIT_RECORD = 18;
public static final int SIZE_ROLLBACK_RECORD = JournalImpl.BASIC_SIZE + DataConstants.SIZE_LONG;
public static final byte ROLLBACK_RECORD = 19;
protected static final byte FILL_CHARACTER = (byte) 'J';
// Attributes ----------------------------------------------------
private volatile boolean autoReclaim = true;
private final int userVersion;
private final int minFiles;
private final float compactPercentage;
private final int compactMinFiles;
private final SequentialFileFactory fileFactory;
private final JournalFilesRepository filesRepository;
// Compacting may replace this structure
private final ConcurrentMap<Long, JournalRecord> records = new ConcurrentHashMap<>();
private final Set<Long> pendingRecords = new ConcurrentHashSet<>();
// Compacting may replace this structure
private final ConcurrentMap<Long, JournalTransaction> transactions = new ConcurrentHashMap<>();
// This will be set only while the JournalCompactor is being executed
private volatile JournalCompactor compactor;
private final AtomicBoolean compactorRunning = new AtomicBoolean();
private Executor filesExecutor = null;
private Executor compactorExecutor = null;
private Executor appendExecutor = null;
private ConcurrentHashSet<CountDownLatch> latches = new ConcurrentHashSet<>();
private final ExecutorFactory providedIOThreadPool;
protected ExecutorFactory ioExecutorFactory;
private ThreadPoolExecutor threadPool;
/**
* We don't lock the journal during the whole compacting operation. During compacting we only
* lock it (i) when gathering the initial structure, and (ii) when replicating the structures
* after finished compacting.
*
* However we need to lock it while taking and updating snapshots
*/
private final ReadWriteLock journalLock = new ReentrantReadWriteLock();
private final ReadWriteLock compactorLock = new ReentrantReadWriteLock();
private volatile JournalFile currentFile;
private volatile JournalState state = JournalState.STOPPED;
private volatile int compactCount = 0;
private final Reclaimer reclaimer = new Reclaimer();
// Constructors --------------------------------------------------
public JournalImpl(final int fileSize,
final int minFiles,
final int poolSize,
final int compactMinFiles,
final int compactPercentage,
final SequentialFileFactory fileFactory,
final String filePrefix,
final String fileExtension,
final int maxAIO) {
this(fileSize, minFiles, poolSize, compactMinFiles, compactPercentage, fileFactory, filePrefix, fileExtension, maxAIO, 0);
}
public JournalImpl(final int fileSize,
final int minFiles,
final int poolSize,
final int compactMinFiles,
final int compactPercentage,
final SequentialFileFactory fileFactory,
final String filePrefix,
final String fileExtension,
final int maxAIO,
final int userVersion) {
this(null, fileSize, minFiles, poolSize, compactMinFiles, compactPercentage, fileFactory, filePrefix, fileExtension, maxAIO, userVersion);
}
public JournalImpl(final ExecutorFactory ioExecutors,
final int fileSize,
final int minFiles,
final int poolSize,
final int compactMinFiles,
final int compactPercentage,
final SequentialFileFactory fileFactory,
final String filePrefix,
final String fileExtension,
final int maxAIO,
final int userVersion) {
super(fileFactory.isSupportsCallbacks(), fileSize);
this.providedIOThreadPool = ioExecutors;
if (fileSize % fileFactory.getAlignment() != 0) {
throw new IllegalArgumentException("Invalid journal-file-size " + fileSize + ", It should be multiple of " +
fileFactory.getAlignment());
}
if (minFiles < 2) {
throw new IllegalArgumentException("minFiles cannot be less than 2");
}
if (compactPercentage < 0 || compactPercentage > 100) {
throw new IllegalArgumentException("Compact Percentage out of range");
}
if (compactPercentage == 0) {
this.compactPercentage = 0;
} else {
this.compactPercentage = compactPercentage / 100f;
}
this.compactMinFiles = compactMinFiles;
this.minFiles = minFiles;
this.fileFactory = fileFactory;
filesRepository = new JournalFilesRepository(fileFactory, this, filePrefix, fileExtension, userVersion, maxAIO, fileSize, minFiles, poolSize);
this.userVersion = userVersion;
}
@Override
public String toString() {
return "JournalImpl(state=" + state + ", currentFile=[" + currentFile + "], hash=" + super.toString() + ")";
}
@Override
public void runDirectJournalBlast() throws Exception {
final int numIts = 100000000;
ActiveMQJournalLogger.LOGGER.runningJournalBlast(numIts);
final CountDownLatch latch = new CountDownLatch(numIts * 2);
class MyAIOCallback implements IOCompletion {
@Override
public void done() {
latch.countDown();
}
@Override
public void onError(final int errorCode, final String errorMessage) {
}
@Override
public void storeLineUp() {
}
}
final MyAIOCallback task = new MyAIOCallback();
final int recordSize = 1024;
final byte[] bytes = new byte[recordSize];
class MyRecord implements EncodingSupport {
@Override
public void decode(final ActiveMQBuffer buffer) {
}
@Override
public void encode(final ActiveMQBuffer buffer) {
buffer.writeBytes(bytes);
}
@Override
public int getEncodeSize() {
return recordSize;
}
}
MyRecord record = new MyRecord();
for (int i = 0; i < numIts; i++) {
appendAddRecord(i, (byte) 1, record, true, task);
appendDeleteRecord(i, true, task);
}
latch.await();
}
@Override
public Map<Long, JournalRecord> getRecords() {
return records;
}
@Override
public JournalFile getCurrentFile() {
return currentFile;
}
@Override
public JournalCompactor getCompactor() {
return compactor;
}
/**
* this method is used internally only however tools may use it to maintenance.
* It won't be part of the interface as the tools should be specific to the implementation
*/
public List<JournalFile> orderFiles() throws Exception {
List<String> fileNames = fileFactory.listFiles(filesRepository.getFileExtension());
List<JournalFile> orderedFiles = new ArrayList<>(fileNames.size());
for (String fileName : fileNames) {
SequentialFile file = fileFactory.createSequentialFile(fileName);
if (file.size() >= SIZE_HEADER) {
file.open();
try {
JournalFileImpl jrnFile = readFileHeader(file);
orderedFiles.add(jrnFile);
} finally {
file.close();
}
} else {
ActiveMQJournalLogger.LOGGER.ignoringShortFile(fileName);
file.delete();
}
}
// Now order them by ordering id - we can't use the file name for ordering
// since we can re-use dataFiles
Collections.sort(orderedFiles, new JournalFileComparator());
return orderedFiles;
}
/**
* this method is used internally only however tools may use it to maintenance.
*/
public static int readJournalFile(final SequentialFileFactory fileFactory,
final JournalFile file,
final JournalReaderCallback reader) throws Exception {
file.getFile().open(1, false);
ByteBuffer wholeFileBuffer = null;
try {
final int filesize = (int) file.getFile().size();
wholeFileBuffer = fileFactory.newBuffer(filesize);
final int journalFileSize = file.getFile().read(wholeFileBuffer);
if (journalFileSize != filesize) {
throw new RuntimeException("Invalid read! The system couldn't read the entire file into memory");
}
// First long is the ordering timestamp, we just jump its position
wholeFileBuffer.position(JournalImpl.SIZE_HEADER);
int lastDataPos = JournalImpl.SIZE_HEADER;
while (wholeFileBuffer.hasRemaining()) {
final int pos = wholeFileBuffer.position();
byte recordType = wholeFileBuffer.get();
if (recordType < JournalImpl.ADD_RECORD || recordType > JournalImpl.ROLLBACK_RECORD) {
// I - We scan for any valid record on the file. If a hole
// happened on the middle of the file we keep looking until all
// the possibilities are gone
continue;
}
if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) {
reader.markAsDataFile(file);
wholeFileBuffer.position(pos + 1);
// II - Ignore this record, let's keep looking
continue;
}
// III - Every record has the file-id.
// This is what supports us from not re-filling the whole file
int readFileId = wholeFileBuffer.getInt();
// This record is from a previous file-usage. The file was
// reused and we need to ignore this record
if (readFileId != file.getRecordID()) {
wholeFileBuffer.position(pos + 1);
continue;
}
short compactCount = 0;
if (file.getJournalVersion() >= 2) {
if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_BYTE)) {
reader.markAsDataFile(file);
wholeFileBuffer.position(pos + 1);
continue;
}
compactCount = wholeFileBuffer.get();
}
long transactionID = 0;
if (JournalImpl.isTransaction(recordType)) {
if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_LONG)) {
wholeFileBuffer.position(pos + 1);
reader.markAsDataFile(file);
continue;
}
transactionID = wholeFileBuffer.getLong();
}
long recordID = 0;
// If prepare or commit
if (!JournalImpl.isCompleteTransaction(recordType)) {
if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_LONG)) {
wholeFileBuffer.position(pos + 1);
reader.markAsDataFile(file);
continue;
}
recordID = wholeFileBuffer.getLong();
}
// We use the size of the record to validate the health of the
// record.
// (V) We verify the size of the record
// The variable record portion used on Updates and Appends
int variableSize = 0;
// Used to hold extra data on transaction prepares
int preparedTransactionExtraDataSize = 0;
byte userRecordType = 0;
byte[] record = null;
if (JournalImpl.isContainsBody(recordType)) {
if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) {
wholeFileBuffer.position(pos + 1);
reader.markAsDataFile(file);
continue;
}
variableSize = wholeFileBuffer.getInt();
if (recordType != JournalImpl.DELETE_RECORD_TX) {
if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), 1)) {
wholeFileBuffer.position(pos + 1);
continue;
}
userRecordType = wholeFileBuffer.get();
}
if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), variableSize)) {
wholeFileBuffer.position(pos + 1);
continue;
}
record = new byte[variableSize];
wholeFileBuffer.get(record);
}
// Case this is a transaction, this will contain the number of pendingTransactions on a transaction, at the
// currentFile
int transactionCheckNumberOfRecords = 0;
if (recordType == JournalImpl.PREPARE_RECORD || recordType == JournalImpl.COMMIT_RECORD) {
if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) {
wholeFileBuffer.position(pos + 1);
continue;
}
transactionCheckNumberOfRecords = wholeFileBuffer.getInt();
if (recordType == JournalImpl.PREPARE_RECORD) {
if (JournalImpl.isInvalidSize(journalFileSize, wholeFileBuffer.position(), DataConstants.SIZE_INT)) {
wholeFileBuffer.position(pos + 1);
continue;
}
// Add the variable size required for preparedTransactions
preparedTransactionExtraDataSize = wholeFileBuffer.getInt();
}
variableSize = 0;
}
int recordSize = JournalImpl.getRecordSize(recordType, file.getJournalVersion());
// VI - this is completing V, We will validate the size at the end
// of the record,
// But we avoid buffer overflows by damaged data
if (JournalImpl.isInvalidSize(journalFileSize, pos, recordSize + variableSize +
preparedTransactionExtraDataSize)) {
// Avoid a buffer overflow caused by damaged data... continue
// scanning for more pendingTransactions...
logger.trace("Record at position " + pos +
" recordType = " +
recordType +
" file:" +
file.getFile().getFileName() +
" recordSize: " +
recordSize +
" variableSize: " +
variableSize +
" preparedTransactionExtraDataSize: " +
preparedTransactionExtraDataSize +
" is corrupted and it is being ignored (II)");
// If a file has damaged pendingTransactions, we make it a dataFile, and the
// next reclaiming will fix it
reader.markAsDataFile(file);
wholeFileBuffer.position(pos + 1);
continue;
}
int oldPos = wholeFileBuffer.position();
wholeFileBuffer.position(pos + variableSize +
recordSize +
preparedTransactionExtraDataSize - DataConstants.SIZE_INT);
int checkSize = wholeFileBuffer.getInt();
// VII - The checkSize at the end has to match with the size
// informed at the beginning.
// This is like testing a hash for the record. (We could replace the
// checkSize by some sort of calculated hash)
if (checkSize != variableSize + recordSize + preparedTransactionExtraDataSize) {
logger.trace("Record at position " + pos +
" recordType = " +
recordType +
" possible transactionID = " +
transactionID +
" possible recordID = " +
recordID +
" file:" +
file.getFile().getFileName() +
" is corrupted and it is being ignored (III)");
// If a file has damaged pendingTransactions, we make it a dataFile, and the
// next reclaiming will fix it
reader.markAsDataFile(file);
wholeFileBuffer.position(pos + DataConstants.SIZE_BYTE);
continue;
}
wholeFileBuffer.position(oldPos);
// At this point everything is checked. So we relax and just load
// the data now.
switch (recordType) {
case ADD_RECORD: {
reader.onReadAddRecord(new RecordInfo(recordID, userRecordType, record, false, compactCount));
break;
}
case UPDATE_RECORD: {
reader.onReadUpdateRecord(new RecordInfo(recordID, userRecordType, record, true, compactCount));
break;
}
case DELETE_RECORD: {
reader.onReadDeleteRecord(recordID);
break;
}
case ADD_RECORD_TX: {
reader.onReadAddRecordTX(transactionID, new RecordInfo(recordID, userRecordType, record, false, compactCount));
break;
}
case UPDATE_RECORD_TX: {
reader.onReadUpdateRecordTX(transactionID, new RecordInfo(recordID, userRecordType, record, true, compactCount));
break;
}
case DELETE_RECORD_TX: {
reader.onReadDeleteRecordTX(transactionID, new RecordInfo(recordID, (byte) 0, record, true, compactCount));
break;
}
case PREPARE_RECORD: {
byte[] extraData = new byte[preparedTransactionExtraDataSize];
wholeFileBuffer.get(extraData);
reader.onReadPrepareRecord(transactionID, extraData, transactionCheckNumberOfRecords);
break;
}
case COMMIT_RECORD: {
reader.onReadCommitRecord(transactionID, transactionCheckNumberOfRecords);
break;
}
case ROLLBACK_RECORD: {
reader.onReadRollbackRecord(transactionID);
break;
}
default: {
throw new IllegalStateException("Journal " + file.getFile().getFileName() +
" is corrupt, invalid record type " +
recordType);
}
}
checkSize = wholeFileBuffer.getInt();
// This is a sanity check about the loading code itself.
// If this checkSize doesn't match, it means the reading method is
// not doing what it was supposed to do
if (checkSize != variableSize + recordSize + preparedTransactionExtraDataSize) {
throw new IllegalStateException("Internal error on loading file. Position doesn't match with checkSize, file = " + file.getFile() +
", pos = " +
pos);
}
lastDataPos = wholeFileBuffer.position();
}
return lastDataPos;
} catch (Throwable e) {
ActiveMQJournalLogger.LOGGER.errorReadingFile(e);
throw new Exception(e.getMessage(), e);
} finally {
if (wholeFileBuffer != null) {
fileFactory.releaseBuffer(wholeFileBuffer);
}
try {
file.getFile().close();
} catch (Throwable ignored) {
}
}
}
// Journal implementation
// ----------------------------------------------------------------
@Override
public void appendAddRecord(final long id,
final byte recordType,
final Persister persister,
final Object record,
final boolean sync,
final IOCompletion callback) throws Exception {
checkJournalIsLoaded();
lineUpContext(callback);
pendingRecords.add(id);
final SimpleFuture<Boolean> result = newSyncAndCallbackResult(sync, callback);
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
JournalInternalRecord addRecord = new JournalAddRecord(true, id, recordType, persister, record);
JournalFile usedFile = appendRecord(addRecord, false, sync, null, callback);
records.put(id, new JournalRecord(usedFile, addRecord.getEncodeSize()));
if (logger.isTraceEnabled()) {
logger.trace("appendAddRecord::id=" + id +
", userRecordType=" +
recordType +
", record = " + record +
", usedFile = " +
usedFile);
}
if (result != null) {
result.set(true);
}
} catch (Exception e) {
if (result != null) {
result.fail(e);
}
logger.error("appendAddRecord::" + e, e);
} finally {
pendingRecords.remove(id);
journalLock.readLock().unlock();
}
}
});
if (result != null) {
result.get();
}
}
@Override
public void appendUpdateRecord(final long id,
final byte recordType,
final Persister persister,
final Object record,
final boolean sync,
final IOCompletion callback) throws Exception {
checkJournalIsLoaded();
lineUpContext(callback);
checkKnownRecordID(id);
final SimpleFuture<Boolean> result = newSyncAndCallbackResult(sync, callback);
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
JournalRecord jrnRecord = records.get(id);
JournalInternalRecord updateRecord = new JournalAddRecord(false, id, recordType, persister, record);
JournalFile usedFile = appendRecord(updateRecord, false, sync, null, callback);
if (logger.isTraceEnabled()) {
logger.trace("appendUpdateRecord::id=" + id +
", userRecordType=" +
recordType +
", usedFile = " +
usedFile);
}
// record==null here could only mean there is a compactor
// computing the delete should be done after compacting is done
if (jrnRecord == null) {
compactor.addCommandUpdate(id, usedFile, updateRecord.getEncodeSize());
} else {
jrnRecord.addUpdateFile(usedFile, updateRecord.getEncodeSize());
}
if (result != null) {
result.set(true);
}
} catch (Exception e) {
if (result != null) {
result.fail(e);
}
logger.error("appendUpdateRecord:" + e, e);
} finally {
journalLock.readLock().unlock();
}
}
});
if (result != null) {
result.get();
}
}
@Override
public void appendDeleteRecord(final long id, final boolean sync, final IOCompletion callback) throws Exception {
checkJournalIsLoaded();
lineUpContext(callback);
checkKnownRecordID(id);
final SimpleFuture<Boolean> result = newSyncAndCallbackResult(sync, callback);
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
JournalRecord record = null;
if (compactor == null) {
record = records.remove(id);
}
JournalInternalRecord deleteRecord = new JournalDeleteRecord(id);
JournalFile usedFile = appendRecord(deleteRecord, false, sync, null, callback);
if (logger.isTraceEnabled()) {
logger.trace("appendDeleteRecord::id=" + id + ", usedFile = " + usedFile);
}
// record==null here could only mean there is a compactor
// computing the delete should be done after compacting is done
if (record == null) {
compactor.addCommandDelete(id, usedFile);
} else {
record.delete(usedFile);
}
if (result != null) {
result.set(true);
}
} catch (Exception e) {
if (result != null) {
result.fail(e);
}
logger.error("appendDeleteRecord:" + e, e);
} finally {
journalLock.readLock().unlock();
}
}
});
if (result != null) {
result.get();
}
}
private static SimpleFuture<Boolean> newSyncAndCallbackResult(boolean sync, IOCompletion callback) {
return (sync && callback == null) ? new SimpleFuture<Boolean>() : null;
}
@Override
public void appendAddRecordTransactional(final long txID,
final long id,
final byte recordType,
final Persister persister,
final Object record) throws Exception {
checkJournalIsLoaded();
final JournalTransaction tx = getTransactionInfo(txID);
tx.checkErrorCondition();
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
JournalInternalRecord addRecord = new JournalAddRecordTX(true, txID, id, recordType, persister, record);
JournalFile usedFile = appendRecord(addRecord, false, false, tx, null);
if (logger.isTraceEnabled()) {
logger.trace("appendAddRecordTransactional:txID=" + txID +
",id=" +
id +
", userRecordType=" +
recordType +
", record = " + record +
", usedFile = " +
usedFile);
}
tx.addPositive(usedFile, id, addRecord.getEncodeSize());
} catch (Exception e) {
logger.error("appendAddRecordTransactional:" + e, e);
setErrorCondition(tx, e);
} finally {
journalLock.readLock().unlock();
}
}
});
}
private void checkKnownRecordID(final long id) throws Exception {
if (records.containsKey(id) || pendingRecords.contains(id) || (compactor != null && compactor.lookupRecord(id))) {
return;
}
final SimpleFuture<Boolean> known = new SimpleFuture<>();
// retry on the append thread. maybe the appender thread is not keeping up.
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
known.set(records.containsKey(id)
|| pendingRecords.contains(id)
|| (compactor != null && compactor.lookupRecord(id)));
} finally {
journalLock.readLock().unlock();
}
}
});
if (!known.get()) {
throw new IllegalStateException("Cannot find add info " + id + " on compactor or current records");
}
}
private void checkJournalIsLoaded() {
if (state != JournalState.LOADED && state != JournalState.SYNCING) {
throw new IllegalStateException("Journal must be in state=" + JournalState.LOADED + ", was [" + state + "]");
}
}
private void setJournalState(JournalState newState) {
state = newState;
}
@Override
public void appendUpdateRecordTransactional(final long txID,
final long id,
final byte recordType,
final Persister persister,
final Object record) throws Exception {
checkJournalIsLoaded();
final JournalTransaction tx = getTransactionInfo(txID);
tx.checkErrorCondition();
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
JournalInternalRecord updateRecordTX = new JournalAddRecordTX( false, txID, id, recordType, persister, record );
JournalFile usedFile = appendRecord( updateRecordTX, false, false, tx, null );
if ( logger.isTraceEnabled() ) {
logger.trace( "appendUpdateRecordTransactional::txID=" + txID +
",id=" +
id +
", userRecordType=" +
recordType +
", record = " + record +
", usedFile = " +
usedFile );
}
tx.addPositive( usedFile, id, updateRecordTX.getEncodeSize() );
} catch ( Exception e ) {
logger.error("appendUpdateRecordTransactional:" + e.getMessage(), e );
setErrorCondition( tx, e );
} finally {
journalLock.readLock().unlock();
}
}
});
}
@Override
public void appendDeleteRecordTransactional(final long txID,
final long id,
final EncodingSupport record) throws Exception {
checkJournalIsLoaded();
final JournalTransaction tx = getTransactionInfo(txID);
tx.checkErrorCondition();
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
JournalInternalRecord deleteRecordTX = new JournalDeleteRecordTX(txID, id, record);
JournalFile usedFile = appendRecord(deleteRecordTX, false, false, tx, null);
if (logger.isTraceEnabled()) {
logger.trace("appendDeleteRecordTransactional::txID=" + txID +
", id=" +
id +
", usedFile = " +
usedFile);
}
tx.addNegative(usedFile, id);
} catch (Exception e) {
logger.error("appendDeleteRecordTransactional:" + e, e);
setErrorCondition(tx, e);
} finally {
journalLock.readLock().unlock();
}
}
});
}
/**
* <p>If the system crashed after a prepare was called, it should store information that is required to bring the transaction
* back to a state it could be committed. </p>
* <p> transactionData allows you to store any other supporting user-data related to the transaction</p>
* <p> This method also uses the same logic applied on {@link JournalImpl#appendCommitRecord(long, boolean)}
*
* @param txID
* @param transactionData extra user data for the prepare
* @throws Exception
*/
@Override
public void appendPrepareRecord(final long txID,
final EncodingSupport transactionData,
final boolean sync,
final IOCompletion callback) throws Exception {
checkJournalIsLoaded();
lineUpContext(callback);
final JournalTransaction tx = getTransactionInfo(txID);
tx.checkErrorCondition();
final SimpleFuture<Boolean> result = newSyncAndCallbackResult(sync, callback);
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
JournalInternalRecord prepareRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.PREPARE, txID, transactionData);
JournalFile usedFile = appendRecord(prepareRecord, true, sync, tx, callback);
if (logger.isTraceEnabled()) {
logger.trace("appendPrepareRecord::txID=" + txID + ", usedFile = " + usedFile);
}
tx.prepare(usedFile);
if (result != null) {
result.set(true);
}
} catch (Exception e) {
if (result != null) {
result.fail(e);
}
logger.error("appendPrepareRecord:" + e, e);
setErrorCondition(tx, e);
} finally {
journalLock.readLock().unlock();
}
}
});
if (result != null) {
result.get();
tx.checkErrorCondition();
}
}
@Override
public void lineUpContext(IOCompletion callback) {
if (callback != null) {
callback.storeLineUp();
}
}
private void setErrorCondition(JournalTransaction jt, Throwable t) {
if (jt != null) {
TransactionCallback callback = jt.getCurrentCallback();
if (callback != null && callback.getErrorMessage() != null) {
callback.onError(ActiveMQExceptionType.IO_ERROR.getCode(), t.getMessage());
}
}
}
/**
* Regarding the number of operations in a given file see {@link JournalCompleteRecordTX}.
*/
@Override
public void appendCommitRecord(final long txID,
final boolean sync,
final IOCompletion callback,
final boolean lineUpContext) throws Exception {
checkJournalIsLoaded();
if (lineUpContext) {
lineUpContext(callback);
}
final JournalTransaction tx = transactions.remove(txID);
if (tx == null) {
throw new IllegalStateException("Cannot find tx with id " + txID);
}
tx.checkErrorCondition();
final SimpleFuture<Boolean> result = newSyncAndCallbackResult(sync, callback);
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
JournalInternalRecord commitRecord = new JournalCompleteRecordTX(TX_RECORD_TYPE.COMMIT, txID, null);
JournalFile usedFile = appendRecord(commitRecord, true, sync, tx, callback);
if (logger.isTraceEnabled()) {
logger.trace("appendCommitRecord::txID=" + txID + ", usedFile = " + usedFile);
}
tx.commit(usedFile);
if (result != null) {
result.set(true);
}
} catch (Exception e) {
if (result != null) {
result.fail(e);
}
logger.error("appendCommitRecord:" + e, e);
setErrorCondition(tx, e);
} finally {
journalLock.readLock().unlock();
}
}
});
if (result != null) {
result.get();
tx.checkErrorCondition();
}
}
@Override
public void appendRollbackRecord(final long txID, final boolean sync, final IOCompletion callback) throws Exception {
checkJournalIsLoaded();
lineUpContext(callback);
final JournalTransaction tx = transactions.remove(txID);
if (tx == null) {
throw new IllegalStateException("Cannot find tx with id " + txID);
}
tx.checkErrorCondition();
final SimpleFuture<Boolean> result = newSyncAndCallbackResult(sync, callback);
appendExecutor.execute(new Runnable() {
@Override
public void run() {
journalLock.readLock().lock();
try {
JournalInternalRecord rollbackRecord = new JournalRollbackRecordTX(txID);
JournalFile usedFile = appendRecord(rollbackRecord, false, sync, tx, callback);
tx.rollback(usedFile);
if (result != null) {
result.set(true);
}
} catch (Exception e) {
if (result != null) {
result.fail(e);
}
logger.error("appendRollbackRecord:" + e, e);
setErrorCondition(tx, e);
} finally {
journalLock.readLock().unlock();
}
}
});
if (result != null) {
result.get();
tx.checkErrorCondition();
}
}
// XXX make it protected?
@Override
public int getAlignment() throws Exception {
return fileFactory.getAlignment();
}
private static final class DummyLoader implements LoaderCallback {
static final LoaderCallback INSTANCE = new DummyLoader();
@Override
public void failedTransaction(final long transactionID,
final List<RecordInfo> records,
final List<RecordInfo> recordsToDelete) {
}
@Override
public void updateRecord(final RecordInfo info) {
}
@Override
public void deleteRecord(final long id) {
}
@Override
public void addRecord(final RecordInfo info) {
}
@Override
public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) {
}
}
@Override
public synchronized JournalLoadInformation loadInternalOnly() throws Exception {
return load(DummyLoader.INSTANCE, true, null);
}
@Override
public synchronized JournalLoadInformation loadSyncOnly(JournalState syncState) throws Exception {
assert syncState == JournalState.SYNCING || syncState == JournalState.SYNCING_UP_TO_DATE;
return load(DummyLoader.INSTANCE, true, syncState);
}
@Override
public JournalLoadInformation load(final List<RecordInfo> committedRecords,
final List<PreparedTransactionInfo> preparedTransactions,
final TransactionFailureCallback failureCallback) throws Exception {
return load(committedRecords, preparedTransactions, failureCallback, true);
}
/**
* @see JournalImpl#load(LoaderCallback)
*/
public synchronized JournalLoadInformation load(final List<RecordInfo> committedRecords,
final List<PreparedTransactionInfo> preparedTransactions,
final TransactionFailureCallback failureCallback,
final boolean fixBadTX) throws Exception {
final Set<Long> recordsToDelete = new HashSet<>();
// ArrayList was taking too long to delete elements on checkDeleteSize
final List<RecordInfo> records = new LinkedList<>();
final int DELETE_FLUSH = 20000;
JournalLoadInformation info = load(new LoaderCallback() {
Runtime runtime = Runtime.getRuntime();
private void checkDeleteSize() {
// HORNETQ-482 - Flush deletes only if memory is critical
if (recordsToDelete.size() > DELETE_FLUSH && runtime.freeMemory() < runtime.maxMemory() * 0.2) {
ActiveMQJournalLogger.LOGGER.debug("Flushing deletes during loading, deleteCount = " + recordsToDelete.size());
// Clean up when the list is too large, or it won't be possible to load large sets of files
// Done as part of JBMESSAGING-1678
Iterator<RecordInfo> iter = records.iterator();
while (iter.hasNext()) {
RecordInfo record = iter.next();
if (recordsToDelete.contains(record.id)) {
iter.remove();
}
}
recordsToDelete.clear();
ActiveMQJournalLogger.LOGGER.debug("flush delete done");
}
}
@Override
public void addPreparedTransaction(final PreparedTransactionInfo preparedTransaction) {
preparedTransactions.add(preparedTransaction);
checkDeleteSize();
}
@Override
public void addRecord(final RecordInfo info) {
records.add(info);
checkDeleteSize();
}
@Override
public void updateRecord(final RecordInfo info) {
records.add(info);
checkDeleteSize();
}
@Override
public void deleteRecord(final long id) {
recordsToDelete.add(id);
checkDeleteSize();
}
@Override
public void failedTransaction(final long transactionID,
final List<RecordInfo> records,
final List<RecordInfo> recordsToDelete) {
if (failureCallback != null) {
failureCallback.failedTransaction(transactionID, records, recordsToDelete);
}
}
}, fixBadTX, null);
for (RecordInfo record : records) {
if (!recordsToDelete.contains(record.id)) {
committedRecords.add(record);
}
}
return info;
}
@Override
public void scheduleCompactAndBlock(int timeout) throws Exception {
final AtomicInteger errors = new AtomicInteger(0);
final CountDownLatch latch = newLatch(1);
compactorRunning.set(true);
// We can't use the executor for the compacting... or we would dead lock because of file open and creation
// operations (that will use the executor)
compactorExecutor.execute(new Runnable() {
@Override
public void run() {
try {
JournalImpl.this.compact();
} catch (Throwable e) {
errors.incrementAndGet();
ActiveMQJournalLogger.LOGGER.errorCompacting(e);
} finally {
latch.countDown();
}
}
});
try {
awaitLatch(latch, timeout);
if (errors.get() > 0) {
throw new RuntimeException("Error during compact, look at the logs");
}
} finally {
compactorRunning.set(false);
}
}
/**
* Note: This method can't be called from the main executor, as it will invoke other methods
* depending on it.
*
* Note: only synchronized methods on journal are methods responsible for the life-cycle such as
* stop, start records will still come as this is being executed
*/
public synchronized void compact() throws Exception {
if (compactor != null) {
throw new IllegalStateException("There is pending compacting operation");
}
if (ActiveMQJournalLogger.LOGGER.isDebugEnabled()) {
ActiveMQJournalLogger.LOGGER.debug("JournalImpl::compact compacting journal " + (++compactCount));
}
compactorLock.writeLock().lock();
try {
ArrayList<JournalFile> dataFilesToProcess = new ArrayList<>(filesRepository.getDataFilesCount());
boolean previousReclaimValue = isAutoReclaim();
try {
ActiveMQJournalLogger.LOGGER.debug("Starting compacting operation on journal");
onCompactStart();
// We need to guarantee that the journal is frozen for this short time
// We don't freeze the journal as we compact, only for the short time where we replace records
journalLock.writeLock().lock();
try {
if (state != JournalState.LOADED) {
return;
}
onCompactLockingTheJournal();
setAutoReclaim(false);
// We need to move to the next file, as we need a clear start for negatives and positives counts
moveNextFile(false);
// Take the snapshots and replace the structures
dataFilesToProcess.addAll(filesRepository.getDataFiles());
filesRepository.clearDataFiles();
if (dataFilesToProcess.size() == 0) {
logger.trace("Finishing compacting, nothing to process");
return;
}
compactor = new JournalCompactor(fileFactory, this, filesRepository, records.keySet(), dataFilesToProcess.get(0).getFileID());
for (Map.Entry<Long, JournalTransaction> entry : transactions.entrySet()) {
compactor.addPendingTransaction(entry.getKey(), entry.getValue().getPositiveArray());
entry.getValue().setCompacting();
}
// We will calculate the new records during compacting, what will take the position the records will take
// after compacting
records.clear();
} finally {
journalLock.writeLock().unlock();
}
Collections.sort(dataFilesToProcess, new JournalFileComparator());
// This is where most of the work is done, taking most of the time of the compacting routine.
// Notice there are no locks while this is being done.
// Read the files, and use the JournalCompactor class to create the new outputFiles, and the new collections as
// well
for (final JournalFile file : dataFilesToProcess) {
try {
JournalImpl.readJournalFile(fileFactory, file, compactor);
} catch (Throwable e) {
ActiveMQJournalLogger.LOGGER.compactReadError(file);
throw new Exception("Error on reading compacting for " + file, e);
}
}
compactor.flush();
// pointcut for tests
// We need to test concurrent updates on the journal, as the compacting is being performed.
// Usually tests will use this to hold the compacting while other structures are being updated.
onCompactDone();
List<JournalFile> newDatafiles = null;
JournalCompactor localCompactor = compactor;
SequentialFile controlFile = createControlFile(dataFilesToProcess, compactor.getNewDataFiles(), null);
journalLock.writeLock().lock();
try {
// Need to clear the compactor here, or the replay commands will send commands back (infinite loop)
compactor = null;
onCompactLockingTheJournal();
newDatafiles = localCompactor.getNewDataFiles();
// Restore newRecords created during compacting
for (Map.Entry<Long, JournalRecord> newRecordEntry : localCompactor.getNewRecords().entrySet()) {
records.put(newRecordEntry.getKey(), newRecordEntry.getValue());
}
// Restore compacted dataFiles
for (int i = newDatafiles.size() - 1; i >= 0; i--) {
JournalFile fileToAdd = newDatafiles.get(i);
if (logger.isTraceEnabled()) {
logger.trace("Adding file " + fileToAdd + " back as datafile");
}
filesRepository.addDataFileOnTop(fileToAdd);
}
if (logger.isTraceEnabled()) {
logger.trace("There are " + filesRepository.getDataFilesCount() + " datafiles Now");
}
// Replay pending commands (including updates, deletes and commits)
for (JournalTransaction newTransaction : localCompactor.getNewTransactions().values()) {
newTransaction.replaceRecordProvider(this);
}
localCompactor.replayPendingCommands();
// Merge transactions back after compacting.
// This has to be done after the replay pending commands, as we need to delete commits
// that happened during the compacting
for (JournalTransaction newTransaction : localCompactor.getNewTransactions().values()) {
if (logger.isTraceEnabled()) {
logger.trace("Merging pending transaction " + newTransaction + " after compacting the journal");
}
JournalTransaction liveTransaction = transactions.get(newTransaction.getId());
if (liveTransaction != null) {
liveTransaction.merge(newTransaction);
} else {
ActiveMQJournalLogger.LOGGER.compactMergeError(newTransaction.getId());
}
}
} finally {
journalLock.writeLock().unlock();
}
// At this point the journal is unlocked. We keep renaming files while the journal is already operational
renameFiles(dataFilesToProcess, newDatafiles);
deleteControlFile(controlFile);
ActiveMQJournalLogger.LOGGER.debug("Finished compacting on journal");
} finally {
// An Exception was probably thrown, and the compactor was not cleared
if (compactor != null) {
try {
compactor.flush();
} catch (Throwable ignored) {
}
compactor = null;
}
setAutoReclaim(previousReclaimValue);
}
} finally {
compactorLock.writeLock().unlock();
}
}
/**
* <p>Load data accordingly to the record layouts</p>
* <p>Basic record layout:</p>
* <table border=1 summary="">
* <tr><td><b>Field Name</b></td><td><b>Size</b></td></tr>
* <tr><td>RecordType</td><td>Byte (1)</td></tr>
* <tr><td>FileID</td><td>Integer (4 bytes)</td></tr>
* <tr><td>Compactor Counter</td><td>1 byte</td></tr>
* <tr><td>TransactionID <i>(if record is transactional)</i></td><td>Long (8 bytes)</td></tr>
* <tr><td>RecordID</td><td>Long (8 bytes)</td></tr>
* <tr><td>BodySize(Add, update and delete)</td><td>Integer (4 bytes)</td></tr>
* <tr><td>UserDefinedRecordType (If add/update only)</td><td>Byte (1)</td></tr>
* <tr><td>RecordBody</td><td>Byte Array (size=BodySize)</td></tr>
* <tr><td>Check Size</td><td>Integer (4 bytes)</td></tr>
* </table>
* <p> The check-size is used to validate if the record is valid and complete </p>
* <p>Commit/Prepare record layout:</p>
* <table border=1 summary="">
* <tr><td><b>Field Name</b></td><td><b>Size</b></td></tr>
* <tr><td>RecordType</td><td>Byte (1)</td></tr>
* <tr><td>FileID</td><td>Integer (4 bytes)</td></tr>
* <tr><td>Compactor Counter</td><td>1 byte</td></tr>
* <tr><td>TransactionID <i>(if record is transactional)</i></td><td>Long (8 bytes)</td></tr>
* <tr><td>ExtraDataLength (Prepares only)</td><td>Integer (4 bytes)</td></tr>
* <tr><td>Number Of Files (N)</td><td>Integer (4 bytes)</td></tr>
* <tr><td>ExtraDataBytes</td><td>Bytes (sized by ExtraDataLength)</td></tr>
* <tr><td>* FileID(n)</td><td>Integer (4 bytes)</td></tr>
* <tr><td>* NumberOfElements(n)</td><td>Integer (4 bytes)</td></tr>
* <tr><td>CheckSize</td><td>Integer (4 bytes)</td></tr>
* </table>
* <p> * FileID and NumberOfElements are the transaction summary, and they will be repeated (N)umberOfFiles times </p>
*/
@Override
public JournalLoadInformation load(final LoaderCallback loadManager) throws Exception {
return load(loadManager, true, null);
}
/**
* @param loadManager
* @param changeData
* @param replicationSync {@code true} will place
* @return
* @throws Exception
*/
private synchronized JournalLoadInformation load(final LoaderCallback loadManager,
final boolean changeData,
final JournalState replicationSync) throws Exception {
if (state == JournalState.STOPPED || state == JournalState.LOADED) {
throw new IllegalStateException("Journal " + this + " must be in " + JournalState.STARTED + " state, was " +
state);
}
if (state == replicationSync) {
throw new IllegalStateException("Journal cannot be in state " + JournalState.STARTED);
}
checkControlFile();
records.clear();
filesRepository.clear();
transactions.clear();
currentFile = null;
final Map<Long, TransactionHolder> loadTransactions = new LinkedHashMap<>();
final List<JournalFile> orderedFiles = orderFiles();
filesRepository.calculateNextfileID(orderedFiles);
int lastDataPos = JournalImpl.SIZE_HEADER;
// AtomicLong is used only as a reference, not as an Atomic value
final AtomicLong maxID = new AtomicLong(-1);
for (final JournalFile file : orderedFiles) {
logger.trace("Loading file " + file.getFile().getFileName());
final AtomicBoolean hasData = new AtomicBoolean(false);
int resultLastPost = JournalImpl.readJournalFile(fileFactory, file, new JournalReaderCallback() {
private void checkID(final long id) {
if (id > maxID.longValue()) {
maxID.set(id);
}
}
@Override
public void onReadAddRecord(final RecordInfo info) throws Exception {
checkID(info.id);
hasData.set(true);
loadManager.addRecord(info);
records.put(info.id, new JournalRecord(file, info.data.length + JournalImpl.SIZE_ADD_RECORD + 1));
}
@Override
public void onReadUpdateRecord(final RecordInfo info) throws Exception {
checkID(info.id);
hasData.set(true);
loadManager.updateRecord(info);
JournalRecord posFiles = records.get(info.id);
if (posFiles != null) {
// It's legal for this to be null. The file(s) with the may
// have been deleted
// just leaving some updates in this file
posFiles.addUpdateFile(file, info.data.length + JournalImpl.SIZE_ADD_RECORD + 1); // +1 = compact
// count
}
}
@Override
public void onReadDeleteRecord(final long recordID) throws Exception {
hasData.set(true);
loadManager.deleteRecord(recordID);
JournalRecord posFiles = records.remove(recordID);
if (posFiles != null) {
posFiles.delete(file);
}
}
@Override
public void onReadUpdateRecordTX(final long transactionID, final RecordInfo info) throws Exception {
onReadAddRecordTX(transactionID, info);
}
@Override
public void onReadAddRecordTX(final long transactionID, final RecordInfo info) throws Exception {
checkID(info.id);
hasData.set(true);
TransactionHolder tx = loadTransactions.get(transactionID);
if (tx == null) {
tx = new TransactionHolder(transactionID);
loadTransactions.put(transactionID, tx);
}
tx.recordInfos.add(info);
JournalTransaction tnp = transactions.get(transactionID);
if (tnp == null) {
tnp = new JournalTransaction(transactionID, JournalImpl.this);
transactions.put(transactionID, tnp);
}
tnp.addPositive(file, info.id, info.data.length + JournalImpl.SIZE_ADD_RECORD_TX + 1); // +1 = compact
// count
}
@Override
public void onReadDeleteRecordTX(final long transactionID, final RecordInfo info) throws Exception {
hasData.set(true);
TransactionHolder tx = loadTransactions.get(transactionID);
if (tx == null) {
tx = new TransactionHolder(transactionID);
loadTransactions.put(transactionID, tx);
}
tx.recordsToDelete.add(info);
JournalTransaction tnp = transactions.get(transactionID);
if (tnp == null) {
tnp = new JournalTransaction(transactionID, JournalImpl.this);
transactions.put(transactionID, tnp);
}
tnp.addNegative(file, info.id);
}
@Override
public void onReadPrepareRecord(final long transactionID,
final byte[] extraData,
final int numberOfRecords) throws Exception {
hasData.set(true);
TransactionHolder tx = loadTransactions.get(transactionID);
if (tx == null) {
// The user could choose to prepare empty transactions
tx = new TransactionHolder(transactionID);
loadTransactions.put(transactionID, tx);
}
tx.prepared = true;
tx.extraData = extraData;
JournalTransaction journalTransaction = transactions.get(transactionID);
if (journalTransaction == null) {
journalTransaction = new JournalTransaction(transactionID, JournalImpl.this);
transactions.put(transactionID, journalTransaction);
}
boolean healthy = checkTransactionHealth(file, journalTransaction, orderedFiles, numberOfRecords);
if (healthy) {
journalTransaction.prepare(file);
} else {
ActiveMQJournalLogger.LOGGER.preparedTXIncomplete(transactionID);
tx.invalid = true;
}
}
@Override
public void onReadCommitRecord(final long transactionID, final int numberOfRecords) throws Exception {
TransactionHolder tx = loadTransactions.remove(transactionID);
// The commit could be alone on its own journal-file and the
// whole transaction body was reclaimed but not the
// commit-record
// So it is completely legal to not find a transaction at this
// point
// If we can't find it, we assume the TX was reclaimed and we
// ignore this
if (tx != null) {
JournalTransaction journalTransaction = transactions.remove(transactionID);
if (journalTransaction == null) {
throw new IllegalStateException("Cannot find tx " + transactionID);
}
boolean healthy = checkTransactionHealth(file, journalTransaction, orderedFiles, numberOfRecords);
if (healthy) {
for (RecordInfo txRecord : tx.recordInfos) {
if (txRecord.isUpdate) {
loadManager.updateRecord(txRecord);
} else {
loadManager.addRecord(txRecord);
}
}
for (RecordInfo deleteValue : tx.recordsToDelete) {
loadManager.deleteRecord(deleteValue.id);
}
journalTransaction.commit(file);
} else {
ActiveMQJournalLogger.LOGGER.txMissingElements(transactionID);
journalTransaction.forget();
}
hasData.set(true);
}
}
@Override
public void onReadRollbackRecord(final long transactionID) throws Exception {
TransactionHolder tx = loadTransactions.remove(transactionID);
// The rollback could be alone on its own journal-file and the
// whole transaction body was reclaimed but the commit-record
// So it is completely legal to not find a transaction at this
// point
if (tx != null) {
JournalTransaction tnp = transactions.remove(transactionID);
if (tnp == null) {
throw new IllegalStateException("Cannot find tx " + transactionID);
}
// There is no need to validate summaries/holes on
// Rollbacks.. We will ignore the data anyway.
tnp.rollback(file);
hasData.set(true);
}
}
@Override
public void markAsDataFile(final JournalFile file) {
hasData.set(true);
}
});
if (hasData.get()) {
lastDataPos = resultLastPost;
filesRepository.addDataFileOnBottom(file);
} else {
if (changeData) {
// Empty dataFiles with no data
filesRepository.addFreeFile(file, false, false);
}
}
}
if (replicationSync == JournalState.SYNCING) {
assert filesRepository.getDataFiles().isEmpty();
setJournalState(JournalState.SYNCING);
return new JournalLoadInformation(0, -1);
}
setUpCurrentFile(lastDataPos);
setJournalState(JournalState.LOADED);
for (TransactionHolder transaction : loadTransactions.values()) {
if ((!transaction.prepared || transaction.invalid) && replicationSync != JournalState.SYNCING_UP_TO_DATE) {
ActiveMQJournalLogger.LOGGER.uncomittedTxFound(transaction.transactionID);
if (changeData) {
// I append a rollback record here, because otherwise compacting will be throwing messages because of unknown transactions
this.appendRollbackRecord(transaction.transactionID, false);
}
loadManager.failedTransaction(transaction.transactionID, transaction.recordInfos, transaction.recordsToDelete);
} else {
for (RecordInfo info : transaction.recordInfos) {
if (info.id > maxID.get()) {
maxID.set(info.id);
}
}
PreparedTransactionInfo info = new PreparedTransactionInfo(transaction.transactionID, transaction.extraData);
info.getRecords().addAll(transaction.recordInfos);
info.getRecordsToDelete().addAll(transaction.recordsToDelete);
loadManager.addPreparedTransaction(info);
}
}
checkReclaimStatus();
return new JournalLoadInformation(records.size(), maxID.longValue());
}
/**
* @return true if cleanup was called
*/
@Override
public final boolean checkReclaimStatus() throws Exception {
if (compactorRunning.get()) {
return false;
}
// We can't start reclaim while compacting is working
while (true) {
if (state != JournalImpl.JournalState.LOADED)
return false;
if (!isAutoReclaim())
return false;
if (journalLock.readLock().tryLock(250, TimeUnit.MILLISECONDS))
break;
}
try {
reclaimer.scan(getDataFiles());
for (JournalFile file : filesRepository.getDataFiles()) {
if (file.isCanReclaim()) {
// File can be reclaimed or deleted
if (logger.isTraceEnabled()) {
logger.trace("Reclaiming file " + file);
}
filesRepository.removeDataFile(file);
filesRepository.addFreeFile(file, false);
}
}
} finally {
journalLock.readLock().unlock();
}
return false;
}
private boolean needsCompact() throws Exception {
JournalFile[] dataFiles = getDataFiles();
long totalLiveSize = 0;
for (JournalFile file : dataFiles) {
totalLiveSize += file.getLiveSize();
}
long totalBytes = dataFiles.length * (long) fileSize;
long compactMargin = (long) (totalBytes * compactPercentage);
boolean needCompact = totalLiveSize < compactMargin && dataFiles.length > compactMinFiles;
return needCompact;
}
private void checkCompact() throws Exception {
if (compactMinFiles == 0) {
// compacting is disabled
return;
}
if (state != JournalState.LOADED) {
return;
}
if (!compactorRunning.get() && needsCompact()) {
scheduleCompact();
}
}
private void scheduleCompact() {
if (!compactorRunning.compareAndSet(false, true)) {
return;
}
// We can't use the executor for the compacting... or we would dead lock because of file open and creation
// operations (that will use the executor)
compactorExecutor.execute(new Runnable() {
@Override
public void run() {
try {
JournalImpl.this.compact();
} catch (Throwable e) {
ActiveMQJournalLogger.LOGGER.errorCompacting(e);
} finally {
compactorRunning.set(false);
}
}
});
}
// TestableJournal implementation
// --------------------------------------------------------------
@Override
public final void setAutoReclaim(final boolean autoReclaim) {
this.autoReclaim = autoReclaim;
}
@Override
public final boolean isAutoReclaim() {
return autoReclaim;
}
/* Only meant to be used in tests. */
@Override
public String debug() throws Exception {
reclaimer.scan(getDataFiles());
StringBuilder builder = new StringBuilder();
for (JournalFile file : filesRepository.getDataFiles()) {
builder.append("DataFile:" + file +
" posCounter = " +
file.getPosCount() +
" reclaimStatus = " +
file.isCanReclaim() +
" live size = " +
file.getLiveSize() +
"\n");
if (file instanceof JournalFileImpl) {
builder.append(((JournalFileImpl) file).debug());
}
}
for (JournalFile file : filesRepository.getFreeFiles()) {
builder.append("FreeFile:" + file + "\n");
}
if (currentFile != null) {
builder.append("CurrentFile:" + currentFile + " posCounter = " + currentFile.getPosCount() + "\n");
if (currentFile instanceof JournalFileImpl) {
builder.append(((JournalFileImpl) currentFile).debug());
}
} else {
builder.append("CurrentFile: No current file at this point!");
}
return builder.toString();
}
/**
* Method for use on testcases.
* It will call waitComplete on every transaction, so any assertions on the file system will be correct after this
*/
@Override
public void debugWait() throws InterruptedException {
fileFactory.flush();
flushExecutor(filesExecutor);
flushExecutor(appendExecutor);
}
@Override
public void flush() throws Exception {
fileFactory.flush();
flushExecutor(appendExecutor);
flushExecutor(filesExecutor);
flushExecutor(compactorExecutor);
}
private void flushExecutor(Executor executor) throws InterruptedException {
if (executor != null) {
// Send something to the closingExecutor, just to make sure we went until its end
final CountDownLatch latch = new CountDownLatch(1);
try {
executor.execute(new Runnable() {
@Override
public void run() {
latch.countDown();
}
});
latch.await(10, TimeUnit.SECONDS);
} catch (RejectedExecutionException ignored ) {
// this is fine
}
}
}
@Override
public int getDataFilesCount() {
return filesRepository.getDataFilesCount();
}
@Override
public JournalFile[] getDataFiles() {
return filesRepository.getDataFilesArray();
}
@Override
public int getFreeFilesCount() {
return filesRepository.getFreeFilesCount();
}
@Override
public int getOpenedFilesCount() {
return filesRepository.getOpenedFilesCount();
}
@Override
public int getIDMapSize() {
return records.size();
}
@Override
public int getFileSize() {
return fileSize;
}
@Override
public int getMinFiles() {
return minFiles;
}
@Override
public String getFilePrefix() {
return filesRepository.getFilePrefix();
}
@Override
public String getFileExtension() {
return filesRepository.getFileExtension();
}
@Override
public int getMaxAIO() {
return filesRepository.getMaxAIO();
}
@Override
public int getUserVersion() {
return userVersion;
}
// In some tests we need to force the journal to move to a next file
@Override
public void forceMoveNextFile() throws Exception {
debugWait();
journalLock.writeLock().lock();
try {
moveNextFile(false);
} finally {
journalLock.writeLock().unlock();
}
}
// ActiveMQComponent implementation
// ---------------------------------------------------
@Override
public synchronized boolean isStarted() {
return state != JournalState.STOPPED;
}
@Override
public synchronized void start() {
if (state != JournalState.STOPPED) {
throw new IllegalStateException("Journal " + this + " is not stopped, state is " + state);
}
if (providedIOThreadPool == null) {
ThreadFactory factory = AccessController.doPrivileged(new PrivilegedAction<ThreadFactory>() {
@Override
public ThreadFactory run() {
return new ActiveMQThreadFactory("ArtemisIOThread", true, JournalImpl.class.getClassLoader());
}
});
threadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L,TimeUnit.SECONDS, new SynchronousQueue(), factory);
ioExecutorFactory = new OrderedExecutorFactory(threadPool);
} else {
ioExecutorFactory = providedIOThreadPool;
}
filesExecutor = ioExecutorFactory.getExecutor();
compactorExecutor = ioExecutorFactory.getExecutor();
appendExecutor = ioExecutorFactory.getExecutor();
filesRepository.setExecutor(filesExecutor);
fileFactory.start();
setJournalState(JournalState.STARTED);
}
@Override
public synchronized void stop() throws Exception {
if (state == JournalState.STOPPED) {
return;
}
setJournalState(JournalState.STOPPED);
flush();
if (providedIOThreadPool == null) {
threadPool.shutdown();
if (!threadPool.awaitTermination(120, TimeUnit.SECONDS)) {
threadPool.shutdownNow();
}
threadPool = null;
ioExecutorFactory = null;
}
journalLock.writeLock().lock();
try {
try {
for (CountDownLatch latch : latches) {
latch.countDown();
}
} catch (Throwable e) {
ActiveMQJournalLogger.LOGGER.warn(e.getMessage(), e);
}
fileFactory.deactivateBuffer();
if (currentFile != null && currentFile.getFile().isOpen()) {
currentFile.getFile().close();
}
filesRepository.clear();
fileFactory.stop();
currentFile = null;
} finally {
journalLock.writeLock().unlock();
}
}
@Override
public int getNumberOfRecords() {
return records.size();
}
protected SequentialFile createControlFile(final List<JournalFile> files,
final List<JournalFile> newFiles,
final Pair<String, String> cleanupRename) throws Exception {
ArrayList<Pair<String, String>> cleanupList;
if (cleanupRename == null) {
cleanupList = null;
} else {
cleanupList = new ArrayList<>();
cleanupList.add(cleanupRename);
}
return AbstractJournalUpdateTask.writeControlFile(fileFactory, files, newFiles, cleanupList);
}
protected void deleteControlFile(final SequentialFile controlFile) throws Exception {
controlFile.delete();
}
/**
* being protected as testcases can override this method
*/
protected void renameFiles(final List<JournalFile> oldFiles, final List<JournalFile> newFiles) throws Exception {
// addFreeFiles has to be called through filesExecutor, or the fileID on the orderedFiles may end up in a wrong
// order
// These files are already freed, and are described on the compactor file control.
// In case of crash they will be cleared anyways
final CountDownLatch done = newLatch(1);
filesExecutor.execute(new Runnable() {
@Override
public void run() {
try {
for (JournalFile file : oldFiles) {
try {
filesRepository.addFreeFile(file, false);
} catch (Throwable e) {
ActiveMQJournalLogger.LOGGER.errorReinitializingFile(e, file);
}
}
} finally {
done.countDown();
}
}
});
// need to wait all old files to be freed
// to avoid a race where the CTR file is deleted before the init for these files is already done
// what could cause a duplicate in case of a crash after the CTR is deleted and before the file is initialized
awaitLatch(done, -1);
for (JournalFile file : newFiles) {
String newName = JournalImpl.renameExtensionFile(file.getFile().getFileName(), ".cmp");
file.getFile().renameTo(newName);
}
}
/**
* @param name
* @return
*/
protected static String renameExtensionFile(String name, final String extension) {
name = name.substring(0, name.lastIndexOf(extension));
return name;
}
/**
* This is an interception point for testcases, when the compacted files are written, before replacing the data structures
*/
protected void onCompactStart() throws Exception {
}
/**
* This is an interception point for testcases, when the compacted files are written, to be called
* as soon as the compactor gets a writeLock
*/
protected void onCompactLockingTheJournal() throws Exception {
}
/**
* This is an interception point for testcases, when the compacted files are written, before replacing the data structures
*/
protected void onCompactDone() {
}
// Private
// -----------------------------------------------------------------------------
/**
* <br>
* Checks for holes on the transaction (a commit written but with an incomplete transaction).
* <br>
* This method will validate if the transaction (PREPARE/COMMIT) is complete as stated on the
* COMMIT-RECORD.
* <br>
* For details see {@link JournalCompleteRecordTX} about how the transaction-summary is recorded.
*
* @param journalTransaction
* @param orderedFiles
* @param numberOfRecords
* @return
*/
private boolean checkTransactionHealth(final JournalFile currentFile,
final JournalTransaction journalTransaction,
final List<JournalFile> orderedFiles,
final int numberOfRecords) {
return journalTransaction.getCounter(currentFile) == numberOfRecords;
}
private static boolean isTransaction(final byte recordType) {
return recordType == JournalImpl.ADD_RECORD_TX || recordType == JournalImpl.UPDATE_RECORD_TX ||
recordType == JournalImpl.DELETE_RECORD_TX ||
JournalImpl.isCompleteTransaction(recordType);
}
private static boolean isCompleteTransaction(final byte recordType) {
return recordType == JournalImpl.COMMIT_RECORD || recordType == JournalImpl.PREPARE_RECORD ||
recordType == JournalImpl.ROLLBACK_RECORD;
}
private static boolean isContainsBody(final byte recordType) {
return recordType >= JournalImpl.ADD_RECORD && recordType <= JournalImpl.DELETE_RECORD_TX;
}
private static int getRecordSize(final byte recordType, final int journalVersion) {
// The record size (without the variable portion)
int recordSize = 0;
switch (recordType) {
case ADD_RECORD:
recordSize = JournalImpl.SIZE_ADD_RECORD;
break;
case UPDATE_RECORD:
recordSize = JournalImpl.SIZE_ADD_RECORD;
break;
case ADD_RECORD_TX:
recordSize = JournalImpl.SIZE_ADD_RECORD_TX;
break;
case UPDATE_RECORD_TX:
recordSize = JournalImpl.SIZE_ADD_RECORD_TX;
break;
case DELETE_RECORD:
recordSize = JournalImpl.SIZE_DELETE_RECORD;
break;
case DELETE_RECORD_TX:
recordSize = JournalImpl.SIZE_DELETE_RECORD_TX;
break;
case PREPARE_RECORD:
recordSize = JournalImpl.SIZE_PREPARE_RECORD;
break;
case COMMIT_RECORD:
recordSize = JournalImpl.SIZE_COMMIT_RECORD;
break;
case ROLLBACK_RECORD:
recordSize = JournalImpl.SIZE_ROLLBACK_RECORD;
break;
default:
// Sanity check, this was previously tested, nothing different
// should be on this switch
throw new IllegalStateException("Record other than expected");
}
if (journalVersion >= 2) {
return recordSize + 1;
} else {
return recordSize;
}
}
/**
* @param file
* @return
* @throws Exception
*/
private JournalFileImpl readFileHeader(final SequentialFile file) throws Exception {
ByteBuffer bb = fileFactory.newBuffer(JournalImpl.SIZE_HEADER);
file.read(bb);
int journalVersion = bb.getInt();
if (journalVersion != JournalImpl.FORMAT_VERSION) {
boolean isCompatible = false;
for (int v : JournalImpl.COMPATIBLE_VERSIONS) {
if (v == journalVersion) {
isCompatible = true;
}
}
if (!isCompatible) {
throw ActiveMQJournalBundle.BUNDLE.journalFileMisMatch();
}
}
int readUserVersion = bb.getInt();
if (readUserVersion != userVersion) {
throw ActiveMQJournalBundle.BUNDLE.journalDifferentVersion();
}
long fileID = bb.getLong();
fileFactory.releaseBuffer(bb);
bb = null;
return new JournalFileImpl(file, fileID, journalVersion);
}
/**
* @param fileID
* @param sequentialFile
* @throws Exception
*/
public static int initFileHeader(final SequentialFileFactory fileFactory,
final SequentialFile sequentialFile,
final int userVersion,
final long fileID) throws Exception {
// We don't need to release buffers while writing.
ByteBuffer bb = fileFactory.newBuffer(JournalImpl.SIZE_HEADER);
ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(bb);
try {
JournalImpl.writeHeader(buffer, userVersion, fileID);
bb.rewind();
int bufferSize = bb.limit();
sequentialFile.position(0);
sequentialFile.writeDirect(bb, true);
return bufferSize;
} finally {
// release it by first unwrap the unreleasable buffer and then release it.
buffer.byteBuf().unwrap().release();
}
}
/**
* @param buffer
* @param userVersion
* @param fileID
*/
public static void writeHeader(final ActiveMQBuffer buffer, final int userVersion, final long fileID) {
buffer.writeInt(JournalImpl.FORMAT_VERSION);
buffer.writeInt(userVersion);
buffer.writeLong(fileID);
}
/**
* @param completeTransaction If the appendRecord is for a prepare or commit, where we should
* update the number of pendingTransactions on the current file
* @throws Exception
*/
private JournalFile appendRecord(final JournalInternalRecord encoder,
final boolean completeTransaction,
final boolean sync,
final JournalTransaction tx,
final IOCallback parameterCallback) throws Exception {
final IOCallback callback;
final int size = encoder.getEncodeSize();
switchFileIfNecessary(size);
if (tx != null) {
// The callback of a transaction has to be taken inside the lock,
// when we guarantee the currentFile will not be changed,
// since we individualize the callback per file
if (fileFactory.isSupportsCallbacks()) {
// Set the delegated callback as a parameter
TransactionCallback txcallback = tx.getCallback(currentFile);
if (parameterCallback != null) {
txcallback.setDelegateCompletion(parameterCallback);
}
callback = txcallback;
} else {
callback = null;
}
// We need to add the number of records on currentFile if prepare or commit
if (completeTransaction) {
// Filling the number of pendingTransactions at the current file
tx.fillNumberOfRecords(currentFile, encoder);
}
} else {
callback = parameterCallback;
}
// Adding fileID
encoder.setFileID(currentFile.getRecordID());
if (callback != null) {
currentFile.getFile().write(encoder, sync, callback);
} else {
currentFile.getFile().write(encoder, sync);
}
return currentFile;
}
@Override
void scheduleReclaim() {
if (state != JournalState.LOADED) {
return;
}
if (isAutoReclaim() && !compactorRunning.get()) {
compactorExecutor.execute(new Runnable() {
@Override
public void run() {
try {
if (!checkReclaimStatus()) {
checkCompact();
}
} catch (Exception e) {
ActiveMQJournalLogger.LOGGER.errorSchedulingCompacting(e);
}
}
});
}
}
private JournalTransaction getTransactionInfo(final long txID) {
JournalTransaction tx = transactions.get(txID);
if (tx == null) {
tx = new JournalTransaction(txID, this);
JournalTransaction trans = transactions.putIfAbsent(txID, tx);
if (trans != null) {
tx = trans;
}
}
return tx;
}
/**
* @throws Exception
*/
private void checkControlFile() throws Exception {
ArrayList<String> dataFiles = new ArrayList<>();
ArrayList<String> newFiles = new ArrayList<>();
ArrayList<Pair<String, String>> renames = new ArrayList<>();
SequentialFile controlFile = JournalCompactor.readControlFile(fileFactory, dataFiles, newFiles, renames);
if (controlFile != null) {
for (String dataFile : dataFiles) {
SequentialFile file = fileFactory.createSequentialFile(dataFile);
if (file.exists()) {
file.delete();
}
}
for (String newFile : newFiles) {
SequentialFile file = fileFactory.createSequentialFile(newFile);
if (file.exists()) {
final String originalName = file.getFileName();
final String newName = originalName.substring(0, originalName.lastIndexOf(".cmp"));
file.renameTo(newName);
}
}
for (Pair<String, String> rename : renames) {
SequentialFile fileTmp = fileFactory.createSequentialFile(rename.getA());
SequentialFile fileTo = fileFactory.createSequentialFile(rename.getB());
// We should do the rename only if the tmp file still exist, or else we could
// delete a valid file depending on where the crash occurred during the control file delete
if (fileTmp.exists()) {
fileTo.delete();
fileTmp.renameTo(rename.getB());
}
}
controlFile.delete();
}
cleanupTmpFiles(".cmp");
cleanupTmpFiles(".tmp");
return;
}
/**
* @throws Exception
*/
private void cleanupTmpFiles(final String extension) throws Exception {
List<String> leftFiles = fileFactory.listFiles(getFileExtension() + extension);
if (leftFiles.size() > 0) {
ActiveMQJournalLogger.LOGGER.tempFilesLeftOpen();
for (String fileToDelete : leftFiles) {
ActiveMQJournalLogger.LOGGER.deletingOrphanedFile(fileToDelete);
SequentialFile file = fileFactory.createSequentialFile(fileToDelete);
file.delete();
}
}
}
private static boolean isInvalidSize(final int fileSize, final int bufferPos, final int size) {
if (size < 0) {
return true;
} else {
final int position = bufferPos + size;
return position > fileSize || position < 0;
}
}
// Inner classes
// ---------------------------------------------------------------------------
// Used on Load
private static final class TransactionHolder {
private TransactionHolder(final long id) {
transactionID = id;
}
public final long transactionID;
public final List<RecordInfo> recordInfos = new ArrayList<>();
public final List<RecordInfo> recordsToDelete = new ArrayList<>();
public boolean prepared;
public boolean invalid;
public byte[] extraData;
}
private static final class JournalFileComparator implements Comparator<JournalFile>, Serializable {
private static final long serialVersionUID = -6264728973604070321L;
@Override
public int compare(final JournalFile f1, final JournalFile f2) {
long id1 = f1.getFileID();
long id2 = f2.getFileID();
return id1 < id2 ? -1 : id1 == id2 ? 0 : 1;
}
}
@Override
public final void synchronizationLock() {
compactorLock.writeLock().lock();
journalLock.writeLock().lock();
}
@Override
public final void synchronizationUnlock() {
try {
compactorLock.writeLock().unlock();
} finally {
journalLock.writeLock().unlock();
}
}
/**
* Returns Map with a {@link JournalFile} for all existing files.
*
* These are the files needed to be sent to a backup in order to synchronize it.
*
* @param fileIds
* @return map with the IDs and corresponding {@link JournalFile}s
* @throws Exception
*/
@Override
public synchronized Map<Long, JournalFile> createFilesForBackupSync(long[] fileIds) throws Exception {
synchronizationLock();
try {
Map<Long, JournalFile> map = new HashMap<>();
long maxID = -1;
for (long id : fileIds) {
maxID = Math.max(maxID, id);
map.put(id, filesRepository.createRemoteBackupSyncFile(id));
}
filesRepository.setNextFileID(maxID);
return map;
} finally {
synchronizationUnlock();
}
}
@Override
public SequentialFileFactory getFileFactory() {
return fileFactory;
}
/**
* @param lastDataPos
* @return
* @throws Exception
*/
protected JournalFile setUpCurrentFile(int lastDataPos) throws Exception {
// Create any more files we need
filesRepository.ensureMinFiles();
// The current file is the last one that has data
currentFile = filesRepository.pollLastDataFile();
if (currentFile != null) {
if (!currentFile.getFile().isOpen())
currentFile.getFile().open();
currentFile.getFile().position(currentFile.getFile().calculateBlockStart(lastDataPos));
} else {
currentFile = filesRepository.getFreeFile();
filesRepository.openFile(currentFile, true);
}
fileFactory.activateBuffer(currentFile.getFile());
filesRepository.pushOpenedFile();
return currentFile;
}
/**
* @param size
* @return
* @throws Exception
*/
protected JournalFile switchFileIfNecessary(int size) throws Exception {
// We take into account the fileID used on the Header
if (size > fileSize - currentFile.getFile().calculateBlockStart(JournalImpl.SIZE_HEADER)) {
throw new IllegalArgumentException("Record is too large to store " + size);
}
if (!currentFile.getFile().fits(size)) {
moveNextFile(true);
// The same check needs to be done at the new file also
if (!currentFile.getFile().fits(size)) {
// Sanity check, this should never happen
throw new IllegalStateException("Invalid logic on buffer allocation");
}
}
return currentFile;
}
private CountDownLatch newLatch(int countDown) {
if (state == JournalState.STOPPED) {
throw new RuntimeException("Server is not started");
}
CountDownLatch latch = new CountDownLatch(countDown);
latches.add(latch);
return latch;
}
private void awaitLatch(CountDownLatch latch, int timeout) throws InterruptedException {
try {
if (timeout < 0) {
latch.await();
} else {
latch.await(timeout, TimeUnit.SECONDS);
}
// in case of an interrupted server, we need to make sure we don't proceed on anything
if (state == JournalState.STOPPED) {
throw new RuntimeException("Server is not started");
}
} finally {
latches.remove(latch);
}
}
/**
* You need to guarantee lock.acquire() before calling this method!
*/
private void moveNextFile(final boolean scheduleReclaim) throws Exception {
filesRepository.closeFile(currentFile);
currentFile = filesRepository.openFile();
if (scheduleReclaim) {
scheduleReclaim();
}
if (logger.isTraceEnabled()) {
logger.trace("Moving next file " + currentFile);
}
fileFactory.activateBuffer(currentFile.getFile());
}
@Override
public void replicationSyncPreserveOldFiles() {
setAutoReclaim(false);
}
@Override
public void replicationSyncFinished() {
setAutoReclaim(true);
}
@Override
public void testCompact() {
try {
scheduleCompactAndBlock(60);
} catch (Exception e) {
logger.warn("Error during compact", e.getMessage(), e);
throw new RuntimeException(e);
}
}
/**
* For tests only
*/
public int getCompactCount() {
return compactCount;
}
}
| {
"content_hash": "519fe18bca3f017626e8d7a2e246f8b7",
"timestamp": "",
"source": "github",
"line_count": 2874,
"max_line_length": 148,
"avg_line_length": 34.48016701461378,
"alnum_prop": 0.5768951319932187,
"repo_name": "mtaylor/activemq-artemis",
"id": "24bb91607d5a4b5dc5fdb069a025057f88beccb3",
"size": "99895",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "artemis-journal/src/main/java/org/apache/activemq/artemis/core/journal/impl/JournalImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "11634"
},
{
"name": "C",
"bytes": "26484"
},
{
"name": "C++",
"bytes": "1197"
},
{
"name": "CMake",
"bytes": "4260"
},
{
"name": "CSS",
"bytes": "11732"
},
{
"name": "HTML",
"bytes": "19329"
},
{
"name": "Java",
"bytes": "23916388"
},
{
"name": "Shell",
"bytes": "34875"
}
],
"symlink_target": ""
} |
package ninja.utils;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* CookieDataCodec and CookieDataCodecTest are imported from Play Framework.
*
* Enables us to use the same sessions as Play Framework if
* the secret is the same.
*
* Also really important because we want to make sure that our client
* side session mechanism is widely used and stable.
* We don't want to reinvent
* the wheel of securely encoding / decoding and signing cookie data.
*
* All praise goes to Play Framework and their awesome work.
*
*/
public class NinjaModeHelperTest {
@Test
public void testNinjaModeHelperWorksWithNoModeSet() {
assertEquals(false, NinjaModeHelper.determineModeFromSystemProperties().isPresent());
assertEquals(NinjaMode.prod, NinjaModeHelper.determineModeFromSystemPropertiesOrProdIfNotSet());
}
@Test
public void testNinjaModeHelperWorksWithTestSet() {
System.setProperty(NinjaConstant.MODE_KEY_NAME, NinjaConstant.MODE_TEST);
assertEquals(NinjaMode.test, NinjaModeHelper.determineModeFromSystemProperties().get());
assertEquals(NinjaMode.test, NinjaModeHelper.determineModeFromSystemPropertiesOrProdIfNotSet());
System.clearProperty(NinjaConstant.MODE_KEY_NAME);
}
@Test
public void testNinjaModeHelperWorksWithDevSet() {
System.setProperty(NinjaConstant.MODE_KEY_NAME, NinjaConstant.MODE_DEV);
assertEquals(NinjaMode.dev, NinjaModeHelper.determineModeFromSystemProperties().get());
assertEquals(NinjaMode.dev, NinjaModeHelper.determineModeFromSystemPropertiesOrProdIfNotSet());
System.clearProperty(NinjaConstant.MODE_KEY_NAME);
}
@Test
public void testNinjaModeHelperWorksWithProdSet() {
System.setProperty(NinjaConstant.MODE_KEY_NAME, NinjaConstant.MODE_PROD);
assertEquals(NinjaMode.prod, NinjaModeHelper.determineModeFromSystemProperties().get());
assertEquals(NinjaMode.prod, NinjaModeHelper.determineModeFromSystemPropertiesOrProdIfNotSet());
System.clearProperty(NinjaConstant.MODE_KEY_NAME);
}
}
| {
"content_hash": "aee69621bec1560b51cda39a2155ca06",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 104,
"avg_line_length": 33.220588235294116,
"alnum_prop": 0.7118193891102258,
"repo_name": "StetsiukRoman/ninja",
"id": "948a9bad7cb37fb29ec848878c33e32f629ce34c",
"size": "2883",
"binary": false,
"copies": "16",
"ref": "refs/heads/develop",
"path": "ninja-core/src/test/java/ninja/utils/NinjaModeHelperTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5574"
},
{
"name": "HTML",
"bytes": "59715"
},
{
"name": "Java",
"bytes": "1484901"
}
],
"symlink_target": ""
} |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1998
Desugaring foreign declarations (see also DsCCall).
-}
{-# LANGUAGE CPP #-}
module DsForeign ( dsForeigns
, dsForeigns'
, dsFImport, dsCImport, dsFCall, dsPrimCall
, dsFExport, dsFExportDynamic, mkFExportCBits
, toCType
, foreignExportInitialiser
) where
#include "HsVersions.h"
import TcRnMonad -- temp
import TypeRep
import CoreSyn
import DsCCall
import DsMonad
import HsSyn
import DataCon
import CoreUnfold
import Id
import Literal
import Module
import Name
import Type
import TyCon
import Coercion
import TcEnv
import TcType
import CmmExpr
import CmmUtils
import HscTypes
import ForeignCall
import TysWiredIn
import TysPrim
import PrelNames
import BasicTypes
import SrcLoc
import Outputable
import FastString
import DynFlags
import Platform
import Config
import OrdList
import Pair
import Util
import Hooks
import Data.Maybe
import Data.List
{-
Desugaring of @foreign@ declarations is naturally split up into
parts, an @import@ and an @export@ part. A @foreign import@
declaration
\begin{verbatim}
foreign import cc nm f :: prim_args -> IO prim_res
\end{verbatim}
is the same as
\begin{verbatim}
f :: prim_args -> IO prim_res
f a1 ... an = _ccall_ nm cc a1 ... an
\end{verbatim}
so we reuse the desugaring code in @DsCCall@ to deal with these.
-}
type Binding = (Id, CoreExpr) -- No rec/nonrec structure;
-- the occurrence analyser will sort it all out
dsForeigns :: [LForeignDecl Id]
-> DsM (ForeignStubs, OrdList Binding)
dsForeigns fos = getHooked dsForeignsHook dsForeigns' >>= ($ fos)
dsForeigns' :: [LForeignDecl Id]
-> DsM (ForeignStubs, OrdList Binding)
dsForeigns' []
= return (NoStubs, nilOL)
dsForeigns' fos = do
fives <- mapM do_ldecl fos
let
(hs, cs, idss, bindss) = unzip4 fives
fe_ids = concat idss
fe_init_code = map foreignExportInitialiser fe_ids
--
return (ForeignStubs
(vcat hs)
(vcat cs $$ vcat fe_init_code),
foldr (appOL . toOL) nilOL bindss)
where
do_ldecl (L loc decl) = putSrcSpanDs loc (do_decl decl)
do_decl (ForeignImport id _ co spec) = do
traceIf (text "fi start" <+> ppr id)
(bs, h, c) <- dsFImport (unLoc id) co spec
traceIf (text "fi end" <+> ppr id)
return (h, c, [], bs)
do_decl (ForeignExport (L _ id) _ co
(CExport (L _ (CExportStatic _ ext_nm cconv)) _)) = do
(h, c, _, _) <- dsFExport id co ext_nm cconv False
return (h, c, [id], [])
{-
************************************************************************
* *
\subsection{Foreign import}
* *
************************************************************************
Desugaring foreign imports is just the matter of creating a binding
that on its RHS unboxes its arguments, performs the external call
(using the @CCallOp@ primop), before boxing the result up and returning it.
However, we create a worker/wrapper pair, thus:
foreign import f :: Int -> IO Int
==>
f x = IO ( \s -> case x of { I# x# ->
case fw s x# of { (# s1, y# #) ->
(# s1, I# y# #)}})
fw s x# = ccall f s x#
The strictness/CPR analyser won't do this automatically because it doesn't look
inside returned tuples; but inlining this wrapper is a Really Good Idea
because it exposes the boxing to the call site.
-}
dsFImport :: Id
-> Coercion
-> ForeignImport
-> DsM ([Binding], SDoc, SDoc)
dsFImport id co (CImport cconv safety mHeader spec _) = do
(ids, h, c) <- dsCImport id co spec (unLoc cconv) (unLoc safety) mHeader
return (ids, h, c)
dsCImport :: Id
-> Coercion
-> CImportSpec
-> CCallConv
-> Safety
-> Maybe Header
-> DsM ([Binding], SDoc, SDoc)
dsCImport id co (CLabel cid) cconv _ _ = do
dflags <- getDynFlags
let ty = pFst $ coercionKind co
fod = case tyConAppTyCon_maybe (dropForAlls ty) of
Just tycon
| tyConUnique tycon == funPtrTyConKey ->
IsFunction
_ -> IsData
(resTy, foRhs) <- resultWrapper ty
ASSERT(fromJust resTy `eqType` addrPrimTy) -- typechecker ensures this
let
rhs = foRhs (Lit (MachLabel cid stdcall_info fod))
rhs' = Cast rhs co
stdcall_info = fun_type_arg_stdcall_info dflags cconv ty
in
return ([(id, rhs')], empty, empty)
dsCImport id co (CFunction target) cconv@PrimCallConv safety _
= dsPrimCall id co (CCall (CCallSpec target cconv safety))
dsCImport id co (CFunction target) cconv safety mHeader
= dsFCall id co (CCall (CCallSpec target cconv safety)) mHeader
dsCImport id co CWrapper cconv _ _
= dsFExportDynamic id co cconv
-- For stdcall labels, if the type was a FunPtr or newtype thereof,
-- then we need to calculate the size of the arguments in order to add
-- the @n suffix to the label.
fun_type_arg_stdcall_info :: DynFlags -> CCallConv -> Type -> Maybe Int
fun_type_arg_stdcall_info dflags StdCallConv ty
| Just (tc,[arg_ty]) <- splitTyConApp_maybe ty,
tyConUnique tc == funPtrTyConKey
= let
(_tvs,sans_foralls) = tcSplitForAllTys arg_ty
(fe_arg_tys, _orig_res_ty) = tcSplitFunTys sans_foralls
in Just $ sum (map (widthInBytes . typeWidth . typeCmmType dflags . getPrimTyOf) fe_arg_tys)
fun_type_arg_stdcall_info _ _other_conv _
= Nothing
{-
************************************************************************
* *
\subsection{Foreign calls}
* *
************************************************************************
-}
dsFCall :: Id -> Coercion -> ForeignCall -> Maybe Header
-> DsM ([(Id, Expr TyVar)], SDoc, SDoc)
dsFCall fn_id co fcall mDeclHeader = do
let
ty = pFst $ coercionKind co
(tvs, fun_ty) = tcSplitForAllTys ty
(arg_tys, io_res_ty) = tcSplitFunTys fun_ty
-- Must use tcSplit* functions because we want to
-- see that (IO t) in the corner
args <- newSysLocalsDs arg_tys
(val_args, arg_wrappers) <- mapAndUnzipM unboxArg (map Var args)
let
work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars
(ccall_result_ty, res_wrapper) <- boxResult io_res_ty
ccall_uniq <- newUnique
work_uniq <- newUnique
dflags <- getDynFlags
(fcall', cDoc) <-
case fcall of
CCall (CCallSpec (StaticTarget _ cName mUnitId isFun)
CApiConv safety) ->
do wrapperName <- mkWrapperName "ghc_wrapper" (unpackFS cName)
let fcall' = CCall (CCallSpec
(StaticTarget (unpackFS wrapperName)
wrapperName mUnitId
True)
CApiConv safety)
c = includes
$$ fun_proto <+> braces (cRet <> semi)
includes = vcat [ text "#include <" <> ftext h <> text ">"
| Header _ h <- nub headers ]
fun_proto = cResType <+> pprCconv <+> ppr wrapperName <> parens argTypes
cRet
| isVoidRes = cCall
| otherwise = text "return" <+> cCall
cCall = if isFun
then ppr cName <> parens argVals
else if null arg_tys
then ppr cName
else panic "dsFCall: Unexpected arguments to FFI value import"
raw_res_ty = case tcSplitIOType_maybe io_res_ty of
Just (_ioTyCon, res_ty) -> res_ty
Nothing -> io_res_ty
isVoidRes = raw_res_ty `eqType` unitTy
(mHeader, cResType)
| isVoidRes = (Nothing, text "void")
| otherwise = toCType raw_res_ty
pprCconv = ccallConvAttribute CApiConv
mHeadersArgTypeList
= [ (header, cType <+> char 'a' <> int n)
| (t, n) <- zip arg_tys [1..]
, let (header, cType) = toCType t ]
(mHeaders, argTypeList) = unzip mHeadersArgTypeList
argTypes = if null argTypeList
then text "void"
else hsep $ punctuate comma argTypeList
mHeaders' = mDeclHeader : mHeader : mHeaders
headers = catMaybes mHeaders'
argVals = hsep $ punctuate comma
[ char 'a' <> int n
| (_, n) <- zip arg_tys [1..] ]
return (fcall', c)
_ ->
return (fcall, empty)
let
-- Build the worker
worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty)
the_ccall_app = mkFCall dflags ccall_uniq fcall' val_args ccall_result_ty
work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app)
work_id = mkSysLocal (fsLit "$wccall") work_uniq worker_ty
-- Build the wrapper
work_app = mkApps (mkVarApps (Var work_id) tvs) val_args
wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers
wrap_rhs = mkLams (tvs ++ args) wrapper_body
wrap_rhs' = Cast wrap_rhs co
fn_id_w_inl = fn_id `setIdUnfolding` mkInlineUnfolding (Just (length args)) wrap_rhs'
return ([(work_id, work_rhs), (fn_id_w_inl, wrap_rhs')], empty, cDoc)
{-
************************************************************************
* *
\subsection{Primitive calls}
* *
************************************************************************
This is for `@foreign import prim@' declarations.
Currently, at the core level we pretend that these primitive calls are
foreign calls. It may make more sense in future to have them as a distinct
kind of Id, or perhaps to bundle them with PrimOps since semantically and
for calling convention they are really prim ops.
-}
dsPrimCall :: Id -> Coercion -> ForeignCall
-> DsM ([(Id, Expr TyVar)], SDoc, SDoc)
dsPrimCall fn_id co fcall = do
let
ty = pFst $ coercionKind co
(tvs, fun_ty) = tcSplitForAllTys ty
(arg_tys, io_res_ty) = tcSplitFunTys fun_ty
-- Must use tcSplit* functions because we want to
-- see that (IO t) in the corner
args <- newSysLocalsDs arg_tys
ccall_uniq <- newUnique
dflags <- getDynFlags
let
call_app = mkFCall dflags ccall_uniq fcall (map Var args) io_res_ty
rhs = mkLams tvs (mkLams args call_app)
rhs' = Cast rhs co
return ([(fn_id, rhs')], empty, empty)
{-
************************************************************************
* *
\subsection{Foreign export}
* *
************************************************************************
The function that does most of the work for `@foreign export@' declarations.
(see below for the boilerplate code a `@foreign export@' declaration expands
into.)
For each `@foreign export foo@' in a module M we generate:
\begin{itemize}
\item a C function `@foo@', which calls
\item a Haskell stub `@M.\$ffoo@', which calls
\end{itemize}
the user-written Haskell function `@M.foo@'.
-}
dsFExport :: Id -- Either the exported Id,
-- or the foreign-export-dynamic constructor
-> Coercion -- Coercion between the Haskell type callable
-- from C, and its representation type
-> CLabelString -- The name to export to C land
-> CCallConv
-> Bool -- True => foreign export dynamic
-- so invoke IO action that's hanging off
-- the first argument's stable pointer
-> DsM ( SDoc -- contents of Module_stub.h
, SDoc -- contents of Module_stub.c
, String -- string describing type to pass to createAdj.
, Int -- size of args to stub function
)
dsFExport fn_id co ext_name cconv isDyn = do
let
ty = pSnd $ coercionKind co
(_tvs,sans_foralls) = tcSplitForAllTys ty
(fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls
-- We must use tcSplits here, because we want to see
-- the (IO t) in the corner of the type!
fe_arg_tys | isDyn = tail fe_arg_tys'
| otherwise = fe_arg_tys'
-- Look at the result type of the exported function, orig_res_ty
-- If it's IO t, return (t, True)
-- If it's plain t, return (t, False)
(res_ty, is_IO_res_ty) = case tcSplitIOType_maybe orig_res_ty of
-- The function already returns IO t
Just (_ioTyCon, res_ty) -> (res_ty, True)
-- The function returns t
Nothing -> (orig_res_ty, False)
dflags <- getDynFlags
return $
mkFExportCBits dflags ext_name
(if isDyn then Nothing else Just fn_id)
fe_arg_tys res_ty is_IO_res_ty cconv
{-
@foreign import "wrapper"@ (previously "foreign export dynamic") lets
you dress up Haskell IO actions of some fixed type behind an
externally callable interface (i.e., as a C function pointer). Useful
for callbacks and stuff.
\begin{verbatim}
type Fun = Bool -> Int -> IO Int
foreign import "wrapper" f :: Fun -> IO (FunPtr Fun)
-- Haskell-visible constructor, which is generated from the above:
-- SUP: No check for NULL from createAdjustor anymore???
f :: Fun -> IO (FunPtr Fun)
f cback =
bindIO (newStablePtr cback)
(\StablePtr sp# -> IO (\s1# ->
case _ccall_ createAdjustor cconv sp# ``f_helper'' <arg info> s1# of
(# s2#, a# #) -> (# s2#, A# a# #)))
foreign import "&f_helper" f_helper :: FunPtr (StablePtr Fun -> Fun)
-- and the helper in C: (approximately; see `mkFExportCBits` below)
f_helper(StablePtr s, HsBool b, HsInt i)
{
Capability *cap;
cap = rts_lock();
rts_evalIO(&cap,
rts_apply(rts_apply(deRefStablePtr(s),
rts_mkBool(b)), rts_mkInt(i)));
rts_unlock(cap);
}
\end{verbatim}
-}
dsFExportDynamic :: Id
-> Coercion
-> CCallConv
-> DsM ([Binding], SDoc, SDoc)
dsFExportDynamic id co0 cconv = do
fe_id <- newSysLocalDs ty
mod <- getModule
dflags <- getDynFlags
let
-- hack: need to get at the name of the C stub we're about to generate.
-- TODO: There's no real need to go via String with
-- (mkFastString . zString). In fact, is there a reason to convert
-- to FastString at all now, rather than sticking with FastZString?
fe_nm = mkFastString (zString (zEncodeFS (moduleNameFS (moduleName mod))) ++ "_" ++ toCName dflags fe_id)
cback <- newSysLocalDs arg_ty
newStablePtrId <- dsLookupGlobalId newStablePtrName
stable_ptr_tycon <- dsLookupTyCon stablePtrTyConName
let
stable_ptr_ty = mkTyConApp stable_ptr_tycon [arg_ty]
export_ty = mkFunTy stable_ptr_ty arg_ty
bindIOId <- dsLookupGlobalId bindIOName
stbl_value <- newSysLocalDs stable_ptr_ty
(h_code, c_code, typestring, args_size) <- dsFExport id (mkReflCo Representational export_ty) fe_nm cconv True
let
{-
The arguments to the external function which will
create a little bit of (template) code on the fly
for allowing the (stable pointed) Haskell closure
to be entered using an external calling convention
(stdcall, ccall).
-}
adj_args = [ mkIntLitInt dflags (ccallConvToInt cconv)
, Var stbl_value
, Lit (MachLabel fe_nm mb_sz_args IsFunction)
, Lit (mkMachString typestring)
]
-- name of external entry point providing these services.
-- (probably in the RTS.)
adjustor = fsLit "createAdjustor"
-- Determine the number of bytes of arguments to the stub function,
-- so that we can attach the '@N' suffix to its label if it is a
-- stdcall on Windows.
mb_sz_args = case cconv of
StdCallConv -> Just args_size
_ -> Nothing
ccall_adj <- dsCCall adjustor adj_args PlayRisky (mkTyConApp io_tc [res_ty])
-- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback
let io_app = mkLams tvs $
Lam cback $
mkApps (Var bindIOId)
[ Type stable_ptr_ty
, Type res_ty
, mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ]
, Lam stbl_value ccall_adj
]
fed = (id `setInlineActivation` NeverActive, Cast io_app co0)
-- Never inline the f.e.d. function, because the litlit
-- might not be in scope in other modules.
return ([fed], h_code, c_code)
where
ty = pFst (coercionKind co0)
(tvs,sans_foralls) = tcSplitForAllTys ty
([arg_ty], fn_res_ty) = tcSplitFunTys sans_foralls
Just (io_tc, res_ty) = tcSplitIOType_maybe fn_res_ty
-- Must have an IO type; hence Just
toCName :: DynFlags -> Id -> String
toCName dflags i = showSDoc dflags (pprCode CStyle (ppr (idName i)))
{-
*
\subsection{Generating @foreign export@ stubs}
*
For each @foreign export@ function, a C stub function is generated.
The C stub constructs the application of the exported Haskell function
using the hugs/ghc rts invocation API.
-}
mkFExportCBits :: DynFlags
-> FastString
-> Maybe Id -- Just==static, Nothing==dynamic
-> [Type]
-> Type
-> Bool -- True <=> returns an IO type
-> CCallConv
-> (SDoc,
SDoc,
String, -- the argument reps
Int -- total size of arguments
)
mkFExportCBits dflags c_nm maybe_target arg_htys res_hty is_IO_res_ty cc
= (header_bits, c_bits, type_string,
sum [ widthInBytes (typeWidth rep) | (_,_,_,rep) <- aug_arg_info] -- all the args
-- NB. the calculation here isn't strictly speaking correct.
-- We have a primitive Haskell type (eg. Int#, Double#), and
-- we want to know the size, when passed on the C stack, of
-- the associated C type (eg. HsInt, HsDouble). We don't have
-- this information to hand, but we know what GHC's conventions
-- are for passing around the primitive Haskell types, so we
-- use that instead. I hope the two coincide --SDM
)
where
-- list the arguments to the C function
arg_info :: [(SDoc, -- arg name
SDoc, -- C type
Type, -- Haskell type
CmmType)] -- the CmmType
arg_info = [ let stg_type = showStgType ty in
(arg_cname n stg_type,
stg_type,
ty,
typeCmmType dflags (getPrimTyOf ty))
| (ty,n) <- zip arg_htys [1::Int ..] ]
arg_cname n stg_ty
| libffi = char '*' <> parens (stg_ty <> char '*') <>
ptext (sLit "args") <> brackets (int (n-1))
| otherwise = text ('a':show n)
-- generate a libffi-style stub if this is a "wrapper" and libffi is enabled
libffi = cLibFFI && isNothing maybe_target
type_string
-- libffi needs to know the result type too:
| libffi = primTyDescChar dflags res_hty : arg_type_string
| otherwise = arg_type_string
arg_type_string = [primTyDescChar dflags ty | (_,_,ty,_) <- arg_info]
-- just the real args
-- add some auxiliary args; the stable ptr in the wrapper case, and
-- a slot for the dummy return address in the wrapper + ccall case
aug_arg_info
| isNothing maybe_target = stable_ptr_arg : insertRetAddr dflags cc arg_info
| otherwise = arg_info
stable_ptr_arg =
(text "the_stableptr", text "StgStablePtr", undefined,
typeCmmType dflags (mkStablePtrPrimTy alphaTy))
-- stuff to do with the return type of the C function
res_hty_is_unit = res_hty `eqType` unitTy -- Look through any newtypes
cResType | res_hty_is_unit = text "void"
| otherwise = showStgType res_hty
-- when the return type is integral and word-sized or smaller, it
-- must be assigned as type ffi_arg (#3516). To see what type
-- libffi is expecting here, take a look in its own testsuite, e.g.
-- libffi/testsuite/libffi.call/cls_align_ulonglong.c
ffi_cResType
| is_ffi_arg_type = text "ffi_arg"
| otherwise = cResType
where
res_ty_key = getUnique (getName (typeTyCon res_hty))
is_ffi_arg_type = res_ty_key `notElem`
[floatTyConKey, doubleTyConKey,
int64TyConKey, word64TyConKey]
-- Now we can cook up the prototype for the exported function.
pprCconv = ccallConvAttribute cc
header_bits = ptext (sLit "extern") <+> fun_proto <> semi
fun_args
| null aug_arg_info = text "void"
| otherwise = hsep $ punctuate comma
$ map (\(nm,ty,_,_) -> ty <+> nm) aug_arg_info
fun_proto
| libffi
= ptext (sLit "void") <+> ftext c_nm <>
parens (ptext (sLit "void *cif STG_UNUSED, void* resp, void** args, void* the_stableptr"))
| otherwise
= cResType <+> pprCconv <+> ftext c_nm <> parens fun_args
-- the target which will form the root of what we ask rts_evalIO to run
the_cfun
= case maybe_target of
Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)"
Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure"
cap = text "cap" <> comma
-- the expression we give to rts_evalIO
expr_to_run
= foldl appArg the_cfun arg_info -- NOT aug_arg_info
where
appArg acc (arg_cname, _, arg_hty, _)
= text "rts_apply"
<> parens (cap <> acc <> comma <> mkHObj arg_hty <> parens (cap <> arg_cname))
-- various other bits for inside the fn
declareResult = text "HaskellObj ret;"
declareCResult | res_hty_is_unit = empty
| otherwise = cResType <+> text "cret;"
assignCResult | res_hty_is_unit = empty
| otherwise =
text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi
-- an extern decl for the fn being called
extern_decl
= case maybe_target of
Nothing -> empty
Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi
-- finally, the whole darn thing
c_bits =
space $$
extern_decl $$
fun_proto $$
vcat
[ lbrace
, ptext (sLit "Capability *cap;")
, declareResult
, declareCResult
, text "cap = rts_lock();"
-- create the application + perform it.
, ptext (sLit "rts_evalIO") <> parens (
char '&' <> cap <>
ptext (sLit "rts_apply") <> parens (
cap <>
text "(HaskellObj)"
<> ptext (if is_IO_res_ty
then (sLit "runIO_closure")
else (sLit "runNonIO_closure"))
<> comma
<> expr_to_run
) <+> comma
<> text "&ret"
) <> semi
, ptext (sLit "rts_checkSchedStatus") <> parens (doubleQuotes (ftext c_nm)
<> comma <> text "cap") <> semi
, assignCResult
, ptext (sLit "rts_unlock(cap);")
, ppUnless res_hty_is_unit $
if libffi
then char '*' <> parens (ffi_cResType <> char '*') <>
ptext (sLit "resp = cret;")
else ptext (sLit "return cret;")
, rbrace
]
foreignExportInitialiser :: Id -> SDoc
foreignExportInitialiser hs_fn =
-- Initialise foreign exports by registering a stable pointer from an
-- __attribute__((constructor)) function.
-- The alternative is to do this from stginit functions generated in
-- codeGen/CodeGen.hs; however, stginit functions have a negative impact
-- on binary sizes and link times because the static linker will think that
-- all modules that are imported directly or indirectly are actually used by
-- the program.
-- (this is bad for big umbrella modules like Graphics.Rendering.OpenGL)
vcat
[ text "static void stginit_export_" <> ppr hs_fn
<> text "() __attribute__((constructor));"
, text "static void stginit_export_" <> ppr hs_fn <> text "()"
, braces (text "foreignExportStablePtr"
<> parens (text "(StgPtr) &" <> ppr hs_fn <> text "_closure")
<> semi)
]
mkHObj :: Type -> SDoc
mkHObj t = text "rts_mk" <> text (showFFIType t)
unpackHObj :: Type -> SDoc
unpackHObj t = text "rts_get" <> text (showFFIType t)
showStgType :: Type -> SDoc
showStgType t = text "Hs" <> text (showFFIType t)
showFFIType :: Type -> String
showFFIType t = getOccString (getName (typeTyCon t))
toCType :: Type -> (Maybe Header, SDoc)
toCType = f False
where f voidOK t
-- First, if we have (Ptr t) of (FunPtr t), then we need to
-- convert t to a C type and put a * after it. If we don't
-- know a type for t, then "void" is fine, though.
| Just (ptr, [t']) <- splitTyConApp_maybe t
, tyConName ptr `elem` [ptrTyConName, funPtrTyConName]
= case f True t' of
(mh, cType') ->
(mh, cType' <> char '*')
-- Otherwise, if we have a type constructor application, then
-- see if there is a C type associated with that constructor.
-- Note that we aren't looking through type synonyms or
-- anything, as it may be the synonym that is annotated.
| TyConApp tycon _ <- t
, Just (CType _ mHeader (_,cType)) <- tyConCType_maybe tycon
= (mHeader, ftext cType)
-- If we don't know a C type for this type, then try looking
-- through one layer of type synonym etc.
| Just t' <- coreView t
= f voidOK t'
-- Otherwise we don't know the C type. If we are allowing
-- void then return that; otherwise something has gone wrong.
| voidOK = (Nothing, ptext (sLit "void"))
| otherwise
= pprPanic "toCType" (ppr t)
typeTyCon :: Type -> TyCon
typeTyCon ty
| UnaryRep rep_ty <- repType ty
, Just (tc, _) <- tcSplitTyConApp_maybe rep_ty
= tc
| otherwise
= pprPanic "DsForeign.typeTyCon" (ppr ty)
insertRetAddr :: DynFlags -> CCallConv
-> [(SDoc, SDoc, Type, CmmType)]
-> [(SDoc, SDoc, Type, CmmType)]
insertRetAddr dflags CCallConv args
= case platformArch platform of
ArchX86_64
| platformOS platform == OSMinGW32 ->
-- On other Windows x86_64 we insert the return address
-- after the 4th argument, because this is the point
-- at which we need to flush a register argument to the stack
-- (See rts/Adjustor.c for details).
let go :: Int -> [(SDoc, SDoc, Type, CmmType)]
-> [(SDoc, SDoc, Type, CmmType)]
go 4 args = ret_addr_arg dflags : args
go n (arg:args) = arg : go (n+1) args
go _ [] = []
in go 0 args
| otherwise ->
-- On other x86_64 platforms we insert the return address
-- after the 6th integer argument, because this is the point
-- at which we need to flush a register argument to the stack
-- (See rts/Adjustor.c for details).
let go :: Int -> [(SDoc, SDoc, Type, CmmType)]
-> [(SDoc, SDoc, Type, CmmType)]
go 6 args = ret_addr_arg dflags : args
go n (arg@(_,_,_,rep):args)
| cmmEqType_ignoring_ptrhood rep b64 = arg : go (n+1) args
| otherwise = arg : go n args
go _ [] = []
in go 0 args
_ ->
ret_addr_arg dflags : args
where platform = targetPlatform dflags
insertRetAddr _ _ args = args
ret_addr_arg :: DynFlags -> (SDoc, SDoc, Type, CmmType)
ret_addr_arg dflags = (text "original_return_addr", text "void*", undefined,
typeCmmType dflags addrPrimTy)
-- This function returns the primitive type associated with the boxed
-- type argument to a foreign export (eg. Int ==> Int#).
getPrimTyOf :: Type -> UnaryType
getPrimTyOf ty
| isBoolTy rep_ty = intPrimTy
-- Except for Bool, the types we are interested in have a single constructor
-- with a single primitive-typed argument (see TcType.legalFEArgTyCon).
| otherwise =
case splitDataProductType_maybe rep_ty of
Just (_, _, data_con, [prim_ty]) ->
ASSERT(dataConSourceArity data_con == 1)
ASSERT2(isUnLiftedType prim_ty, ppr prim_ty)
prim_ty
_other -> pprPanic "DsForeign.getPrimTyOf" (ppr ty)
where
UnaryRep rep_ty = repType ty
-- represent a primitive type as a Char, for building a string that
-- described the foreign function type. The types are size-dependent,
-- e.g. 'W' is a signed 32-bit integer.
primTyDescChar :: DynFlags -> Type -> Char
primTyDescChar dflags ty
| ty `eqType` unitTy = 'v'
| otherwise
= case typePrimRep (getPrimTyOf ty) of
IntRep -> signed_word
WordRep -> unsigned_word
Int64Rep -> 'L'
Word64Rep -> 'l'
AddrRep -> 'p'
FloatRep -> 'f'
DoubleRep -> 'd'
_ -> pprPanic "primTyDescChar" (ppr ty)
where
(signed_word, unsigned_word)
| wORD_SIZE dflags == 4 = ('W','w')
| wORD_SIZE dflags == 8 = ('L','l')
| otherwise = panic "primTyDescChar"
| {
"content_hash": "ed48e1b934086f6f944771ddd93f28a7",
"timestamp": "",
"source": "github",
"line_count": 817,
"max_line_length": 116,
"avg_line_length": 38.67931456548347,
"alnum_prop": 0.5431473687541534,
"repo_name": "da-x/ghc",
"id": "acea47c57ba156ce07816e4a70823be02d854b04",
"size": "31601",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "compiler/deSugar/DsForeign.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "5560"
},
{
"name": "Bison",
"bytes": "62938"
},
{
"name": "C",
"bytes": "2551434"
},
{
"name": "C++",
"bytes": "47948"
},
{
"name": "CSS",
"bytes": "984"
},
{
"name": "DTrace",
"bytes": "3887"
},
{
"name": "Emacs Lisp",
"bytes": "734"
},
{
"name": "Game Maker Language",
"bytes": "14164"
},
{
"name": "Gnuplot",
"bytes": "103851"
},
{
"name": "Groff",
"bytes": "3840"
},
{
"name": "HTML",
"bytes": "6144"
},
{
"name": "Haskell",
"bytes": "17538484"
},
{
"name": "Haxe",
"bytes": "218"
},
{
"name": "Logos",
"bytes": "119660"
},
{
"name": "Makefile",
"bytes": "490284"
},
{
"name": "Objective-C",
"bytes": "19601"
},
{
"name": "Objective-C++",
"bytes": "535"
},
{
"name": "Pascal",
"bytes": "113781"
},
{
"name": "Perl",
"bytes": "191194"
},
{
"name": "Perl6",
"bytes": "236343"
},
{
"name": "PostScript",
"bytes": "63"
},
{
"name": "Python",
"bytes": "104531"
},
{
"name": "Shell",
"bytes": "84402"
},
{
"name": "TeX",
"bytes": "667"
}
],
"symlink_target": ""
} |
class Libtensorflow < Formula
include Language::Python::Virtualenv
desc "C interface for Google's OS library for Machine Intelligence"
homepage "https://www.tensorflow.org/"
url "https://github.com/tensorflow/tensorflow/archive/v2.3.0.tar.gz"
sha256 "2595a5c401521f20a2734c4e5d54120996f8391f00bb62a57267d930bce95350"
license "Apache-2.0"
bottle do
cellar :any
sha256 "687fe75656a903bf42b6fe49b842571419ba7bd4b234ac23b500a6eedc65d406" => :catalina
sha256 "541b32b5a74cc3da9d571a854e6325900c43e94c195a1def841169a437b808ea" => :mojave
sha256 "a05569b17e31de59106a7503118d126d096ebd246308b0dea4ca8819d1d945f9" => :high_sierra
end
depends_on "bazel" => :build
depends_on "numpy" => :build
depends_on "python@3.8" => :build
resource "test-model" do
url "https://github.com/tensorflow/models/raw/v1.13.0/samples/languages/java/training/model/graph.pb"
sha256 "147fab50ddc945972818516418942157de5e7053d4b67e7fca0b0ada16733ecb"
end
def install
# Allow tensorflow to use current version of bazel
(buildpath / ".bazelversion").atomic_write Formula["bazel"].version
ENV["PYTHON_BIN_PATH"] = Formula["python@3.8"].opt_bin/"python3"
ENV["CC_OPT_FLAGS"] = "-march=native"
ENV["TF_IGNORE_MAX_BAZEL_VERSION"] = "1"
ENV["TF_NEED_JEMALLOC"] = "1"
ENV["TF_NEED_GCP"] = "0"
ENV["TF_NEED_HDFS"] = "0"
ENV["TF_ENABLE_XLA"] = "0"
ENV["USE_DEFAULT_PYTHON_LIB_PATH"] = "1"
ENV["TF_NEED_OPENCL"] = "0"
ENV["TF_NEED_CUDA"] = "0"
ENV["TF_NEED_MKL"] = "0"
ENV["TF_NEED_VERBS"] = "0"
ENV["TF_NEED_MPI"] = "0"
ENV["TF_NEED_S3"] = "1"
ENV["TF_NEED_GDR"] = "0"
ENV["TF_NEED_KAFKA"] = "0"
ENV["TF_NEED_OPENCL_SYCL"] = "0"
ENV["TF_NEED_ROCM"] = "0"
ENV["TF_DOWNLOAD_CLANG"] = "0"
ENV["TF_SET_ANDROID_WORKSPACE"] = "0"
ENV["TF_CONFIGURE_IOS"] = "0"
system "./configure"
bazel_args =%W[
--jobs=#{ENV.make_jobs}
--compilation_mode=opt
--copt=-march=native
]
targets = %w[
tensorflow:libtensorflow.so
tensorflow/tools/benchmark:benchmark_model
tensorflow/tools/graph_transforms:summarize_graph
tensorflow/tools/graph_transforms:transform_graph
]
system "bazel", "build", *bazel_args, *targets
lib.install Dir["bazel-bin/tensorflow/*.so*", "bazel-bin/tensorflow/*.dylib*"]
(include/"tensorflow/c").install %w[
tensorflow/c/c_api.h
tensorflow/c/c_api_experimental.h
tensorflow/c/tf_attrtype.h
tensorflow/c/tf_datatype.h
tensorflow/c/tf_status.h
tensorflow/c/tf_tensor.h
]
bin.install %w[
bazel-bin/tensorflow/tools/benchmark/benchmark_model
bazel-bin/tensorflow/tools/graph_transforms/summarize_graph
bazel-bin/tensorflow/tools/graph_transforms/transform_graph
]
(lib/"pkgconfig/tensorflow.pc").write <<~EOS
Name: tensorflow
Description: Tensorflow library
Version: #{version}
Libs: -L#{lib} -ltensorflow
Cflags: -I#{include}
EOS
end
test do
(testpath/"test.c").write <<~EOS
#include <stdio.h>
#include <tensorflow/c/c_api.h>
int main() {
printf("%s", TF_Version());
}
EOS
system ENV.cc, "-L#{lib}", "-ltensorflow", "-o", "test_tf", "test.c"
assert_equal version, shell_output("./test_tf")
resource("test-model").stage(testpath)
summarize_graph_output = shell_output("#{bin}/summarize_graph --in_graph=#{testpath}/graph.pb 2>&1")
variables_match = /Found \d+ variables:.+$/.match(summarize_graph_output)
assert_not_nil variables_match, "Unexpected stdout from summarize_graph for graph.pb (no found variables)"
variables_names = variables_match[0].scan(/name=([^,]+)/).flatten.sort
transform_command = %W[
#{bin}/transform_graph
--in_graph=#{testpath}/graph.pb
--out_graph=#{testpath}/graph-new.pb
--inputs=n/a
--outputs=n/a
--transforms="obfuscate_names"
2>&1
].join(" ")
shell_output(transform_command)
assert_predicate testpath/"graph-new.pb", :exist?, "transform_graph did not create an output graph"
new_summarize_graph_output = shell_output("#{bin}/summarize_graph --in_graph=#{testpath}/graph-new.pb 2>&1")
new_variables_match = /Found \d+ variables:.+$/.match(new_summarize_graph_output)
assert_not_nil new_variables_match, "Unexpected summarize_graph output for graph-new.pb (no found variables)"
new_variables_names = new_variables_match[0].scan(/name=([^,]+)/).flatten.sort
assert_not_equal variables_names, new_variables_names, "transform_graph didn't obfuscate variable names"
benchmark_model_match = /benchmark_model -- (.+)$/.match(new_summarize_graph_output)
assert_not_nil benchmark_model_match,
"Unexpected summarize_graph output for graph-new.pb (no benchmark_model example)"
benchmark_model_args = benchmark_model_match[1].split(" ")
benchmark_model_args.delete("--show_flops")
benchmark_model_command = [
"#{bin}/benchmark_model",
"--time_limit=10",
"--num_threads=1",
*benchmark_model_args,
"2>&1",
].join(" ")
assert_includes shell_output(benchmark_model_command),
"Timings (microseconds):",
"Unexpected benchmark_model output (no timings)"
end
end
| {
"content_hash": "7a0f506b1cb2b1bb9e7f15d0a7b4f87b",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 113,
"avg_line_length": 36.054421768707485,
"alnum_prop": 0.6598113207547169,
"repo_name": "maxim-belkin/homebrew-core",
"id": "339bffdf0646e73113a08b454a95f68329f1c188",
"size": "5300",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Formula/libtensorflow.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Perl",
"bytes": "628"
},
{
"name": "Ruby",
"bytes": "8614761"
}
],
"symlink_target": ""
} |
from collections import deque;
if __name__ == "__main__":
queue = deque()
print (queue)
queue.append(2)
queue.append(4)
queue.append(6)
print (queue)
queue.popleft()
print (queue)
queue.pop()
print (queue) | {
"content_hash": "026a0455cc2e53a14e9da0b2fb2ab52a",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 30,
"avg_line_length": 13.944444444444445,
"alnum_prop": 0.5657370517928287,
"repo_name": "cprakashagr/PythonClass",
"id": "a59cfc2890a23ed6898f2f13c8d363941190eb9b",
"size": "251",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ds/Queue.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "726190"
},
{
"name": "Python",
"bytes": "37362"
}
],
"symlink_target": ""
} |
/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include "JSONResolvePossibleRef.h"
// Library/third-party includes
#include <json/reader.h>
#include <boost/filesystem.hpp>
// Standard includes
#include <fstream>
namespace osvr {
namespace server {
/// @brief Helper function to load a JSON file given a full path to the
/// file.
/// @returns a null json value if load failed.
static inline Json::Value attemptLoad(std::string fullFn) {
Json::Value ret{Json::nullValue};
std::ifstream file{fullFn};
if (!file) {
return ret;
}
Json::Reader reader;
if (!reader.parse(file, ret)) {
ret = Json::nullValue;
return ret;
}
return ret;
}
/// @brief Helper function to load a JSON file by name in a search path.
/// @return Json::nullValue if could not load, otherwise parsed contents of
/// file.
static inline Json::Value
loadFromFile(std::string fn, std::vector<std::string> const &searchPath) {
Json::Value ret{Json::nullValue};
for (auto const &path : searchPath) {
auto fullFn = boost::filesystem::path(path) / fn;
ret = attemptLoad(fullFn.string());
if (!ret.isNull()) {
return ret;
}
}
// Last ditch effort, or only attempt if no search path provided
// This effectively uses the current working directory.
ret = attemptLoad(fn);
return ret;
}
Json::Value resolvePossibleRef(Json::Value const &input,
bool stringAcceptableResult,
std::vector<std::string> const &searchPath) {
Json::Value ret{Json::nullValue};
if (input.isString()) {
ret = loadFromFile(input.asString(), searchPath);
if (ret.isNull() && stringAcceptableResult) {
ret = input;
}
return ret;
}
if (input.isObject() && input.isMember("$ref")) {
/// @todo remove things after the filename in the ref.
ret = loadFromFile(input["$ref"].asString(), searchPath);
if (!ret.isNull()) {
return ret;
}
}
ret = input;
return ret;
}
} // namespace server
} // namespace osvr
| {
"content_hash": "b78df9c9fe0d002d187c92074d507730",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 80,
"avg_line_length": 32.297872340425535,
"alnum_prop": 0.5922266139657444,
"repo_name": "d235j/OSVR-Core",
"id": "eacec88a5c49a2df773c97cb9288ff22f303fc7b",
"size": "3036",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/osvr/Server/JSONResolvePossibleRef.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1294"
},
{
"name": "C",
"bytes": "155839"
},
{
"name": "C++",
"bytes": "1723732"
},
{
"name": "CMake",
"bytes": "787267"
},
{
"name": "HTML",
"bytes": "171455"
},
{
"name": "Objective-C",
"bytes": "311"
},
{
"name": "PowerShell",
"bytes": "3546"
},
{
"name": "Python",
"bytes": "4904"
},
{
"name": "Shell",
"bytes": "3126"
}
],
"symlink_target": ""
} |
<?php namespace You;
use Redirect;
use View;
use Auth;
use Input;
use Session;
use Ki\Validators\User as UserValidator;
use Ki\Validators\Profile as ProfileValidator;
use Ki\Common\Exceptions\ValidationException;
use Ki\Common\Uploader\UploaderInterface;
use Ki\Common\Uploader\UploadFailedException;
class SettingsController extends \BaseController {
public function __construct(
UploaderInterface $uploader,
UserValidator $userValidator,
ProfileValidator $profileValidator
)
{
$this->uploader = $uploader;
$this->userValidator = $userValidator;
$this->profileValidator = $profileValidator;
}
public function index()
{
$user = Auth::user();
$profile = $user->profile;
return View::make('you.settings.index', compact('user', 'profile'));
}
public function user()
{
$input = Input::only([
'password',
'password_confirmation'
]);
try
{
$rules = ['username' => '', 'email' => ''];
$this->userValidator->validate($input, $rules);
}
catch(ValidationException $e)
{
Session::flash('settings.user.error', $e->getMessage());
return Redirect::back();
}
$user = Auth::user();
$user->password = $input['password'];
$user->save();
$message = 'Your account has been successfully updated!';
Session::flash('settings.user.success', $message);
Redirect::to('dashboard.you.settings.index');
}
public function profile()
{
$input = $this->input([
'first_name',
'middle_name',
'last_name',
'address',
'birthdate',
'avatar',
'contact_no'
]);
try
{
$this->profileValidator->validate($input);
}
catch(ValidationException $e)
{
return $this
->flash('settings.profile.error', $e->getMessage())
->back();
}
$profile = Auth::user()->profile;
$profile->first_name = $input['first_name'];
$profile->middle_name = $input['middle_name'];
$profile->last_name = $input['last_name'];
$profile->full_name = "{$input['first_name']} {$input['middle_name']} {$input['last_name']}";
$profile->contact_no = $input['contact_no'];
$profile->address = Input::has('address') ? $input['address'] : null;
$profile->birthdate = Input::has('birthdate') ? date('Y-m-d', strtotime($input['birthdate'])) : null;
if(Input::hasFile('avatar')) $profile->avatar = $this->uploader->upload($input['avatar']);
$profile->save();
$message = 'Your profile has been successfully updated!';
Session::flash('settings.profile.success', $message);
return Redirect::back();
}
} | {
"content_hash": "fe82cd183769cd469817f3ff1f928cfd",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 103,
"avg_line_length": 23.884615384615383,
"alnum_prop": 0.6574074074074074,
"repo_name": "srph/e-dental",
"id": "04742b692930b46d58f2acd9d106008063ca85d7",
"size": "2484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/You/SettingsController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "356"
},
{
"name": "PHP",
"bytes": "124946"
}
],
"symlink_target": ""
} |
require 'test_helper'
class RssSourceTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
end
| {
"content_hash": "763b4738bd9f17ee2a9697ffdf72bc4f",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 53,
"avg_line_length": 18.714285714285715,
"alnum_prop": 0.7175572519083969,
"repo_name": "camumino/feed_twitter_bot",
"id": "23ffe521850ae3a82e013cf847eb353af09faba8",
"size": "131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/integration/feed_twitter_bot/rss_source_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2666"
},
{
"name": "HTML",
"bytes": "13881"
},
{
"name": "JavaScript",
"bytes": "1627"
},
{
"name": "Ruby",
"bytes": "73965"
}
],
"symlink_target": ""
} |
The :mod:`nova..volume.driver` Module
==============================================================================
.. automodule:: nova..volume.driver
:members:
:undoc-members:
:show-inheritance:
| {
"content_hash": "1690bb37154dab042a889e3b3f557472",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 78,
"avg_line_length": 34,
"alnum_prop": 0.43137254901960786,
"repo_name": "termie/nova-migration-demo",
"id": "51f5c07295c09ef033da2481c0dff58dfc4810ef",
"size": "204",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "doc/source/api/nova..volume.driver.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "47238"
},
{
"name": "Python",
"bytes": "2431410"
},
{
"name": "Shell",
"bytes": "31459"
}
],
"symlink_target": ""
} |
package org.apache.jackrabbit.jcr2spi;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.spi.XASessionInfo;
import org.apache.jackrabbit.jcr2spi.config.RepositoryConfig;
import javax.transaction.xa.XAResource;
/**
* <code>HippoXASessionImpl</code> extends the regular session implementation with
* access to the <code>XAResource</code>.
*/
public class HippoXASessionImpl extends HippoSessionImpl implements XASession {
/**
* The HippoXASessionInfo of this <code>SessionImpl</code>.
*/
private final XASessionInfo sessionInfo;
/**
* Creates a new <code>HippoXASessionImpl</code>.
*
* @param repository the repository instance associated with this session.
* @param sessionInfo the session info.
* @param config the underlying repository configuration.
* @throws RepositoryException if an error occurs while creating a session.
*/
HippoXASessionImpl(XASessionInfo sessionInfo, Repository repository,
RepositoryConfig config) throws RepositoryException {
super(sessionInfo, repository, config);
this.sessionInfo = sessionInfo;
}
//--------------------------------< XASession >-----------------------------
/**
* @inheritDoc
* @see org.apache.jackrabbit.jcr2spi.XASession#getXAResource()
*/
public XAResource getXAResource() {
return sessionInfo.getXAResource();
}
}
| {
"content_hash": "7b8e56deb0ad513cc76088113f972636",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 82,
"avg_line_length": 31.73913043478261,
"alnum_prop": 0.6856164383561644,
"repo_name": "canhnt/hippo-repo-xacml",
"id": "f2ca605d721604524ef159ce127394cfc3193ef0",
"size": "2098",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hippo-repository-3.1.x-xacml/connector/src/main/java/org/apache/jackrabbit/jcr2spi/HippoXASessionImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "5133"
},
{
"name": "HTML",
"bytes": "2709"
},
{
"name": "Java",
"bytes": "4510422"
},
{
"name": "JavaScript",
"bytes": "633"
}
],
"symlink_target": ""
} |
<?php
/*
Safe sample
input : Get a serialize string in POST and unserialize it
sanitize : use of intval
construction : use of sprintf via a %u
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$string = $_POST['UserData'] ;
$tainted = unserialize($string);
$tainted = intval($tainted);
$query = sprintf("SELECT * FROM COURSE c WHERE c.id IN (SELECT idcourse FROM REGISTRATION WHERE idstudent=%u)", $tainted);
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password)
mysql_select_db('dbname') ;
echo "query : ". $query ."<br /><br />" ;
$res = mysql_query($query); //execution
while($data =mysql_fetch_array($res)){
print_r($data) ;
echo "<br />" ;
}
mysql_close($conn);
?> | {
"content_hash": "11e43496699acec10a60c22f4d635b11",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 123,
"avg_line_length": 24.861538461538462,
"alnum_prop": 0.7407178217821783,
"repo_name": "stivalet/PHP-Vulnerability-test-suite",
"id": "8e3de1f2a3ce0d72b0dc8b48e0e0c440a711d7d1",
"size": "1616",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Injection/CWE_89/safe/CWE_89__unserialize__func_intval__multiple_select-sprintf_%u.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "64184004"
}
],
"symlink_target": ""
} |
define({
define : {
allow : "*",
require : [
"morphism",
"transistor",
"event_master",
],
},
make : function ( define ) {
var event_circle, body, option_name,
default_value = define.option.default_value || define.option.choice[0]
body = this.library.transistor.make(this.define_body({
name : "main",
option : {
default_value : default_value,
choice : define.option.choice,
mark : define.option.mark
},
class_name : define.class_name
}))
event_circle = this.library.event_master.make({
events : this.define_event({
body : body.body
}),
state : {
option : {
"main" : default_value
}
},
})
event_circle.add_listener(this.define_listener({
default_value : default_value,
choice : define.option.choice,
mark : define.option.mark
}))
body.append( define.append_to )
return {}
},
define_state : function ( define ) {
return {
value : define.with.option.value || define.with.option.choice[0]
}
},
define_event : function ( define ) {
return [
{
called : "toggle dropdown",
that_happens : [
{
on : define.with.body,
is : [ "click" ]
}
],
only_if : function ( heard ) {
return (
heard.event.target.hasAttribute("data-dropdown") ||
heard.event.target.parentElement.hasAttribute("data-dropdown")
)
}
},
{
called : "option select",
that_happens : [
{
on : define.with.body,
is : [ "click" ]
}
],
only_if : function ( heard ) {
return ( heard.event.target.getAttribute("data-dropdown-value") )
}
}
]
},
define_listener : function ( define ) {
return [
{
for : "toggle dropdown",
that_does : function ( heard ) {
var dropdown_body
dropdown_body = (
heard.event.target.getAttribute("data-dropdown") ?
heard.event.target :
heard.event.target.parentElement
)
if ( dropdown_body.nextSibling.style.display === "none" ) {
dropdown_body.nextSibling.style.display = "block"
dropdown_body.lastChild.textContent = dropdown_body.getAttribute("data-mark-open")
} else {
dropdown_body.nextSibling.style.display = "none"
dropdown_body.lastChild.textContent = dropdown_body.getAttribute("data-mark-closed")
}
return heard
}
},
{
for : "option select",
that_does : function ( heard ) {
var wrap, name, value, text, notation, option, option_state
option = heard.event.target
wrap = option.parentElement
text = wrap.previousSibling.firstChild
notation = wrap.previousSibling.lastChild
name = option.getAttribute("data-dropdown-name")
value = option.getAttribute("data-dropdown-value")
option_state = heard.state.option[name]
wrap.style.display = "none"
notation.textContent = wrap.previousSibling.getAttribute("data-mark-closed")
text.textContent = option.getAttribute("data-dropdown-text")
option_state.value = value
return heard
},
}
]
},
define_body : function ( define ) {
var self = this
return {
"class" : define.class_name.main,
child : [
{
"class" : define.class_name.option_selected_wrap,
"data-dropdown" : "true",
"data-mark-closed" : define.with.option.mark.closed,
"data-mark-open" : define.with.option.mark.open,
"child" : [
{
"class" : define.class_name.option_selected,
"text" : define.with.option.value || define.with.option.choice[0]
},
{
"class" : define.class_name.option_selector,
"text" : define.with.option.mark.closed
},
]
},
{
"display" : "none",
"class" : define.class_name.option_wrap,
"child" : this.library.morphism.index_loop({
array : define.with.option.choice,
else_do : function ( loop ) {
return loop.into.concat(self.define_option({
class_name : define.class_name,
name : define.name,
option : loop.indexed
}))
return loop.into.concat({
"class" : define.class_name.option,
"data-dropdown-name" : define.name,
"data-dropdown-value" : loop.indexed,
"text" : loop.indexed
})
}
})
}
]
}
},
define_option : function ( define ) {
var definition
definition = {
"class" : define.class_name.option,
"data-dropdown-name" : define.name,
}
if ( define.option.value && define.option.text ) {
definition["data-dropdown-value"] = define.option.value,
definition["data-dropdown-text"] = define.option.text,
definition["text"] = define.option.text
} else {
definition["data-dropdown-value"] = define.option,
definition["data-dropdown-text"] = define.option,
definition["text"] = define.option
}
return definition
}
})
// could create a context finder that is fed a definiton and then finds what he needs based upon it
// accepts definition,
// node that is meant to represent it,
// what he needs to find,
// returns the node needing to be found
// should also have a more concrete way of assignign events to certain thigns so that hter eare no conflicts
// in the case of using only if checkers.
// perhaps a context assigner as opsoded to the finder. | {
"content_hash": "6ece77245732daf9feb88e0718707e76",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 108,
"avg_line_length": 28.13,
"alnum_prop": 0.5776750799857803,
"repo_name": "spiralnebula/tabularasa",
"id": "38c90318421e207eebe5f8b9b96e51988aa51257",
"size": "5626",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/eloquent/library/dropdown/dropdown.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "133905"
},
{
"name": "JavaScript",
"bytes": "5124412"
}
],
"symlink_target": ""
} |
/**
\file statusmessage.h
\brief Class provides to read and write actions of osspecialization status file
\date 07-03-2012 09:46:03
\author Jayashree Singanallur (jayasing)
*/
/*----------------------------------------------------------------------------*/
#ifndef STATUSMESSAGE_H
#define STATUSMESSAGE_H
#include <scxcorelib/stringaid.h>
#include <util/XElement.h>
#include <util/Unicode.h>
#include <util/LogHandleCache.h>
namespace VMM
{
namespace GuestAgent
{
namespace StatusManager
{
class StatusMessage : public SCXCoreLib::SCXSingleton<StatusMessage>
{
public:
/*----------------------------------------------------------------------------*/
/**
Constructor for StatusMessage
*/
StatusMessage()
: m_logHandle(SCX::Util::LogHandleCache::Instance().GetLogHandle(
"scx.vmmguestagent.statusmanager.statusmessage"))
, mp_xelementRoot(NULL)
{
SetUp();
}
/*----------------------------------------------------------------------------*/
/**
Virtual Destructor for StatusMessage
*/
virtual ~StatusMessage()
{}
/*----------------------------------------------------------------------------*/
/**
Add Status Element to root
\return None
*/
bool AddChildToRoot(const SCX::Util::Xml::XElementPtr& element);
/*----------------------------------------------------------------------------*/
/**
Read element from Root
\param elementName ElementName being searched
\param elementValue Value of the element being searched
\return bool True if element was found. False otherwise
*/
bool ReadChildOfRoot(const std::string& elementName,
std::string& elementValue);
private:
/** Making the class a friend to enable destruction */
friend class SCXCoreLib::SCXSingleton<StatusMessage>;
/** Log Handle */
SCXCoreLib::SCXLogHandle m_logHandle;
/** Pointer to the Root Element */
SCX::Util::Xml::XElementPtr mp_xelementRoot;
/** XML String */
SCX::Util::Utf8String m_xmlString;
/** Status File */
std::string m_statusFile;
/*----------------------------------------------------------------------------*/
/**
Helper function to set up directories where status will be persisted
\return None
*/
void SetUp();
/*----------------------------------------------------------------------------*/
/**
Create root element
\return None
*/
void AddRoot();
/*----------------------------------------------------------------------------*/
/**
Helper function to read the file as a string
\return string File read as a string
*/
std::string ReadStatusFileAsString();
/*----------------------------------------------------------------------------*/
/**
Helper function to persist xml object in memory to file
\return None
*/
void Write();
}; // End of OSConfigurationStatus class
} // End of StatusManager namespace
} // End of GuestAgent namespace
} // End of VMM namespace
#endif /* STATUSMESSAGE_H */
/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/
| {
"content_hash": "c0d5265b6f851b3bbfec47e65fa6f011",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 96,
"avg_line_length": 30.496598639455783,
"alnum_prop": 0.34708900289984385,
"repo_name": "Microsoft/SCVMMLinuxGuestAgent",
"id": "239bc7d398a3693185bc9887e7da71a574752b24",
"size": "5189",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vmm/dev/src/include/statusmessage.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2517"
},
{
"name": "C",
"bytes": "4366"
},
{
"name": "C++",
"bytes": "3307131"
},
{
"name": "Makefile",
"bytes": "83773"
},
{
"name": "Shell",
"bytes": "124832"
}
],
"symlink_target": ""
} |
package infodynamics.measures.mixed;
import infodynamics.utils.EmpiricalMeasurementDistribution;
import infodynamics.measures.continuous.ConditionalMutualInfoCalculatorMultiVariate;
/**
* A conditional mutual information calculator between a joint set of continuous variables,
* and a discrete variable, conditioned on another discrete variable.
*
* <p>These calculators are <b>EXPERIMENTAL</b> -- not properly tested,
* and not well documented. The intended calling pattern is similar to
* {@link ConditionalMutualInfoCalculatorMultiVariate}
* </p>
*
* @author Joseph Lizier (<a href="joseph.lizier at gmail.com">email</a>,
* <a href="http://lizier.me/joseph/">www</a>)
*/
public interface ConditionalMutualInfoCalculatorMultiVariateWithDiscrete {
/**
*
*
* @param dimensions the number of joint continuous variables
* @param base the base of the discrete variable
* @param condBase the base of the discrete variable to condition on
* @throws Exception
*/
public void initialise(int dimensions, int base, int condBase) throws Exception;
public void setProperty(String propertyName, String propertyValue);
public void setObservations(double[][] continuousObservations,
int[] discreteObservations, int[] conditionedObservations) throws Exception;
public double computeAverageLocalOfObservations() throws Exception;
public double[] computeLocalUsingPreviousObservations(double[][] contStates,
int[] discreteStates, int[] conditionedStates) throws Exception;
public EmpiricalMeasurementDistribution computeSignificance(int numPermutationsToCheck) throws Exception;
public EmpiricalMeasurementDistribution computeSignificance(int[][] newOrderings) throws Exception;
public void setDebug(boolean debug);
public double getLastAverage();
public int getNumObservations();
}
| {
"content_hash": "b5a1b9c595658e65cd42ef673fd3994a",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 106,
"avg_line_length": 36.25,
"alnum_prop": 0.7649867374005305,
"repo_name": "jmmccracken/ECA",
"id": "2482d889fc3ca236e54fe8926c6338032aa40138",
"size": "2658",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "infodynamics-dist-1.2.1/java/source/infodynamics/measures/mixed/ConditionalMutualInfoCalculatorMultiVariateWithDiscrete.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2858"
},
{
"name": "C",
"bytes": "1277"
},
{
"name": "CSS",
"bytes": "11582"
},
{
"name": "Clojure",
"bytes": "9942"
},
{
"name": "HTML",
"bytes": "7661043"
},
{
"name": "Java",
"bytes": "2725558"
},
{
"name": "Julia",
"bytes": "13274"
},
{
"name": "M",
"bytes": "377"
},
{
"name": "Matlab",
"bytes": "538546"
},
{
"name": "Python",
"bytes": "27160"
},
{
"name": "R",
"bytes": "18416"
},
{
"name": "Shell",
"bytes": "3925"
}
],
"symlink_target": ""
} |
package cz.znj.kvr.sw.exp.java.spring.concurrent;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.util.concurrent.SettableListenableFuture;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class FutureTest
{
@Test
public void testSuccessListeners()
{
AtomicReference ran = new AtomicReference();
SettableListenableFuture<Object> future = new SettableListenableFuture<Object>();
future.addCallback(new ListenableFutureCallback<Object>() {
@Override
public void onFailure(Throwable throwable) {
Assert.fail("Unexpected success on cancelled future");
}
@Override
public void onSuccess(Object o) {
ran.set(o);
}
});
future.set(Integer.valueOf(0));
Assert.assertEquals(0, (int) ran.get());
}
@Test
public void testExceptionListeners()
{
AtomicReference ran = new AtomicReference();
SettableListenableFuture<Object> future = new SettableListenableFuture<Object>();
future.addCallback(new ListenableFutureCallback<Object>() {
@Override
public void onFailure(Throwable throwable) {
ran.set(throwable);
}
@Override
public void onSuccess(Object o) {
Assert.fail("Unexpected success on excepted future");
}
});
future.setException(new NumberFormatException());
Assert.assertTrue(ran.get() instanceof NumberFormatException);
}
@Test
public void testCancelListeners()
{
AtomicReference ran = new AtomicReference();
SettableListenableFuture<Object> future = new SettableListenableFuture<Object>();
future.addCallback(new ListenableFutureCallback<Object>() {
@Override
public void onFailure(Throwable throwable) {
ran.set(throwable);
}
@Override
public void onSuccess(Object o) {
Assert.fail("Unexpected success on cancelled future");
}
});
future.cancel(true);
Assert.assertTrue(ran.get() instanceof CancellationException);
}
}
| {
"content_hash": "eceb1d1408a601595402451a6a30a4eb",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 83,
"avg_line_length": 28.594594594594593,
"alnum_prop": 0.7301512287334594,
"repo_name": "kvr000/zbynek-java-exp",
"id": "6cc155ff75129974b22fc8eda6db1e403c352bff",
"size": "2116",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spring-exp/spring-websocket-exp/src/test/java/cz/znj/kvr/sw/exp/java/spring/concurrent/FutureTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1953"
},
{
"name": "Java",
"bytes": "809011"
},
{
"name": "JavaScript",
"bytes": "2481030"
},
{
"name": "Perl",
"bytes": "4643"
},
{
"name": "Python",
"bytes": "5031"
},
{
"name": "TypeScript",
"bytes": "701"
}
],
"symlink_target": ""
} |
use ast::*;
use ast;
use ast_util;
use codemap::{respan, Span, Spanned};
use parse::token;
use owned_slice::OwnedSlice;
use util::small_vector::SmallVector;
use std::rc::Rc;
use std::gc::{Gc, GC};
pub trait Folder {
// Any additions to this trait should happen in form
// of a call to a public `noop_*` function that only calls
// out to the folder again, not other `noop_*` functions.
//
// This is a necessary API workaround to the problem of not
// being able to call out to the super default method
// in an overridden default method.
fn fold_crate(&mut self, c: Crate) -> Crate {
noop_fold_crate(c, self)
}
fn fold_meta_items(&mut self, meta_items: &[Gc<MetaItem>]) -> Vec<Gc<MetaItem>> {
noop_fold_meta_items(meta_items, self)
}
fn fold_meta_item(&mut self, meta_item: &MetaItem) -> MetaItem {
noop_fold_meta_item(meta_item, self)
}
fn fold_view_path(&mut self, view_path: Gc<ViewPath>) -> Gc<ViewPath> {
noop_fold_view_path(view_path, self)
}
fn fold_view_item(&mut self, vi: &ViewItem) -> ViewItem {
noop_fold_view_item(vi, self)
}
fn fold_foreign_item(&mut self, ni: Gc<ForeignItem>) -> Gc<ForeignItem> {
noop_fold_foreign_item(&*ni, self)
}
fn fold_item(&mut self, i: Gc<Item>) -> SmallVector<Gc<Item>> {
noop_fold_item(&*i, self)
}
fn fold_item_simple(&mut self, i: &Item) -> Item {
noop_fold_item_simple(i, self)
}
fn fold_struct_field(&mut self, sf: &StructField) -> StructField {
noop_fold_struct_field(sf, self)
}
fn fold_item_underscore(&mut self, i: &Item_) -> Item_ {
noop_fold_item_underscore(i, self)
}
fn fold_fn_decl(&mut self, d: &FnDecl) -> P<FnDecl> {
noop_fold_fn_decl(d, self)
}
fn fold_type_method(&mut self, m: &TypeMethod) -> TypeMethod {
noop_fold_type_method(m, self)
}
fn fold_method(&mut self, m: Gc<Method>) -> SmallVector<Gc<Method>> {
noop_fold_method(&*m, self)
}
fn fold_block(&mut self, b: P<Block>) -> P<Block> {
noop_fold_block(b, self)
}
fn fold_stmt(&mut self, s: &Stmt) -> SmallVector<Gc<Stmt>> {
noop_fold_stmt(s, self)
}
fn fold_arm(&mut self, a: &Arm) -> Arm {
noop_fold_arm(a, self)
}
fn fold_pat(&mut self, p: Gc<Pat>) -> Gc<Pat> {
noop_fold_pat(p, self)
}
fn fold_decl(&mut self, d: Gc<Decl>) -> SmallVector<Gc<Decl>> {
noop_fold_decl(d, self)
}
fn fold_expr(&mut self, e: Gc<Expr>) -> Gc<Expr> {
noop_fold_expr(e, self)
}
fn fold_ty(&mut self, t: P<Ty>) -> P<Ty> {
noop_fold_ty(t, self)
}
fn fold_mod(&mut self, m: &Mod) -> Mod {
noop_fold_mod(m, self)
}
fn fold_foreign_mod(&mut self, nm: &ForeignMod) -> ForeignMod {
noop_fold_foreign_mod(nm, self)
}
fn fold_variant(&mut self, v: &Variant) -> P<Variant> {
noop_fold_variant(v, self)
}
fn fold_ident(&mut self, i: Ident) -> Ident {
noop_fold_ident(i, self)
}
fn fold_path(&mut self, p: &Path) -> Path {
noop_fold_path(p, self)
}
fn fold_local(&mut self, l: Gc<Local>) -> Gc<Local> {
noop_fold_local(l, self)
}
fn fold_mac(&mut self, _macro: &Mac) -> Mac {
fail!("fold_mac disabled by default");
// NB: see note about macros above.
// if you really want a folder that
// works on macros, use this
// definition in your trait impl:
// fold::noop_fold_mac(_macro, self)
}
fn fold_explicit_self(&mut self, es: &ExplicitSelf) -> ExplicitSelf {
noop_fold_explicit_self(es, self)
}
fn fold_explicit_self_underscore(&mut self, es: &ExplicitSelf_) -> ExplicitSelf_ {
noop_fold_explicit_self_underscore(es, self)
}
fn fold_lifetime(&mut self, l: &Lifetime) -> Lifetime {
noop_fold_lifetime(l, self)
}
fn fold_lifetime_def(&mut self, l: &LifetimeDef) -> LifetimeDef {
noop_fold_lifetime_def(l, self)
}
fn fold_attribute(&mut self, at: Attribute) -> Attribute {
noop_fold_attribute(at, self)
}
fn fold_arg(&mut self, a: &Arg) -> Arg {
noop_fold_arg(a, self)
}
fn fold_generics(&mut self, generics: &Generics) -> Generics {
noop_fold_generics(generics, self)
}
fn fold_trait_ref(&mut self, p: &TraitRef) -> TraitRef {
noop_fold_trait_ref(p, self)
}
fn fold_struct_def(&mut self, struct_def: Gc<StructDef>) -> Gc<StructDef> {
noop_fold_struct_def(struct_def, self)
}
fn fold_lifetimes(&mut self, lts: &[Lifetime]) -> Vec<Lifetime> {
noop_fold_lifetimes(lts, self)
}
fn fold_lifetime_defs(&mut self, lts: &[LifetimeDef]) -> Vec<LifetimeDef> {
noop_fold_lifetime_defs(lts, self)
}
fn fold_ty_param(&mut self, tp: &TyParam) -> TyParam {
noop_fold_ty_param(tp, self)
}
fn fold_ty_params(&mut self, tps: &[TyParam]) -> OwnedSlice<TyParam> {
noop_fold_ty_params(tps, self)
}
fn fold_tt(&mut self, tt: &TokenTree) -> TokenTree {
noop_fold_tt(tt, self)
}
fn fold_tts(&mut self, tts: &[TokenTree]) -> Vec<TokenTree> {
noop_fold_tts(tts, self)
}
fn fold_token(&mut self, t: &token::Token) -> token::Token {
noop_fold_token(t, self)
}
fn fold_interpolated(&mut self, nt : &token::Nonterminal) -> token::Nonterminal {
noop_fold_interpolated(nt, self)
}
fn fold_opt_lifetime(&mut self, o_lt: &Option<Lifetime>) -> Option<Lifetime> {
noop_fold_opt_lifetime(o_lt, self)
}
fn fold_variant_arg(&mut self, va: &VariantArg) -> VariantArg {
noop_fold_variant_arg(va, self)
}
fn fold_opt_bounds(&mut self, b: &Option<OwnedSlice<TyParamBound>>)
-> Option<OwnedSlice<TyParamBound>> {
noop_fold_opt_bounds(b, self)
}
fn fold_bounds(&mut self, b: &OwnedSlice<TyParamBound>)
-> OwnedSlice<TyParamBound> {
noop_fold_bounds(b, self)
}
fn fold_ty_param_bound(&mut self, tpb: &TyParamBound) -> TyParamBound {
noop_fold_ty_param_bound(tpb, self)
}
fn fold_mt(&mut self, mt: &MutTy) -> MutTy {
noop_fold_mt(mt, self)
}
fn fold_field(&mut self, field: Field) -> Field {
noop_fold_field(field, self)
}
fn fold_where_clause(&mut self, where_clause: &WhereClause)
-> WhereClause {
noop_fold_where_clause(where_clause, self)
}
fn fold_where_predicate(&mut self, where_predicate: &WherePredicate)
-> WherePredicate {
noop_fold_where_predicate(where_predicate, self)
}
// Helper methods:
fn map_exprs(&self, f: |Gc<Expr>| -> Gc<Expr>,
es: &[Gc<Expr>]) -> Vec<Gc<Expr>> {
es.iter().map(|x| f(*x)).collect()
}
fn new_id(&mut self, i: NodeId) -> NodeId {
i
}
fn new_span(&mut self, sp: Span) -> Span {
sp
}
}
pub fn noop_fold_meta_items<T: Folder>(meta_items: &[Gc<MetaItem>], fld: &mut T)
-> Vec<Gc<MetaItem>> {
meta_items.iter().map(|x| box (GC) fld.fold_meta_item(&**x)).collect()
}
pub fn noop_fold_view_path<T: Folder>(view_path: Gc<ViewPath>, fld: &mut T) -> Gc<ViewPath> {
let inner_view_path = match view_path.node {
ViewPathSimple(ref ident, ref path, node_id) => {
let id = fld.new_id(node_id);
ViewPathSimple(ident.clone(),
fld.fold_path(path),
id)
}
ViewPathGlob(ref path, node_id) => {
let id = fld.new_id(node_id);
ViewPathGlob(fld.fold_path(path), id)
}
ViewPathList(ref path, ref path_list_idents, node_id) => {
let id = fld.new_id(node_id);
ViewPathList(fld.fold_path(path),
path_list_idents.iter().map(|path_list_ident| {
Spanned {
node: match path_list_ident.node {
PathListIdent { id, name } =>
PathListIdent {
id: fld.new_id(id),
name: name.clone()
},
PathListMod { id } =>
PathListMod { id: fld.new_id(id) }
},
span: fld.new_span(path_list_ident.span)
}
}).collect(),
id)
}
};
box(GC) Spanned {
node: inner_view_path,
span: fld.new_span(view_path.span),
}
}
pub fn noop_fold_arm<T: Folder>(a: &Arm, fld: &mut T) -> Arm {
Arm {
attrs: a.attrs.iter().map(|x| fld.fold_attribute(*x)).collect(),
pats: a.pats.iter().map(|x| fld.fold_pat(*x)).collect(),
guard: a.guard.map(|x| fld.fold_expr(x)),
body: fld.fold_expr(a.body),
}
}
pub fn noop_fold_decl<T: Folder>(d: Gc<Decl>, fld: &mut T) -> SmallVector<Gc<Decl>> {
let node = match d.node {
DeclLocal(ref l) => SmallVector::one(DeclLocal(fld.fold_local(*l))),
DeclItem(it) => {
fld.fold_item(it).move_iter().map(|i| DeclItem(i)).collect()
}
};
node.move_iter().map(|node| {
box(GC) Spanned {
node: node,
span: fld.new_span(d.span),
}
}).collect()
}
pub fn noop_fold_ty<T: Folder>(t: P<Ty>, fld: &mut T) -> P<Ty> {
let id = fld.new_id(t.id);
let node = match t.node {
TyNil | TyBot | TyInfer => t.node.clone(),
TyBox(ty) => TyBox(fld.fold_ty(ty)),
TyUniq(ty) => TyUniq(fld.fold_ty(ty)),
TyVec(ty) => TyVec(fld.fold_ty(ty)),
TyPtr(ref mt) => TyPtr(fld.fold_mt(mt)),
TyRptr(ref region, ref mt) => {
TyRptr(fld.fold_opt_lifetime(region), fld.fold_mt(mt))
}
TyClosure(ref f) => {
TyClosure(box(GC) ClosureTy {
fn_style: f.fn_style,
onceness: f.onceness,
bounds: fld.fold_bounds(&f.bounds),
decl: fld.fold_fn_decl(&*f.decl),
lifetimes: fld.fold_lifetime_defs(f.lifetimes.as_slice()),
})
}
TyProc(ref f) => {
TyProc(box(GC) ClosureTy {
fn_style: f.fn_style,
onceness: f.onceness,
bounds: fld.fold_bounds(&f.bounds),
decl: fld.fold_fn_decl(&*f.decl),
lifetimes: fld.fold_lifetime_defs(f.lifetimes.as_slice()),
})
}
TyBareFn(ref f) => {
TyBareFn(box(GC) BareFnTy {
lifetimes: fld.fold_lifetime_defs(f.lifetimes.as_slice()),
fn_style: f.fn_style,
abi: f.abi,
decl: fld.fold_fn_decl(&*f.decl)
})
}
TyUnboxedFn(ref f) => {
TyUnboxedFn(box(GC) UnboxedFnTy {
decl: fld.fold_fn_decl(&*f.decl),
kind: f.kind,
})
}
TyTup(ref tys) => TyTup(tys.iter().map(|&ty| fld.fold_ty(ty)).collect()),
TyParen(ref ty) => TyParen(fld.fold_ty(*ty)),
TyPath(ref path, ref bounds, id) => {
let id = fld.new_id(id);
TyPath(fld.fold_path(path),
fld.fold_opt_bounds(bounds),
id)
}
TyFixedLengthVec(ty, e) => {
TyFixedLengthVec(fld.fold_ty(ty), fld.fold_expr(e))
}
TyTypeof(expr) => TyTypeof(fld.fold_expr(expr)),
};
P(Ty {
id: id,
span: fld.new_span(t.span),
node: node,
})
}
pub fn noop_fold_foreign_mod<T: Folder>(nm: &ForeignMod, fld: &mut T) -> ForeignMod {
ast::ForeignMod {
abi: nm.abi,
view_items: nm.view_items
.iter()
.map(|x| fld.fold_view_item(x))
.collect(),
items: nm.items
.iter()
.map(|x| fld.fold_foreign_item(*x))
.collect(),
}
}
pub fn noop_fold_variant<T: Folder>(v: &Variant, fld: &mut T) -> P<Variant> {
let id = fld.new_id(v.node.id);
let kind;
match v.node.kind {
TupleVariantKind(ref variant_args) => {
kind = TupleVariantKind(variant_args.iter().map(|x|
fld.fold_variant_arg(x)).collect())
}
StructVariantKind(ref struct_def) => {
kind = StructVariantKind(box(GC) ast::StructDef {
fields: struct_def.fields.iter()
.map(|f| fld.fold_struct_field(f)).collect(),
ctor_id: struct_def.ctor_id.map(|c| fld.new_id(c)),
super_struct: match struct_def.super_struct {
Some(t) => Some(fld.fold_ty(t)),
None => None
},
is_virtual: struct_def.is_virtual,
})
}
}
let attrs = v.node.attrs.iter().map(|x| fld.fold_attribute(*x)).collect();
let de = match v.node.disr_expr {
Some(e) => Some(fld.fold_expr(e)),
None => None
};
let node = ast::Variant_ {
name: v.node.name,
attrs: attrs,
kind: kind,
id: id,
disr_expr: de,
vis: v.node.vis,
};
P(Spanned {
node: node,
span: fld.new_span(v.span),
})
}
pub fn noop_fold_ident<T: Folder>(i: Ident, _: &mut T) -> Ident {
i
}
pub fn noop_fold_path<T: Folder>(p: &Path, fld: &mut T) -> Path {
ast::Path {
span: fld.new_span(p.span),
global: p.global,
segments: p.segments.iter().map(|segment| ast::PathSegment {
identifier: fld.fold_ident(segment.identifier),
lifetimes: segment.lifetimes.iter().map(|l| fld.fold_lifetime(l)).collect(),
types: segment.types.iter().map(|&typ| fld.fold_ty(typ)).collect(),
}).collect()
}
}
pub fn noop_fold_local<T: Folder>(l: Gc<Local>, fld: &mut T) -> Gc<Local> {
let id = fld.new_id(l.id); // Needs to be first, for ast_map.
box(GC) Local {
id: id,
ty: fld.fold_ty(l.ty),
pat: fld.fold_pat(l.pat),
init: l.init.map(|e| fld.fold_expr(e)),
span: fld.new_span(l.span),
source: l.source,
}
}
pub fn noop_fold_attribute<T: Folder>(at: Attribute, fld: &mut T) -> Attribute {
Spanned {
span: fld.new_span(at.span),
node: ast::Attribute_ {
id: at.node.id,
style: at.node.style,
value: box (GC) fld.fold_meta_item(&*at.node.value),
is_sugared_doc: at.node.is_sugared_doc
}
}
}
pub fn noop_fold_explicit_self_underscore<T: Folder>(es: &ExplicitSelf_, fld: &mut T)
-> ExplicitSelf_ {
match *es {
SelfStatic | SelfValue(_) => *es,
SelfRegion(ref lifetime, m, id) => {
SelfRegion(fld.fold_opt_lifetime(lifetime), m, id)
}
SelfExplicit(ref typ, id) => SelfExplicit(fld.fold_ty(*typ), id),
}
}
pub fn noop_fold_explicit_self<T: Folder>(es: &ExplicitSelf, fld: &mut T) -> ExplicitSelf {
Spanned {
span: fld.new_span(es.span),
node: fld.fold_explicit_self_underscore(&es.node)
}
}
pub fn noop_fold_mac<T: Folder>(macro: &Mac, fld: &mut T) -> Mac {
Spanned {
node: match macro.node {
MacInvocTT(ref p, ref tts, ctxt) => {
MacInvocTT(fld.fold_path(p),
fld.fold_tts(tts.as_slice()),
ctxt)
}
},
span: fld.new_span(macro.span)
}
}
pub fn noop_fold_meta_item<T: Folder>(mi: &MetaItem, fld: &mut T) -> MetaItem {
Spanned {
node:
match mi.node {
MetaWord(ref id) => MetaWord((*id).clone()),
MetaList(ref id, ref mis) => {
MetaList((*id).clone(),
mis.iter()
.map(|e| box (GC) fld.fold_meta_item(&**e)).collect())
}
MetaNameValue(ref id, ref s) => {
MetaNameValue((*id).clone(), (*s).clone())
}
},
span: fld.new_span(mi.span) }
}
pub fn noop_fold_arg<T: Folder>(a: &Arg, fld: &mut T) -> Arg {
let id = fld.new_id(a.id); // Needs to be first, for ast_map.
Arg {
id: id,
ty: fld.fold_ty(a.ty),
pat: fld.fold_pat(a.pat),
}
}
pub fn noop_fold_tt<T: Folder>(tt: &TokenTree, fld: &mut T) -> TokenTree {
match *tt {
TTTok(span, ref tok) =>
TTTok(span, fld.fold_token(tok)),
TTDelim(ref tts) => TTDelim(Rc::new(fld.fold_tts(tts.as_slice()))),
TTSeq(span, ref pattern, ref sep, is_optional) =>
TTSeq(span,
Rc::new(fld.fold_tts(pattern.as_slice())),
sep.as_ref().map(|tok| fld.fold_token(tok)),
is_optional),
TTNonterminal(sp,ref ident) =>
TTNonterminal(sp,fld.fold_ident(*ident))
}
}
pub fn noop_fold_tts<T: Folder>(tts: &[TokenTree], fld: &mut T) -> Vec<TokenTree> {
tts.iter().map(|tt| fld.fold_tt(tt)).collect()
}
// apply ident folder if it's an ident, apply other folds to interpolated nodes
pub fn noop_fold_token<T: Folder>(t: &token::Token, fld: &mut T) -> token::Token {
match *t {
token::IDENT(id, followed_by_colons) => {
token::IDENT(fld.fold_ident(id), followed_by_colons)
}
token::LIFETIME(id) => token::LIFETIME(fld.fold_ident(id)),
token::INTERPOLATED(ref nt) => token::INTERPOLATED(fld.fold_interpolated(nt)),
_ => (*t).clone()
}
}
/// apply folder to elements of interpolated nodes
//
// NB: this can occur only when applying a fold to partially expanded code, where
// parsed pieces have gotten implanted ito *other* macro invocations. This is relevant
// for macro hygiene, but possibly not elsewhere.
//
// One problem here occurs because the types for fold_item, fold_stmt, etc. allow the
// folder to return *multiple* items; this is a problem for the nodes here, because
// they insist on having exactly one piece. One solution would be to mangle the fold
// trait to include one-to-many and one-to-one versions of these entry points, but that
// would probably confuse a lot of people and help very few. Instead, I'm just going
// to put in dynamic checks. I think the performance impact of this will be pretty much
// nonexistent. The danger is that someone will apply a fold to a partially expanded
// node, and will be confused by the fact that their "fold_item" or "fold_stmt" isn't
// getting called on NtItem or NtStmt nodes. Hopefully they'll wind up reading this
// comment, and doing something appropriate.
//
// BTW, design choice: I considered just changing the type of, e.g., NtItem to contain
// multiple items, but decided against it when I looked at parse_item_or_view_item and
// tried to figure out what I would do with multiple items there....
pub fn noop_fold_interpolated<T: Folder>(nt : &token::Nonterminal, fld: &mut T)
-> token::Nonterminal {
match *nt {
token::NtItem(item) =>
token::NtItem(fld.fold_item(item)
// this is probably okay, because the only folds likely
// to peek inside interpolated nodes will be renamings/markings,
// which map single items to single items
.expect_one("expected fold to produce exactly one item")),
token::NtBlock(block) => token::NtBlock(fld.fold_block(block)),
token::NtStmt(stmt) =>
token::NtStmt(fld.fold_stmt(&*stmt)
// this is probably okay, because the only folds likely
// to peek inside interpolated nodes will be renamings/markings,
// which map single items to single items
.expect_one("expected fold to produce exactly one statement")),
token::NtPat(pat) => token::NtPat(fld.fold_pat(pat)),
token::NtExpr(expr) => token::NtExpr(fld.fold_expr(expr)),
token::NtTy(ty) => token::NtTy(fld.fold_ty(ty)),
token::NtIdent(ref id, is_mod_name) =>
token::NtIdent(box fld.fold_ident(**id),is_mod_name),
token::NtMeta(meta_item) => token::NtMeta(box (GC) fld.fold_meta_item(&*meta_item)),
token::NtPath(ref path) => token::NtPath(box fld.fold_path(&**path)),
token::NtTT(tt) => token::NtTT(box (GC) fld.fold_tt(&*tt)),
// it looks to me like we can leave out the matchers: token::NtMatchers(matchers)
_ => (*nt).clone()
}
}
pub fn noop_fold_fn_decl<T: Folder>(decl: &FnDecl, fld: &mut T) -> P<FnDecl> {
P(FnDecl {
inputs: decl.inputs.iter().map(|x| fld.fold_arg(x)).collect(), // bad copy
output: fld.fold_ty(decl.output),
cf: decl.cf,
variadic: decl.variadic
})
}
pub fn noop_fold_ty_param_bound<T: Folder>(tpb: &TyParamBound, fld: &mut T)
-> TyParamBound {
match *tpb {
TraitTyParamBound(ref ty) => TraitTyParamBound(fld.fold_trait_ref(ty)),
RegionTyParamBound(ref lifetime) => RegionTyParamBound(fld.fold_lifetime(lifetime)),
UnboxedFnTyParamBound(ref unboxed_function_type) => {
UnboxedFnTyParamBound(UnboxedFnTy {
decl: fld.fold_fn_decl(&*unboxed_function_type.decl),
kind: unboxed_function_type.kind,
})
}
}
}
pub fn noop_fold_ty_param<T: Folder>(tp: &TyParam, fld: &mut T) -> TyParam {
let id = fld.new_id(tp.id);
TyParam {
ident: tp.ident,
id: id,
bounds: fld.fold_bounds(&tp.bounds),
unbound: tp.unbound.as_ref().map(|x| fld.fold_ty_param_bound(x)),
default: tp.default.map(|x| fld.fold_ty(x)),
span: tp.span
}
}
pub fn noop_fold_ty_params<T: Folder>(tps: &[TyParam], fld: &mut T)
-> OwnedSlice<TyParam> {
tps.iter().map(|tp| fld.fold_ty_param(tp)).collect()
}
pub fn noop_fold_lifetime<T: Folder>(l: &Lifetime, fld: &mut T) -> Lifetime {
let id = fld.new_id(l.id);
Lifetime {
id: id,
span: fld.new_span(l.span),
name: l.name
}
}
pub fn noop_fold_lifetime_def<T: Folder>(l: &LifetimeDef, fld: &mut T)
-> LifetimeDef
{
LifetimeDef {
lifetime: fld.fold_lifetime(&l.lifetime),
bounds: fld.fold_lifetimes(l.bounds.as_slice()),
}
}
pub fn noop_fold_lifetimes<T: Folder>(lts: &[Lifetime], fld: &mut T) -> Vec<Lifetime> {
lts.iter().map(|l| fld.fold_lifetime(l)).collect()
}
pub fn noop_fold_lifetime_defs<T: Folder>(lts: &[LifetimeDef], fld: &mut T) -> Vec<LifetimeDef> {
lts.iter().map(|l| fld.fold_lifetime_def(l)).collect()
}
pub fn noop_fold_opt_lifetime<T: Folder>(o_lt: &Option<Lifetime>, fld: &mut T)
-> Option<Lifetime> {
o_lt.as_ref().map(|lt| fld.fold_lifetime(lt))
}
pub fn noop_fold_generics<T: Folder>(generics: &Generics, fld: &mut T) -> Generics {
Generics {
ty_params: fld.fold_ty_params(generics.ty_params.as_slice()),
lifetimes: fld.fold_lifetime_defs(generics.lifetimes.as_slice()),
where_clause: fld.fold_where_clause(&generics.where_clause),
}
}
pub fn noop_fold_where_clause<T: Folder>(
where_clause: &WhereClause,
fld: &mut T)
-> WhereClause {
WhereClause {
id: fld.new_id(where_clause.id),
predicates: where_clause.predicates.iter().map(|predicate| {
fld.fold_where_predicate(predicate)
}).collect(),
}
}
pub fn noop_fold_where_predicate<T: Folder>(
predicate: &WherePredicate,
fld: &mut T)
-> WherePredicate {
WherePredicate {
id: fld.new_id(predicate.id),
span: fld.new_span(predicate.span),
ident: fld.fold_ident(predicate.ident),
bounds: predicate.bounds.map(|x| {
fld.fold_ty_param_bound(x)
}),
}
}
pub fn noop_fold_struct_def<T: Folder>(struct_def: Gc<StructDef>,
fld: &mut T) -> Gc<StructDef> {
box(GC) ast::StructDef {
fields: struct_def.fields.iter().map(|f| fld.fold_struct_field(f)).collect(),
ctor_id: struct_def.ctor_id.map(|cid| fld.new_id(cid)),
super_struct: match struct_def.super_struct {
Some(t) => Some(fld.fold_ty(t)),
None => None
},
is_virtual: struct_def.is_virtual,
}
}
pub fn noop_fold_trait_ref<T: Folder>(p: &TraitRef, fld: &mut T) -> TraitRef {
let id = fld.new_id(p.ref_id);
ast::TraitRef {
path: fld.fold_path(&p.path),
ref_id: id,
}
}
pub fn noop_fold_struct_field<T: Folder>(f: &StructField, fld: &mut T) -> StructField {
let id = fld.new_id(f.node.id);
Spanned {
node: ast::StructField_ {
kind: f.node.kind,
id: id,
ty: fld.fold_ty(f.node.ty),
attrs: f.node.attrs.iter().map(|a| fld.fold_attribute(*a)).collect(),
},
span: fld.new_span(f.span),
}
}
pub fn noop_fold_field<T: Folder>(field: Field, folder: &mut T) -> Field {
ast::Field {
ident: respan(field.ident.span, folder.fold_ident(field.ident.node)),
expr: folder.fold_expr(field.expr),
span: folder.new_span(field.span),
}
}
pub fn noop_fold_mt<T: Folder>(mt: &MutTy, folder: &mut T) -> MutTy {
MutTy {
ty: folder.fold_ty(mt.ty),
mutbl: mt.mutbl,
}
}
pub fn noop_fold_opt_bounds<T: Folder>(b: &Option<OwnedSlice<TyParamBound>>, folder: &mut T)
-> Option<OwnedSlice<TyParamBound>> {
b.as_ref().map(|bounds| folder.fold_bounds(bounds))
}
fn noop_fold_bounds<T: Folder>(bounds: &TyParamBounds, folder: &mut T)
-> TyParamBounds {
bounds.map(|bound| folder.fold_ty_param_bound(bound))
}
pub fn noop_fold_variant_arg<T: Folder>(va: &VariantArg, folder: &mut T) -> VariantArg {
let id = folder.new_id(va.id);
ast::VariantArg {
ty: folder.fold_ty(va.ty),
id: id,
}
}
pub fn noop_fold_view_item<T: Folder>(vi: &ViewItem, folder: &mut T)
-> ViewItem{
let inner_view_item = match vi.node {
ViewItemExternCrate(ref ident, ref string, node_id) => {
ViewItemExternCrate(ident.clone(),
(*string).clone(),
folder.new_id(node_id))
}
ViewItemUse(ref view_path) => {
ViewItemUse(folder.fold_view_path(*view_path))
}
};
ViewItem {
node: inner_view_item,
attrs: vi.attrs.iter().map(|a| folder.fold_attribute(*a)).collect(),
vis: vi.vis,
span: folder.new_span(vi.span),
}
}
pub fn noop_fold_block<T: Folder>(b: P<Block>, folder: &mut T) -> P<Block> {
let id = folder.new_id(b.id); // Needs to be first, for ast_map.
let view_items = b.view_items.iter().map(|x| folder.fold_view_item(x)).collect();
let stmts = b.stmts.iter().flat_map(|s| folder.fold_stmt(&**s).move_iter()).collect();
P(Block {
id: id,
view_items: view_items,
stmts: stmts,
expr: b.expr.map(|x| folder.fold_expr(x)),
rules: b.rules,
span: folder.new_span(b.span),
})
}
pub fn noop_fold_item_underscore<T: Folder>(i: &Item_, folder: &mut T) -> Item_ {
match *i {
ItemStatic(t, m, e) => {
ItemStatic(folder.fold_ty(t), m, folder.fold_expr(e))
}
ItemFn(decl, fn_style, abi, ref generics, body) => {
ItemFn(
folder.fold_fn_decl(&*decl),
fn_style,
abi,
folder.fold_generics(generics),
folder.fold_block(body)
)
}
ItemMod(ref m) => ItemMod(folder.fold_mod(m)),
ItemForeignMod(ref nm) => ItemForeignMod(folder.fold_foreign_mod(nm)),
ItemTy(t, ref generics) => {
ItemTy(folder.fold_ty(t), folder.fold_generics(generics))
}
ItemEnum(ref enum_definition, ref generics) => {
ItemEnum(
ast::EnumDef {
variants: enum_definition.variants.iter().map(|&x| {
folder.fold_variant(&*x)
}).collect(),
},
folder.fold_generics(generics))
}
ItemStruct(ref struct_def, ref generics) => {
let struct_def = folder.fold_struct_def(*struct_def);
ItemStruct(struct_def, folder.fold_generics(generics))
}
ItemImpl(ref generics, ref ifce, ty, ref impl_items) => {
ItemImpl(folder.fold_generics(generics),
ifce.as_ref().map(|p| folder.fold_trait_ref(p)),
folder.fold_ty(ty),
impl_items.iter()
.flat_map(|impl_item| {
match *impl_item {
MethodImplItem(x) => {
folder.fold_method(x)
.move_iter()
.map(|x| MethodImplItem(x))
}
}
}).collect()
)
}
ItemTrait(ref generics, ref unbound, ref bounds, ref methods) => {
let bounds = folder.fold_bounds(bounds);
let methods = methods.iter().flat_map(|method| {
let r = match *method {
RequiredMethod(ref m) => {
SmallVector::one(RequiredMethod(
folder.fold_type_method(m))).move_iter()
}
ProvidedMethod(method) => {
// the awkward collect/iter idiom here is because
// even though an iter and a map satisfy the same trait bound,
// they're not actually the same type, so the method arms
// don't unify.
let methods : SmallVector<ast::TraitItem> =
folder.fold_method(method).move_iter()
.map(|m| ProvidedMethod(m)).collect();
methods.move_iter()
}
};
r
}).collect();
ItemTrait(folder.fold_generics(generics),
unbound.clone(),
bounds,
methods)
}
ItemMac(ref m) => ItemMac(folder.fold_mac(m)),
}
}
pub fn noop_fold_type_method<T: Folder>(m: &TypeMethod, fld: &mut T) -> TypeMethod {
let id = fld.new_id(m.id); // Needs to be first, for ast_map.
TypeMethod {
id: id,
ident: fld.fold_ident(m.ident),
attrs: m.attrs.iter().map(|a| fld.fold_attribute(*a)).collect(),
fn_style: m.fn_style,
abi: m.abi,
decl: fld.fold_fn_decl(&*m.decl),
generics: fld.fold_generics(&m.generics),
explicit_self: fld.fold_explicit_self(&m.explicit_self),
span: fld.new_span(m.span),
vis: m.vis,
}
}
pub fn noop_fold_mod<T: Folder>(m: &Mod, folder: &mut T) -> Mod {
ast::Mod {
inner: folder.new_span(m.inner),
view_items: m.view_items
.iter()
.map(|x| folder.fold_view_item(x)).collect(),
items: m.items.iter().flat_map(|x| folder.fold_item(*x).move_iter()).collect(),
}
}
pub fn noop_fold_crate<T: Folder>(c: Crate, folder: &mut T) -> Crate {
Crate {
module: folder.fold_mod(&c.module),
attrs: c.attrs.iter().map(|x| folder.fold_attribute(*x)).collect(),
config: c.config.iter().map(|x| box (GC) folder.fold_meta_item(&**x)).collect(),
span: folder.new_span(c.span),
exported_macros: c.exported_macros
}
}
// fold one item into possibly many items
pub fn noop_fold_item<T: Folder>(i: &Item,
folder: &mut T) -> SmallVector<Gc<Item>> {
SmallVector::one(box(GC) folder.fold_item_simple(i))
}
// fold one item into exactly one item
pub fn noop_fold_item_simple<T: Folder>(i: &Item, folder: &mut T) -> Item {
let id = folder.new_id(i.id); // Needs to be first, for ast_map.
let node = folder.fold_item_underscore(&i.node);
let ident = match node {
// The node may have changed, recompute the "pretty" impl name.
ItemImpl(_, ref maybe_trait, ty, _) => {
ast_util::impl_pretty_name(maybe_trait, &*ty)
}
_ => i.ident
};
Item {
id: id,
ident: folder.fold_ident(ident),
attrs: i.attrs.iter().map(|e| folder.fold_attribute(*e)).collect(),
node: node,
vis: i.vis,
span: folder.new_span(i.span)
}
}
pub fn noop_fold_foreign_item<T: Folder>(ni: &ForeignItem,
folder: &mut T) -> Gc<ForeignItem> {
let id = folder.new_id(ni.id); // Needs to be first, for ast_map.
box(GC) ForeignItem {
id: id,
ident: folder.fold_ident(ni.ident),
attrs: ni.attrs.iter().map(|x| folder.fold_attribute(*x)).collect(),
node: match ni.node {
ForeignItemFn(ref fdec, ref generics) => {
ForeignItemFn(P(FnDecl {
inputs: fdec.inputs.iter().map(|a| folder.fold_arg(a)).collect(),
output: folder.fold_ty(fdec.output),
cf: fdec.cf,
variadic: fdec.variadic
}), folder.fold_generics(generics))
}
ForeignItemStatic(t, m) => {
ForeignItemStatic(folder.fold_ty(t), m)
}
},
span: folder.new_span(ni.span),
vis: ni.vis,
}
}
// Default fold over a method.
// Invariant: produces exactly one method.
pub fn noop_fold_method<T: Folder>(m: &Method, folder: &mut T) -> SmallVector<Gc<Method>> {
let id = folder.new_id(m.id); // Needs to be first, for ast_map.
SmallVector::one(box(GC) Method {
attrs: m.attrs.iter().map(|a| folder.fold_attribute(*a)).collect(),
id: id,
span: folder.new_span(m.span),
node: match m.node {
MethDecl(ident,
ref generics,
abi,
ref explicit_self,
fn_style,
decl,
body,
vis) => {
MethDecl(folder.fold_ident(ident),
folder.fold_generics(generics),
abi,
folder.fold_explicit_self(explicit_self),
fn_style,
folder.fold_fn_decl(&*decl),
folder.fold_block(body),
vis)
},
MethMac(ref mac) => MethMac(folder.fold_mac(mac)),
}
})
}
pub fn noop_fold_pat<T: Folder>(p: Gc<Pat>, folder: &mut T) -> Gc<Pat> {
let id = folder.new_id(p.id);
let node = match p.node {
PatWild(k) => PatWild(k),
PatIdent(binding_mode, ref pth1, ref sub) => {
PatIdent(binding_mode,
Spanned{span: folder.new_span(pth1.span),
node: folder.fold_ident(pth1.node)},
sub.map(|x| folder.fold_pat(x)))
}
PatLit(e) => PatLit(folder.fold_expr(e)),
PatEnum(ref pth, ref pats) => {
PatEnum(folder.fold_path(pth),
pats.as_ref().map(|pats| pats.iter().map(|x| folder.fold_pat(*x)).collect()))
}
PatStruct(ref pth, ref fields, etc) => {
let pth_ = folder.fold_path(pth);
let fs = fields.iter().map(|f| {
ast::FieldPat {
ident: f.ident,
pat: folder.fold_pat(f.pat)
}
}).collect();
PatStruct(pth_, fs, etc)
}
PatTup(ref elts) => PatTup(elts.iter().map(|x| folder.fold_pat(*x)).collect()),
PatBox(inner) => PatBox(folder.fold_pat(inner)),
PatRegion(inner) => PatRegion(folder.fold_pat(inner)),
PatRange(e1, e2) => {
PatRange(folder.fold_expr(e1), folder.fold_expr(e2))
},
PatVec(ref before, ref slice, ref after) => {
PatVec(before.iter().map(|x| folder.fold_pat(*x)).collect(),
slice.map(|x| folder.fold_pat(x)),
after.iter().map(|x| folder.fold_pat(*x)).collect())
}
PatMac(ref mac) => PatMac(folder.fold_mac(mac)),
};
box(GC) Pat {
id: id,
span: folder.new_span(p.span),
node: node,
}
}
pub fn noop_fold_expr<T: Folder>(e: Gc<Expr>, folder: &mut T) -> Gc<Expr> {
let id = folder.new_id(e.id);
let node = match e.node {
ExprBox(p, e) => {
ExprBox(folder.fold_expr(p), folder.fold_expr(e))
}
ExprVec(ref exprs) => {
ExprVec(exprs.iter().map(|&x| folder.fold_expr(x)).collect())
}
ExprRepeat(expr, count) => {
ExprRepeat(folder.fold_expr(expr), folder.fold_expr(count))
}
ExprTup(ref elts) => ExprTup(elts.iter().map(|x| folder.fold_expr(*x)).collect()),
ExprCall(f, ref args) => {
ExprCall(folder.fold_expr(f),
args.iter().map(|&x| folder.fold_expr(x)).collect())
}
ExprMethodCall(i, ref tps, ref args) => {
ExprMethodCall(
respan(i.span, folder.fold_ident(i.node)),
tps.iter().map(|&x| folder.fold_ty(x)).collect(),
args.iter().map(|&x| folder.fold_expr(x)).collect())
}
ExprBinary(binop, lhs, rhs) => {
ExprBinary(binop,
folder.fold_expr(lhs),
folder.fold_expr(rhs))
}
ExprUnary(binop, ohs) => {
ExprUnary(binop, folder.fold_expr(ohs))
}
ExprLit(_) => e.node.clone(),
ExprCast(expr, ty) => {
ExprCast(folder.fold_expr(expr), folder.fold_ty(ty))
}
ExprAddrOf(m, ohs) => ExprAddrOf(m, folder.fold_expr(ohs)),
ExprIf(cond, tr, fl) => {
ExprIf(folder.fold_expr(cond),
folder.fold_block(tr),
fl.map(|x| folder.fold_expr(x)))
}
ExprWhile(cond, body, opt_ident) => {
ExprWhile(folder.fold_expr(cond),
folder.fold_block(body),
opt_ident.map(|i| folder.fold_ident(i)))
}
ExprForLoop(pat, iter, body, ref opt_ident) => {
ExprForLoop(folder.fold_pat(pat),
folder.fold_expr(iter),
folder.fold_block(body),
opt_ident.map(|i| folder.fold_ident(i)))
}
ExprLoop(body, opt_ident) => {
ExprLoop(folder.fold_block(body),
opt_ident.map(|i| folder.fold_ident(i)))
}
ExprMatch(expr, ref arms) => {
ExprMatch(folder.fold_expr(expr),
arms.iter().map(|x| folder.fold_arm(x)).collect())
}
ExprFnBlock(capture_clause, ref decl, ref body) => {
ExprFnBlock(capture_clause,
folder.fold_fn_decl(&**decl),
folder.fold_block(body.clone()))
}
ExprProc(ref decl, ref body) => {
ExprProc(folder.fold_fn_decl(&**decl),
folder.fold_block(body.clone()))
}
ExprUnboxedFn(capture_clause, kind, ref decl, ref body) => {
ExprUnboxedFn(capture_clause,
kind,
folder.fold_fn_decl(&**decl),
folder.fold_block(*body))
}
ExprBlock(ref blk) => ExprBlock(folder.fold_block(*blk)),
ExprAssign(el, er) => {
ExprAssign(folder.fold_expr(el), folder.fold_expr(er))
}
ExprAssignOp(op, el, er) => {
ExprAssignOp(op,
folder.fold_expr(el),
folder.fold_expr(er))
}
ExprField(el, id, ref tys) => {
ExprField(folder.fold_expr(el),
respan(id.span, folder.fold_ident(id.node)),
tys.iter().map(|&x| folder.fold_ty(x)).collect())
}
ExprIndex(el, er) => {
ExprIndex(folder.fold_expr(el), folder.fold_expr(er))
}
ExprPath(ref pth) => ExprPath(folder.fold_path(pth)),
ExprBreak(opt_ident) => ExprBreak(opt_ident.map(|x| folder.fold_ident(x))),
ExprAgain(opt_ident) => ExprAgain(opt_ident.map(|x| folder.fold_ident(x))),
ExprRet(ref e) => {
ExprRet(e.map(|x| folder.fold_expr(x)))
}
ExprInlineAsm(ref a) => {
ExprInlineAsm(InlineAsm {
inputs: a.inputs.iter().map(|&(ref c, input)| {
((*c).clone(), folder.fold_expr(input))
}).collect(),
outputs: a.outputs.iter().map(|&(ref c, out, is_rw)| {
((*c).clone(), folder.fold_expr(out), is_rw)
}).collect(),
.. (*a).clone()
})
}
ExprMac(ref mac) => ExprMac(folder.fold_mac(mac)),
ExprStruct(ref path, ref fields, maybe_expr) => {
ExprStruct(folder.fold_path(path),
fields.iter().map(|x| folder.fold_field(*x)).collect(),
maybe_expr.map(|x| folder.fold_expr(x)))
},
ExprParen(ex) => ExprParen(folder.fold_expr(ex))
};
box(GC) Expr {
id: id,
node: node,
span: folder.new_span(e.span),
}
}
pub fn noop_fold_stmt<T: Folder>(s: &Stmt,
folder: &mut T) -> SmallVector<Gc<Stmt>> {
let nodes = match s.node {
StmtDecl(d, id) => {
let id = folder.new_id(id);
folder.fold_decl(d).move_iter()
.map(|d| StmtDecl(d, id))
.collect()
}
StmtExpr(e, id) => {
let id = folder.new_id(id);
SmallVector::one(StmtExpr(folder.fold_expr(e), id))
}
StmtSemi(e, id) => {
let id = folder.new_id(id);
SmallVector::one(StmtSemi(folder.fold_expr(e), id))
}
StmtMac(ref mac, semi) => SmallVector::one(StmtMac(folder.fold_mac(mac), semi))
};
nodes.move_iter().map(|node| box(GC) Spanned {
node: node,
span: folder.new_span(s.span),
}).collect()
}
#[cfg(test)]
mod test {
use std::io;
use ast;
use util::parser_testing::{string_to_crate, matches_codepattern};
use parse::token;
use print::pprust;
use fold;
use super::*;
// this version doesn't care about getting comments or docstrings in.
fn fake_print_crate(s: &mut pprust::State,
krate: &ast::Crate) -> io::IoResult<()> {
s.print_mod(&krate.module, krate.attrs.as_slice())
}
// change every identifier to "zz"
struct ToZzIdentFolder;
impl Folder for ToZzIdentFolder {
fn fold_ident(&mut self, _: ast::Ident) -> ast::Ident {
token::str_to_ident("zz")
}
fn fold_mac(&mut self, macro: &ast::Mac) -> ast::Mac {
fold::noop_fold_mac(macro, self)
}
}
// maybe add to expand.rs...
macro_rules! assert_pred (
($pred:expr, $predname:expr, $a:expr , $b:expr) => (
{
let pred_val = $pred;
let a_val = $a;
let b_val = $b;
if !(pred_val(a_val.as_slice(),b_val.as_slice())) {
fail!("expected args satisfying {}, got {:?} and {:?}",
$predname, a_val, b_val);
}
}
)
)
// make sure idents get transformed everywhere
#[test] fn ident_transformation () {
let mut zz_fold = ToZzIdentFolder;
let ast = string_to_crate(
"#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
let folded_crate = zz_fold.fold_crate(ast);
assert_pred!(
matches_codepattern,
"matches_codepattern",
pprust::to_string(|s| fake_print_crate(s, &folded_crate)),
"#[a]mod zz{fn zz(zz:zz,zz:zz){zz!(zz,zz,zz);zz;zz}}".to_string());
}
// even inside macro defs....
#[test] fn ident_transformation_in_defs () {
let mut zz_fold = ToZzIdentFolder;
let ast = string_to_crate(
"macro_rules! a {(b $c:expr $(d $e:token)f+ => \
(g $(d $d $e)+))} ".to_string());
let folded_crate = zz_fold.fold_crate(ast);
assert_pred!(
matches_codepattern,
"matches_codepattern",
pprust::to_string(|s| fake_print_crate(s, &folded_crate)),
"zz!zz((zz$zz:zz$(zz $zz:zz)zz+=>(zz$(zz$zz$zz)+)))".to_string());
}
}
| {
"content_hash": "48c6fec7afaeb9d17d0bfcbb2543fa5e",
"timestamp": "",
"source": "github",
"line_count": 1294,
"max_line_length": 97,
"avg_line_length": 35.475270479134466,
"alnum_prop": 0.5137348872671822,
"repo_name": "erickt/rust",
"id": "7deabed04b824505eb4c754f9ce60f35f2bffa5b",
"size": "46850",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/libsyntax/fold.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "3206"
},
{
"name": "Assembly",
"bytes": "25901"
},
{
"name": "Awk",
"bytes": "159"
},
{
"name": "C",
"bytes": "685127"
},
{
"name": "C++",
"bytes": "54059"
},
{
"name": "CSS",
"bytes": "20180"
},
{
"name": "Emacs Lisp",
"bytes": "43154"
},
{
"name": "JavaScript",
"bytes": "32223"
},
{
"name": "Perl",
"bytes": "1076"
},
{
"name": "Puppet",
"bytes": "11385"
},
{
"name": "Python",
"bytes": "99103"
},
{
"name": "Rust",
"bytes": "16621557"
},
{
"name": "Shell",
"bytes": "281700"
},
{
"name": "Vim script",
"bytes": "34089"
}
],
"symlink_target": ""
} |
.class Lcom/android/internal/widget/ActionBarView$HomeView;
.super Landroid/widget/FrameLayout;
.source "ActionBarView.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/android/internal/widget/ActionBarView;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0xa
name = "HomeView"
.end annotation
# static fields
.field private static final DEFAULT_TRANSITION_DURATION:J = 0x96L
# instance fields
.field private mDefaultUpIndicator:Landroid/graphics/drawable/Drawable;
.field private mIconView:Landroid/widget/ImageView;
.field private mStartOffset:I
.field private mUpIndicator:Landroid/graphics/drawable/Drawable;
.field private mUpIndicatorRes:I
.field private mUpView:Landroid/widget/ImageView;
.field private mUpWidth:I
# direct methods
.method public constructor <init>(Landroid/content/Context;)V
.locals 1
.param p1, "context" # Landroid/content/Context;
.prologue
.line 1393
const/4 v0, 0x0
invoke-direct {p0, p1, v0}, Lcom/android/internal/widget/ActionBarView$HomeView;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
.line 1394
return-void
.end method
.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
.locals 4
.param p1, "context" # Landroid/content/Context;
.param p2, "attrs" # Landroid/util/AttributeSet;
.prologue
.line 1397
invoke-direct {p0, p1, p2}, Landroid/widget/FrameLayout;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
.line 1398
invoke-virtual {p0}, Lcom/android/internal/widget/ActionBarView$HomeView;->getLayoutTransition()Landroid/animation/LayoutTransition;
move-result-object v0
.line 1399
.local v0, "t":Landroid/animation/LayoutTransition;
if-eqz v0, :cond_0
.line 1401
const-wide/16 v2, 0x96
invoke-virtual {v0, v2, v3}, Landroid/animation/LayoutTransition;->setDuration(J)V
.line 1403
:cond_0
return-void
.end method
.method private updateUpIndicator()V
.locals 3
.prologue
.line 1435
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpIndicator:Landroid/graphics/drawable/Drawable;
if-eqz v0, :cond_0
.line 1436
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
iget-object v1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpIndicator:Landroid/graphics/drawable/Drawable;
invoke-virtual {v0, v1}, Landroid/widget/ImageView;->setImageDrawable(Landroid/graphics/drawable/Drawable;)V
.line 1442
:goto_0
return-void
.line 1437
:cond_0
iget v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpIndicatorRes:I
if-eqz v0, :cond_1
.line 1438
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
invoke-virtual {p0}, Lcom/android/internal/widget/ActionBarView$HomeView;->getContext()Landroid/content/Context;
move-result-object v1
iget v2, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpIndicatorRes:I
invoke-virtual {v1, v2}, Landroid/content/Context;->getDrawable(I)Landroid/graphics/drawable/Drawable;
move-result-object v1
invoke-virtual {v0, v1}, Landroid/widget/ImageView;->setImageDrawable(Landroid/graphics/drawable/Drawable;)V
goto :goto_0
.line 1440
:cond_1
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
iget-object v1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mDefaultUpIndicator:Landroid/graphics/drawable/Drawable;
invoke-virtual {v0, v1}, Landroid/widget/ImageView;->setImageDrawable(Landroid/graphics/drawable/Drawable;)V
goto :goto_0
.end method
# virtual methods
.method public dispatchHoverEvent(Landroid/view/MotionEvent;)Z
.locals 1
.param p1, "event" # Landroid/view/MotionEvent;
.prologue
.line 1471
invoke-virtual {p0, p1}, Lcom/android/internal/widget/ActionBarView$HomeView;->onHoverEvent(Landroid/view/MotionEvent;)Z
move-result v0
return v0
.end method
.method public dispatchPopulateAccessibilityEvent(Landroid/view/accessibility/AccessibilityEvent;)Z
.locals 1
.param p1, "event" # Landroid/view/accessibility/AccessibilityEvent;
.prologue
.line 1455
invoke-virtual {p0, p1}, Lcom/android/internal/widget/ActionBarView$HomeView;->onPopulateAccessibilityEvent(Landroid/view/accessibility/AccessibilityEvent;)V
.line 1456
const/4 v0, 0x1
return v0
.end method
.method public getStartOffset()I
.locals 2
.prologue
.line 1482
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
invoke-virtual {v0}, Landroid/widget/ImageView;->getVisibility()I
move-result v0
const/16 v1, 0x8
if-ne v0, v1, :cond_0
iget v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mStartOffset:I
:goto_0
return v0
:cond_0
const/4 v0, 0x0
goto :goto_0
.end method
.method public getUpWidth()I
.locals 1
.prologue
.line 1486
iget v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpWidth:I
return v0
.end method
.method protected onConfigurationChanged(Landroid/content/res/Configuration;)V
.locals 1
.param p1, "newConfig" # Landroid/content/res/Configuration;
.prologue
.line 1446
invoke-super {p0, p1}, Landroid/widget/FrameLayout;->onConfigurationChanged(Landroid/content/res/Configuration;)V
.line 1447
iget v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpIndicatorRes:I
if-eqz v0, :cond_0
.line 1449
invoke-direct {p0}, Lcom/android/internal/widget/ActionBarView$HomeView;->updateUpIndicator()V
.line 1451
:cond_0
return-void
.end method
.method protected onFinishInflate()V
.locals 1
.prologue
.line 1476
const v0, 0x102003b
invoke-virtual {p0, v0}, Lcom/android/internal/widget/ActionBarView$HomeView;->findViewById(I)Landroid/view/View;
move-result-object v0
check-cast v0, Landroid/widget/ImageView;
iput-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
.line 1477
const v0, 0x102002c
invoke-virtual {p0, v0}, Lcom/android/internal/widget/ActionBarView$HomeView;->findViewById(I)Landroid/view/View;
move-result-object v0
check-cast v0, Landroid/widget/ImageView;
iput-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
.line 1478
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
invoke-virtual {v0}, Landroid/widget/ImageView;->getDrawable()Landroid/graphics/drawable/Drawable;
move-result-object v0
iput-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mDefaultUpIndicator:Landroid/graphics/drawable/Drawable;
.line 1479
return-void
.end method
.method protected onLayout(ZIIII)V
.locals 27
.param p1, "changed" # Z
.param p2, "l" # I
.param p3, "t" # I
.param p4, "r" # I
.param p5, "b" # I
.prologue
.line 1542
sub-int v25, p5, p3
div-int/lit8 v23, v25, 0x2
.line 1543
.local v23, "vCenter":I
invoke-virtual/range {p0 .. p0}, Lcom/android/internal/widget/ActionBarView$HomeView;->isLayoutRtl()Z
move-result v13
.line 1544
.local v13, "isLayoutRtl":Z
invoke-virtual/range {p0 .. p0}, Lcom/android/internal/widget/ActionBarView$HomeView;->getWidth()I
move-result v24
.line 1545
.local v24, "width":I
const/16 v19, 0x0
.line 1546
.local v19, "upOffset":I
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
move-object/from16 v25, v0
invoke-virtual/range {v25 .. v25}, Landroid/widget/ImageView;->getVisibility()I
move-result v25
const/16 v26, 0x8
move/from16 v0, v25
move/from16 v1, v26
if-eq v0, v1, :cond_0
.line 1547
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
move-object/from16 v25, v0
invoke-virtual/range {v25 .. v25}, Landroid/widget/ImageView;->getLayoutParams()Landroid/view/ViewGroup$LayoutParams;
move-result-object v18
check-cast v18, Landroid/widget/FrameLayout$LayoutParams;
.line 1548
.local v18, "upLp":Landroid/widget/FrameLayout$LayoutParams;
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
move-object/from16 v25, v0
invoke-virtual/range {v25 .. v25}, Landroid/widget/ImageView;->getMeasuredHeight()I
move-result v16
.line 1549
.local v16, "upHeight":I
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
move-object/from16 v25, v0
invoke-virtual/range {v25 .. v25}, Landroid/widget/ImageView;->getMeasuredWidth()I
move-result v22
.line 1550
.local v22, "upWidth":I
move-object/from16 v0, v18
iget v0, v0, Landroid/widget/FrameLayout$LayoutParams;->leftMargin:I
move/from16 v25, v0
add-int v25, v25, v22
move-object/from16 v0, v18
iget v0, v0, Landroid/widget/FrameLayout$LayoutParams;->rightMargin:I
move/from16 v26, v0
add-int v19, v25, v26
.line 1551
div-int/lit8 v25, v16, 0x2
sub-int v21, v23, v25
.line 1552
.local v21, "upTop":I
add-int v15, v21, v16
.line 1555
.local v15, "upBottom":I
if-eqz v13, :cond_1
.line 1556
move/from16 v20, v24
.line 1557
.local v20, "upRight":I
sub-int v17, v20, v22
.line 1558
.local v17, "upLeft":I
sub-int p4, p4, v19
.line 1564
:goto_0
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
move-object/from16 v25, v0
move-object/from16 v0, v25
move/from16 v1, v17
move/from16 v2, v21
move/from16 v3, v20
invoke-virtual {v0, v1, v2, v3, v15}, Landroid/widget/ImageView;->layout(IIII)V
.line 1567
.end local v15 # "upBottom":I
.end local v16 # "upHeight":I
.end local v17 # "upLeft":I
.end local v18 # "upLp":Landroid/widget/FrameLayout$LayoutParams;
.end local v20 # "upRight":I
.end local v21 # "upTop":I
.end local v22 # "upWidth":I
:cond_0
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
move-object/from16 v25, v0
invoke-virtual/range {v25 .. v25}, Landroid/widget/ImageView;->getLayoutParams()Landroid/view/ViewGroup$LayoutParams;
move-result-object v9
check-cast v9, Landroid/widget/FrameLayout$LayoutParams;
.line 1568
.local v9, "iconLp":Landroid/widget/FrameLayout$LayoutParams;
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
move-object/from16 v25, v0
invoke-virtual/range {v25 .. v25}, Landroid/widget/ImageView;->getMeasuredHeight()I
move-result v7
.line 1569
.local v7, "iconHeight":I
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
move-object/from16 v25, v0
invoke-virtual/range {v25 .. v25}, Landroid/widget/ImageView;->getMeasuredWidth()I
move-result v12
.line 1570
.local v12, "iconWidth":I
sub-int v25, p4, p2
div-int/lit8 v5, v25, 0x2
.line 1571
.local v5, "hCenter":I
iget v0, v9, Landroid/widget/FrameLayout$LayoutParams;->topMargin:I
move/from16 v25, v0
div-int/lit8 v26, v7, 0x2
sub-int v26, v23, v26
invoke-static/range {v25 .. v26}, Ljava/lang/Math;->max(II)I
move-result v11
.line 1572
.local v11, "iconTop":I
add-int v6, v11, v7
.line 1575
.local v6, "iconBottom":I
invoke-virtual {v9}, Landroid/widget/FrameLayout$LayoutParams;->getMarginStart()I
move-result v14
.line 1576
.local v14, "marginStart":I
div-int/lit8 v25, v12, 0x2
sub-int v25, v5, v25
move/from16 v0, v25
invoke-static {v14, v0}, Ljava/lang/Math;->max(II)I
move-result v4
.line 1577
.local v4, "delta":I
if-eqz v13, :cond_2
.line 1578
sub-int v25, v24, v19
sub-int v10, v25, v4
.line 1579
.local v10, "iconRight":I
sub-int v8, v10, v12
.line 1584
.local v8, "iconLeft":I
:goto_1
move-object/from16 v0, p0
iget-object v0, v0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
move-object/from16 v25, v0
move-object/from16 v0, v25
invoke-virtual {v0, v8, v11, v10, v6}, Landroid/widget/ImageView;->layout(IIII)V
.line 1585
return-void
.line 1560
.end local v4 # "delta":I
.end local v5 # "hCenter":I
.end local v6 # "iconBottom":I
.end local v7 # "iconHeight":I
.end local v8 # "iconLeft":I
.end local v9 # "iconLp":Landroid/widget/FrameLayout$LayoutParams;
.end local v10 # "iconRight":I
.end local v11 # "iconTop":I
.end local v12 # "iconWidth":I
.end local v14 # "marginStart":I
.restart local v15 # "upBottom":I
.restart local v16 # "upHeight":I
.restart local v18 # "upLp":Landroid/widget/FrameLayout$LayoutParams;
.restart local v21 # "upTop":I
.restart local v22 # "upWidth":I
:cond_1
move/from16 v20, v22
.line 1561
.restart local v20 # "upRight":I
const/16 v17, 0x0
.line 1562
.restart local v17 # "upLeft":I
add-int p2, p2, v19
goto :goto_0
.line 1581
.end local v15 # "upBottom":I
.end local v16 # "upHeight":I
.end local v17 # "upLeft":I
.end local v18 # "upLp":Landroid/widget/FrameLayout$LayoutParams;
.end local v20 # "upRight":I
.end local v21 # "upTop":I
.end local v22 # "upWidth":I
.restart local v4 # "delta":I
.restart local v5 # "hCenter":I
.restart local v6 # "iconBottom":I
.restart local v7 # "iconHeight":I
.restart local v9 # "iconLp":Landroid/widget/FrameLayout$LayoutParams;
.restart local v11 # "iconTop":I
.restart local v12 # "iconWidth":I
.restart local v14 # "marginStart":I
:cond_2
add-int v8, v19, v4
.line 1582
.restart local v8 # "iconLeft":I
add-int v10, v8, v12
.restart local v10 # "iconRight":I
goto :goto_1
.end method
.method protected onMeasure(II)V
.locals 14
.param p1, "widthMeasureSpec" # I
.param p2, "heightMeasureSpec" # I
.prologue
.line 1491
iget-object v1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
const/4 v3, 0x0
const/4 v5, 0x0
move-object v0, p0
move v2, p1
move/from16 v4, p2
invoke-virtual/range {v0 .. v5}, Lcom/android/internal/widget/ActionBarView$HomeView;->measureChildWithMargins(Landroid/view/View;IIII)V
.line 1492
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
invoke-virtual {v0}, Landroid/widget/ImageView;->getLayoutParams()Landroid/view/ViewGroup$LayoutParams;
move-result-object v10
check-cast v10, Landroid/widget/FrameLayout$LayoutParams;
.line 1493
.local v10, "upLp":Landroid/widget/FrameLayout$LayoutParams;
iget v0, v10, Landroid/widget/FrameLayout$LayoutParams;->leftMargin:I
iget v1, v10, Landroid/widget/FrameLayout$LayoutParams;->rightMargin:I
add-int v11, v0, v1
.line 1494
.local v11, "upMargins":I
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
invoke-virtual {v0}, Landroid/widget/ImageView;->getMeasuredWidth()I
move-result v0
iput v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpWidth:I
.line 1495
iget v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpWidth:I
add-int/2addr v0, v11
iput v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mStartOffset:I
.line 1496
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
invoke-virtual {v0}, Landroid/widget/ImageView;->getVisibility()I
move-result v0
const/16 v1, 0x8
if-ne v0, v1, :cond_1
const/4 v3, 0x0
.line 1497
.local v3, "width":I
:goto_0
iget v0, v10, Landroid/widget/FrameLayout$LayoutParams;->topMargin:I
iget-object v1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
invoke-virtual {v1}, Landroid/widget/ImageView;->getMeasuredHeight()I
move-result v1
add-int/2addr v0, v1
iget v1, v10, Landroid/widget/FrameLayout$LayoutParams;->bottomMargin:I
add-int v6, v0, v1
.line 1499
.local v6, "height":I
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
invoke-virtual {v0}, Landroid/widget/ImageView;->getVisibility()I
move-result v0
const/16 v1, 0x8
if-eq v0, v1, :cond_2
.line 1500
iget-object v1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
const/4 v5, 0x0
move-object v0, p0
move v2, p1
move/from16 v4, p2
invoke-virtual/range {v0 .. v5}, Lcom/android/internal/widget/ActionBarView$HomeView;->measureChildWithMargins(Landroid/view/View;IIII)V
.line 1501
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
invoke-virtual {v0}, Landroid/widget/ImageView;->getLayoutParams()Landroid/view/ViewGroup$LayoutParams;
move-result-object v9
check-cast v9, Landroid/widget/FrameLayout$LayoutParams;
.line 1502
.local v9, "iconLp":Landroid/widget/FrameLayout$LayoutParams;
iget v0, v9, Landroid/widget/FrameLayout$LayoutParams;->leftMargin:I
iget-object v1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
invoke-virtual {v1}, Landroid/widget/ImageView;->getMeasuredWidth()I
move-result v1
add-int/2addr v0, v1
iget v1, v9, Landroid/widget/FrameLayout$LayoutParams;->rightMargin:I
add-int/2addr v0, v1
add-int/2addr v3, v0
.line 1503
iget v0, v9, Landroid/widget/FrameLayout$LayoutParams;->topMargin:I
iget-object v1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
invoke-virtual {v1}, Landroid/widget/ImageView;->getMeasuredHeight()I
move-result v1
add-int/2addr v0, v1
iget v1, v9, Landroid/widget/FrameLayout$LayoutParams;->bottomMargin:I
add-int/2addr v0, v1
invoke-static {v6, v0}, Ljava/lang/Math;->max(II)I
move-result v6
.line 1510
.end local v9 # "iconLp":Landroid/widget/FrameLayout$LayoutParams;
:cond_0
:goto_1
invoke-static {p1}, Landroid/view/View$MeasureSpec;->getMode(I)I
move-result v12
.line 1511
.local v12, "widthMode":I
invoke-static/range {p2 .. p2}, Landroid/view/View$MeasureSpec;->getMode(I)I
move-result v7
.line 1512
.local v7, "heightMode":I
invoke-static {p1}, Landroid/view/View$MeasureSpec;->getSize(I)I
move-result v13
.line 1513
.local v13, "widthSize":I
invoke-static/range {p2 .. p2}, Landroid/view/View$MeasureSpec;->getSize(I)I
move-result v8
.line 1515
.local v8, "heightSize":I
sparse-switch v12, :sswitch_data_0
.line 1526
:goto_2
sparse-switch v7, :sswitch_data_1
.line 1537
:goto_3
invoke-virtual {p0, v3, v6}, Lcom/android/internal/widget/ActionBarView$HomeView;->setMeasuredDimension(II)V
.line 1538
return-void
.line 1496
.end local v3 # "width":I
.end local v6 # "height":I
.end local v7 # "heightMode":I
.end local v8 # "heightSize":I
.end local v12 # "widthMode":I
.end local v13 # "widthSize":I
:cond_1
iget v3, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mStartOffset:I
goto :goto_0
.line 1505
.restart local v3 # "width":I
.restart local v6 # "height":I
:cond_2
if-gez v11, :cond_0
.line 1507
sub-int/2addr v3, v11
goto :goto_1
.line 1517
.restart local v7 # "heightMode":I
.restart local v8 # "heightSize":I
.restart local v12 # "widthMode":I
.restart local v13 # "widthSize":I
:sswitch_0
invoke-static {v3, v13}, Ljava/lang/Math;->min(II)I
move-result v3
.line 1518
goto :goto_2
.line 1520
:sswitch_1
move v3, v13
.line 1521
goto :goto_2
.line 1528
:sswitch_2
invoke-static {v6, v8}, Ljava/lang/Math;->min(II)I
move-result v6
.line 1529
goto :goto_3
.line 1531
:sswitch_3
move v6, v8
.line 1532
goto :goto_3
.line 1515
:sswitch_data_0
.sparse-switch
-0x80000000 -> :sswitch_0
0x40000000 -> :sswitch_1
.end sparse-switch
.line 1526
:sswitch_data_1
.sparse-switch
-0x80000000 -> :sswitch_2
0x40000000 -> :sswitch_3
.end sparse-switch
.end method
.method public onPopulateAccessibilityEvent(Landroid/view/accessibility/AccessibilityEvent;)V
.locals 2
.param p1, "event" # Landroid/view/accessibility/AccessibilityEvent;
.prologue
.line 1461
invoke-super {p0, p1}, Landroid/widget/FrameLayout;->onPopulateAccessibilityEvent(Landroid/view/accessibility/AccessibilityEvent;)V
.line 1462
invoke-virtual {p0}, Lcom/android/internal/widget/ActionBarView$HomeView;->getContentDescription()Ljava/lang/CharSequence;
move-result-object v0
.line 1463
.local v0, "cdesc":Ljava/lang/CharSequence;
invoke-static {v0}, Landroid/text/TextUtils;->isEmpty(Ljava/lang/CharSequence;)Z
move-result v1
if-nez v1, :cond_0
.line 1464
invoke-virtual {p1}, Landroid/view/accessibility/AccessibilityEvent;->getText()Ljava/util/List;
move-result-object v1
invoke-interface {v1, v0}, Ljava/util/List;->add(Ljava/lang/Object;)Z
.line 1466
:cond_0
return-void
.end method
.method public setDefaultUpIndicator(Landroid/graphics/drawable/Drawable;)V
.locals 0
.param p1, "d" # Landroid/graphics/drawable/Drawable;
.prologue
.line 1424
iput-object p1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mDefaultUpIndicator:Landroid/graphics/drawable/Drawable;
.line 1425
invoke-direct {p0}, Lcom/android/internal/widget/ActionBarView$HomeView;->updateUpIndicator()V
.line 1426
return-void
.end method
.method public setIcon(Landroid/graphics/drawable/Drawable;)V
.locals 1
.param p1, "icon" # Landroid/graphics/drawable/Drawable;
.prologue
.line 1414
iget-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
invoke-virtual {v0, p1}, Landroid/widget/ImageView;->setImageDrawable(Landroid/graphics/drawable/Drawable;)V
.line 1415
return-void
.end method
.method public setShowIcon(Z)V
.locals 2
.param p1, "showIcon" # Z
.prologue
.line 1410
iget-object v1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mIconView:Landroid/widget/ImageView;
if-eqz p1, :cond_0
const/4 v0, 0x0
:goto_0
invoke-virtual {v1, v0}, Landroid/widget/ImageView;->setVisibility(I)V
.line 1411
return-void
.line 1410
:cond_0
const/16 v0, 0x8
goto :goto_0
.end method
.method public setShowUp(Z)V
.locals 2
.param p1, "isUp" # Z
.prologue
.line 1406
iget-object v1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpView:Landroid/widget/ImageView;
if-eqz p1, :cond_0
const/4 v0, 0x0
:goto_0
invoke-virtual {v1, v0}, Landroid/widget/ImageView;->setVisibility(I)V
.line 1407
return-void
.line 1406
:cond_0
const/16 v0, 0x8
goto :goto_0
.end method
.method public setUpIndicator(I)V
.locals 1
.param p1, "resId" # I
.prologue
.line 1429
iput p1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpIndicatorRes:I
.line 1430
const/4 v0, 0x0
iput-object v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpIndicator:Landroid/graphics/drawable/Drawable;
.line 1431
invoke-direct {p0}, Lcom/android/internal/widget/ActionBarView$HomeView;->updateUpIndicator()V
.line 1432
return-void
.end method
.method public setUpIndicator(Landroid/graphics/drawable/Drawable;)V
.locals 1
.param p1, "d" # Landroid/graphics/drawable/Drawable;
.prologue
.line 1418
iput-object p1, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpIndicator:Landroid/graphics/drawable/Drawable;
.line 1419
const/4 v0, 0x0
iput v0, p0, Lcom/android/internal/widget/ActionBarView$HomeView;->mUpIndicatorRes:I
.line 1420
invoke-direct {p0}, Lcom/android/internal/widget/ActionBarView$HomeView;->updateUpIndicator()V
.line 1421
return-void
.end method
| {
"content_hash": "2ce90904015cabbe016359cac673e011",
"timestamp": "",
"source": "github",
"line_count": 999,
"max_line_length": 161,
"avg_line_length": 25.873873873873872,
"alnum_prop": 0.687867533271433,
"repo_name": "shumxin/FlymeOS_A5DUG",
"id": "134c4c463cfa47eca8d06790d1feeda401efc58c",
"size": "25848",
"binary": false,
"copies": "1",
"ref": "refs/heads/lollipop-5.0",
"path": "framework.jar.out/smali/com/android/internal/widget/ActionBarView$HomeView.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "96769"
},
{
"name": "Makefile",
"bytes": "13678"
},
{
"name": "Shell",
"bytes": "103420"
},
{
"name": "Smali",
"bytes": "189389087"
}
],
"symlink_target": ""
} |
package org.apache.jmeter.functions;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
* This class wraps the {@link XPathFileContainer} for use across multiple threads.
* <p>
* It maintains a list of nodelist containers, one for each file/xpath combination
*
*/
final class XPathWrapper {
private static final Logger log = LoggerFactory.getLogger(XPathWrapper.class);
/**
* This Map serves two purposes:
* <ul>
* <li>maps names to containers</li>
* <li>ensures only one container per file across all threads</li>
* </ul>
* The key is the concatenation of the file name and the XPath string
*/
private static final Map<String, XPathFileContainer> fileContainers =
new HashMap<>();
/* The cache of file packs - for faster local access */
private static final ThreadLocal<Map<String, XPathFileContainer>> filePacks =
ThreadLocal.withInitial(HashMap::new);
private XPathWrapper() {// Prevent separate instantiation
super();
}
private static XPathFileContainer open(String file, String xpathString) {
if (log.isInfoEnabled()) {
log.info("{}: Opening {}", Thread.currentThread().getName(), file);
}
XPathFileContainer frcc=null;
try {
frcc = new XPathFileContainer(file, xpathString);
} catch (TransformerException | SAXException
| ParserConfigurationException | IOException e) {
log.warn(e.getLocalizedMessage());
}
return frcc;
}
/**
* Not thread-safe - must be called from a synchronized method.
*
* @param file name of the file
* @param xpathString xpath to look up in file
* @return the next row from the file container
*/
public static String getXPathString(String file, String xpathString) {
Map<String, XPathFileContainer> my = filePacks.get();
String key = file+xpathString;
XPathFileContainer xpfc = my.get(key);
if (xpfc == null) // We don't have a local copy
{
synchronized(fileContainers){
xpfc = fileContainers.get(key);
if (xpfc == null) { // There's no global copy either
xpfc=open(file, xpathString);
}
if (xpfc != null) {
fileContainers.put(key, xpfc);// save the global copy
}
}
// TODO improve the error handling
if (xpfc == null) {
log.error("XPathFileContainer is null!");
return ""; //$NON-NLS-1$
}
my.put(key,xpfc); // save our local copy
}
if (xpfc.size()==0){
log.warn("XPathFileContainer has no nodes: {} {}", file, xpathString);
return ""; //$NON-NLS-1$
}
int currentRow = xpfc.nextRow();
if (log.isDebugEnabled()) {
log.debug("getting match number {}", Integer.toString(currentRow));
}
return xpfc.getXPathString(currentRow);
}
public static void clearAll() {
log.debug("clearAll()");
filePacks.get().clear();
if (log.isInfoEnabled()) {
log.info("{}: clearing container", Thread.currentThread().getName());
}
synchronized (fileContainers) {
fileContainers.clear();
}
}
}
| {
"content_hash": "e5938da27677a923ac80a9265b7f4b7e",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 83,
"avg_line_length": 33.27522935779817,
"alnum_prop": 0.5969120485249517,
"repo_name": "apache/jmeter",
"id": "f78ade2033c721b1c910a84518aa4772c95fb5a2",
"size": "4424",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/functions/src/main/java/org/apache/jmeter/functions/XPathWrapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "25552"
},
{
"name": "CSS",
"bytes": "23066"
},
{
"name": "Groovy",
"bytes": "163162"
},
{
"name": "HTML",
"bytes": "93440"
},
{
"name": "Java",
"bytes": "9107417"
},
{
"name": "JavaScript",
"bytes": "36223"
},
{
"name": "Kotlin",
"bytes": "198418"
},
{
"name": "Less",
"bytes": "6310"
},
{
"name": "Shell",
"bytes": "24265"
},
{
"name": "XSLT",
"bytes": "91415"
}
],
"symlink_target": ""
} |
$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__))
require 'sequel'
require 'polymorphic'
Sequel::Model.plugin :polymorphic
DB = Sequel.connect('sqlite://fantasy.db')
require 'models/photo'
require 'models/author'
require 'models/book'
require 'models/chapter'
require 'models/series'
require 'models/store'
| {
"content_hash": "57e4e47cb8e82954424655982b517ce9",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 59,
"avg_line_length": 22.857142857142858,
"alnum_prop": 0.7625,
"repo_name": "endpoints/fantasy-database",
"id": "4538bf73938af0ab1a7ca7a26e0bc03f739d8769",
"size": "320",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ruby/sequel/index.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3083"
},
{
"name": "Ruby",
"bytes": "5941"
}
],
"symlink_target": ""
} |
from distutils.core import setup
from pyql import __author__, __version__, __email__, __license__, __maintainer__
short_description = 'YQL Queries and Yahoo Weather in Python v.%s' % __version__
try:
long_description = open('README.md').read()
except:
long_description = "YQL Queries and Yahoo Weather in Python v.%s" % __version__
setup(name='pyql-weather',
version=__version__,
description=short_description,
long_description=long_description,
license=__license__,
author=__author__,
author_email=__email__,
maintainer=__maintainer__,
maintainer_email=__email__,
url='http://www.github.com/alexdzul/pyql-weather/',
packages=['pyql', 'pyql.weather', 'pyql.geo', 'demos'],
data_files=[('', ['README.md', 'LICENSE'])],
keywords=['pyql', 'yahoo', 'weather', 'forecast', 'yql'],
platforms='any',
classifiers=["Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries :: Python Modules",
]
) | {
"content_hash": "79d567c1d0f1f5449b8dc644cf9058ea",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 83,
"avg_line_length": 42.26190476190476,
"alnum_prop": 0.540281690140845,
"repo_name": "alexdzul/pyql-weather",
"id": "0acc91a884190a920219e44376a146e5d6569e69",
"size": "1797",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "67096"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Mon Jan 15 08:36:52 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package org.wildfly.swarm.ejb.detect (BOM: * : All 2018.1.0 API)</title>
<meta name="date" content="2018-01-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.wildfly.swarm.ejb.detect (BOM: * : All 2018.1.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.1.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/ejb/detect/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package org.wildfly.swarm.ejb.detect" class="title">Uses of Package<br>org.wildfly.swarm.ejb.detect</h1>
</div>
<div class="contentContainer">No usage of org.wildfly.swarm.ejb.detect</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.1.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/ejb/detect/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "db050c54a576cad94e69559fd1bb5f5a",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 135,
"avg_line_length": 34.828125,
"alnum_prop": 0.6099147599820547,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "d40404e8ea4ff818484a71aa237d023e5e90b56c",
"size": "4458",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2018.1.0/apidocs/org/wildfly/swarm/ejb/detect/package-use.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace corsairs.core.worldgen.biomes
{
public class Beach : Biome
{
public override bool ConditionsMet(int height, int drainage, bool isWater, double temp)
{
return false;
}
public override char DebugSymbol
{
get { return 'b'; }
}
public override bool SuitableForPOI
{
get
{
return true;
}
}
}
}
| {
"content_hash": "50a2bdd492177b8da918f5dedff4ec48",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 95,
"avg_line_length": 20.96551724137931,
"alnum_prop": 0.5230263157894737,
"repo_name": "danrose/corsairs",
"id": "350a025e079a5370828e75d481caeb3420d7b1cf",
"size": "610",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "corsairs.core/worldgen/biomes/Beach.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "91295"
}
],
"symlink_target": ""
} |
package keywords;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class FinalKeyword {
final int[] ia = new int[] {1, 2};
final long[] la;
final List<String> sl = new ArrayList<String>();
final Set<Integer> is;
public FinalKeyword() {
la = new long[] {7L, 6L};
is = new HashSet<Integer>();
}
private void printOut() {
System.out.println("\nint array");
for (int i = 0; i < ia.length; i++) {
System.out.print(ia[i] + " ");
}
System.out.println("\nlong array");
for (int i = 0; i < ia.length; i++) {
System.out.print(la[i] + " ");
}
System.out.println("\nString list");
for (String s : sl) {
System.out.print(s + " ");
}
System.out.println("\nInteger set");
for (Integer i : is) {
System.out.print(i + " ");
}
}
private void extend() {
// ia = new int[] {1, 2, 3}; // compiler error
// la = new long[] {5L, 6L, 7L}; // compiler error
// sl = new ArrayList<String>(); // compiler error
sl.add("one");
sl.add("two");
// is = new HashSet<Integer>();// compiler error
is.add(3);
is.add(4);
is.add(5);
}
public static void main(String[] args) {
FinalKeyword fk = new FinalKeyword();
fk.printOut();
fk.extend();
fk.printOut();
}
}
| {
"content_hash": "d81ebddc1110b67db420c6e1c949f48a",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 54,
"avg_line_length": 24.57894736842105,
"alnum_prop": 0.5367594575303355,
"repo_name": "antalpeti/Test",
"id": "cc6b9c494a23f5fb89c206b848f234b8f907fc2f",
"size": "1401",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/keywords/FinalKeyword.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "549"
},
{
"name": "Java",
"bytes": "75305"
}
],
"symlink_target": ""
} |
ActionBoxButtonView::ActionBoxButtonView(Browser* browser,
const gfx::Point& menu_offset)
: views::MenuButton(NULL, string16(), this, false),
browser_(browser),
menu_offset_(menu_offset),
ALLOW_THIS_IN_INITIALIZER_LIST(controller_(browser, this)) {
set_id(VIEW_ID_ACTION_BOX_BUTTON);
SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_ACTION_BOX_BUTTON));
SetIcon(*ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
IDR_ACTION_BOX_BUTTON_NORMAL));
SetHoverIcon(*ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
IDR_ACTION_BOX_BUTTON_HOVER));
SetPushedIcon(*ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
IDR_ACTION_BOX_BUTTON_PRESSED));
set_accessibility_focusable(true);
set_border(NULL);
SizeToPreferredSize();
}
ActionBoxButtonView::~ActionBoxButtonView() {
}
int ActionBoxButtonView::GetBuiltInHorizontalPadding() const {
return GetBuiltInHorizontalPaddingImpl();
}
void ActionBoxButtonView::GetAccessibleState(ui::AccessibleViewState* state) {
MenuButton::GetAccessibleState(state);
state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_ACTION_BOX_BUTTON);
}
void ActionBoxButtonView::OnMenuButtonClicked(View* source,
const gfx::Point& point) {
controller_.OnButtonClicked();
}
void ActionBoxButtonView::ShowMenu(scoped_ptr<ActionBoxMenuModel> menu_model) {
menu_ = ActionBoxMenu::Create(browser_, menu_model.Pass());
menu_->RunMenu(this, menu_offset_);
}
| {
"content_hash": "573acfda4dd8bef31b0b17268b30fb70",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 79,
"avg_line_length": 38.8,
"alnum_prop": 0.7145618556701031,
"repo_name": "codenote/chromium-test",
"id": "181e4b3b9880fd9f78dbddf7b4329b95b27270d5",
"size": "2335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chrome/browser/ui/views/location_bar/action_box_button_view.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
promise_test(async (t) => {
// Wait for after the load event so that we're definitely testing intentional,
// navigate()-caused replacement and not the replacement that happens
// automatically before the load event completes.
await new Promise(r => window.onload = () => t.step_timeout(r, 0));
const entriesBefore = navigation.entries();
const currentBefore = navigation.currentEntry;
let disposeCalled = false;
navigation.currentEntry.ondispose = t.step_func(e => {
disposeCalled = true;
assert_equals(e.constructor, Event);
assert_equals(e.bubbles, false);
assert_equals(e.cancelable, false);
assert_equals(e.composed, false);
assert_not_equals(navigation.currentEntry, currentBefore);
assert_array_equals(navigation.entries(), [navigation.currentEntry]);
assert_equals((new URL(navigation.currentEntry.url)).search, "?replacement");
assert_equals(navigation.transition.navigationType, "replace");
assert_equals(navigation.transition.from, entriesBefore[0]);
assert_equals(location.search, "?replacement");
});
navigation.addEventListener("navigate", e => e.intercept());
navigation.navigate("?replacement", { history: "replace" });
assert_true(disposeCalled);
}, "dispose events when doing a same-document replace using navigation.navigate() and intercept()");
</script>
| {
"content_hash": "e097154d583ad297fb7b81616fe9bc56",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 100,
"avg_line_length": 41.111111111111114,
"alnum_prop": 0.727027027027027,
"repo_name": "chromium/chromium",
"id": "4e492e30aedeb69030cb596e2e5b8f117290d2de",
"size": "1480",
"binary": false,
"copies": "13",
"ref": "refs/heads/main",
"path": "third_party/blink/web_tests/external/wpt/navigation-api/per-entry-events/dispose-same-document-replace-with-intercept.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
#include "modules/data/tools/smart_recorder/post_record_processor.h"
#include <dirent.h>
#include <algorithm>
#include <memory>
#include "cyber/common/file.h"
#include "cyber/common/log.h"
#include "cyber/record/record_reader.h"
#include "cyber/record/record_viewer.h"
#include "modules/common/util/string_util.h"
#include "modules/data/tools/smart_recorder/channel_pool.h"
#include "modules/data/tools/smart_recorder/interval_pool.h"
namespace apollo {
namespace data {
using apollo::common::util::StrCat;
using cyber::common::DirectoryExists;
using cyber::record::RecordReader;
using cyber::record::RecordViewer;
using cyber::record::RecordWriter;
bool PostRecordProcessor::Init(const SmartRecordTrigger& trigger_conf) {
if (!DirectoryExists(source_record_dir_)) {
AERROR << "source record dir does not exist: " << source_record_dir_;
return false;
}
LoadSourceRecords();
if (source_record_files_.empty()) {
AERROR << "source record dir does not have any records: "
<< source_record_dir_;
return false;
}
if (!RecordProcessor::Init(trigger_conf)) {
AERROR << "base init failed";
return false;
}
return true;
}
bool PostRecordProcessor::Process() {
// First scan, get intervals
for (const std::string& record : source_record_files_) {
const auto reader =
std::make_shared<RecordReader>(StrCat(source_record_dir_, "/", record));
RecordViewer viewer(reader, 0, UINT64_MAX,
ChannelPool::Instance()->GetAllChannels());
AINFO << record << ":" << viewer.begin_time() << " - " << viewer.end_time();
for (const auto& msg : viewer) {
for (const auto& trigger : triggers_) {
trigger->Pull(msg);
}
}
}
// Second scan, restore messages based on intervals in the first scan
IntervalPool::Instance()->ReorgIntervals();
IntervalPool::Instance()->PrintIntervals();
for (const std::string& record : source_record_files_) {
const auto reader =
std::make_shared<RecordReader>(StrCat(source_record_dir_, "/", record));
RecordViewer viewer(reader, 0, UINT64_MAX,
ChannelPool::Instance()->GetAllChannels());
for (const auto& msg : viewer) {
// If the message fall into generated intervals,
// or required by any triggers, restore it
if (IntervalPool::Instance()->MessageFallIntoRange(msg.time) ||
ShouldRestore(msg)) {
writer_->WriteChannel(msg.channel_name,
reader->GetMessageType(msg.channel_name),
reader->GetProtoDesc(msg.channel_name));
writer_->WriteMessage(msg.channel_name, msg.content, msg.time);
}
}
}
return true;
}
std::string PostRecordProcessor::GetDefaultOutputFile() const {
std::string src_file_name = source_record_files_.front();
const std::string record_flag(".record");
src_file_name.resize(src_file_name.size() - src_file_name.find(record_flag) +
record_flag.size() + 1);
return StrCat(restored_output_dir_, "/", src_file_name);
}
void PostRecordProcessor::LoadSourceRecords() {
DIR* dirp = opendir(source_record_dir_.c_str());
if (dirp == nullptr) {
AERROR << "failed to open source dir: " << source_record_dir_;
return;
}
struct dirent* dp = nullptr;
while ((dp = readdir(dirp)) != nullptr) {
const std::string file_name = dp->d_name;
if (dp->d_type == DT_REG &&
file_name.find(".record") != std::string::npos) {
source_record_files_.push_back(file_name);
}
}
closedir(dirp);
std::sort(source_record_files_.begin(), source_record_files_.end());
}
} // namespace data
} // namespace apollo
| {
"content_hash": "371363ac43d5154e33bfcbe024c34ed3",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 80,
"avg_line_length": 33.518181818181816,
"alnum_prop": 0.6484947111472742,
"repo_name": "wanglei828/apollo",
"id": "0c74a94703ae5ddef4fd24d1650d6c077a0c6584",
"size": "4459",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/data/tools/smart_recorder/post_record_processor.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "1922"
},
{
"name": "Batchfile",
"bytes": "791"
},
{
"name": "C",
"bytes": "22662"
},
{
"name": "C++",
"bytes": "17378263"
},
{
"name": "CMake",
"bytes": "3600"
},
{
"name": "CSS",
"bytes": "40785"
},
{
"name": "Cuda",
"bytes": "97324"
},
{
"name": "Dockerfile",
"bytes": "11960"
},
{
"name": "GLSL",
"bytes": "7000"
},
{
"name": "HTML",
"bytes": "21068"
},
{
"name": "JavaScript",
"bytes": "364183"
},
{
"name": "Makefile",
"bytes": "6626"
},
{
"name": "Python",
"bytes": "1902086"
},
{
"name": "Shell",
"bytes": "302902"
},
{
"name": "Smarty",
"bytes": "33258"
}
],
"symlink_target": ""
} |
<pre>
And the man who gives himself to drinking intoxicating liquors,
he, even in this world, digs up his own root. 247
</pre> | {
"content_hash": "00aa1a96bc874048d847e62e75c8bf4d",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 65,
"avg_line_length": 32.5,
"alnum_prop": 0.7307692307692307,
"repo_name": "mkristian/webfortune",
"id": "08b12d5afabf5694d4905f0ae328a6b300a62254",
"size": "130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dhammapada/src/main/resources/de/saumya/webfortune/public/Max Mueller/240.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "21150"
}
],
"symlink_target": ""
} |
@class LoginViewController;
@interface Connect : Requester <NSURLConnectionDelegate> {
}
- (void) connectWithLogin:(NSString *)login andPassword:(NSString *)password;
@end
| {
"content_hash": "febe334c02b2f0b2c14d5a5e182b2c22",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 77,
"avg_line_length": 21.875,
"alnum_prop": 0.7714285714285715,
"repo_name": "BertrandClarke/travelbook",
"id": "3b13aae032ebf766ff0e4c597a3f34b14bf3ddaa",
"size": "329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TravelBook/Connect.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "4905"
},
{
"name": "Objective-C",
"bytes": "1938881"
},
{
"name": "Shell",
"bytes": "2570"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>
<!--
---- (c) Copyright 2002-2006 by Lutz Sammer, Russell Smith
---- 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; only version 2 of the License.
----
---- This program is distributed in the hope that it will be useful,
---- but WITHOUT ANY WARRANTY; without even the implied warranty of
---- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
---- GNU General Public License for more details.
----
---- You should have received a copy of the GNU General Public License
---- along with this program; if not, write to the Free Software
---- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
---- 02111-1307, USA.
-->
<title>Stratagus Configuration Language Description: UnitType</title>
<meta http-equiv="Content-Type" content="text/html; CHARSET=iso-8859-1">
<meta name="Author" content="johns98@gmx.net">
<meta name="Keyword" content="script,unittype">
<meta name="Description" content="">
</head>
<body>
<h1>Stratagus Configuration Language Description: UnitType</h1>
<hr><pre width=80>
_________ __ __
/ _____// |_____________ _/ |______ ____ __ __ ______
\_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/
/ \| | | | \// __ \| | / __ \_/ /_/ > | /\___ \
/_______ /|__| |__| (____ /__| (____ /\___ /|____//____ >
\/ \/ \//_____/ \/
______________________ ______________________
T H E W A R B E G I N S
Stratagus - A free fantasy real time strategy game engine
</pre>
<p><b>(C) Copyright 1998-2006 by The Stratagus Project. Distributed under the
<a href="../gpl.html">"GNU General Public License"</a></b>
<hr>
<a href="../index.html">Stratagus</a>
<a href="../faq.html">FAQ</a>
<a href="ui.html">PREV</a>
<a href="ai.html">NEXT</a>
<a href="index.html">LUA Index</a>
<hr>
<a href="#DefineAnimations">DefineAnimations</a>
<a href="#DefineBoolFlags">DefineBoolFlags</a>
<a href="#DefineVariables">DefineVariables</a>
<a href="#DefineUnitStats">DefineUnitStats</a>
<a href="#DefineUnitType">DefineUnitType</a>
<a href="#GetUnitTypeIdent">GetUnitTypeIdent</a>
<a href="#GetUnitTypeName">GetUnitTypeName</a>
<a href="#SetUnitTypeName">SetUnitTypeName</a>
<a href="#UnitType">UnitType</a>
<a href="#UnitTypeArray">UnitTypeArray</a>
<hr>
<h2>Intro - Introduction to unit-type functions and variables</h2>
Everything around the C UnitType structure.
<h2>Functions</h2>
<a name="DefineAnimations"></a>
<h3>DefineAnimations("ident-name", {type = {script}, ...})</h3>
Define animations.
<dl>
<dt>"ident-name"</dt>
<dd>Name of the animation to define. The name tells stratagus when to play the
animation.</dd>
<dt>type</dt>
<dd>Supported types:
<ul>
<li>Still</li>
<li>Move</li>
<li>Attack</li>
<li>Repair</li>
<li>Train</li>
<li>Research</li>
<li>Upgrade</li>
<li>Build</li>
<li>Harvest_ followed by the name of the harvested resource</li>
<li>Death</li>
</ul>
</dd>
<dt>script</dt>
<dd>
A script is a list of operations. Supported operations:
<ul>
<li>"frame X": Display this frame plus the direction offset</li>
<li>"exact-frame X": Display this exact frame</li>
<li>"wait X": Wait this number of cycles</li>
<li>"random-wait X Y": Wait a random number of cycles between X and Y</li>
<li>"sound X": Play this sound</li>
<li>"random-sound X Y Z ...": Randomly play one of the listed sounds</li>
<li>"attack": Attack</li>
<li>"rotate X": Rotate unit, positive for clockwise, negative for counterclockwise</li>
<li>"random-rotate X": Rotate in a random direction</li>
<li>"move X": Move this number of pixels</li>
<li>"unbreakable {begin|end}": Start or end an unbreakable section</li>
<li>"label X": Create a label (used by goto and random-goto)</li>
<li>"goto X": Goto a label position</li>
<li>"random-goto X Y": Goto label Y with X percent probability</li>
</dd>
</dl>
<h4>Example</h4>
<pre>
DefineAnimations("animations-footman", {
Still = {"frame 0", "wait 4", "frame 0", "wait 1",},
Move = {"unbreakable begin", "frame 0", "move 3", "wait 2", "frame 5", "move 3", "wait 1",
"frame 5", "move 3", "wait 2", "frame 10", "move 2", "wait 1",
"frame 10", "move 3", "wait 1", "frame 0", "move 2", "wait 1",
"frame 0", "move 3", "wait 2", "frame 15", "move 3", "wait 1",
"frame 15", "move 3", "wait 2", "frame 20", "move 2", "wait 1",
"frame 20", "move 3", "wait 1", "frame 0", "move 2", "unbreakable end", "wait 1",},
Attack = {"unbreakable begin", "frame 25", "wait 3", "frame 30", "wait 3", "frame 35", "wait 3",
"frame 40", "attack", "sound footman-attack", "wait 5", "frame 0", "wait 10",
"frame 0", "unbreakable end", "wait 1",},
Death = {"unbreakable begin", "frame 45", "wait 3", "frame 50", "wait 3", "frame 55", "wait 100",
"frame 55", "unbreakable end", "wait 1",}
</pre>
<a name="DefineBoolFlags"></a>
<h3>DefineBoolFlags( "flag-1", "flag-2", ...)</h3>
Define boolean unit flags. Examples are organic, mechanical, undead, etc.
Spells use these to determine who to hit, and units can be restricted too.
Try to avoid using names with other meanings (nothing from spell condition definition.)
Some Flags are already defined in the engine : the UnitType flags.
So following flags are the value of the unitType :
"Building", "BuilderOutSide", "BuilderLost", "ShoreBuilding",
"Coward", "Harvester", "Revealer", "Teleporter",
"LandUnit", "AirUnit", "SeaUnit",
"ExplodeWhenKilled", "VisibleUnderFog", "PermanentCloack", "AttackFromTransporter",
"GroundAttack", "CanAttack", "CanHarvest",
"Vanishes", "Flip", "Decoration", "IsNotSelectable", "SelectableByRectangle",
"Indestructible".
<h4>Example</h4>
<pre>
DefineBoolFlags("organic", "hero", "mechanical", "undead", "demonic", "angelic")
</pre>
<a name="DefineVariables"></a>
<h3>DefineVariables( "varname-1", {tag = value}, "varname-2", {tag = value}, ...)</h3>
Define variable for unit. Spells could use these to determine who to hit, and units can be restricted too.
Try to avoid using names with other meanings (nothing from unit definitions
or spell condition definition).
tag = value represent default value for UnitType. These values can be overwritten in UnitType definition.
<dl>
<dt>Value = number</dt>
<dd>Initial value for the variable</dd>
<dt>Max = number</dt>
<dd>Max value for the number, assuming 0 is the min.</dd>
<dt>Increase = number</dt>
<dd>Number to add each second if possible, negative value are possible.</dd>
<dt>Enable = boolean</dt>
<dd>if the variable is active by default.
For example, Mana is active only for caster, but HP is available for every unit.
</dd>
</dl>
<h4>Note</h4>
Some variables are predefined and could be used with some restriction. You cannot modify their values,
there are readonly (but no errors are generated), So see DefineUnit() for initialise them
(some variables are computed in play and be initialised).
Also, the max value which is always greater than value, may have no sense or be equal at some player statistic.<br>
The predefined values are :
<dl>
<dt>HitPoints</dt>
<dd>Hp of the unit.</dd>
<dt>Build</dt>
<dd>State of the construction in building.</dd>
<dt>Mana</dt>
<dd>Mana point of the unit.</dd>
<dt>Transport</dt>
<dd>Number of unit inside (for transporter only, no build inside).</dd>
<dt>Research</dt>
<dd>Time for the current upgrade in searching.</dd>
<dt>Training</dt>
<dd>Time for the current unit in training.</dd>
<dt>UpgradeTo</dt>
<dd>Time for the unit to upgrade to an other.</dd>
<dt>GiveResource</dt>
<dd>Resource that the unit gives ("resource-name" mine for exemple)</dd>
<dt>CarryResource</dt>
<dd>How many the unit carries the current resource.</dd>
<dt>Xp</dt>
<dd>Experience of the unit</dd>
<dt>Kill</dt>
<dd>Number of unit killed by the unit.</dd>
<dt>Supply</dt>
<dd>How many the unit supply to the player. Max is the total supply for the player.</dd>
<dt>Demand</dt>
<dd>How many the unit demand to the player. Max is the total demand for the player.</dd>
<dt>Armor</dt>
<dd>Armor of the unit.</dd>
<dt>SightRange</dt>
<dd>Sight range of the unit.</dd>
<dt>RadarRange</dt>
<dd>Radar range of the unit.</dd>
<dt>RadarJammerRange</dt>
<dd>Radar Jamming range of the unit.</dd>
<dt>AttackRange</dt>
<dd>Attack range of the unit.</dd>
<dt>PiercingDamage</dt>
<dd>piercing damage of the unit.</dd>
<dt>BasicDamage</dt>
<dd>Basic damage of the unit.</dd>
<dt>PosX</dt>
<dd>X position of the unit. Max is the Map size.</dd>
<dt>PosY</dt>
<dd>Y position of the unit. Max is the Map size.</dd>
<dt>AutoRepairRange</dt>
<dd>Range to check for unit to repair. (for unit which can repair)<dd>
<dt>BloodLust</dt>
<dd>Time remaining during which unit do more damage (damage * 2).<dd>
<dt>Haste</dt>
<dd>Time remaining during which unit is haste (its action take 2 less time).<dd>
<dt>Slow</dt>
<dd>Time remaining during which unit is slow (its action take 2 more time).<dd>
<dt>Invisible</dt>
<dd>Time remaining during which unit is invisible for opponent.<dd>
<dt>UnholyArmor</dt>
<dd>Time remaining during which unit is invulnerable.<dd>
<dt>Slot</dt>
<dd>Unique number that identifies the unit (begin at 0). Max is the last valid slot number.</dd>
</dl>
<h4>Example</h4>
<pre>
DefineVariable("cooldown", {Value = 0, Increase = -1, Max = 50, Enable = false})
</pre>
<a name="DefineUnitStats"></a>
<h3>DefineUnitStats("unit-type", player, "tag1", value1, "tag2", value2 ...)</h3>
Define unit stats. This is almost only used in savegames, but included
here for completeness. In the game every unit of the same type of one
player have the same stats, affected by upgrades.
<dl>
<dt>"unit-type"</dt>
<dd>Ident of the unit. This obviousely means that it should be defined after units.
</dd>
<dt>player</dt>
<dd>Player number.</dd>
<dt>Possible tags:</dt>
<dd><dl>
<dt>"costs", </dt>
<dd>The cost to train this unit. This is a standard resource/value list.
A special 'resource' is "time", the time to train the unit in cycles.
</dd>
<dt>"Variable", number or {Value = number, Max = number, Increase = number}</dt>
<dd>Variable is one of the already defined with <a href="#DefineVariables">DefineVariables()</a>.</dd>
</dl></dd>
</dl>
<h4>Example</h4>
<pre>
-- Stat of archer unit for player 14.
DefineUnitStats("unit-archer", 14,
"Level", 1, "AttackRange", 4, "SightRange", 5,
"Armor", 0, "BasicDamage", 3, "PiercingDamage", 6,
"HitPoints", {Max = 40, Increase = 0},
"costs", {"time", 100, "titanium", 50, "crystal", 100, "gas", 0, "ore", 0,
"stone", 0, "coal", 0})
</pre>
<a name="DefineUnitType"></a>
<h3>DefineUnitType( "ident", { tag1 = value1, tag2 = value2, ...})</h3>
Define the unit types in game. A lot of the data in this struct used to be
based on the UDTA section of puds, with unit statistics, but it is now a lot
bigger and more configurable.
<dl>
<dt>ident</dt>
<dd>The unit-type unique identifier. It is used to reference unit-types in
game. F.E: "unit-knight", "unit-gold-mine". Please use all-lowercase names
prefixed with unit-, it is easier to read this way.
</dd>
</dl>
Possible tags:
<dl>
<dt>Name = "show-name"</dt>
<dd>The unit-type name shown in the game. F.E: "Knight", "Gold Mine".
If the name is too long, it is split at space.
</dd>
<dt>Image = {"file", filename, "size", {x, y}}</dt>
<dd>Defines the graphics used to display the unit-type in game.</dd>
<dt>Offset = {x, y}</dt>
<dd>Defines the offset for the graphics in pixels used to display the unit-type</dd>
<dt>Shadow = {tag, value, ...}</dt>
<dd>Defines the Parameters for the shadow the unit is casting in the game</dd>
<dd>Possible tags:
<dl>
<dt>"file", filename</dt>
<dd>Defines the graphics used to display the shadow of the unit-type</dd>
<dt>"size", {width, height}</dt>
<dd>Defines the size of the graphics in pixels used to display the shadow of the unit-type</dd>
<dt>"offset", {x, y}</dt>
<dd>Defines the offset of the graphics in pixels used to display the shadow of the unit-type. Note that this is relative to the unit graphics including its own offset</dd>
</dl></dd>
<dt>DrawLevel = number</dt>
<dd>This is used when sorting units and missiles for drawing. Units with a higher draw
order will always be on top of units with lower draw order. Units are also sorted from
top to the bottom of the screen.
</dd>
<dt>Animations = "animation-type"</dt>
<dd>Identifier to reference the animation sequences (scripts) for the
unit-type. F.E. "animations-knight", "animations-gold-mine".
</dd>
<dt>Size = {x, y}</dt>
<dd>Size of the unit-type graphic in pixels.
</dd>
<dt>TileSize = {x, y}</dt>
<dd>Define the unit-type size in tiles. NOTE: currently only buildings could
be bigger than one tile.
</dd>
<dt>BoxSize = {width, height}</dt>
<dd>Define the size of the unit selection box. This is drawn centered around
the unit and most of the time it is equal to the tile size of the unit* the size
of a terrain tile, for an almost perfect fit.
</dd>
<dt>NumDirections = number</dt>
<dd>Define the number of directions a unit can face. Default 1 for buildings and 8
for units. Can be adjusted from the default. Useful for rotating buildings
</dd>
<dt>IsNotSelectable = boolean</dt>
<dd>set whether the unit is able to be selected or not.</dd>
<dt>Decoration = boolean</dt>
<dd>set whether the unit is a decoration (act like a tile) or not.</dd>
<dt>Indestructible = boolean</dt>
<dd>set whether the unit is indestructible not.</dd>
<dt>NeutralMinimapColor = {r, g, b}</dt>
<dd>sets the color of a unit when belonging to the neutral player. F.E. '(0 0 0) for a
black oil patch.
</dd>
<dt>Icon = "Icon-name"</dt>
<dd>Identifier to reference the icon shown in game for this unit-type.
F.E. "icon-knight", "icon-gold-mine".
</dd>
<dt>Portrait = {main-file, other-file, ...}</dt>
<dd>The first file is the main animation. It will randomly play one of the other files.
</dd>
<dt>Sounds = {event, "sound-name", ...}</dt>
<dd>The following events are supported:
<dl><dd>
<ul>
<li>"selected": Happens when the unit is selected.
<li>"acknowledge": Happens when the unit received an order.
<li>"attack": Attack sound of the unit. Used when giving an attack order, it
can override the acknowledge sound.
<li>"ready": Happens when the unit finished training (and it's ready)
<li>"repair": Happens when the unit is repairing.
<li>"help": Happens when the unit is under attack.
<li>"dead": Happens when the unit is killed.
</ul></dd>
</dl></dd>
<dd>
You can use the same help or ready sound for all units if you want generic
"Your unit is under attack", "Some unit was trained" sounds. The actual sound
files are not declared here. Please see the documentation on <a href="sound.html#MakeSound">sounds</a>
</dd>
<!--
<dt>The following stats are also included in a unit stats struct and are upgradeable, see
<a href="#DefineUnitStats">DefineUnitStats</a>
</dt>
-->
<dt>MaxAttackRange = number</dt>
<dd>Attack range (in tiles) of this unit. Use 1 for melee units.
</dd>
<dt>MinAttackRange = number</dt>
<dd>Minimum attack range (in tiles) of this unit. This is usefull for siege units you
want to make vulnerable to close range attacks.
</dd>
<dt>SightRange = number</dt>
<dd>Sight range (in tiles) of this unit.
</dd>
<dt>RadarRange = number</dt>
<dd>Radar range of the unit.</dd>
<dt>RadarJammerRange = number</dt>
<dd>Radar Jamming range of the unit.</dd>
<dt>Armor = number</dt>
<dd>Basic armor of the unit.
</dd>
<dt>BasicDamage = number</dt>
<dd>Unit's basic damage. FIXME calculations?
</dd>
<dt>PiercingDamage = number</dt>
<dd>Unit's piercing damage. FIXME calculations?
</dd>
<dt>RegenerationRate = number</dt>
<dd>amount of HP a unit gains per seconds
</dd>
<dt>HitPoints = number</dt>
<dd>Maximum hitpoints for this Unit.
</dd>
<dt>Costs = {"resource-name", amount, ...}</dt>
<dd>Define the costs to build (or aquire) this unit.
F.E.: Costs = {"time", 200, "gold", 2000, "wood", 1000, "oil", 200}
</dd>
<dt>RightMouseAction = "none" or "move" or "attack" or "harvest"
or "spell-cast" or "sail"</dt>
<dd><dl>
<dt>"none"</dt>
<dd>Do nothing.</dd>
<dt>"move"</dt>
<dd>Right clicking defaults to move. This should be used for unit's that can't attack.
</dd>
<dt>"attack"</dt>
<dd>Right clicking defaults to attack. This should be used for most combat units.
</dd>
<dt>"harvest"</dt>
<dd>This should be used for resource gathering units. It will return goods when
on a deposit and mine when on a resource.
</dd>
<dt>"spell-cast"</dt>
<dd>This is an ugly hack for demolishing units. The unit will cast it's first
known spell(in order of spell definition) instead of attacking a hostile unit.
</dd>
</dl></dd>
<dt>CanGatherResources = {flag, value}</dt>
<dd>This will begin a block of resoure gathering information. The folowing tags are available in this section:
<dl>
<dt>"resource-id", ressource-name</dt>
<dd>The resource identification. Has to be a resource-name defined before.
</dd>
<dt>"final-resource", ressource-name</dt>
<dd>The resource is converted to this at the depot. Usefull for a fisherman who harvests fish,
but it all turns to food at the depot. Warning: curently ignored by the Ai.
</dd>
<dt>"wait-at-resource", number</dt>
<dd>Cycles the unit waits while inside at a resource to get one resource step
(see below). This is completely independent of animation length and such.
</dd>
<dt>"wait-at-depot", number</dt>
<dd>Cycles the unit waits while inside the depot to unload.
</dd>
<dt>"resource-step", number</dt>
<dd>The unit makes so-caled mining cycles. Each mining cycle it does some sort
of animation and gains resource-step resources. You can stop after any number of
steps. When the quantity in the harvester reaches the maximum (resource-capacity)
it will return home. If this is not included then it's considered infinity, and
resource-capacity will be the limit.
</dd>
<dt>"resource-capacity", number</dt>
<dd>Maximum amount of resources a harvester can carry. The actual amount can be
modified while unloading, with improve-incomes.
</dd>
<dt>"file-when-loaded", filename</dt>
<dd>The harvester's animation file will change when it's loaded.
</dd>
<dt>"file-when-empty", filename</dt>
<dd>The harvester's animation file will change when it's empty.The standard animation
is used only when building/repairing.
</dd>
<dt>"harvest-from-outside"</dt>
<dd>Unit will harvest from the outside. The unit will use it's attack animation
(seems it turned into a generic Action anim.)
</dd>
<dt>"lose-resources"</dt>
<dd>Special lossy behaviour for loaded harvesters. Harvesters with loads other
than 0 and ResourceCapacity will lose their cargo on any new order.
</dd>
<dt>"terrain-harvester"</dt>
<dd>The unit will harvest terrain. For now this only works for wood.</dd>
</dl></dd>
<dt>GivesResource = resource-name</dt>
<dd>This will make the unit (normally a building) a resource (sugar mine, geyser, etc).
It's followed by a resource ident F.E. "gives-resource", "gold"
</dd>
<dt>CanHarvest = boolean</dt>
<dd>This is a flag for harvestable resource buildings. You can ommit it, and give every
race a building that is built on top of this (see below) and has the can-harvest flag.
</dd>
<dt>CanStore = {resource-name, ...}</dt>
<dd>This flag makes the unit a resource storage, units will come here and unload their cargo.
It's followed by a list of accepted resource identifiers. F.E. can-store '(stone coal)
</dd>
<dt>Building = boolean</dt>
<dd>Unit is a building, and imobile. Available as a spell target check.
</dd>
<dt>VisibleUnderFog = boolean</dt>
<dd>Unit remains visible under fog of war. In most games this is true for and only for
buildings.
</dd>
<dt>ShoreBuilding = boolean</dt>
<dd>Unit is a shore building, and imobile. This is used for those unique buildings
that have to be build on sea and have at least one point on coast.
</dd>
<dt>BuilderOutside</dt>
<dd>true if the builder builds a building from the outside</dd>
<dt>BuilderLost</dt>
<dd>true if you would like the builder to die once the building has been completed (used for morphing
into a building)</dd>
<dt>AutoBuildRate</dt>
<dd>The rate at which the building builds itself <b>NOT IMPLEMENTED</b></dd>
<dt>BuildingRules = { { "distance", { Distance = 3, DistanceType = ">", Type = "unit-gold-mine"}}}
<dd>BuildingRules allows you to specify a list of restrictions to make when building. The
list is in nested tables, the inter list is and'd together, and or'd with the other lists. See
the example for details.
<dl>
<dt>"distance"</dt>
<dd>Specifies a distance constraint.
<dl>
<dt>Distance</dt>
<dd>The distance in tiles to measure</dd>
<dt>DistancType</dt>
<dd><, >, <=, >=, ==, !=</dd>
<dt>Type</dt>
<dd>The type of the unit that this distance restriction applies to</dd>
<dt>Except <b>NOT IMPLEMENTED</b></dt>
<dd>boolen, #t implies all units, except this type must be</dd>
</dl></dd>
<dt>"addon"</dt>
<dd>Specifies an addon to an existing building.
<dl>
<dt>OffsetX</dt>
<dd>Offset from the top left of the parent building that this unit must be placed.
eg, -2 would left two of the building. (you need to consider the size of the
parent building)</dd>
<dt>OffsetY</dt>
<dd>As with OffsetX, except in the Y direction</dd>
<dt>Type</dt>
<dd>Type of the unit that this unit is an addon too</dd>
</dl></dd>
<dt>"tile" <b>NOT IMPLEMENTED</b></dt>
<dd>Implement a tile restriction, unit must be placed on certain types of tiles.
<dl>
<dt>NumberOnMask</dt>
<dd>The number of tiles that are needed until the build of a type to satisfy</dd>
<dt>Mask</dt>
<dd>Mask of the tiles that needs to be meet <b>Will be updated to tiletype</b></dd>
</dl></dd>
<dt>"ontop"</dt>
<dd>Building must be built on top of another building type
NOTE: the engine may not be able to guess the correct parent if the rules are complex enough.
<dl>
<dt>Type</dt>
<dd>The unit-type that we are to build on top of</dd>
<dt>ReplaceOnDie</dt>
<dd>boolean, true if you want the original unit to be replaced when this unit dies</dd>
<dt>ReplaceOnBuild</dt>
<dd>boolean, true if you want to remove the old unit underneath when you build this one</dd>
</dl></dd>
<dt>"direction" <b>NOT IMPLEMENTED</b></dt>
<dd><dl>
<dt>Direction</dt>
<dd>A bitmask in int format for the directions to build. (bits not specified yet)</dd>
</dl></dd>
</dl>
<dt>Coward = boolean</dt>
<dd>Unit will not attack on sight, and will run away instead of retaliating.
Use this for units that can't attack or are next to useless in combat (like
resource workers) Available as a spell target check.
</dd>
<dt>CanCastSpell = {spell-name, ...}</dt>
<dd>This is used to determine what spells can this unit cast. It is followed by a
list of spell names. Spells have to be declared already. Since some spells also
rely on units being defined this can lead to a chicken and egg problem. It's
better to declare an unit type in advance with just DefineUnitType( "unit-whatever", {}).
Please see the documentation on spells. F.E. CanCastSpell = {"spell-healing", "spell-exorcism"}
</dd>
<dt>Supply = number</dt>
<dd>This is the amount of food supplied by the unit. Food is a global per-player
counter that signifies the maximum amount of units.
</dd>
<dt>Demand = number</dt>
<dd>This is the amount of food required by the unit. It should be 0 for buildings.
It can have values greater than one, for bigger units.
</dd>
<dt>ImproveProduction = {resource-name, amount, ...}</dt>
<dd>Define the production increase from defaults that this unit adds. The
values are treated like percents. Improvement from multiple buildings do
not stack, but the maximum is what matters.
F.E.: ImproveProduction = {"gold", 20, "wood", 5} will give 120% gold and 105% wood.
</dd>
<dt>RepairRange = number</dt>
<dd>Range that a unit can repair from, eg. RepairRange = 1.
</dd>
<dt>AutoRepairRange = number</dt>
<dd>Range to check for unit to repair. (for unit which can repair)<dd>
<dt>RepairHp = number</dt>
<dd>Defines the amount of hp a unit gain for each repair animation. Units can only be
repaired if this value is non-zero.
F.E.: RepairHp = 4.
</dd>
<dt>RepairCosts = {resource-name, cost, ...}</dt>
<dd>Define the costs to repair this unit.
F.E.: RepairCosts = {"gold", 2, "wood", 1, "oil", 1 )
</dd>
<dt>PermanentCloak = boolean</dt>
<dd>Unit is permanently cloaked, and can only be seen by detectors (see below.)
</dd>
<dt>DetectCloak = boolean</dt>
<dd>Unit can detect cloaked units. If an unit is detected other units can attack it as well\
</dd>
<dt>RandomMovementProbablitity = number</dt>
<dd>When the unit is idle this is the probability that it will take a
step in a random direction, in percents. Usefull for neutral animals.
</dd>
<dt>ClicksToExplode = number</dt>
<dd>If this is non-zero, then after that many clicks the unit will commit
suicide. Doesn't work with resource workers/resources.
</dd>
<dt>ComputerReactionRange = number</dt>
<dd>This is supossed to be the reaction range for AI units, but it is not used.
</dd>
<dt>PersonReactionRange = number</dt>
<dd>This is supossed to be the reaction range for human player units, but it is not used.
</dd>
<dt>Priority = number</dt>
<dd>This is the ai priority level. High damage low-hp units for instancce should have
higher priorities than say a peasant. It can be safely ignored.
</dd>
<dt>AnnoyComputerFactor = number</dt>
<dd>This is another ai priority level. This is not used, but included in wc2 data. Maybe
it should be used to attack resource buildings first? You can safely ignore it.
</dd>
<dt>Decay = number</dt>
<dd>This is the unit's decay rate, in 1/6 seconds. It should be really really really changed to
cycles. If you set this the unit will die by itself after a while. Don't use it for spells,
spells will override this with their own ttl setting.
</dd>
<dt>BurnPercent = number</dt>
<dd>The unit will start burning when it has less health than this, in percents.
</dd>
<dt>BurnDamageRate = number</dt>
<dd>The rate at which the unit will get damaged. The period is the same as with regeneration.
</dd>
<dt>Points = number</dt>
<dd>This is the score value of an unit. Used for the final score.
</dd>
<dt>Missile = missile-name</dt>
<dd>Some units fire by throwing missiles, this is the missile thrown. You can use it for
close range units as well, but I can't really see the point.
</dd>
<dt>Corpse = {unittype-name, number}</dt>
<dd>This is the corpse of the unit. When the unit dies and passes through it's
death animation it turns into this. It's a list of an unit-name and a a corpse frame
number. As you can see in <a href="#DefineAnimations">DefineAnimations()</a>,
an animation is composed out of several script frames, this is the frame to
start the script from. FE: Corpse = {"unit-dead-body", 0}
</dd>
<dt>ExplodeWhenKilled = missile-name</dt>
<dd>Sets unit to explode when killed, syntax is followed by the missile to use.
eg. ExplodeWhenKilled "missile-explosion"
</dd>
<dt>AttackFromTransporter = boolean</dt>
<dd>Gives units with range the ability to attack from within a transporter such as a building.
These can act like amoured personnel carriers or bunkers
</dd>
<dt>CanTransport = {flag, "true" or "only" or "false", ...}</dt>
<dd>Unit is a transporter, you can place units with good flag inside.
<br>Note: If you want the unit to be able to transport all land unit, use CanTransport = {}.
<br>Note: you really should add an unload button for transporters.
<br>Note: flag must be defined before with <a href="#define-bool-flags">DefineBoolFlags()</a>
</dd>
<dt>MaxOnBoard = number</dt>
<dd>This is only used for transporters, It's the maximum allowed on board. Curently
you can't have more that 6, or you won't get any buttons for the rest.
</dd>
<dt>Revealer = boolean</dt>
<dd>This is a special flag to use for reveal map spells. A reveal map smell is
in fact a summon spell with an infinite range, that summons an unit with the
revealer flag. Revealer are summoned and marked removed, but they still keep
their sight. This way a revealer unit can't be attacked, won't show on the minimap
and can't be interacted with. Please see the documentation on spells.</dd>
<dt>SelectableByRectangle = boolean</dt>
<dd>Most units should have this flag. When false the unit will only get selected
alone, use this for buildings. Enemy units are never selectable by rectangle.
</dd>
<dt>flags = boolean</dt>
<dd>You can add a bunch of flags, defined with <a href="#DefineBoolFlags">DefineBoolFlags()</a>
You can add how many flags you would like, but keep in mind that you have to call
<a href="#DefineBoolFlags">DefineBoolFlags()</a> before.
</dd>
<dt>variable = {tag = value , ...} or number or boolean</dt>
<dd>You can add a bunch variable, defined with <a href="#DefineVariables">DefineVariables()</a>
You can add how many flags you would like, but keep in mind that you have to call
<a href="#DefineVariables">DefineVariables()</a> before.
You can overwrite each tag/value by the same method you use for <a href="#DefineVariables">DefineVariables()</a>
or simply Enable/disable it with a boolean, or set Max and value with a number
</dd>
<dt>CanTargetFlag = {flag, "true" or "only" or "false", ...}</dt>
<dd>This allows check for targetting similar to spell conditions.
By default everything is set to true, so you can target everything. Only means that
you can only fire units with that flag, and false only units without that flag.
</dd>
<dt>FIXME: continue documentation.</dt>
<dd>FIXME: continue documentation.</dd>
<!--IDEA:<dt>force-minimap-color<dt>
<dd>An unit with this flag will ignore any friend/foe/owning player considerations
for the minimap color, and will force this. It takes a number from the palette here.
</dd>-->
</dl>
<h4>Example</h4>
Sorry, but due to the huge number of available flags we can only show a limited example.
<pre>
DefineUnitType("unit-footman", { Name = "Footman",
Image = {"file", "alliance/units/footman.png", "size", {72, 72}},
Animations = "animations-footman", Icon = "icon-footman",
Costs = {"time", 60, "gold", 600},
Speed = 10, -- Variable Defined
HitPoints = 60,
DrawLevel = 40,
TileSize = {1, 1}, BoxSize = {31, 31},
SightRange = 4, ComputerReactionRange = 6, PersonReactionRange = 4,
Armor = 2, BasicDamage = 6, PiercingDamage = 3, Missile = "missile-none",
MaxAttackRange = 1,
Priority = 60,
Points = 50,
Demand = 1,
Corpse = {"unit-dead-body", 6},
Type = "land",
RightMouseAction = "attack",
CanAttack = true,
CanTargetLand = true,
LandUnit = true,
organic = true,
SelectableByRectangle = true,
-- distance is >3 from gold, and <2 from a watch tower
-- or distance is >6 from goldmine
BuildingRules = { { "distance", { Distance = 3, DistanceType = ">", Type = "unit-gold-mine"},
"distance", { Distance = 2, DistanceType = "<", Type = "unit-gold-mine"}},
{ "distance", { Distance = 6, DistanceType = ">", Type = "unit-gold-mine"},
}
},
Sounds = {
"selected", "footman-selected",
"acknowledge", "footman-acknowledge",
"ready", "footman-ready",
"help", "basic alliance voices help 1",
"dead", "basic alliance voices dead",
"attack", "footman-attack"} } )
</pre>
<!--
<LI><var>unit-type</var><br>
Get the pointer to the unit type structure.<p>
(unit-type ident)
<dl>
<dt>ident</dt>
<dd>The unit-type unique identifier.</dd>
</dl>
<p>
<h4>Example:</h4>
(unit-type "unit-peon")<p>
Get the unit type structure of the peon. #<unittype 0x80ac350 unit-peon><p>
<li><var>unit-type-array</var><br>
Get an array of all currently defined unit type structures.<p>
(unit-type-array)
<p>
<li><var>get-unit-type-ident</var><br>
Get the unique identfier of the unit type structure.<p>
(get-unit-type-ident type)
<dl>
<dt>type</dt>
<dd>Unit type pointer</dd>
</dl>
<p>
<h4>Example:</h4>
(get-unit-type-ident (unit-type "unit-peon"))<p>
Get the identifier of the unit type peon.<p>
-->
<a name="GetUnitTypeIdent"></a>
<h3>GetUnitTypeIdent(unit-type)</h3>
Get the ident of the unit-type structure.
<dl>
<dt>unit-type</dt>
<dd>.
</dd>
</dl>
<h4>Example</h4>
<pre>
GetUnitTypeIdent(unit-type)
</pre>
<a name="GetUnitTypeName"></a>
<h3>GetUnitTypeName(unit-type)</h3>
Get the name of the unit-type structure.
<dl>
<dt>unit-type</dt>
<dd>.
</dd>
</dl>
<h4>Example</h4>
<pre>
GetUnitTypeName(unit-type)
</pre>
<a name="SetUnitTypeName"></a>
<h3>SetUnitTypeName(unit-type, name)</h3>
Set the name of the unit-type structure.
<dl>
<dt>unit-type</dt>
<dd>.
</dd>
<dt>name</dt>
<dd>.
</dd>
</dl>
<h4>Example</h4>
<pre>
SetUnitTypeName(unit-type, name)
</pre>
<a name="UnitType"></a>
<h3>UnitType(ident)</h3>
Get unit-type structure.
<dl>
<dt>ident</dt>
<dd>.
</dd>
</dl>
<h4>Example</h4>
<pre>
UnitType("unit-great-hall")
</pre>
<a name="UnitTypeArray"></a>
<h3>UnitTypeArray()</h3>
Get all unit-type structures.
<h4>Example</h4>
<pre>
UnitTypeArray()
</pre>
<hr>
Last changed: $Id: unittype.html 7629 2006-10-28 18:11:38Z jsalmon3 $<br>
All trademarks and copyrights on this page are owned by their respective owners.
<address>(c) 2002-2006 by <a href="http://stratagus.org">
The Stratagus Project</a></address></body></html>
| {
"content_hash": "2a0a57dd2def4e033188b38a82dd3600",
"timestamp": "",
"source": "github",
"line_count": 874,
"max_line_length": 171,
"avg_line_length": 39.85469107551487,
"alnum_prop": 0.666551833031895,
"repo_name": "k1643/StratagusAI",
"id": "14837beeee382007dfab5b29d4472c827bac04ca",
"size": "34833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "engine/code/doc/scripts/unittype.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1471691"
},
{
"name": "C++",
"bytes": "4010215"
},
{
"name": "Java",
"bytes": "810158"
},
{
"name": "Lua",
"bytes": "4050"
},
{
"name": "Objective-C",
"bytes": "111499"
},
{
"name": "Python",
"bytes": "105086"
},
{
"name": "Shell",
"bytes": "2476"
}
],
"symlink_target": ""
} |
---
uid: SolidEdgePart.Dimple.SetProfiles(System.Int32,System.Array@)
summary:
remarks:
syntax:
parameters:
- id: NumProfiles
description: Specifies the number of profiles in the Profiles array.
- id: Profiles
description: Contains the profiles for the referenced object.
---
| {
"content_hash": "6aa76161d0f4fa962259caae9f6ab78e",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 74,
"avg_line_length": 27.545454545454547,
"alnum_prop": 0.7161716171617162,
"repo_name": "SolidEdgeCommunity/docs",
"id": "be2d162763ddaf2cd129d23eabea85bafb2756ea",
"size": "305",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docfx_project/apidoc/SolidEdgePart.Dimple.SetProfiles.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "38"
},
{
"name": "C#",
"bytes": "5048212"
},
{
"name": "C++",
"bytes": "2265"
},
{
"name": "CSS",
"bytes": "148"
},
{
"name": "PowerShell",
"bytes": "180"
},
{
"name": "Smalltalk",
"bytes": "1996"
},
{
"name": "Visual Basic",
"bytes": "10236277"
}
],
"symlink_target": ""
} |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST, REFERENCE_IDENTITY_CLASS, REFERENCE_ENUM_CLASS, REFERENCE_BITS, REFERENCE_UNION, ANYXML_CLASS
from ydk.errors import YPYError, YPYModelError
from ydk.providers._importer import _yang_ns
_meta_table = {
'Snmpv2Mib.System' : {
'meta_info' : _MetaInfoClass('Snmpv2Mib.System',
False,
[
_MetaInfoClassMember('sysContact', ATTRIBUTE, 'str' , None, None,
[(0, 255)], [],
''' The textual identification of the contact person for
this managed node, together with information on how
to contact this person. If no contact information is
known, the value is the zero-length string.
''',
'syscontact',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysDescr', ATTRIBUTE, 'str' , None, None,
[(0, 255)], [],
''' A textual description of the entity. This value should
include the full name and version identification of
the system's hardware type, software operating-system,
and networking software.
''',
'sysdescr',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysLocation', ATTRIBUTE, 'str' , None, None,
[(0, 255)], [],
''' The physical location of this node (e.g., 'telephone
closet, 3rd floor'). If the location is unknown, the
value is the zero-length string.
''',
'syslocation',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysName', ATTRIBUTE, 'str' , None, None,
[(0, 255)], [],
''' An administratively-assigned name for this managed
node. By convention, this is the node's fully-qualified
domain name. If the name is unknown, the value is
the zero-length string.
''',
'sysname',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysObjectID', ATTRIBUTE, 'str' , None, None,
[], [b'(([0-1](\\.[1-3]?[0-9]))|(2\\.(0|([1-9]\\d*))))(\\.(0|([1-9]\\d*)))*'],
''' The vendor's authoritative identification of the
network management subsystem contained in the entity.
This value is allocated within the SMI enterprises
subtree (1.3.6.1.4.1) and provides an easy and
unambiguous means for determining `what kind of box' is
being managed. For example, if vendor `Flintstones,
Inc.' was assigned the subtree 1.3.6.1.4.1.424242,
it could assign the identifier 1.3.6.1.4.1.424242.1.1
to its `Fred Router'.
''',
'sysobjectid',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysORLastChange', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The value of sysUpTime at the time of the most recent
change in state or value of any instance of sysORID.
''',
'sysorlastchange',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysServices', ATTRIBUTE, 'int' , None, None,
[('0', '127')], [],
''' A value which indicates the set of services that this
entity may potentially offer. The value is a sum.
This sum initially takes the value zero. Then, for
each layer, L, in the range 1 through 7, that this node
performs transactions for, 2 raised to (L - 1) is added
to the sum. For example, a node which performs only
routing functions would have a value of 4 (2^(3-1)).
In contrast, a node which is a host offering application
services would have a value of 72 (2^(4-1) + 2^(7-1)).
Note that in the context of the Internet suite of
protocols, values should be calculated accordingly:
layer functionality
1 physical (e.g., repeaters)
2 datalink/subnetwork (e.g., bridges)
3 internet (e.g., supports the IP)
4 end-to-end (e.g., supports the TCP)
7 applications (e.g., supports the SMTP)
For systems including OSI protocols, layers 5 and 6
may also be counted.
''',
'sysservices',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysUpTime', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The time (in hundredths of a second) since the
network management portion of the system was last
re-initialized.
''',
'sysuptime',
'SNMPv2-MIB', False),
],
'SNMPv2-MIB',
'system',
_yang_ns._namespaces['SNMPv2-MIB'],
'ydk.models.cisco_ios_xe.SNMPv2_MIB'
),
},
'Snmpv2Mib.Snmp.SnmpenableauthentrapsEnum' : _MetaInfoEnum('SnmpenableauthentrapsEnum', 'ydk.models.cisco_ios_xe.SNMPv2_MIB',
{
'enabled':'enabled',
'disabled':'disabled',
}, 'SNMPv2-MIB', _yang_ns._namespaces['SNMPv2-MIB']),
'Snmpv2Mib.Snmp' : {
'meta_info' : _MetaInfoClass('Snmpv2Mib.Snmp',
False,
[
_MetaInfoClassMember('snmpEnableAuthenTraps', REFERENCE_ENUM_CLASS, 'SnmpenableauthentrapsEnum' , 'ydk.models.cisco_ios_xe.SNMPv2_MIB', 'Snmpv2Mib.Snmp.SnmpenableauthentrapsEnum',
[], [],
''' Indicates whether the SNMP entity is permitted to
generate authenticationFailure traps. The value of this
object overrides any configuration information; as such,
it provides a means whereby all authenticationFailure
traps may be disabled.
Note that it is strongly recommended that this object
be stored in non-volatile memory so that it remains
constant across re-initializations of the network
management system.
''',
'snmpenableauthentraps',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInASNParseErrs', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of ASN.1 or BER errors encountered by
the SNMP entity when decoding received SNMP messages.
''',
'snmpinasnparseerrs',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInBadCommunityNames', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of community-based SNMP messages (for
example, SNMPv1) delivered to the SNMP entity which
used an SNMP community name not known to said entity.
Also, implementations which authenticate community-based
SNMP messages using check(s) in addition to matching
the community name (for example, by also checking
whether the message originated from a transport address
allowed to use a specified community name) MAY include
in this value the number of messages which failed the
additional check(s). It is strongly RECOMMENDED that
the documentation for any security model which is used
to authenticate community-based SNMP messages specify
the precise conditions that contribute to this value.
''',
'snmpinbadcommunitynames',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInBadCommunityUses', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of community-based SNMP messages (for
example, SNMPv1) delivered to the SNMP entity which
represented an SNMP operation that was not allowed for
the SNMP community named in the message. The precise
conditions under which this counter is incremented
(if at all) depend on how the SNMP entity implements
its access control mechanism and how its applications
interact with that access control mechanism. It is
strongly RECOMMENDED that the documentation for any
access control mechanism which is used to control access
to and visibility of MIB instrumentation specify the
precise conditions that contribute to this value.
''',
'snmpinbadcommunityuses',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInBadValues', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP PDUs which were
delivered to the SNMP protocol entity and for
which the value of the error-status field was
`badValue'.
''',
'snmpinbadvalues',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInBadVersions', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP messages which were delivered
to the SNMP entity and were for an unsupported SNMP
version.
''',
'snmpinbadversions',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInGenErrs', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP PDUs which were delivered
to the SNMP protocol entity and for which the value
of the error-status field was `genErr'.
''',
'snmpingenerrs',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInGetNexts', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Get-Next PDUs which have been
accepted and processed by the SNMP protocol entity.
''',
'snmpingetnexts',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInGetRequests', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Get-Request PDUs which
have been accepted and processed by the SNMP
protocol entity.
''',
'snmpingetrequests',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInGetResponses', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Get-Response PDUs which
have been accepted and processed by the SNMP protocol
entity.
''',
'snmpingetresponses',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInNoSuchNames', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP PDUs which were
delivered to the SNMP protocol entity and for
which the value of the error-status field was
`noSuchName'.
''',
'snmpinnosuchnames',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInPkts', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of messages delivered to the SNMP
entity from the transport service.
''',
'snmpinpkts',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInReadOnlys', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number valid SNMP PDUs which were delivered
to the SNMP protocol entity and for which the value
of the error-status field was `readOnly'. It should
be noted that it is a protocol error to generate an
SNMP PDU which contains the value `readOnly' in the
error-status field, as such this object is provided
as a means of detecting incorrect implementations of
the SNMP.
''',
'snmpinreadonlys',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInSetRequests', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Set-Request PDUs which
have been accepted and processed by the SNMP protocol
entity.
''',
'snmpinsetrequests',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInTooBigs', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP PDUs which were
delivered to the SNMP protocol entity and for
which the value of the error-status field was
`tooBig'.
''',
'snmpintoobigs',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInTotalReqVars', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of MIB objects which have been
retrieved successfully by the SNMP protocol entity
as the result of receiving valid SNMP Get-Request
and Get-Next PDUs.
''',
'snmpintotalreqvars',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInTotalSetVars', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of MIB objects which have been
altered successfully by the SNMP protocol entity as
the result of receiving valid SNMP Set-Request PDUs.
''',
'snmpintotalsetvars',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpInTraps', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Trap PDUs which have been
accepted and processed by the SNMP protocol entity.
''',
'snmpintraps',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutBadValues', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP PDUs which were generated
by the SNMP protocol entity and for which the value
of the error-status field was `badValue'.
''',
'snmpoutbadvalues',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutGenErrs', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP PDUs which were generated
by the SNMP protocol entity and for which the value
of the error-status field was `genErr'.
''',
'snmpoutgenerrs',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutGetNexts', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Get-Next PDUs which have
been generated by the SNMP protocol entity.
''',
'snmpoutgetnexts',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutGetRequests', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Get-Request PDUs which
have been generated by the SNMP protocol entity.
''',
'snmpoutgetrequests',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutGetResponses', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Get-Response PDUs which
have been generated by the SNMP protocol entity.
''',
'snmpoutgetresponses',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutNoSuchNames', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP PDUs which were generated
by the SNMP protocol entity and for which the value
of the error-status was `noSuchName'.
''',
'snmpoutnosuchnames',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutPkts', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Messages which were
passed from the SNMP protocol entity to the
transport service.
''',
'snmpoutpkts',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutSetRequests', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Set-Request PDUs which
have been generated by the SNMP protocol entity.
''',
'snmpoutsetrequests',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutTooBigs', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP PDUs which were generated
by the SNMP protocol entity and for which the value
of the error-status field was `tooBig.'
''',
'snmpouttoobigs',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpOutTraps', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of SNMP Trap PDUs which have
been generated by the SNMP protocol entity.
''',
'snmpouttraps',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpProxyDrops', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of Confirmed Class PDUs
(such as GetRequest-PDUs, GetNextRequest-PDUs,
GetBulkRequest-PDUs, SetRequest-PDUs, and
InformRequest-PDUs) delivered to the SNMP entity which
were silently dropped because the transmission of
the (possibly translated) message to a proxy target
failed in a manner (other than a time-out) such that
no Response Class PDU (such as a Response-PDU) could
be returned.
''',
'snmpproxydrops',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpSilentDrops', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The total number of Confirmed Class PDUs (such as
GetRequest-PDUs, GetNextRequest-PDUs,
GetBulkRequest-PDUs, SetRequest-PDUs, and
InformRequest-PDUs) delivered to the SNMP entity which
were silently dropped because the size of a reply
containing an alternate Response Class PDU (such as a
Response-PDU) with an empty variable-bindings field
was greater than either a local constraint or the
maximum message size associated with the originator of
the request.
''',
'snmpsilentdrops',
'SNMPv2-MIB', False),
],
'SNMPv2-MIB',
'snmp',
_yang_ns._namespaces['SNMPv2-MIB'],
'ydk.models.cisco_ios_xe.SNMPv2_MIB'
),
},
'Snmpv2Mib.Snmpset' : {
'meta_info' : _MetaInfoClass('Snmpv2Mib.Snmpset',
False,
[
_MetaInfoClassMember('snmpSetSerialNo', ATTRIBUTE, 'int' , None, None,
[('0', '2147483647')], [],
''' An advisory lock used to allow several cooperating
command generator applications to coordinate their
use of the SNMP set operation.
This object is used for coarse-grain coordination.
To achieve fine-grain coordination, one or more similar
objects might be defined within each MIB group, as
appropriate.
''',
'snmpsetserialno',
'SNMPv2-MIB', False),
],
'SNMPv2-MIB',
'snmpSet',
_yang_ns._namespaces['SNMPv2-MIB'],
'ydk.models.cisco_ios_xe.SNMPv2_MIB'
),
},
'Snmpv2Mib.Sysortable.Sysorentry' : {
'meta_info' : _MetaInfoClass('Snmpv2Mib.Sysortable.Sysorentry',
False,
[
_MetaInfoClassMember('sysORIndex', ATTRIBUTE, 'int' , None, None,
[('1', '2147483647')], [],
''' The auxiliary variable used for identifying instances
of the columnar objects in the sysORTable.
''',
'sysorindex',
'SNMPv2-MIB', True),
_MetaInfoClassMember('sysORDescr', ATTRIBUTE, 'str' , None, None,
[], [],
''' A textual description of the capabilities identified
by the corresponding instance of sysORID.
''',
'sysordescr',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysORID', ATTRIBUTE, 'str' , None, None,
[], [b'(([0-1](\\.[1-3]?[0-9]))|(2\\.(0|([1-9]\\d*))))(\\.(0|([1-9]\\d*)))*'],
''' An authoritative identification of a capabilities
statement with respect to various MIB modules supported
by the local SNMP application acting as a command
responder.
''',
'sysorid',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysORUpTime', ATTRIBUTE, 'int' , None, None,
[('0', '4294967295')], [],
''' The value of sysUpTime at the time this conceptual
row was last instantiated.
''',
'sysoruptime',
'SNMPv2-MIB', False),
],
'SNMPv2-MIB',
'sysOREntry',
_yang_ns._namespaces['SNMPv2-MIB'],
'ydk.models.cisco_ios_xe.SNMPv2_MIB'
),
},
'Snmpv2Mib.Sysortable' : {
'meta_info' : _MetaInfoClass('Snmpv2Mib.Sysortable',
False,
[
_MetaInfoClassMember('sysOREntry', REFERENCE_LIST, 'Sysorentry' , 'ydk.models.cisco_ios_xe.SNMPv2_MIB', 'Snmpv2Mib.Sysortable.Sysorentry',
[], [],
''' An entry (conceptual row) in the sysORTable.
''',
'sysorentry',
'SNMPv2-MIB', False),
],
'SNMPv2-MIB',
'sysORTable',
_yang_ns._namespaces['SNMPv2-MIB'],
'ydk.models.cisco_ios_xe.SNMPv2_MIB'
),
},
'Snmpv2Mib' : {
'meta_info' : _MetaInfoClass('Snmpv2Mib',
False,
[
_MetaInfoClassMember('snmp', REFERENCE_CLASS, 'Snmp' , 'ydk.models.cisco_ios_xe.SNMPv2_MIB', 'Snmpv2Mib.Snmp',
[], [],
''' ''',
'snmp',
'SNMPv2-MIB', False),
_MetaInfoClassMember('snmpSet', REFERENCE_CLASS, 'Snmpset' , 'ydk.models.cisco_ios_xe.SNMPv2_MIB', 'Snmpv2Mib.Snmpset',
[], [],
''' ''',
'snmpset',
'SNMPv2-MIB', False),
_MetaInfoClassMember('sysORTable', REFERENCE_CLASS, 'Sysortable' , 'ydk.models.cisco_ios_xe.SNMPv2_MIB', 'Snmpv2Mib.Sysortable',
[], [],
''' The (conceptual) table listing the capabilities of
the local SNMP application acting as a command
responder with respect to various MIB modules.
SNMP entities having dynamically-configurable support
of MIB modules will have a dynamically-varying number
of conceptual rows.
''',
'sysortable',
'SNMPv2-MIB', False),
_MetaInfoClassMember('system', REFERENCE_CLASS, 'System' , 'ydk.models.cisco_ios_xe.SNMPv2_MIB', 'Snmpv2Mib.System',
[], [],
''' ''',
'system',
'SNMPv2-MIB', False),
],
'SNMPv2-MIB',
'SNMPv2-MIB',
_yang_ns._namespaces['SNMPv2-MIB'],
'ydk.models.cisco_ios_xe.SNMPv2_MIB'
),
},
}
_meta_table['Snmpv2Mib.Sysortable.Sysorentry']['meta_info'].parent =_meta_table['Snmpv2Mib.Sysortable']['meta_info']
_meta_table['Snmpv2Mib.System']['meta_info'].parent =_meta_table['Snmpv2Mib']['meta_info']
_meta_table['Snmpv2Mib.Snmp']['meta_info'].parent =_meta_table['Snmpv2Mib']['meta_info']
_meta_table['Snmpv2Mib.Snmpset']['meta_info'].parent =_meta_table['Snmpv2Mib']['meta_info']
_meta_table['Snmpv2Mib.Sysortable']['meta_info'].parent =_meta_table['Snmpv2Mib']['meta_info']
| {
"content_hash": "b2a4c6e9bcc0ae6fb08161ef3dca80d6",
"timestamp": "",
"source": "github",
"line_count": 533,
"max_line_length": 197,
"avg_line_length": 51.35647279549718,
"alnum_prop": 0.5026851276805612,
"repo_name": "111pontes/ydk-py",
"id": "67031c064833cf2e367b44ce94fecabff8c388ef",
"size": "27376",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cisco-ios-xe/ydk/models/cisco_ios_xe/_meta/_SNMPv2_MIB.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "7226"
},
{
"name": "Python",
"bytes": "446117948"
}
],
"symlink_target": ""
} |
package android.app;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
import android.content.Intent;
import android.content.IIntentReceiver;
import android.content.IIntentSender;
import android.content.IntentSender;
import android.os.Bundle;
import android.os.Looper;
import android.os.RemoteException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Process;
import android.os.UserHandle;
import android.util.AndroidException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* A description of an Intent and target action to perform with it. Instances
* of this class are created with {@link #getActivity}, {@link #getActivities},
* {@link #getBroadcast}, and {@link #getService}; the returned object can be
* handed to other applications so that they can perform the action you
* described on your behalf at a later time.
*
* <p>By giving a PendingIntent to another application,
* you are granting it the right to perform the operation you have specified
* as if the other application was yourself (with the same permissions and
* identity). As such, you should be careful about how you build the PendingIntent:
* almost always, for example, the base Intent you supply should have the component
* name explicitly set to one of your own components, to ensure it is ultimately
* sent there and nowhere else.
*
* <p>A PendingIntent itself is simply a reference to a token maintained by
* the system describing the original data used to retrieve it. This means
* that, even if its owning application's process is killed, the
* PendingIntent itself will remain usable from other processes that
* have been given it. If the creating application later re-retrieves the
* same kind of PendingIntent (same operation, same Intent action, data,
* categories, and components, and same flags), it will receive a PendingIntent
* representing the same token if that is still valid, and can thus call
* {@link #cancel} to remove it.
*
* <p>Because of this behavior, it is important to know when two Intents
* are considered to be the same for purposes of retrieving a PendingIntent.
* A common mistake people make is to create multiple PendingIntent objects
* with Intents that only vary in their "extra" contents, expecting to get
* a different PendingIntent each time. This does <em>not</em> happen. The
* parts of the Intent that are used for matching are the same ones defined
* by {@link Intent#filterEquals(Intent) Intent.filterEquals}. If you use two
* Intent objects that are equivalent as per
* {@link Intent#filterEquals(Intent) Intent.filterEquals}, then you will get
* the same PendingIntent for both of them.
*
* <p>There are two typical ways to deal with this.
*
* <p>If you truly need multiple distinct PendingIntent objects active at
* the same time (such as to use as two notifications that are both shown
* at the same time), then you will need to ensure there is something that
* is different about them to associate them with different PendingIntents.
* This may be any of the Intent attributes considered by
* {@link Intent#filterEquals(Intent) Intent.filterEquals}, or different
* request code integers supplied to {@link #getActivity}, {@link #getActivities},
* {@link #getBroadcast}, or {@link #getService}.
*
* <p>If you only need one PendingIntent active at a time for any of the
* Intents you will use, then you can alternatively use the flags
* {@link #FLAG_CANCEL_CURRENT} or {@link #FLAG_UPDATE_CURRENT} to either
* cancel or modify whatever current PendingIntent is associated with the
* Intent you are supplying.
*/
public final class PendingIntent implements Parcelable {
private final IIntentSender mTarget;
/** @hide */
@IntDef(flag = true,
value = {
FLAG_ONE_SHOT,
FLAG_NO_CREATE,
FLAG_CANCEL_CURRENT,
FLAG_UPDATE_CURRENT,
Intent.FILL_IN_ACTION,
Intent.FILL_IN_DATA,
Intent.FILL_IN_CATEGORIES,
Intent.FILL_IN_COMPONENT,
Intent.FILL_IN_PACKAGE,
Intent.FILL_IN_SOURCE_BOUNDS,
Intent.FILL_IN_SELECTOR,
Intent.FILL_IN_CLIP_DATA
})
@Retention(RetentionPolicy.SOURCE)
public @interface Flags {}
/**
* Flag indicating that this PendingIntent can be used only once.
* For use with {@link #getActivity}, {@link #getBroadcast}, and
* {@link #getService}. <p>If set, after
* {@link #send()} is called on it, it will be automatically
* canceled for you and any future attempt to send through it will fail.
*/
public static final int FLAG_ONE_SHOT = 1<<30;
/**
* Flag indicating that if the described PendingIntent does not
* already exist, then simply return null instead of creating it.
* For use with {@link #getActivity}, {@link #getBroadcast}, and
* {@link #getService}.
*/
public static final int FLAG_NO_CREATE = 1<<29;
/**
* Flag indicating that if the described PendingIntent already exists,
* the current one should be canceled before generating a new one.
* For use with {@link #getActivity}, {@link #getBroadcast}, and
* {@link #getService}. <p>You can use
* this to retrieve a new PendingIntent when you are only changing the
* extra data in the Intent; by canceling the previous pending intent,
* this ensures that only entities given the new data will be able to
* launch it. If this assurance is not an issue, consider
* {@link #FLAG_UPDATE_CURRENT}.
*/
public static final int FLAG_CANCEL_CURRENT = 1<<28;
/**
* Flag indicating that if the described PendingIntent already exists,
* then keep it but replace its extra data with what is in this new
* Intent. For use with {@link #getActivity}, {@link #getBroadcast}, and
* {@link #getService}. <p>This can be used if you are creating intents where only the
* extras change, and don't care that any entities that received your
* previous PendingIntent will be able to launch it with your new
* extras even if they are not explicitly given to it.
*/
public static final int FLAG_UPDATE_CURRENT = 1<<27;
/**
* Flag indicating that the created PendingIntent should be immutable.
* This means that the additional intent argument passed to the send
* methods to fill in unpopulated properties of this intent will be
* ignored.
*/
public static final int FLAG_IMMUTABLE = 1<<26;
/**
* Exception thrown when trying to send through a PendingIntent that
* has been canceled or is otherwise no longer able to execute the request.
*/
public static class CanceledException extends AndroidException {
public CanceledException() {
}
public CanceledException(String name) {
super(name);
}
public CanceledException(Exception cause) {
super(cause);
}
}
/**
* Callback interface for discovering when a send operation has
* completed. Primarily for use with a PendingIntent that is
* performing a broadcast, this provides the same information as
* calling {@link Context#sendOrderedBroadcast(Intent, String,
* android.content.BroadcastReceiver, Handler, int, String, Bundle)
* Context.sendBroadcast()} with a final BroadcastReceiver.
*/
public interface OnFinished {
/**
* Called when a send operation as completed.
*
* @param pendingIntent The PendingIntent this operation was sent through.
* @param intent The original Intent that was sent.
* @param resultCode The final result code determined by the send.
* @param resultData The final data collected by a broadcast.
* @param resultExtras The final extras collected by a broadcast.
*/
void onSendFinished(PendingIntent pendingIntent, Intent intent,
int resultCode, String resultData, Bundle resultExtras);
}
private static class FinishedDispatcher extends IIntentReceiver.Stub
implements Runnable {
private final PendingIntent mPendingIntent;
private final OnFinished mWho;
private final Handler mHandler;
private Intent mIntent;
private int mResultCode;
private String mResultData;
private Bundle mResultExtras;
private static Handler sDefaultSystemHandler;
FinishedDispatcher(PendingIntent pi, OnFinished who, Handler handler) {
mPendingIntent = pi;
mWho = who;
if (handler == null && ActivityThread.isSystem()) {
// We assign a default handler for the system process to avoid deadlocks when
// processing receivers in various components that hold global service locks.
if (sDefaultSystemHandler == null) {
sDefaultSystemHandler = new Handler(Looper.getMainLooper());
}
mHandler = sDefaultSystemHandler;
} else {
mHandler = handler;
}
}
public void performReceive(Intent intent, int resultCode, String data,
Bundle extras, boolean serialized, boolean sticky, int sendingUser) {
mIntent = intent;
mResultCode = resultCode;
mResultData = data;
mResultExtras = extras;
if (mHandler == null) {
run();
} else {
mHandler.post(this);
}
}
public void run() {
mWho.onSendFinished(mPendingIntent, mIntent, mResultCode,
mResultData, mResultExtras);
}
}
/**
* Listener for observing when pending intents are written to a parcel.
*
* @hide
*/
public interface OnMarshaledListener {
/**
* Called when a pending intent is written to a parcel.
*
* @param intent The pending intent.
* @param parcel The parcel to which it was written.
* @param flags The parcel flags when it was written.
*/
void onMarshaled(PendingIntent intent, Parcel parcel, int flags);
}
private static final ThreadLocal<OnMarshaledListener> sOnMarshaledListener
= new ThreadLocal<>();
/**
* Registers an listener for pending intents being written to a parcel.
*
* @param listener The listener, null to clear.
*
* @hide
*/
public static void setOnMarshaledListener(OnMarshaledListener listener) {
sOnMarshaledListener.set(listener);
}
/**
* Retrieve a PendingIntent that will start a new activity, like calling
* {@link Context#startActivity(Intent) Context.startActivity(Intent)}.
* Note that the activity will be started outside of the context of an
* existing activity, so you must use the {@link Intent#FLAG_ACTIVITY_NEW_TASK
* Intent.FLAG_ACTIVITY_NEW_TASK} launch flag in the Intent.
*
* <p class="note">For security reasons, the {@link android.content.Intent}
* you supply here should almost always be an <em>explicit intent</em>,
* that is specify an explicit component to be delivered to through
* {@link Intent#setClass(android.content.Context, Class) Intent.setClass}</p>
*
* @param context The Context in which this PendingIntent should start
* the activity.
* @param requestCode Private request code for the sender
* @param intent Intent of the activity to be launched.
* @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE},
* {@link #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT},
* or any of the flags as supported by
* {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
* of the intent that can be supplied when the actual send happens.
*
* @return Returns an existing or new PendingIntent matching the given
* parameters. May return null only if {@link #FLAG_NO_CREATE} has been
* supplied.
*/
public static PendingIntent getActivity(Context context, int requestCode,
Intent intent, @Flags int flags) {
return getActivity(context, requestCode, intent, flags, null);
}
/**
* Retrieve a PendingIntent that will start a new activity, like calling
* {@link Context#startActivity(Intent) Context.startActivity(Intent)}.
* Note that the activity will be started outside of the context of an
* existing activity, so you must use the {@link Intent#FLAG_ACTIVITY_NEW_TASK
* Intent.FLAG_ACTIVITY_NEW_TASK} launch flag in the Intent.
*
* <p class="note">For security reasons, the {@link android.content.Intent}
* you supply here should almost always be an <em>explicit intent</em>,
* that is specify an explicit component to be delivered to through
* {@link Intent#setClass(android.content.Context, Class) Intent.setClass}</p>
*
* @param context The Context in which this PendingIntent should start
* the activity.
* @param requestCode Private request code for the sender
* @param intent Intent of the activity to be launched.
* @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE},
* {@link #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT},
* or any of the flags as supported by
* {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
* of the intent that can be supplied when the actual send happens.
* @param options Additional options for how the Activity should be started.
* May be null if there are no options.
*
* @return Returns an existing or new PendingIntent matching the given
* parameters. May return null only if {@link #FLAG_NO_CREATE} has been
* supplied.
*/
public static PendingIntent getActivity(Context context, int requestCode,
@NonNull Intent intent, @Flags int flags, @Nullable Bundle options) {
String packageName = context.getPackageName();
String resolvedType = intent != null ? intent.resolveTypeIfNeeded(
context.getContentResolver()) : null;
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(context);
IIntentSender target =
ActivityManagerNative.getDefault().getIntentSender(
ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
null, null, requestCode, new Intent[] { intent },
resolvedType != null ? new String[] { resolvedType } : null,
flags, options, UserHandle.myUserId());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
}
return null;
}
/**
* @hide
* Note that UserHandle.CURRENT will be interpreted at the time the
* activity is started, not when the pending intent is created.
*/
public static PendingIntent getActivityAsUser(Context context, int requestCode,
@NonNull Intent intent, int flags, Bundle options, UserHandle user) {
String packageName = context.getPackageName();
String resolvedType = intent != null ? intent.resolveTypeIfNeeded(
context.getContentResolver()) : null;
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(context);
IIntentSender target =
ActivityManagerNative.getDefault().getIntentSender(
ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
null, null, requestCode, new Intent[] { intent },
resolvedType != null ? new String[] { resolvedType } : null,
flags, options, user.getIdentifier());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
}
return null;
}
/**
* Like {@link #getActivity(Context, int, Intent, int)}, but allows an
* array of Intents to be supplied. The last Intent in the array is
* taken as the primary key for the PendingIntent, like the single Intent
* given to {@link #getActivity(Context, int, Intent, int)}. Upon sending
* the resulting PendingIntent, all of the Intents are started in the same
* way as they would be by passing them to {@link Context#startActivities(Intent[])}.
*
* <p class="note">
* The <em>first</em> intent in the array will be started outside of the context of an
* existing activity, so you must use the {@link Intent#FLAG_ACTIVITY_NEW_TASK
* Intent.FLAG_ACTIVITY_NEW_TASK} launch flag in the Intent. (Activities after
* the first in the array are started in the context of the previous activity
* in the array, so FLAG_ACTIVITY_NEW_TASK is not needed nor desired for them.)
* </p>
*
* <p class="note">
* The <em>last</em> intent in the array represents the key for the
* PendingIntent. In other words, it is the significant element for matching
* (as done with the single intent given to {@link #getActivity(Context, int, Intent, int)},
* its content will be the subject of replacement by
* {@link #send(Context, int, Intent)} and {@link #FLAG_UPDATE_CURRENT}, etc.
* This is because it is the most specific of the supplied intents, and the
* UI the user actually sees when the intents are started.
* </p>
*
* <p class="note">For security reasons, the {@link android.content.Intent} objects
* you supply here should almost always be <em>explicit intents</em>,
* that is specify an explicit component to be delivered to through
* {@link Intent#setClass(android.content.Context, Class) Intent.setClass}</p>
*
* @param context The Context in which this PendingIntent should start
* the activity.
* @param requestCode Private request code for the sender
* @param intents Array of Intents of the activities to be launched.
* @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE},
* {@link #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT},
* or any of the flags as supported by
* {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
* of the intent that can be supplied when the actual send happens.
*
* @return Returns an existing or new PendingIntent matching the given
* parameters. May return null only if {@link #FLAG_NO_CREATE} has been
* supplied.
*/
public static PendingIntent getActivities(Context context, int requestCode,
@NonNull Intent[] intents, @Flags int flags) {
return getActivities(context, requestCode, intents, flags, null);
}
/**
* Like {@link #getActivity(Context, int, Intent, int)}, but allows an
* array of Intents to be supplied. The last Intent in the array is
* taken as the primary key for the PendingIntent, like the single Intent
* given to {@link #getActivity(Context, int, Intent, int)}. Upon sending
* the resulting PendingIntent, all of the Intents are started in the same
* way as they would be by passing them to {@link Context#startActivities(Intent[])}.
*
* <p class="note">
* The <em>first</em> intent in the array will be started outside of the context of an
* existing activity, so you must use the {@link Intent#FLAG_ACTIVITY_NEW_TASK
* Intent.FLAG_ACTIVITY_NEW_TASK} launch flag in the Intent. (Activities after
* the first in the array are started in the context of the previous activity
* in the array, so FLAG_ACTIVITY_NEW_TASK is not needed nor desired for them.)
* </p>
*
* <p class="note">
* The <em>last</em> intent in the array represents the key for the
* PendingIntent. In other words, it is the significant element for matching
* (as done with the single intent given to {@link #getActivity(Context, int, Intent, int)},
* its content will be the subject of replacement by
* {@link #send(Context, int, Intent)} and {@link #FLAG_UPDATE_CURRENT}, etc.
* This is because it is the most specific of the supplied intents, and the
* UI the user actually sees when the intents are started.
* </p>
*
* <p class="note">For security reasons, the {@link android.content.Intent} objects
* you supply here should almost always be <em>explicit intents</em>,
* that is specify an explicit component to be delivered to through
* {@link Intent#setClass(android.content.Context, Class) Intent.setClass}</p>
*
* @param context The Context in which this PendingIntent should start
* the activity.
* @param requestCode Private request code for the sender
* @param intents Array of Intents of the activities to be launched.
* @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE},
* {@link #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT},
* {@link #FLAG_IMMUTABLE} or any of the flags as supported by
* {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
* of the intent that can be supplied when the actual send happens.
*
* @return Returns an existing or new PendingIntent matching the given
* parameters. May return null only if {@link #FLAG_NO_CREATE} has been
* supplied.
*/
public static PendingIntent getActivities(Context context, int requestCode,
@NonNull Intent[] intents, @Flags int flags, @Nullable Bundle options) {
String packageName = context.getPackageName();
String[] resolvedTypes = new String[intents.length];
for (int i=0; i<intents.length; i++) {
intents[i].migrateExtraStreamToClipData();
intents[i].prepareToLeaveProcess(context);
resolvedTypes[i] = intents[i].resolveTypeIfNeeded(context.getContentResolver());
}
try {
IIntentSender target =
ActivityManagerNative.getDefault().getIntentSender(
ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
null, null, requestCode, intents, resolvedTypes, flags, options,
UserHandle.myUserId());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
}
return null;
}
/**
* @hide
* Note that UserHandle.CURRENT will be interpreted at the time the
* activity is started, not when the pending intent is created.
*/
public static PendingIntent getActivitiesAsUser(Context context, int requestCode,
@NonNull Intent[] intents, int flags, Bundle options, UserHandle user) {
String packageName = context.getPackageName();
String[] resolvedTypes = new String[intents.length];
for (int i=0; i<intents.length; i++) {
intents[i].migrateExtraStreamToClipData();
intents[i].prepareToLeaveProcess(context);
resolvedTypes[i] = intents[i].resolveTypeIfNeeded(context.getContentResolver());
}
try {
IIntentSender target =
ActivityManagerNative.getDefault().getIntentSender(
ActivityManager.INTENT_SENDER_ACTIVITY, packageName,
null, null, requestCode, intents, resolvedTypes,
flags, options, user.getIdentifier());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
}
return null;
}
/**
* Retrieve a PendingIntent that will perform a broadcast, like calling
* {@link Context#sendBroadcast(Intent) Context.sendBroadcast()}.
*
* <p class="note">For security reasons, the {@link android.content.Intent}
* you supply here should almost always be an <em>explicit intent</em>,
* that is specify an explicit component to be delivered to through
* {@link Intent#setClass(android.content.Context, Class) Intent.setClass}</p>
*
* @param context The Context in which this PendingIntent should perform
* the broadcast.
* @param requestCode Private request code for the sender
* @param intent The Intent to be broadcast.
* @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE},
* {@link #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT},
* {@link #FLAG_IMMUTABLE} or any of the flags as supported by
* {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
* of the intent that can be supplied when the actual send happens.
*
* @return Returns an existing or new PendingIntent matching the given
* parameters. May return null only if {@link #FLAG_NO_CREATE} has been
* supplied.
*/
public static PendingIntent getBroadcast(Context context, int requestCode,
Intent intent, @Flags int flags) {
return getBroadcastAsUser(context, requestCode, intent, flags,
new UserHandle(UserHandle.myUserId()));
}
/**
* @hide
* Note that UserHandle.CURRENT will be interpreted at the time the
* broadcast is sent, not when the pending intent is created.
*/
public static PendingIntent getBroadcastAsUser(Context context, int requestCode,
Intent intent, int flags, UserHandle userHandle) {
String packageName = context.getPackageName();
String resolvedType = intent != null ? intent.resolveTypeIfNeeded(
context.getContentResolver()) : null;
try {
intent.prepareToLeaveProcess(context);
IIntentSender target =
ActivityManagerNative.getDefault().getIntentSender(
ActivityManager.INTENT_SENDER_BROADCAST, packageName,
null, null, requestCode, new Intent[] { intent },
resolvedType != null ? new String[] { resolvedType } : null,
flags, null, userHandle.getIdentifier());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
}
return null;
}
/**
* Retrieve a PendingIntent that will start a service, like calling
* {@link Context#startService Context.startService()}. The start
* arguments given to the service will come from the extras of the Intent.
*
* <p class="note">For security reasons, the {@link android.content.Intent}
* you supply here should almost always be an <em>explicit intent</em>,
* that is specify an explicit component to be delivered to through
* {@link Intent#setClass(android.content.Context, Class) Intent.setClass}</p>
*
* @param context The Context in which this PendingIntent should start
* the service.
* @param requestCode Private request code for the sender
* @param intent An Intent describing the service to be started.
* @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE},
* {@link #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT},
* {@link #FLAG_IMMUTABLE} or any of the flags as supported by
* {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts
* of the intent that can be supplied when the actual send happens.
*
* @return Returns an existing or new PendingIntent matching the given
* parameters. May return null only if {@link #FLAG_NO_CREATE} has been
* supplied.
*/
public static PendingIntent getService(Context context, int requestCode,
@NonNull Intent intent, @Flags int flags) {
String packageName = context.getPackageName();
String resolvedType = intent != null ? intent.resolveTypeIfNeeded(
context.getContentResolver()) : null;
try {
intent.prepareToLeaveProcess(context);
IIntentSender target =
ActivityManagerNative.getDefault().getIntentSender(
ActivityManager.INTENT_SENDER_SERVICE, packageName,
null, null, requestCode, new Intent[] { intent },
resolvedType != null ? new String[] { resolvedType } : null,
flags, null, UserHandle.myUserId());
return target != null ? new PendingIntent(target) : null;
} catch (RemoteException e) {
}
return null;
}
/**
* Retrieve a IntentSender object that wraps the existing sender of the PendingIntent
*
* @return Returns a IntentSender object that wraps the sender of PendingIntent
*
*/
public IntentSender getIntentSender() {
return new IntentSender(mTarget);
}
/**
* Cancel a currently active PendingIntent. Only the original application
* owning a PendingIntent can cancel it.
*/
public void cancel() {
try {
ActivityManagerNative.getDefault().cancelIntentSender(mTarget);
} catch (RemoteException e) {
}
}
/**
* Perform the operation associated with this PendingIntent.
*
* @see #send(Context, int, Intent, android.app.PendingIntent.OnFinished, Handler)
*
* @throws CanceledException Throws CanceledException if the PendingIntent
* is no longer allowing more intents to be sent through it.
*/
public void send() throws CanceledException {
send(null, 0, null, null, null, null, null);
}
/**
* Perform the operation associated with this PendingIntent.
*
* @param code Result code to supply back to the PendingIntent's target.
*
* @see #send(Context, int, Intent, android.app.PendingIntent.OnFinished, Handler)
*
* @throws CanceledException Throws CanceledException if the PendingIntent
* is no longer allowing more intents to be sent through it.
*/
public void send(int code) throws CanceledException {
send(null, code, null, null, null, null, null);
}
/**
* Perform the operation associated with this PendingIntent, allowing the
* caller to specify information about the Intent to use.
*
* @param context The Context of the caller.
* @param code Result code to supply back to the PendingIntent's target.
* @param intent Additional Intent data. See {@link Intent#fillIn
* Intent.fillIn()} for information on how this is applied to the
* original Intent. If flag {@link #FLAG_IMMUTABLE} was set when this
* pending intent was created, this argument will be ignored.
*
* @see #send(Context, int, Intent, android.app.PendingIntent.OnFinished, Handler)
*
* @throws CanceledException Throws CanceledException if the PendingIntent
* is no longer allowing more intents to be sent through it.
*/
public void send(Context context, int code, @Nullable Intent intent)
throws CanceledException {
send(context, code, intent, null, null, null, null);
}
/**
* Perform the operation associated with this PendingIntent, allowing the
* caller to be notified when the send has completed.
*
* @param code Result code to supply back to the PendingIntent's target.
* @param onFinished The object to call back on when the send has
* completed, or null for no callback.
* @param handler Handler identifying the thread on which the callback
* should happen. If null, the callback will happen from the thread
* pool of the process.
*
* @see #send(Context, int, Intent, android.app.PendingIntent.OnFinished, Handler)
*
* @throws CanceledException Throws CanceledException if the PendingIntent
* is no longer allowing more intents to be sent through it.
*/
public void send(int code, @Nullable OnFinished onFinished, @Nullable Handler handler)
throws CanceledException {
send(null, code, null, onFinished, handler, null, null);
}
/**
* Perform the operation associated with this PendingIntent, allowing the
* caller to specify information about the Intent to use and be notified
* when the send has completed.
*
* <p>For the intent parameter, a PendingIntent
* often has restrictions on which fields can be supplied here, based on
* how the PendingIntent was retrieved in {@link #getActivity},
* {@link #getBroadcast}, or {@link #getService}.
*
* @param context The Context of the caller. This may be null if
* <var>intent</var> is also null.
* @param code Result code to supply back to the PendingIntent's target.
* @param intent Additional Intent data. See {@link Intent#fillIn
* Intent.fillIn()} for information on how this is applied to the
* original Intent. Use null to not modify the original Intent.
* If flag {@link #FLAG_IMMUTABLE} was set when this pending intent was
* created, this argument will be ignored.
* @param onFinished The object to call back on when the send has
* completed, or null for no callback.
* @param handler Handler identifying the thread on which the callback
* should happen. If null, the callback will happen from the thread
* pool of the process.
*
* @see #send()
* @see #send(int)
* @see #send(Context, int, Intent)
* @see #send(int, android.app.PendingIntent.OnFinished, Handler)
* @see #send(Context, int, Intent, OnFinished, Handler, String)
*
* @throws CanceledException Throws CanceledException if the PendingIntent
* is no longer allowing more intents to be sent through it.
*/
public void send(Context context, int code, @Nullable Intent intent,
@Nullable OnFinished onFinished, @Nullable Handler handler) throws CanceledException {
send(context, code, intent, onFinished, handler, null, null);
}
/**
* Perform the operation associated with this PendingIntent, allowing the
* caller to specify information about the Intent to use and be notified
* when the send has completed.
*
* <p>For the intent parameter, a PendingIntent
* often has restrictions on which fields can be supplied here, based on
* how the PendingIntent was retrieved in {@link #getActivity},
* {@link #getBroadcast}, or {@link #getService}.
*
* @param context The Context of the caller. This may be null if
* <var>intent</var> is also null.
* @param code Result code to supply back to the PendingIntent's target.
* @param intent Additional Intent data. See {@link Intent#fillIn
* Intent.fillIn()} for information on how this is applied to the
* original Intent. Use null to not modify the original Intent.
* If flag {@link #FLAG_IMMUTABLE} was set when this pending intent was
* created, this argument will be ignored.
* @param onFinished The object to call back on when the send has
* completed, or null for no callback.
* @param handler Handler identifying the thread on which the callback
* should happen. If null, the callback will happen from the thread
* pool of the process.
* @param requiredPermission Name of permission that a recipient of the PendingIntent
* is required to hold. This is only valid for broadcast intents, and
* corresponds to the permission argument in
* {@link Context#sendBroadcast(Intent, String) Context.sendOrderedBroadcast(Intent, String)}.
* If null, no permission is required.
*
* @see #send()
* @see #send(int)
* @see #send(Context, int, Intent)
* @see #send(int, android.app.PendingIntent.OnFinished, Handler)
* @see #send(Context, int, Intent, OnFinished, Handler)
*
* @throws CanceledException Throws CanceledException if the PendingIntent
* is no longer allowing more intents to be sent through it.
*/
public void send(Context context, int code, @Nullable Intent intent,
@Nullable OnFinished onFinished, @Nullable Handler handler,
@Nullable String requiredPermission)
throws CanceledException {
send(context, code, intent, onFinished, handler, requiredPermission, null);
}
/**
* Perform the operation associated with this PendingIntent, allowing the
* caller to specify information about the Intent to use and be notified
* when the send has completed.
*
* <p>For the intent parameter, a PendingIntent
* often has restrictions on which fields can be supplied here, based on
* how the PendingIntent was retrieved in {@link #getActivity},
* {@link #getBroadcast}, or {@link #getService}.
*
* @param context The Context of the caller. This may be null if
* <var>intent</var> is also null.
* @param code Result code to supply back to the PendingIntent's target.
* @param intent Additional Intent data. See {@link Intent#fillIn
* Intent.fillIn()} for information on how this is applied to the
* original Intent. Use null to not modify the original Intent.
* If flag {@link #FLAG_IMMUTABLE} was set when this pending intent was
* created, this argument will be ignored.
* @param onFinished The object to call back on when the send has
* completed, or null for no callback.
* @param handler Handler identifying the thread on which the callback
* should happen. If null, the callback will happen from the thread
* pool of the process.
* @param requiredPermission Name of permission that a recipient of the PendingIntent
* is required to hold. This is only valid for broadcast intents, and
* corresponds to the permission argument in
* {@link Context#sendBroadcast(Intent, String) Context.sendOrderedBroadcast(Intent, String)}.
* If null, no permission is required.
* @param options Additional options the caller would like to provide to modify the sending
* behavior. May be built from an {@link ActivityOptions} to apply to an activity start.
*
* @see #send()
* @see #send(int)
* @see #send(Context, int, Intent)
* @see #send(int, android.app.PendingIntent.OnFinished, Handler)
* @see #send(Context, int, Intent, OnFinished, Handler)
*
* @throws CanceledException Throws CanceledException if the PendingIntent
* is no longer allowing more intents to be sent through it.
*/
public void send(Context context, int code, @Nullable Intent intent,
@Nullable OnFinished onFinished, @Nullable Handler handler,
@Nullable String requiredPermission, @Nullable Bundle options)
throws CanceledException {
try {
String resolvedType = intent != null ?
intent.resolveTypeIfNeeded(context.getContentResolver())
: null;
int res = ActivityManagerNative.getDefault().sendIntentSender(
mTarget, code, intent, resolvedType,
onFinished != null
? new FinishedDispatcher(this, onFinished, handler)
: null,
requiredPermission, options);
if (res < 0) {
throw new CanceledException();
}
} catch (RemoteException e) {
throw new CanceledException(e);
}
}
/**
* @deprecated Renamed to {@link #getCreatorPackage()}.
*/
@Deprecated
public String getTargetPackage() {
try {
return ActivityManagerNative.getDefault()
.getPackageForIntentSender(mTarget);
} catch (RemoteException e) {
// Should never happen.
return null;
}
}
/**
* Return the package name of the application that created this
* PendingIntent, that is the identity under which you will actually be
* sending the Intent. The returned string is supplied by the system, so
* that an application can not spoof its package.
*
* <p class="note">Be careful about how you use this. All this tells you is
* who created the PendingIntent. It does <strong>not</strong> tell you who
* handed the PendingIntent to you: that is, PendingIntent objects are intended to be
* passed between applications, so the PendingIntent you receive from an application
* could actually be one it received from another application, meaning the result
* you get here will identify the original application. Because of this, you should
* only use this information to identify who you expect to be interacting with
* through a {@link #send} call, not who gave you the PendingIntent.</p>
*
* @return The package name of the PendingIntent, or null if there is
* none associated with it.
*/
@Nullable
public String getCreatorPackage() {
try {
return ActivityManagerNative.getDefault()
.getPackageForIntentSender(mTarget);
} catch (RemoteException e) {
// Should never happen.
return null;
}
}
/**
* Return the uid of the application that created this
* PendingIntent, that is the identity under which you will actually be
* sending the Intent. The returned integer is supplied by the system, so
* that an application can not spoof its uid.
*
* <p class="note">Be careful about how you use this. All this tells you is
* who created the PendingIntent. It does <strong>not</strong> tell you who
* handed the PendingIntent to you: that is, PendingIntent objects are intended to be
* passed between applications, so the PendingIntent you receive from an application
* could actually be one it received from another application, meaning the result
* you get here will identify the original application. Because of this, you should
* only use this information to identify who you expect to be interacting with
* through a {@link #send} call, not who gave you the PendingIntent.</p>
*
* @return The uid of the PendingIntent, or -1 if there is
* none associated with it.
*/
public int getCreatorUid() {
try {
return ActivityManagerNative.getDefault()
.getUidForIntentSender(mTarget);
} catch (RemoteException e) {
// Should never happen.
return -1;
}
}
/**
* Return the user handle of the application that created this
* PendingIntent, that is the user under which you will actually be
* sending the Intent. The returned UserHandle is supplied by the system, so
* that an application can not spoof its user. See
* {@link android.os.Process#myUserHandle() Process.myUserHandle()} for
* more explanation of user handles.
*
* <p class="note">Be careful about how you use this. All this tells you is
* who created the PendingIntent. It does <strong>not</strong> tell you who
* handed the PendingIntent to you: that is, PendingIntent objects are intended to be
* passed between applications, so the PendingIntent you receive from an application
* could actually be one it received from another application, meaning the result
* you get here will identify the original application. Because of this, you should
* only use this information to identify who you expect to be interacting with
* through a {@link #send} call, not who gave you the PendingIntent.</p>
*
* @return The user handle of the PendingIntent, or null if there is
* none associated with it.
*/
@Nullable
public UserHandle getCreatorUserHandle() {
try {
int uid = ActivityManagerNative.getDefault()
.getUidForIntentSender(mTarget);
return uid > 0 ? new UserHandle(UserHandle.getUserId(uid)) : null;
} catch (RemoteException e) {
// Should never happen.
return null;
}
}
/**
* @hide
* Check to verify that this PendingIntent targets a specific package.
*/
public boolean isTargetedToPackage() {
try {
return ActivityManagerNative.getDefault()
.isIntentSenderTargetedToPackage(mTarget);
} catch (RemoteException e) {
// Should never happen.
return false;
}
}
/**
* @hide
* Check whether this PendingIntent will launch an Activity.
*/
public boolean isActivity() {
try {
return ActivityManagerNative.getDefault()
.isIntentSenderAnActivity(mTarget);
} catch (RemoteException e) {
// Should never happen.
return false;
}
}
/**
* @hide
* Return the Intent of this PendingIntent.
*/
public Intent getIntent() {
try {
return ActivityManagerNative.getDefault()
.getIntentForIntentSender(mTarget);
} catch (RemoteException e) {
// Should never happen.
return null;
}
}
/**
* @hide
* Return descriptive tag for this PendingIntent.
*/
public String getTag(String prefix) {
try {
return ActivityManagerNative.getDefault()
.getTagForIntentSender(mTarget, prefix);
} catch (RemoteException e) {
// Should never happen.
return null;
}
}
/**
* Comparison operator on two PendingIntent objects, such that true
* is returned then they both represent the same operation from the
* same package. This allows you to use {@link #getActivity},
* {@link #getBroadcast}, or {@link #getService} multiple times (even
* across a process being killed), resulting in different PendingIntent
* objects but whose equals() method identifies them as being the same
* operation.
*/
@Override
public boolean equals(Object otherObj) {
if (otherObj instanceof PendingIntent) {
return mTarget.asBinder().equals(((PendingIntent)otherObj)
.mTarget.asBinder());
}
return false;
}
@Override
public int hashCode() {
return mTarget.asBinder().hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(128);
sb.append("PendingIntent{");
sb.append(Integer.toHexString(System.identityHashCode(this)));
sb.append(": ");
sb.append(mTarget != null ? mTarget.asBinder() : null);
sb.append('}');
return sb.toString();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeStrongBinder(mTarget.asBinder());
OnMarshaledListener listener = sOnMarshaledListener.get();
if (listener != null) {
listener.onMarshaled(this, out, flags);
}
}
public static final Parcelable.Creator<PendingIntent> CREATOR
= new Parcelable.Creator<PendingIntent>() {
public PendingIntent createFromParcel(Parcel in) {
IBinder target = in.readStrongBinder();
return target != null ? new PendingIntent(target) : null;
}
public PendingIntent[] newArray(int size) {
return new PendingIntent[size];
}
};
/**
* Convenience function for writing either a PendingIntent or null pointer to
* a Parcel. You must use this with {@link #readPendingIntentOrNullFromParcel}
* for later reading it.
*
* @param sender The PendingIntent to write, or null.
* @param out Where to write the PendingIntent.
*/
public static void writePendingIntentOrNullToParcel(@Nullable PendingIntent sender,
@NonNull Parcel out) {
out.writeStrongBinder(sender != null ? sender.mTarget.asBinder()
: null);
}
/**
* Convenience function for reading either a Messenger or null pointer from
* a Parcel. You must have previously written the Messenger with
* {@link #writePendingIntentOrNullToParcel}.
*
* @param in The Parcel containing the written Messenger.
*
* @return Returns the Messenger read from the Parcel, or null if null had
* been written.
*/
@Nullable
public static PendingIntent readPendingIntentOrNullFromParcel(@NonNull Parcel in) {
IBinder b = in.readStrongBinder();
return b != null ? new PendingIntent(b) : null;
}
/*package*/ PendingIntent(IIntentSender target) {
mTarget = target;
}
/*package*/ PendingIntent(IBinder target) {
mTarget = IIntentSender.Stub.asInterface(target);
}
/** @hide */
public IIntentSender getTarget() {
return mTarget;
}
}
| {
"content_hash": "46f667e0c64cbb196a1a56b8cdba4c29",
"timestamp": "",
"source": "github",
"line_count": 1096,
"max_line_length": 98,
"avg_line_length": 44.96897810218978,
"alnum_prop": 0.6565353244329019,
"repo_name": "daiqiquan/framework-base",
"id": "cfa242be02aa89156c64f92b6ffb8af3f7ad2acc",
"size": "49905",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/java/android/app/PendingIntent.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "10239"
},
{
"name": "C++",
"bytes": "3841417"
},
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "196467"
},
{
"name": "Java",
"bytes": "56796292"
},
{
"name": "Makefile",
"bytes": "103735"
},
{
"name": "Shell",
"bytes": "423"
}
],
"symlink_target": ""
} |
package com.basho.riak.client.core.operations.itest;
import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.api.commands.buckets.FetchBucketProperties;
import com.basho.riak.client.api.commands.indexes.BinIndexQuery;
import com.basho.riak.client.api.commands.indexes.BucketIndexQuery;
import com.basho.riak.client.api.commands.indexes.RawIndexQuery;
import com.basho.riak.client.api.commands.kv.CoveragePlan;
import com.basho.riak.client.core.RiakCluster;
import com.basho.riak.client.core.RiakNode;
import com.basho.riak.client.core.operations.CoveragePlanOperation.Response.CoverageEntry;
import com.basho.riak.client.core.operations.FetchBucketPropsOperation;
import com.basho.riak.client.core.query.BucketProperties;
import com.basho.riak.client.core.query.Namespace;
import com.basho.riak.client.core.util.HostAndPort;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.*;
/**
* @author Sergey Galkin <sgalkin at basho dot com>
*/
public class ITestCoveragePlan extends ITestAutoCleanupBase
{
private final static Logger logger = LoggerFactory.getLogger(ITestCoveragePlan.class);
@Rule
public ExpectedException exception = ExpectedException.none();
// TODO: Remove assumption as Riak KV with PEx and Coverage plan will be released
@BeforeClass
public static void BeforeClass()
{
Assume.assumeTrue(testTimeSeries);
Assume.assumeTrue(testCoveragePlan);
}
@Test
public void obtainAlternativeCoveragePlan() throws ExecutionException, InterruptedException
{
final int minPartitions = 5;
final RiakClient client = new RiakClient(cluster);
CoveragePlan cmd = CoveragePlan.Builder.create(defaultNamespace())
.withMinPartitions(minPartitions)
.build();
CoveragePlan.Response response = client.execute(cmd);
final List<CoverageEntry> coverageEntries = new ArrayList<>();
for (CoverageEntry ce : response)
{
coverageEntries.add(ce);
}
Assert.assertTrue(coverageEntries.size() > minPartitions);
final CoverageEntry failedEntry = coverageEntries.get(0); // assume this coverage entry failed
// build request for alternative coverage plan
cmd = CoveragePlan.Builder.create(defaultNamespace())
.withMinPartitions(minPartitions)
.withReplaceCoverageEntry(failedEntry)
.withUnavailableCoverageEntries(Collections.singletonList(failedEntry))
.build();
response = client.execute(cmd);
Assert.assertTrue(response.iterator().hasNext());
final HostAndPort failedHostAndPort = HostAndPort.fromParts(failedEntry.getHost(), failedEntry.getPort());
for (CoverageEntry ce : response)
{
HostAndPort alternativeHostAndPort = HostAndPort.fromParts(ce.getHost(), ce.getPort());
// received coverage entry must not be on the same host
assertThat(alternativeHostAndPort, not(equalTo(failedHostAndPort)));
assertThat(ce.getCoverageContext(), not(equalTo(failedEntry.getCoverageContext())));
}
}
@Test
public void obtainCoveragePlan() throws ExecutionException, InterruptedException
{
final int minPartitions = 5;
final RiakClient client = new RiakClient(cluster);
final CoveragePlan cmd = CoveragePlan.Builder.create(defaultNamespace())
.withMinPartitions(minPartitions)
.build();
final CoveragePlan.Response response = client.execute(cmd);
final List<CoverageEntry> lst = new LinkedList<>();
for (CoverageEntry ce: response)
{
lst.add(ce);
}
logger.info("Got the following list of Coverage Entries: {}", lst);
Assert.assertTrue(lst.size() > minPartitions);
}
@Test
public void fetchAllDataByUsingCoverageContext() throws ExecutionException, InterruptedException, UnknownHostException
{
String indexName = "test_coverctx_index";
String keyBase = "k";
String value = "v";
setupIndexTestData(defaultNamespace(), indexName, keyBase, value);
final RiakClient client = new RiakClient(cluster);
final CoveragePlan cmd = CoveragePlan.Builder.create(defaultNamespace())
.build();
final CoveragePlan.Response response = client.execute(cmd);
if (logger.isInfoEnabled())
{
StringBuilder sbld = new StringBuilder("Got the following list of Coverage Entries:");
for (CoverageEntry ce: response)
{
sbld.append(String.format("\n\t%s:%d ('%s')",
ce.getHost(),
ce.getPort(),
ce.getDescription()
));
}
logger.info(sbld.toString());
}
final Map<CoverageEntry, List<BinIndexQuery.Response.Entry<String>>> chunkedKeys
= new HashMap<>();
for (HostAndPort host: response.hosts())
{
final RiakNode node= new RiakNode.Builder()
.withRemoteHost(host)
.withMinConnections(1)
.build();
final RiakCluster cl = RiakCluster.builder(node)
.build();
cl.start();
final RiakClient rc = new RiakClient(cl);
try
{
for (CoverageEntry ce: response.hostEntries(host))
{
final BucketIndexQuery query =
new BucketIndexQuery.Builder(defaultNamespace(), ce.getCoverageContext())
.withTimeout(2000)
.build();
final BinIndexQuery.Response readResponse = rc.execute(query);
chunkedKeys.put(ce, readResponse.getEntries());
assertNotNull(readResponse);
}
}
finally
{
rc.shutdown();
}
}
final Set<String> keys = new HashSet<>(NUMBER_OF_TEST_VALUES);
for (Map.Entry<CoverageEntry, List<BinIndexQuery.Response.Entry<String>>> e: chunkedKeys.entrySet())
{
final CoverageEntry ce = e.getKey();
if (e.getValue().isEmpty())
{
logger.debug("Nothing was returned for CE {}", ce);
}
else
{
final List<String> lst = new ArrayList<>(e.getValue().size());
for (BinIndexQuery.Response.Entry re: e.getValue())
{
lst.add(re.getRiakObjectLocation().getKeyAsString());
}
logger.debug("{} keys were returned for CE {}:\n\t{}",
e.getValue().size(), ce, lst
);
keys.addAll(lst);
}
}
assertEquals(NUMBER_OF_TEST_VALUES, keys.size());
}
@Test
public void alternativeCoveragePlanShouldFailIfNoPrimaryPartitionAvailable()
throws ExecutionException, InterruptedException, UnknownHostException
{
final RiakClient client = new RiakClient(cluster);
final Namespace ns = new Namespace(Namespace.DEFAULT_BUCKET_TYPE, bucketName.toString());
final FetchBucketProperties fetchProps = new FetchBucketProperties.Builder(ns).build();
final FetchBucketPropsOperation.Response fetchResponse = client.execute(fetchProps);
final BucketProperties bp = fetchResponse.getBucketProperties();
final Integer nVal = bp.getNVal();
final int minPartitions = 5;
final CoveragePlan cmd = CoveragePlan.Builder.create(defaultNamespace())
.withMinPartitions(minPartitions)
.build();
final CoveragePlan.Response response = client.execute(cmd);
final List<CoverageEntry> coverageEntries = new LinkedList<>();
for (CoverageEntry ce : response)
{
coverageEntries.add(ce);
}
CoverageEntry failedEntry = coverageEntries.get(0);
List<CoverageEntry> unavailableCoverageEntries = new LinkedList<>();
for (int i = 0; i < nVal-1; i++)
{
unavailableCoverageEntries.add(failedEntry);
final CoveragePlan cmdAlternative = CoveragePlan.Builder.create(defaultNamespace())
.withMinPartitions(minPartitions)
.withReplaceCoverageEntry(failedEntry)
.withUnavailableCoverageEntries(unavailableCoverageEntries)
.build();
final CoveragePlan.Response responseAlternative = client.execute(cmdAlternative);
Assert.assertTrue(responseAlternative.iterator().hasNext());
failedEntry = responseAlternative.iterator().next();
}
unavailableCoverageEntries.add(failedEntry);
//At this moment all virtual nodes for coverage entry are down
//request to get alternative coverage entry should fail
final CoveragePlan cmdAlternativeFailing = CoveragePlan.Builder.create(defaultNamespace())
.withMinPartitions(minPartitions)
.withReplaceCoverageEntry(failedEntry)
.withUnavailableCoverageEntries(unavailableCoverageEntries)
.build();
exception.expect(ExecutionException.class);
exception.expectMessage("com.basho.riak.client.core.netty.RiakResponseException: primary_partition_unavailable");
client.execute(cmdAlternativeFailing);
}
}
| {
"content_hash": "829732c9e55961f668d77ae055b347ad",
"timestamp": "",
"source": "github",
"line_count": 257,
"max_line_length": 122,
"avg_line_length": 38.56420233463035,
"alnum_prop": 0.6367672283321562,
"repo_name": "basho/riak-java-client",
"id": "ed5b5090aaf16372e9371103527922d41a56d08b",
"size": "9911",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/test/java/com/basho/riak/client/core/operations/itest/ITestCoveragePlan.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2127021"
},
{
"name": "Makefile",
"bytes": "3111"
},
{
"name": "Shell",
"bytes": "1888"
},
{
"name": "Smalltalk",
"bytes": "188"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>span::operator= (1 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../index.html" title="Chapter 1. Boost.Beast">
<link rel="up" href="../operator_eq_.html" title="span::operator=">
<link rel="prev" href="../operator_eq_.html" title="span::operator=">
<link rel="next" href="overload2.html" title="span::operator= (2 of 2 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../operator_eq_.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../operator_eq_.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h6 class="title">
<a name="beast.ref.boost__beast__span.operator_eq_.overload1"></a><a class="link" href="overload1.html" title="span::operator= (1 of 2 overloads)">span::operator=
(1 of 2 overloads)</a>
</h6></div></div></div>
<p>
Assignment.
</p>
<h7><a name="beast.ref.boost__beast__span.operator_eq_.overload1.h0"></a>
<span class="phrase"><a name="beast.ref.boost__beast__span.operator_eq_.overload1.synopsis"></a></span><a class="link" href="overload1.html#beast.ref.boost__beast__span.operator_eq_.overload1.synopsis">Synopsis</a>
</h7><pre class="programlisting"><span class="identifier">span</span><span class="special">&</span>
<span class="keyword">operator</span><span class="special">=(</span>
<span class="identifier">span</span> <span class="keyword">const</span><span class="special">&);</span>
</pre>
<h7><a name="beast.ref.boost__beast__span.operator_eq_.overload1.h1"></a>
<span class="phrase"><a name="beast.ref.boost__beast__span.operator_eq_.overload1.description"></a></span><a class="link" href="overload1.html#beast.ref.boost__beast__span.operator_eq_.overload1.description">Description</a>
</h7>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2016, 2017 Vinnie Falco<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../operator_eq_.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../operator_eq_.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "1c8547123df4d08f5b4369cde1a57342",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 468,
"avg_line_length": 72.39285714285714,
"alnum_prop": 0.6060680809077454,
"repo_name": "vslavik/poedit",
"id": "c3e9785f707947a67aa0a70c29ebe54f12430231",
"size": "4054",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "deps/boost/libs/beast/doc/html/beast/ref/boost__beast__span/operator_eq_/overload1.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "48113"
},
{
"name": "C++",
"bytes": "1294527"
},
{
"name": "Inno Setup",
"bytes": "11180"
},
{
"name": "M4",
"bytes": "104017"
},
{
"name": "Makefile",
"bytes": "9507"
},
{
"name": "Objective-C",
"bytes": "16519"
},
{
"name": "Objective-C++",
"bytes": "14681"
},
{
"name": "Python",
"bytes": "6594"
},
{
"name": "Ruby",
"bytes": "292"
},
{
"name": "Shell",
"bytes": "12042"
}
],
"symlink_target": ""
} |
/* @flow */
import { insertRule } from 'glamor';
import { uniq } from 'lodash';
import {
clinicalDonorTracks,
dataTypeTracks,
geneTracks,
geneSetTracks,
gdcTracks,
getColorValue,
} from '@ncigdc/components/Oncogrid/tracks';
import { mapDonors, mapGenes, buildOccurrences } from './dataMapping';
import {
TDonorInput,
TGeneInput,
TSSMOccurrenceInput,
TCNVOccurrenceInput,
} from './dataMapping';
const donorTracks = [...clinicalDonorTracks, ...dataTypeTracks];
const trackColorMap = [...donorTracks, ...geneTracks].reduce(
(acc, t) => ({ ...acc, [t.fieldName]: t.color }),
{},
);
const fillFunc = (track: { fieldName: string, value?: mixed }) =>
getColorValue({
color: trackColorMap[track.fieldName] || '',
value: track.value,
});
function dataTypeLegend(): string {
return `<div><b>Available Data Types:</b></div><div>${dataTypeTracks
.map(t => (t.legend ? t.legend(t) : ''))
.filter(Boolean)
.join('</div><div>')}</div>`;
}
function gdcLegend(max: number): string {
return `<div><b># of Cases Affected:</b></div><div>${gdcTracks
.map(t => (t.legend ? t.legend({ ...t, max }) : ''))
.filter(Boolean)
.join('</div><div>')}`;
}
function geneSetLegend(): string {
return `<div><b>Gene Sets:</b></div><div>${geneSetTracks
.map(t => (t.legend ? t.legend(t) : ''))
.filter(Boolean)
.join('</div><div>')}</div>`;
}
export default function({
donorData,
geneData,
ssmOccurrencesData,
colorMap,
element,
height = 150,
width = 680,
trackPadding,
consequenceTypes,
impacts,
grid = false,
cnvOccurrencesData = [],
heatMap = false,
heatMapColor,
}: {
donorData: Array<TDonorInput>,
geneData: Array<TGeneInput>,
ssmOccurrencesData: Array<TSSMOccurrenceInput>,
cnvOccurrencesData: Array<TCNVOccurrenceInput>,
colorMap: { [key: string]: string },
element: string,
height: number,
width: number,
trackPadding: number,
consequenceTypes: Array<string>,
impacts: Array<string>,
grid?: boolean,
heatMap: boolean,
heatMapColor: string,
}): ?Object {
const {
ssmObservations,
donorIds,
geneIds,
cnvObservations,
} = buildOccurrences(
ssmOccurrencesData,
cnvOccurrencesData,
donorData,
geneData,
consequenceTypes,
impacts,
);
if (!ssmObservations.length && !cnvObservations.length) return null;
let donors = mapDonors(donorData, donorIds);
let genes = mapGenes(geneData, geneIds);
donors = donors.map(donor => ({
...donor,
cnv: cnvObservations.filter(cnv => donor.id === cnv.donorId).length,
}));
genes = genes.map(gene => ({
...gene,
cnv: cnvObservations.filter(cnv => gene.id === cnv.geneId).length,
}));
const maxDaysToDeath = Math.max(...donors.map(d => d.daysToDeath));
const maxAgeAtDiagnosis = Math.max(...donors.map(d => d.age));
const maxDonorsAffected = Math.max(...genes.map(g => g.totalDonors));
const donorOpacityFunc = ({
type,
value,
}: {
type: string,
value: number,
}) => {
switch (type) {
case 'int':
return value / 100;
case 'vital':
return !value || value === 'not reported' ? 0 : 1;
case 'gender':
case 'ethnicity':
case 'race':
case 'primary_diagnosi':
return 1;
case 'bool':
return value ? 1 : 0;
case 'days_to_death':
return value / maxDaysToDeath;
case 'age':
return value / maxAgeAtDiagnosis;
default:
return 0;
}
};
const geneOpacity = ({ type, value }: { type: string, value: number }) => {
switch (type) {
case 'int':
return value / maxDonorsAffected;
case 'bool':
return value ? 1 : 0;
default:
return 1;
}
};
return {
cnvObservations,
donors,
genes,
ssmObservations,
height,
width,
element,
colorMap,
scaleToFit: true,
heatMap,
grid,
minCellHeight: 8,
trackHeight: 12,
trackLegends: {
Clinical: `<div><b>Clinical Data:</b></div><div>${clinicalDonorTracks
.map(
t =>
t.legend
? t.legend({
...t,
maxDaysToDeath,
values: uniq(donors.map(d => d[t.fieldName])),
})
: '',
)
.filter(Boolean)
.join('</div><div>')}</div>`,
'Data Types': dataTypeLegend(),
GDC: gdcLegend(maxDonorsAffected),
'Gene Sets': geneSetLegend(),
},
trackLegendLabel:
'<i style="font-size: 13px; margin-left: 5px" class="fa fa-question-circle"></i>',
donorTracks,
donorOpacityFunc,
donorFillFunc: fillFunc,
geneTracks,
geneOpacityFunc: geneOpacity,
geneFillFunc: fillFunc,
expandableGroups: ['Clinical'],
margin: { top: 20, right: 5, bottom: 20, left: 0 },
leftTextWidth: 120,
trackPadding,
heatMapColor,
};
}
/*----------------------------------------------------------------------------*/
insertRule(`
.onco-track-legend {
margin-right: 5px;
display: inline-block;
width: 12px;
height: 12px;
}
`);
| {
"content_hash": "1386753d9dc8902f76016d08320da000",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 88,
"avg_line_length": 24.251184834123222,
"alnum_prop": 0.587062732069572,
"repo_name": "NCI-GDC/portal-ui",
"id": "71c04f2d9c4be9d35f30e2f7b113e1bb07271fa8",
"size": "5117",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/packages/@ncigdc/components/Oncogrid/oncoGridParams.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "207780"
},
{
"name": "Dockerfile",
"bytes": "1690"
},
{
"name": "HTML",
"bytes": "3336"
},
{
"name": "JavaScript",
"bytes": "3945229"
},
{
"name": "Mustache",
"bytes": "2163"
},
{
"name": "SCSS",
"bytes": "16991"
},
{
"name": "Shell",
"bytes": "3353"
},
{
"name": "TypeScript",
"bytes": "224619"
}
],
"symlink_target": ""
} |
package dagger.producers;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import javax.inject.Scope;
/**
* A scope annotation for provision bindings that are tied to the lifetime of a
* {@link ProductionComponent} or {@link ProductionSubcomponent}.
*/
@Documented
@Retention(RUNTIME)
@Scope
public @interface ProductionScope {}
| {
"content_hash": "2da80ef45912c659cca6df38a3b33279",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 79,
"avg_line_length": 23.72222222222222,
"alnum_prop": 0.7915690866510539,
"repo_name": "dushmis/dagger",
"id": "393c24071d58211d83adf7943f7ae1b9b10b3652",
"size": "1029",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "java/dagger/producers/ProductionScope.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1289133"
},
{
"name": "Shell",
"bytes": "2962"
}
],
"symlink_target": ""
} |
#import "PacoEvaluatorTests.h"
#import "PacoExpressionExecutor.h"
@interface PacoExpressionExecutor ()
+ (void)processRawExpression:(NSString*)expression
withVariableDictionary:(NSDictionary*)variableDict
andBlock:(void(^)(NSString*, NSArray*))block;
+ (NSArray*)tokenize:(NSString*)input;
@end
@implementation PacoEvaluatorTests
#pragma mark ParseKit tokenizer
- (void)testStringTokenize {
NSString* exp = @"a-0==2||b_1!=4 && (c0 >=5 || d<=8) &&c contains 1";
NSArray* tokenList = [PacoExpressionExecutor tokenize:exp];
NSArray* expectResult =
@[@"a-0",@"==",@"2",@"||",@"b_1",@"!=",@"4",@"&&",@"(",@"c0",@">=",@"5",@"||",@"d",@"<=",@"8",@")",
@"&&", @"c", @"contains", @"1"];
XCTAssertEqualObjects(tokenList,expectResult, @"tokenize isn't correct!");
}
#pragma mark pre-process
- (void)testDollarSign {
NSString* exp1 = @"a1 == a10";
NSDictionary* variableDict = @{@"a1" : @NO, @"a10":@NO};
[PacoExpressionExecutor
processRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSString* finalExpression, NSArray* dependencyVariables) {
XCTAssertEqualObjects(finalExpression, @"$a1 == $a10", @"failed to apply $ correctly!");
XCTAssertTrue([dependencyVariables count] == 2, @"dependency should have two objects!");
XCTAssertTrue([dependencyVariables containsObject:@"a1" ], @"dependency should contain a1");
XCTAssertTrue([dependencyVariables containsObject:@"a10"], @"dependency should contain a10");
}];
}
- (void)testUnderscore {
NSString* exp1 = @"a_1 == a10";
NSDictionary* variableDict = @{@"a_1" : @NO, @"a10":@NO};
[PacoExpressionExecutor
processRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSString* finalExpression, NSArray* dependencyVariables) {
XCTAssertEqualObjects(finalExpression, @"$a_1 == $a10", @"failed to parse underscore!");
XCTAssertEqualObjects(dependencyVariables, [variableDict allKeys], @"dependency not detected correctly!");
}];
}
- (void)testHyphen {
NSString* exp1 = @"a-1 == a10";
NSDictionary* variableDict = @{@"a-1" : @NO, @"a10":@NO};
[PacoExpressionExecutor
processRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSString* finalExpression, NSArray* dependencyVariables) {
XCTAssertEqualObjects(finalExpression, @"$a-1 == $a10", @"failed to parse dash!");
XCTAssertEqualObjects(dependencyVariables, [variableDict allKeys], @"dependency not detected correctly!");
}];
}
- (void)testMultiSelectedList {
NSString* exp = @" a >9 ||list == 1";
NSDictionary* variableDict = @{@"a" : @NO, @"list":@YES};
[PacoExpressionExecutor
processRawExpression:exp
withVariableDictionary:variableDict
andBlock:^(NSString* finalExpression, NSArray* dependencyVariables) {
XCTAssertEqualObjects(finalExpression, @"$a > 9 || $list contains 1", @"failed to process == for list!");
XCTAssertTrue([dependencyVariables count] == 2, @"dependency should have two objects!");
XCTAssertTrue([dependencyVariables containsObject:@"a" ], @"dependency should contain a");
XCTAssertTrue([dependencyVariables containsObject:@"list"], @"dependency should contain list");
}];
}
- (void)testMultiSelectedList2 {
NSString* exp = @" a >9 &&list !=b";
NSDictionary* variableDict = @{@"a" : @NO, @"list":@YES};
[PacoExpressionExecutor
processRawExpression:exp
withVariableDictionary:variableDict
andBlock:^(NSString* finalExpression, NSArray* dependencyVariables) {
XCTAssertEqualObjects(finalExpression, @"$a > 9 && not $list contains b", @"failed to process != for list!");
XCTAssertTrue([dependencyVariables count] == 2, @"dependency should have two objects!");
XCTAssertTrue([dependencyVariables containsObject:@"a" ], @"dependency should contain a");
XCTAssertTrue([dependencyVariables containsObject:@"list"], @"dependency should contain list");
}];
}
#pragma mark predicate evaluation
- (void)testContains {
NSString* exp1 = @"a contains 1";
NSDictionary* variableDict = @{@"a" : @NO, @"b" : @NO};
[PacoExpressionExecutor
processRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSString* finalExpression, NSArray* dependencyVariables) {
XCTAssertEqualObjects(finalExpression, @"$a contains 1", @"failed to parse contains!");
XCTAssertEqualObjects(dependencyVariables, @[@"a"], @"dependency not detected correctly!");
}];
}
#pragma mark predicate evaluation for multi-selected list
- (void)testMultiSelectedListContains {
NSString* exp1 = @"list contains 1";
NSDictionary* variableDict = @{@"list" : @YES};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @[@2, @3]};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"contains doesn't work");
dict = @{@"list" : @[@1, @3]};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"contains doesn't work");
}];
}
- (void)testMultiSelectedListNotContains {
NSString* exp1 = @"!(list contains 1)";
NSDictionary* variableDict = @{@"list" : @YES};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @[@2, @3]};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"ListNotContains doesn't work");
dict = @{@"list" : @[@1, @3]};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"ListNotContains doesn't work");
dict = @{@"list" : @[@3, @1, @4]};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"ListNotContains doesn't work");
}];
}
- (void)testMultiSelectedListNotContains2 {
NSString* exp1 = @"not list contains 1";
NSDictionary* variableDict = @{@"list" : @YES};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @[@2, @3]};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"ListNotContains doesn't work");
dict = @{@"list" : @[@1, @3]};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"ListNotContains doesn't work");
dict = @{@"list" : @[@3, @1, @4]};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"ListNotContains doesn't work");
}];
}
- (void)testMultiSelectedListNotContainsCompound {
NSString* exp1 = @"var > 1 ||not list contains 1";
NSDictionary* variableDict = @{@"list" : @YES, @"var" : @NO};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @[@2, @3], @"var" : @0};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"ListNotContains doesn't work");
dict = @{@"list" : @[@1, @3], @"var" : @0};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"ListNotContains doesn't work");
dict = @{@"list" : @[@3, @1, @4], @"var" : @2};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"ListNotContains doesn't work");
}];
}
- (void)testMultiSelectedListEquals {
NSString* exp1 = @"list == 1";
NSDictionary* variableDict = @{@"list" : @YES};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @[@1, @3]};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"Equals shouldn't work");
dict = @{@"list" : @[@2]};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"Equals shouldn't work");
}];
}
- (void)testMultiSelectedListNotEquals {
NSString* exp1 = @"list != 1";
NSDictionary* variableDict = @{@"list" : @YES};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @[@1, @3]};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"Equals shouldn't work");
dict = @{@"list" : @[@2]};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"Equals shouldn't work");
}];
}
#pragma mark predicate evaluation for single-selected list
- (void)testSingleSelectedListContains {
NSString* exp1 = @"list contains 1";
NSDictionary* variableDict = @{@"list" : @NO};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @1};
XCTAssertThrows([predicate evaluateWithObject:nil substitutionVariables:dict],
@"Can't user contains for NSNumber, since it's not a collection");
}];
}
- (void)testSingleSelectedListEquals {
NSString* exp1 = @"list == 1";
NSDictionary* variableDict = @{@"list" : @NO};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @1};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"list should be equal to 1");
dict = @{@"list" : @2};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"list should not be equal to 1");
}];
}
- (void)testSingleSelectedListNotEquals {
NSString* exp1 = @"list != 1";
NSDictionary* variableDict = @{@"list" : @NO};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @1};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"list should not be equal to 1");
dict = @{@"list" : @2};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"list should not be equal to 1");
}];
}
- (void)testSingleSelectedListLessThan {
NSString* exp1 = @"list < 4";
NSDictionary* variableDict = @{@"list" : @NO};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @1};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"list should be less than 4");
dict = @{@"list" : @4};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"list should not be less than 4");
dict = @{@"list" : @5};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"list should not be less than 4");
}];
}
- (void)testSingleSelectedListLessThanOrEqualTo {
NSString* exp1 = @"list <= 4";
NSDictionary* variableDict = @{@"list" : @NO};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @1};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"list should be less than or equal to 4");
dict = @{@"list" : @4};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"list should be less than or equal to 4");
dict = @{@"list" : @5};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"list should not be less than or equal to 4");
}];
}
- (void)testSingleSelectedListLargerThan {
NSString* exp1 = @"list > 4";
NSDictionary* variableDict = @{@"list" : @NO};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @1};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"list should be less than 4");
dict = @{@"list" : @4};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"list should be equal to 4");
dict = @{@"list" : @5};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"list should be larger than 4");
}];
}
- (void)testSingleSelectedListLargerThanOrEqualTo {
NSString* exp1 = @"list >= 4";
NSDictionary* variableDict = @{@"list" : @NO};
[PacoExpressionExecutor
predicateWithRawExpression:exp1
withVariableDictionary:variableDict
andBlock:^(NSPredicate *predicate, NSArray *dependencyVariables) {
NSDictionary* dict = @{@"list" : @1};
BOOL satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertFalse(satisfied, @"list should less than 4");
dict = @{@"list" : @4};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"list should be equal to 4");
dict = @{@"list" : @5};
satisfied = [predicate evaluateWithObject:nil substitutionVariables:dict];
XCTAssertTrue(satisfied, @"list should larger than 4");
}];
}
@end
| {
"content_hash": "8e882720984c43f329b02c4bb06839e6",
"timestamp": "",
"source": "github",
"line_count": 376,
"max_line_length": 114,
"avg_line_length": 39.109042553191486,
"alnum_prop": 0.6926895613736824,
"repo_name": "hlecuanda/paco",
"id": "2dfe20863753afd8efea3654d549b932a5daaaca",
"size": "15317",
"binary": false,
"copies": "10",
"ref": "refs/heads/translation-spanish",
"path": "Paco-iOS/PacoTests/PacoEvaluatorTests.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1407"
},
{
"name": "CSS",
"bytes": "393307"
},
{
"name": "GAP",
"bytes": "5948"
},
{
"name": "HTML",
"bytes": "3696604"
},
{
"name": "Java",
"bytes": "2538080"
},
{
"name": "JavaScript",
"bytes": "1078632"
},
{
"name": "Objective-C",
"bytes": "4554708"
},
{
"name": "Objective-C++",
"bytes": "964"
},
{
"name": "PHP",
"bytes": "3257"
},
{
"name": "Ruby",
"bytes": "3128"
},
{
"name": "Shell",
"bytes": "100211"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-character: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.1 / mathcomp-character - 1.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-character
<small>
1.9.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-01 22:48:36 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-01 22:48:36 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
name: "coq-mathcomp-character"
version: "1.9.0"
maintainer: "Mathematical Components <mathcomp-dev@sympa.inria.fr>"
homepage: "https://math-comp.github.io/"
bug-reports: "https://github.com/math-comp/math-comp/issues"
dev-repo: "git+https://github.com/math-comp/math-comp.git"
license: "CeCILL-B"
build: [ make "-C" "mathcomp/character" "-j" "%{jobs}%" ]
install: [ make "-C" "mathcomp/character" "install" ]
depends: [ "coq-mathcomp-field" { = "1.9.0" } ]
tags: [ "keyword:algebra" "keyword:character" "keyword:small scale reflection" "keyword:mathematical components" "keyword:odd order theorem" "logpath:mathcomp.character" ]
authors: [ "Jeremy Avigad <>" "Andrea Asperti <>" "Stephane Le Roux <>" "Yves Bertot <>" "Laurence Rideau <>" "Enrico Tassi <>" "Ioana Pasca <>" "Georges Gonthier <>" "Sidi Ould Biha <>" "Cyril Cohen <>" "Francois Garillot <>" "Alexey Solovyev <>" "Russell O'Connor <>" "Laurent Théry <>" "Assia Mahboubi <>" ]
synopsis: "Mathematical Components Library on character theory"
description:"""
This library contains definitions and theorems about group
representations, characters and class functions.
"""
url {
src: "http://github.com/math-comp/math-comp/archive/mathcomp-1.9.0.tar.gz"
checksum: "sha256=fe3d157a4db7e96f39212f76e701a7fc1e3f125c54b8c38f06a6a387eda61c96"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-character.1.9.0 coq.8.13.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1).
The following dependencies couldn't be met:
- coq-mathcomp-character -> coq-mathcomp-field = 1.9.0 -> coq-mathcomp-solvable = 1.9.0 -> coq-mathcomp-algebra = 1.9.0 -> coq-mathcomp-fingroup = 1.9.0 -> coq-mathcomp-ssreflect = 1.9.0 -> coq < 8.12~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-character.1.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "4b63330b06af99c3d8b9645831c1c8e6",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 554,
"avg_line_length": 48.30487804878049,
"alnum_prop": 0.5679121433981318,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "a60842ea3e49155f114658ca157ffd18da4a8f9b",
"size": "7948",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.13.1/mathcomp-character/1.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.commons.math3.fitting.leastsquares.AbstractEvaluation (Apache Commons Math 3.6.1 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.commons.math3.fitting.leastsquares.AbstractEvaluation (Apache Commons Math 3.6.1 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/commons/math3/fitting/leastsquares/AbstractEvaluation.html" title="class in org.apache.commons.math3.fitting.leastsquares">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/commons/math3/fitting/leastsquares/class-use/AbstractEvaluation.html" target="_top">Frames</a></li>
<li><a href="AbstractEvaluation.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.commons.math3.fitting.leastsquares.AbstractEvaluation" class="title">Uses of Class<br>org.apache.commons.math3.fitting.leastsquares.AbstractEvaluation</h2>
</div>
<div class="classUseContainer">No usage of org.apache.commons.math3.fitting.leastsquares.AbstractEvaluation</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/commons/math3/fitting/leastsquares/AbstractEvaluation.html" title="class in org.apache.commons.math3.fitting.leastsquares">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/commons/math3/fitting/leastsquares/class-use/AbstractEvaluation.html" target="_top">Frames</a></li>
<li><a href="AbstractEvaluation.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2003–2016 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "eec3e00f14c2922ea9fc251c6a0a68d8",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 191,
"avg_line_length": 42.97435897435897,
"alnum_prop": 0.6332537788385044,
"repo_name": "asampley/FactorioRatioAssistant",
"id": "ffc803da282887ad089bf00ad22920ad1c555001",
"size": "5028",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "src/commons-math3-3.6.1/docs/apidocs/org/apache/commons/math3/fitting/leastsquares/class-use/AbstractEvaluation.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "54"
},
{
"name": "CSS",
"bytes": "22278"
},
{
"name": "HTML",
"bytes": "94914322"
},
{
"name": "Java",
"bytes": "37520"
},
{
"name": "Shell",
"bytes": "55"
}
],
"symlink_target": ""
} |
sophie [](http://go-search.org/view?id=github.com%2Fdaviddengcn%2Fsophie)
======
A sequencial data processing library.
| {
"content_hash": "cde16292c41f5ce04da92b3946e347c9",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 149,
"avg_line_length": 49,
"alnum_prop": 0.7602040816326531,
"repo_name": "daviddengcn/sophie",
"id": "858a9dbfa9026ea615216e29d16211913d6c61f6",
"size": "196",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Go",
"bytes": "69527"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe AboutHelper do
#Delete this example and add some real ones or delete this file
it "should be included in the object returned by #helper" do
included_modules = (class << helper; self; end).send :included_modules
included_modules.should include(AboutHelper)
end
end
| {
"content_hash": "b5554c7965f49f36fa7e867792cbc68c",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 74,
"avg_line_length": 28.363636363636363,
"alnum_prop": 0.7467948717948718,
"repo_name": "cpjobling/Proman-3",
"id": "41d4c537b66a6002d1063972490ac8ff8ecf9239",
"size": "312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/helpers/about_helper_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "28100"
},
{
"name": "Ruby",
"bytes": "101673"
}
],
"symlink_target": ""
} |
#include <iostream>
#include <seqan/sequence.h> // CharString, ...
#include <seqan/file.h> // to stream a CharString into cout
int main(int, char **) {
std::cout << "Hello World!" << std::endl;
seqan::CharString mySeqanString = "Hello SeqAn!";
std::cout << mySeqanString << std::endl;
return 1;
}
| {
"content_hash": "978594d733458d053e6f76c6a88f09b8",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 64,
"avg_line_length": 27.75,
"alnum_prop": 0.6006006006006006,
"repo_name": "bkahlert/seqan-research",
"id": "a00fd3e3f843326675c51314ba70d12b4eeef39f",
"size": "2384",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "raw/workshop11/workshop2011-data-20110925/sources/0meio6dzt3eo1wj7/2/sandbox/my_sandbox/apps/my_app/my_app.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "39014"
},
{
"name": "Awk",
"bytes": "44044"
},
{
"name": "Batchfile",
"bytes": "37736"
},
{
"name": "C",
"bytes": "1261223"
},
{
"name": "C++",
"bytes": "277576131"
},
{
"name": "CMake",
"bytes": "5546616"
},
{
"name": "CSS",
"bytes": "271972"
},
{
"name": "GLSL",
"bytes": "2280"
},
{
"name": "Groff",
"bytes": "2694006"
},
{
"name": "HTML",
"bytes": "15207297"
},
{
"name": "JavaScript",
"bytes": "362928"
},
{
"name": "LSL",
"bytes": "22561"
},
{
"name": "Makefile",
"bytes": "6418610"
},
{
"name": "Objective-C",
"bytes": "3730085"
},
{
"name": "PHP",
"bytes": "3302"
},
{
"name": "Perl",
"bytes": "10468"
},
{
"name": "PostScript",
"bytes": "22762"
},
{
"name": "Python",
"bytes": "9267035"
},
{
"name": "R",
"bytes": "230698"
},
{
"name": "Rebol",
"bytes": "283"
},
{
"name": "Shell",
"bytes": "437340"
},
{
"name": "Tcl",
"bytes": "15439"
},
{
"name": "TeX",
"bytes": "738415"
},
{
"name": "VimL",
"bytes": "12685"
}
],
"symlink_target": ""
} |
#include "third_party/blink/renderer/core/page/viewport_description.h"
#include "base/metrics/histogram_macros.h"
#include "build/build_config.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
namespace blink {
static const float& CompareIgnoringAuto(const float& value1,
const float& value2,
const float& (*compare)(const float&,
const float&)) {
if (value1 == ViewportDescription::kValueAuto)
return value2;
if (value2 == ViewportDescription::kValueAuto)
return value1;
return compare(value1, value2);
}
static void RecordViewportTypeMetric(
ViewportDescription::ViewportUMAType type) {
UMA_HISTOGRAM_ENUMERATION("Viewport.MetaTagType", type);
}
float ViewportDescription::ResolveViewportLength(
const Length& length,
const gfx::SizeF& initial_viewport_size,
Direction direction) {
if (length.IsAuto())
return ViewportDescription::kValueAuto;
if (length.IsFixed())
return length.GetFloatValue();
if (length.IsExtendToZoom())
return ViewportDescription::kValueExtendToZoom;
if (length.IsPercent() && direction == Direction::kHorizontal)
return initial_viewport_size.width() * length.GetFloatValue() / 100.0f;
if (length.IsPercent() && direction == Direction::kVertical)
return initial_viewport_size.height() * length.GetFloatValue() / 100.0f;
if (length.IsDeviceWidth())
return initial_viewport_size.width();
if (length.IsDeviceHeight())
return initial_viewport_size.height();
NOTREACHED();
return ViewportDescription::kValueAuto;
}
PageScaleConstraints ViewportDescription::Resolve(
const gfx::SizeF& initial_viewport_size,
const Length& legacy_fallback_width) const {
float result_width = kValueAuto;
Length copy_max_width = max_width;
Length copy_min_width = min_width;
// In case the width (used for min- and max-width) is undefined.
if (IsLegacyViewportType() && max_width.IsAuto()) {
// The width viewport META property is translated into 'width' descriptors,
// setting the 'min' value to 'extend-to-zoom' and the 'max' value to the
// intended length. In case the UA-defines a min-width, use that as length.
if (zoom == ViewportDescription::kValueAuto) {
copy_min_width = Length::ExtendToZoom();
copy_max_width = legacy_fallback_width;
} else if (max_height.IsAuto()) {
copy_min_width = Length::ExtendToZoom();
copy_max_width = Length::ExtendToZoom();
}
}
float result_max_width = ResolveViewportLength(
copy_max_width, initial_viewport_size, Direction::kHorizontal);
float result_min_width = ResolveViewportLength(
copy_min_width, initial_viewport_size, Direction::kHorizontal);
float result_height = kValueAuto;
float result_max_height = ResolveViewportLength(
max_height, initial_viewport_size, Direction::kVertical);
float result_min_height = ResolveViewportLength(
min_height, initial_viewport_size, Direction::kVertical);
float result_zoom = zoom;
float result_min_zoom = min_zoom;
float result_max_zoom = max_zoom;
bool result_user_zoom = user_zoom;
// Resolve min-zoom and max-zoom values.
if (result_min_zoom != ViewportDescription::kValueAuto &&
result_max_zoom != ViewportDescription::kValueAuto)
result_max_zoom = std::max(result_min_zoom, result_max_zoom);
// Constrain zoom value to the [min-zoom, max-zoom] range.
if (result_zoom != ViewportDescription::kValueAuto)
result_zoom = CompareIgnoringAuto(
result_min_zoom,
CompareIgnoringAuto(result_max_zoom, result_zoom, std::min), std::max);
float extend_zoom =
CompareIgnoringAuto(result_zoom, result_max_zoom, std::min);
// Resolve non-"auto" lengths to pixel lengths.
if (extend_zoom == ViewportDescription::kValueAuto) {
if (result_max_width == ViewportDescription::kValueExtendToZoom)
result_max_width = ViewportDescription::kValueAuto;
if (result_max_height == ViewportDescription::kValueExtendToZoom)
result_max_height = ViewportDescription::kValueAuto;
if (result_min_width == ViewportDescription::kValueExtendToZoom)
result_min_width = result_max_width;
if (result_min_height == ViewportDescription::kValueExtendToZoom)
result_min_height = result_max_height;
} else {
float extend_width = initial_viewport_size.width() / extend_zoom;
float extend_height = initial_viewport_size.height() / extend_zoom;
if (result_max_width == ViewportDescription::kValueExtendToZoom)
result_max_width = extend_width;
if (result_max_height == ViewportDescription::kValueExtendToZoom)
result_max_height = extend_height;
if (result_min_width == ViewportDescription::kValueExtendToZoom)
result_min_width =
CompareIgnoringAuto(extend_width, result_max_width, std::max);
if (result_min_height == ViewportDescription::kValueExtendToZoom)
result_min_height =
CompareIgnoringAuto(extend_height, result_max_height, std::max);
}
// Resolve initial width from min/max descriptors.
if (result_min_width != ViewportDescription::kValueAuto ||
result_max_width != ViewportDescription::kValueAuto)
result_width = CompareIgnoringAuto(
result_min_width,
CompareIgnoringAuto(result_max_width, initial_viewport_size.width(),
std::min),
std::max);
// Resolve initial height from min/max descriptors.
if (result_min_height != ViewportDescription::kValueAuto ||
result_max_height != ViewportDescription::kValueAuto)
result_height = CompareIgnoringAuto(
result_min_height,
CompareIgnoringAuto(result_max_height, initial_viewport_size.height(),
std::min),
std::max);
// Resolve width value.
if (result_width == ViewportDescription::kValueAuto) {
if (result_height == ViewportDescription::kValueAuto ||
!initial_viewport_size.height()) {
result_width = initial_viewport_size.width();
} else {
result_width = result_height * (initial_viewport_size.width() /
initial_viewport_size.height());
}
}
// Resolve height value.
if (result_height == ViewportDescription::kValueAuto) {
if (!initial_viewport_size.width()) {
result_height = initial_viewport_size.height();
} else {
result_height = result_width * initial_viewport_size.height() /
initial_viewport_size.width();
}
}
// Resolve initial-scale value.
if (result_zoom == ViewportDescription::kValueAuto) {
if (result_width != ViewportDescription::kValueAuto && result_width > 0)
result_zoom = initial_viewport_size.width() / result_width;
if (result_height != ViewportDescription::kValueAuto && result_height > 0) {
// if 'auto', the initial-scale will be negative here and thus ignored.
result_zoom = std::max<float>(
result_zoom, initial_viewport_size.height() / result_height);
}
// Reconstrain zoom value to the [min-zoom, max-zoom] range.
result_zoom = CompareIgnoringAuto(
result_min_zoom,
CompareIgnoringAuto(result_max_zoom, result_zoom, std::min), std::max);
}
// If user-scalable = no, lock the min/max scale to the computed initial
// scale.
if (!result_user_zoom)
result_min_zoom = result_max_zoom = result_zoom;
// Only set initialScale to a value if it was explicitly set.
if (zoom == ViewportDescription::kValueAuto)
result_zoom = ViewportDescription::kValueAuto;
PageScaleConstraints result;
result.minimum_scale = result_min_zoom;
result.maximum_scale = result_max_zoom;
result.initial_scale = result_zoom;
result.layout_size.set_width(result_width);
result.layout_size.set_height(result_height);
return result;
}
void ViewportDescription::ReportMobilePageStats(
const LocalFrame* main_frame) const {
if (!main_frame || !main_frame->GetPage() || !main_frame->View() ||
!main_frame->GetDocument())
return;
if (!main_frame->GetSettings() ||
!main_frame->GetSettings()->GetViewportEnabled())
return;
// Avoid chrome:// pages like the new-tab page (on Android new tab is
// non-http).
if (!main_frame->GetDocument()->Url().ProtocolIsInHTTPFamily())
return;
if (!IsSpecifiedByAuthor()) {
RecordViewportTypeMetric(main_frame->GetDocument()->IsMobileDocument()
? ViewportUMAType::kXhtmlMobileProfile
: ViewportUMAType::kNoViewportTag);
return;
}
if (IsMetaViewportType()) {
if (max_width.IsFixed()) {
RecordViewportTypeMetric(ViewportUMAType::kConstantWidth);
} else if (max_width.IsDeviceWidth() || max_width.IsExtendToZoom()) {
RecordViewportTypeMetric(ViewportUMAType::kDeviceWidth);
} else {
// Overflow bucket for cases we may be unaware of.
RecordViewportTypeMetric(ViewportUMAType::kMetaWidthOther);
}
} else if (type == ViewportDescription::kHandheldFriendlyMeta) {
RecordViewportTypeMetric(ViewportUMAType::kMetaHandheldFriendly);
} else if (type == ViewportDescription::kMobileOptimizedMeta) {
RecordViewportTypeMetric(ViewportUMAType::kMetaMobileOptimized);
}
}
} // namespace blink
| {
"content_hash": "030602671a3cdab0059c79a5b2d30aac",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 80,
"avg_line_length": 37.810077519379846,
"alnum_prop": 0.6863147104049205,
"repo_name": "chromium/chromium",
"id": "3bbeee2e2136e62435cdf5b0fb0c39aebf06aa2c",
"size": "11071",
"binary": false,
"copies": "7",
"ref": "refs/heads/main",
"path": "third_party/blink/renderer/core/page/viewport_description.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.ferrylinton.oauth2server.controller;
import java.security.Principal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GlobalController {
@GetMapping("/user")
public Principal user(Principal user) {
return user;
}
}
| {
"content_hash": "b3d5eba88e9ca4b159f64b3f40cef32d",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 62,
"avg_line_length": 21.25,
"alnum_prop": 0.8029411764705883,
"repo_name": "ferrylinton/microservices",
"id": "e3921dfeeafc1c960dbe03e9abbd37006ca7ec74",
"size": "340",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "oauth2server/src/main/java/com/ferrylinton/oauth2server/controller/GlobalController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1876"
},
{
"name": "HTML",
"bytes": "25416"
},
{
"name": "Java",
"bytes": "85050"
},
{
"name": "JavaScript",
"bytes": "2571"
}
],
"symlink_target": ""
} |
/**
* Talisman metrics/smith-waterman
* ================================
*
* Functions computing the Smith-Waterman distance.
*
* [Reference]: https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm
*
* [Article]:
* Smith, Temple F. & Waterman, Michael S. (1981). "Identification of Common
* Molecular Subsequences" (PDF). Journal of Molecular Biology. 147: 195–197.
*
* [Tags]: metric, string metric.
*/
const SIMILARITY = (a, b) => {
return a === b ? 1 : 0;
};
/**
* Function returning the Smith-Waterman score between two sequences.
*
* @param {object} options - Options:
* @param {number} gap - Gap cost.
* @param {function} similarity - Similarity function.
* @param {mixed} a - The first sequence to process.
* @param {mixed} b - The second sequence to process.
* @return {number} - The Smith-Waterman score between a & b.
*/
export function score(options, a, b) {
const {gap = 1, similarity = SIMILARITY} = options;
// Early terminations
if (a === b)
return a.length;
const m = a.length,
n = b.length;
if (!m || !n)
return 0;
// TODO: Possibility to optimize for common prefix, but need to know max substitution cost
const d = new Array(m + 1);
let D = 0;
for (let i = 0; i <= m; i++) {
d[i] = new Array(2);
d[i][0] = 0;
}
for (let j = 1; j <= n; j++) {
d[0][j % 2] = 0;
for (let i = 1; i <= m; i++) {
const cost = similarity(a[i - 1], b[j - 1]);
d[i][j % 2] = Math.max(
0, // Start over
d[i - 1][(j - 1) % 2] + cost, // Substitution
d[i - 1][j % 2] - gap, // Insertion
d[i][(j - 1) % 2] - gap // Deletion
);
// Storing max
if (d[i][j % 2] > D)
D = d[i][j % 2];
}
}
return D;
}
/**
* Exporting standard distance.
*/
const smithWaterman = score.bind(null, {});
export default smithWaterman;
| {
"content_hash": "9fa6a8c6e44b1261065322465437c66d",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 92,
"avg_line_length": 24.02469135802469,
"alnum_prop": 0.5369989722507709,
"repo_name": "Yomguithereal/talisman",
"id": "e4bf848692dfa4f81d205ff910b0db3f0ec3d2a4",
"size": "1948",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/metrics/smith-waterman.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "615800"
}
],
"symlink_target": ""
} |
import Engine from 'Engine';
import pinkmonkey from '../graphics/samples/pinkmonkey.png'
export default new Engine.Graphics.SpriteSet({
default: new Engine.Graphics.Sprite(64, 64, 0, 0, 10, pinkmonkey)
}, 1000 / 10); | {
"content_hash": "068936d70c8f7e1c12fab6257a7ce303",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 69,
"avg_line_length": 36.833333333333336,
"alnum_prop": 0.7375565610859729,
"repo_name": "Gabbersaurus/IsoNgn",
"id": "1517023bfe4b0a47715ef806e80169086dc19ff4",
"size": "221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/games/demo/spritesets/Pinkmonkey.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "281"
},
{
"name": "JavaScript",
"bytes": "36112"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payments', '0005_auto_20170919_1621'),
]
operations = [
migrations.AlterModelOptions(
name='orderpayment',
options={'permissions': (('refund_orderpayment', 'Can refund order payments'),), 'verbose_name': 'order payment', 'verbose_name_plural': 'order payments'},
),
migrations.AlterModelOptions(
name='payment',
options={'ordering': ('-created', '-updated'), 'verbose_name': 'payment', 'verbose_name_plural': 'payments'},
),
migrations.AlterField(
model_name='orderpayment',
name='status',
field=models.CharField(choices=[(b'created', 'Created'), (b'started', 'Started'), (b'cancelled', 'Cancelled'), (b'pledged', 'Pledged'), (b'authorized', 'Authorized'), (b'settled', 'Settled'), (b'charged_back', 'Charged_back'), (b'refund_requested', 'Refund requested'), (b'refunded', 'Refunded'), (b'failed', 'Failed'), (b'unknown', 'Unknown')], default=b'created', max_length=50),
),
migrations.AlterField(
model_name='payment',
name='status',
field=models.CharField(choices=[(b'created', 'Created'), (b'started', 'Started'), (b'cancelled', 'Cancelled'), (b'pledged', 'Pledged'), (b'authorized', 'Authorized'), (b'settled', 'Settled'), (b'charged_back', 'Charged_back'), (b'refund_requested', 'Refund requested'), (b'refunded', 'Refunded'), (b'failed', 'Failed'), (b'unknown', 'Unknown')], default=b'started', max_length=50),
),
]
| {
"content_hash": "ca8fcb2f0664602e82de92caf8a2001d",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 393,
"avg_line_length": 54,
"alnum_prop": 0.6051373954599761,
"repo_name": "onepercentclub/bluebottle",
"id": "7be70c79239d4edca99502580f62a2c85c4bc813",
"size": "1747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bluebottle/payments/migrations/0006_auto_20181115_1321.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "41694"
},
{
"name": "HTML",
"bytes": "246695"
},
{
"name": "Handlebars",
"bytes": "63"
},
{
"name": "JavaScript",
"bytes": "139123"
},
{
"name": "PHP",
"bytes": "35"
},
{
"name": "PLpgSQL",
"bytes": "1369882"
},
{
"name": "PostScript",
"bytes": "2927"
},
{
"name": "Python",
"bytes": "4983116"
},
{
"name": "Rich Text Format",
"bytes": "39109"
},
{
"name": "SCSS",
"bytes": "99555"
},
{
"name": "Shell",
"bytes": "3068"
},
{
"name": "Smarty",
"bytes": "3814"
}
],
"symlink_target": ""
} |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.application;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.SystemInfoRt;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.SystemProperties;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.URLUtil;
import com.sun.jna.TypeMapper;
import com.sun.jna.platform.FileUtils;
import gnu.trove.THashSet;
import net.jpountz.lz4.LZ4Factory;
import org.apache.log4j.Appender;
import org.apache.oro.text.regex.PatternMatcher;
import org.intellij.lang.annotations.Flow;
import org.jdom.Document;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PathManager {
public static final String PROPERTIES_FILE = "idea.properties.file";
public static final String PROPERTIES_FILE_NAME = "idea.properties";
public static final String PROPERTY_HOME_PATH = "idea.home.path";
public static final String PROPERTY_CONFIG_PATH = "idea.config.path";
public static final String PROPERTY_SYSTEM_PATH = "idea.system.path";
public static final String PROPERTY_SCRATCH_PATH = "idea.scratch.path";
public static final String PROPERTY_PLUGINS_PATH = "idea.plugins.path";
public static final String PROPERTY_LOG_PATH = "idea.log.path";
public static final String PROPERTY_GUI_TEST_LOG_FILE = "idea.gui.tests.log.file";
public static final String PROPERTY_PATHS_SELECTOR = "idea.paths.selector";
public static final String OPTIONS_DIRECTORY = "options";
public static final String DEFAULT_EXT = ".xml";
public static final String DEFAULT_OPTIONS_FILE = "other" + DEFAULT_EXT;
private static final String PROPERTY_HOME = "idea.home"; // reduced variant of PROPERTY_HOME_PATH, now deprecated
private static final String LIB_FOLDER = "lib";
private static final String PLUGINS_FOLDER = "plugins";
private static final String BIN_FOLDER = "bin";
private static final String LOG_DIRECTORY = "log";
private static final String CONFIG_FOLDER = "config";
private static final String SYSTEM_FOLDER = "system";
private static final String PATHS_SELECTOR = System.getProperty(PROPERTY_PATHS_SELECTOR);
private static final Pattern PROPERTY_REF = Pattern.compile("\\$\\{(.+?)}");
private static String ourHomePath;
private static String[] ourBinDirectories;
private static String ourConfigPath;
private static String ourSystemPath;
private static String ourScratchPath;
private static String ourPluginsPath;
private static String ourLogPath;
// IDE installation paths
@NotNull
public static String getHomePath() {
return getHomePath(true);
}
/**
* @param insideIde {@code true} if the calling code works inside IDE; {@code false} otherwise (e.g. in a build process or a script)
*/
@Contract("true -> !null")
public static String getHomePath(boolean insideIde) {
if (ourHomePath != null) return ourHomePath;
String fromProperty = System.getProperty(PROPERTY_HOME_PATH, System.getProperty(PROPERTY_HOME));
if (fromProperty != null) {
ourHomePath = getAbsolutePath(fromProperty);
if (!new File(ourHomePath).isDirectory()) {
throw new RuntimeException("Invalid home path '" + ourHomePath + "'");
}
}
else if (insideIde) {
ourHomePath = getHomePathFor(PathManager.class);
if (ourHomePath == null) {
String advice = SystemInfo.isMac ? "reinstall the software." : "make sure bin/idea.properties is present in the installation directory.";
throw new RuntimeException("Could not find installation home path. Please " + advice);
}
}
if (ourHomePath != null && SystemInfo.isWindows) {
ourHomePath = canonicalPath(ourHomePath);
}
ourBinDirectories = ourHomePath != null ? getBinDirectories(new File(ourHomePath)) : ArrayUtil.EMPTY_STRING_ARRAY;
return ourHomePath;
}
public static boolean isUnderHomeDirectory(@NotNull String path) {
return FileUtil.isAncestor(canonicalPath(getHomePath()), canonicalPath(path), true);
}
@Nullable
public static String getHomePathFor(@NotNull Class aClass) {
String rootPath = getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class");
if (rootPath == null) return null;
File root = new File(rootPath).getAbsoluteFile();
do { root = root.getParentFile(); } while (root != null && !isIdeaHome(root));
return root != null ? root.getPath() : null;
}
private static boolean isIdeaHome(File root) {
for (String binDir : getBinDirectories(root)) {
if (new File(binDir, PROPERTIES_FILE_NAME).isFile()) {
return true;
}
}
return false;
}
private static String[] getBinDirectories(File root) {
List<String> binDirs = ContainerUtil.newSmartList();
String[] subDirs = {BIN_FOLDER, "community/bin", "ultimate/community/bin"};
String osSuffix = SystemInfo.isWindows ? "win" : SystemInfo.isMac ? "mac" : "linux";
for (String subDir : subDirs) {
File dir = new File(root, subDir);
if (dir.isDirectory()) {
binDirs.add(dir.getPath());
dir = new File(dir, osSuffix);
if (dir.isDirectory()) {
binDirs.add(dir.getPath());
}
}
}
return ArrayUtil.toStringArray(binDirs);
}
/**
* Bin path may be not what you want when developing an IDE. Consider using {@link #findBinFile(String)} if applicable.
*/
@NotNull
public static String getBinPath() {
return getHomePath() + File.separator + BIN_FOLDER;
}
/**
* Looks for a file in all possible bin directories.
*
* @return first that exists, or {@code null} if nothing found.
* @see #findBinFileWithException(String)
*/
@Nullable
public static File findBinFile(@NotNull String fileName) {
getHomePath();
for (String binDir : ourBinDirectories) {
File file = new File(binDir, fileName);
if (file.isFile()) return file;
}
return null;
}
/**
* Looks for a file in all possible bin directories.
*
* @return first that exists.
* @throws FileNotFoundException if nothing found.
* @see #findBinFile(String)
*/
@NotNull
public static File findBinFileWithException(@NotNull String fileName) throws FileNotFoundException {
File file = findBinFile(fileName);
if (file != null) return file;
String paths = StringUtil.join(ourBinDirectories, "\n");
throw new FileNotFoundException(String.format("'%s' not found in directories:\n%s", fileName, paths));
}
@NotNull
public static String getLibPath() {
return getHomePath() + File.separator + LIB_FOLDER;
}
@NotNull
public static String getPreInstalledPluginsPath() {
return getHomePath() + File.separatorChar + PLUGINS_FOLDER;
}
// config paths
@Nullable
public static String getPathsSelector() {
return PATHS_SELECTOR;
}
@NotNull
public static String getConfigPath() {
if (ourConfigPath != null) return ourConfigPath;
if (System.getProperty(PROPERTY_CONFIG_PATH) != null) {
ourConfigPath = getAbsolutePath(trimPathQuotes(System.getProperty(PROPERTY_CONFIG_PATH)));
}
else if (PATHS_SELECTOR != null) {
ourConfigPath = getDefaultConfigPathFor(PATHS_SELECTOR);
}
else {
ourConfigPath = getHomePath() + File.separator + CONFIG_FOLDER;
}
return ourConfigPath;
}
@NotNull
public static String getScratchPath() {
if (ourScratchPath != null) return ourScratchPath;
if (System.getProperty(PROPERTY_SCRATCH_PATH) != null) {
ourScratchPath = getAbsolutePath(trimPathQuotes(System.getProperty(PROPERTY_SCRATCH_PATH)));
}
else {
ourScratchPath = getConfigPath();
}
return ourScratchPath;
}
@NotNull
public static String getDefaultConfigPathFor(@NotNull String selector) {
return platformPath(selector, "Library/Preferences", CONFIG_FOLDER);
}
public static void ensureConfigFolderExists() {
FileUtil.createDirectory(new File(getConfigPath()));
}
@NotNull
public static String getOptionsPath() {
return getConfigPath() + File.separator + OPTIONS_DIRECTORY;
}
@NotNull
public static File getOptionsFile(@NotNull String fileName) {
return new File(getOptionsPath(), fileName + ".xml");
}
@NotNull
public static String getPluginsPath() {
if (ourPluginsPath != null) return ourPluginsPath;
if (System.getProperty(PROPERTY_PLUGINS_PATH) != null) {
ourPluginsPath = getAbsolutePath(trimPathQuotes(System.getProperty(PROPERTY_PLUGINS_PATH)));
}
else if (SystemInfo.isMac && PATHS_SELECTOR != null) {
ourPluginsPath = platformPath(PATHS_SELECTOR, "Library/Application Support", "");
}
else {
ourPluginsPath = getConfigPath() + File.separatorChar + PLUGINS_FOLDER;
}
return ourPluginsPath;
}
@NotNull
public static String getDefaultPluginPathFor(@NotNull String selector) {
if (SystemInfo.isMac) {
return platformPath(selector, "Library/Application Support", "");
}
else {
return getDefaultConfigPathFor(selector) + File.separatorChar + PLUGINS_FOLDER;
}
}
@Nullable
public static String getCustomOptionsDirectory() {
// do not use getConfigPath() here - as it may be not yet defined
return PATHS_SELECTOR != null ? getDefaultConfigPathFor(PATHS_SELECTOR) : null;
}
// runtime paths
@NotNull
public static String getSystemPath() {
if (ourSystemPath != null) return ourSystemPath;
if (System.getProperty(PROPERTY_SYSTEM_PATH) != null) {
ourSystemPath = getAbsolutePath(trimPathQuotes(System.getProperty(PROPERTY_SYSTEM_PATH)));
}
else if (PATHS_SELECTOR != null) {
ourSystemPath = getDefaultSystemPathFor(PATHS_SELECTOR);
}
else {
ourSystemPath = getHomePath() + File.separator + SYSTEM_FOLDER;
}
FileUtil.createDirectory(new File(ourSystemPath));
return ourSystemPath;
}
@NotNull
public static String getDefaultSystemPathFor(@NotNull String selector) {
return platformPath(selector, "Library/Caches", SYSTEM_FOLDER);
}
@NotNull
public static String getTempPath() {
return getSystemPath() + File.separator + "tmp";
}
@NotNull
public static File getIndexRoot() {
File indexRoot = new File(System.getProperty("index_root_path", getSystemPath() + "/index"));
FileUtil.createDirectory(indexRoot);
return indexRoot;
}
@NotNull
public static String getLogPath() {
if (ourLogPath != null) return ourLogPath;
if (System.getProperty(PROPERTY_LOG_PATH) != null) {
ourLogPath = getAbsolutePath(trimPathQuotes(System.getProperty(PROPERTY_LOG_PATH)));
}
else if (SystemInfo.isMac && PATHS_SELECTOR != null) {
ourLogPath = SystemProperties.getUserHome() + File.separator + "Library/Logs" + File.separator + PATHS_SELECTOR;
}
else {
ourLogPath = getSystemPath() + File.separatorChar + LOG_DIRECTORY;
}
return ourLogPath;
}
@NotNull
public static String getPluginTempPath() {
return getSystemPath() + File.separator + PLUGINS_FOLDER;
}
// misc stuff
/**
* Attempts to detect classpath entry which contains given resource.
*/
@Nullable
public static String getResourceRoot(@NotNull Class context, String path) {
URL url = context.getResource(path);
if (url == null) {
url = ClassLoader.getSystemResource(path.substring(1));
}
return url != null ? extractRoot(url, path) : null;
}
/**
* Attempts to detect classpath entry which contains given resource.
*/
@Nullable
public static String getResourceRoot(@NotNull ClassLoader cl, String resourcePath) {
URL url = cl.getResource(resourcePath);
return url != null ? extractRoot(url, resourcePath) : null;
}
/**
* Attempts to extract classpath entry part from passed URL.
*/
@Nullable
private static String extractRoot(URL resourceURL, String resourcePath) {
if (!(StringUtil.startsWithChar(resourcePath, '/') || StringUtil.startsWithChar(resourcePath, '\\'))) {
log("precondition failed: " + resourcePath);
return null;
}
String resultPath = null;
String protocol = resourceURL.getProtocol();
if (URLUtil.FILE_PROTOCOL.equals(protocol)) {
String path = URLUtil.urlToFile(resourceURL).getPath();
String testPath = path.replace('\\', '/');
String testResourcePath = resourcePath.replace('\\', '/');
if (StringUtil.endsWithIgnoreCase(testPath, testResourcePath)) {
resultPath = path.substring(0, path.length() - resourcePath.length());
}
}
else if (URLUtil.JAR_PROTOCOL.equals(protocol)) {
Pair<String, String> paths = URLUtil.splitJarUrl(resourceURL.getFile());
if (paths != null && paths.first != null) {
resultPath = FileUtil.toSystemDependentName(paths.first);
}
}
else if (URLUtil.JRT_PROTOCOL.equals(protocol)) {
return null;
}
if (resultPath == null) {
log("cannot extract '" + resourcePath + "' from '" + resourceURL + "'");
return null;
}
return StringUtil.trimEnd(resultPath, File.separator);
}
public static void loadProperties() {
getHomePath();
Set<String> paths = new LinkedHashSet<String>();
paths.add(System.getProperty(PROPERTIES_FILE));
paths.add(getCustomPropertiesFile());
paths.add(SystemProperties.getUserHome() + '/' + PROPERTIES_FILE_NAME);
for (String binDir : ourBinDirectories) {
paths.add(binDir + '/' + PROPERTIES_FILE_NAME);
}
Properties sysProperties = System.getProperties();
for (String path : paths) {
if (path != null && new File(path).exists()) {
try {
Reader fis = new BufferedReader(new FileReader(path));
try {
Map<String, String> properties = FileUtil.loadProperties(fis);
for (Map.Entry<String, String> entry : properties.entrySet()) {
String key = entry.getKey();
if (PROPERTY_HOME_PATH.equals(key) || PROPERTY_HOME.equals(key)) {
log(path + ": '" + key + "' cannot be redefined");
}
else if (!sysProperties.containsKey(key)) {
sysProperties.setProperty(key, substituteVars(entry.getValue()));
}
}
}
finally {
fis.close();
}
}
catch (IOException e) {
log("Can't read property file '" + path + "': " + e.getMessage());
}
}
}
}
private static String getCustomPropertiesFile() {
String configPath = getCustomOptionsDirectory();
return configPath != null ? configPath + File.separator + PROPERTIES_FILE_NAME : null;
}
@Contract("null -> null")
public static String substituteVars(String s) {
return substituteVars(s, getHomePath());
}
@Contract("null, _ -> null")
public static String substituteVars(String s, String ideaHomePath) {
if (s == null) return null;
if (s.startsWith("..")) {
s = ideaHomePath + File.separatorChar + BIN_FOLDER + File.separatorChar + s;
}
Matcher m = PROPERTY_REF.matcher(s);
while (m.find()) {
String key = m.group(1);
String value = System.getProperty(key);
if (value == null) {
if (PROPERTY_HOME_PATH.equals(key) || PROPERTY_HOME.equals(key)) {
value = ideaHomePath;
}
else if (PROPERTY_CONFIG_PATH.equals(key)) {
value = getConfigPath();
}
else if (PROPERTY_SYSTEM_PATH.equals(key)) {
value = getSystemPath();
}
}
if (value == null) {
log("Unknown property: " + key);
value = "";
}
s = StringUtil.replace(s, m.group(), value);
m = PROPERTY_REF.matcher(s);
}
return s;
}
@NotNull
public static File findFileInLibDirectory(@NotNull String relativePath) {
File file = new File(getLibPath() + File.separator + relativePath);
return file.exists() ? file : new File(getHomePath(), "community" + File.separator + "lib" + File.separator + relativePath);
}
/**
* @return path to 'community' project home irrespective of current project
*/
@NotNull
public static String getCommunityHomePath() {
String path = getHomePath();
if (new File(path, "community/.idea").isDirectory()) {
return path + File.separator + "community";
}
if (new File(path, "ultimate/community/.idea").isDirectory()) {
return path + File.separator + "ultimate" + File.separator + "community";
}
return path;
}
@Nullable
public static String getJarPathForClass(@NotNull Class aClass) {
String resourceRoot = getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class");
return resourceRoot != null ? new File(resourceRoot).getAbsolutePath() : null;
}
@NotNull
public static Collection<String> getUtilClassPath() {
final Class<?>[] classes = {
PathManager.class, // module 'intellij.platform.util'
Flow.class, // jetbrains-annotations-java5
SystemInfoRt.class, // module 'intellij.platform.util.rt'
Document.class, // jDOM
Appender.class, // log4j
THashSet.class, // trove4j
TypeMapper.class, // JNA
FileUtils.class, // JNA (jna-platform)
PatternMatcher.class, // OROMatcher
LZ4Factory.class, // lz4-java
};
final Set<String> classPath = new HashSet<String>();
for (Class<?> aClass : classes) {
final String path = getJarPathForClass(aClass);
if (path != null) {
classPath.add(path);
}
}
final String resourceRoot = getResourceRoot(PathManager.class, "/messages/CommonBundle.properties"); // intellij.platform.resources.en
if (resourceRoot != null) {
classPath.add(new File(resourceRoot).getAbsolutePath());
}
return Collections.unmodifiableCollection(classPath);
}
// helpers
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void log(String x) {
System.err.println(x);
}
public static String getAbsolutePath(String path) {
path = FileUtil.expandUserHome(path);
return FileUtil.toCanonicalPath(new File(path).getAbsolutePath());
}
private static String trimPathQuotes(String path) {
if (path != null && path.length() >= 3 && StringUtil.startsWithChar(path, '\"') && StringUtil.endsWithChar(path, '\"')) {
path = path.substring(1, path.length() - 1);
}
return path;
}
// todo[r.sh] XDG directories, Windows folders
// http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
// http://www.microsoft.com/security/portal/mmpc/shared/variables.aspx
private static String platformPath(@NotNull String selector, @Nullable String macPart, @NotNull String fallback) {
return platformPath(selector, macPart, null, null, null, fallback);
}
@SuppressWarnings("SameParameterValue")
private static String platformPath(@NotNull String selector,
@Nullable String macPart,
@Nullable String winVar,
@Nullable String xdgVar,
@Nullable String xdgDir,
@NotNull String fallback) {
String userHome = SystemProperties.getUserHome();
if (macPart != null && SystemInfo.isMac) {
return userHome + File.separator + macPart + File.separator + selector;
}
if (winVar != null && SystemInfo.isWindows) {
String dir = System.getenv(winVar);
if (dir != null) {
return dir + File.separator + selector;
}
}
if (xdgVar != null && xdgDir != null && SystemInfo.hasXdgOpen()) {
String dir = System.getenv(xdgVar);
if (dir == null) dir = userHome + File.separator + xdgDir;
return dir + File.separator + selector;
}
return userHome + File.separator + "." + selector + (!fallback.isEmpty() ? File.separator + fallback : "");
}
private static String canonicalPath(String path) {
try {
return new File(path).getCanonicalPath();
}
catch (IOException e) {
return path;
}
}
public static File getLogFile() throws FileNotFoundException {
String logXmlPath = System.getProperty(PROPERTY_GUI_TEST_LOG_FILE);
if (logXmlPath != null) {
File logXmlFile = new File(logXmlPath);
if (logXmlFile.exists()) return logXmlFile;
else {
throw new FileNotFoundException(String.format("'%s' not found.", logXmlPath));
}
}
return findBinFileWithException("log.xml");
}
} | {
"content_hash": "8d42537a8b347d407a41f8c494c1cf9d",
"timestamp": "",
"source": "github",
"line_count": 626,
"max_line_length": 145,
"avg_line_length": 33.694888178913736,
"alnum_prop": 0.6645806665718484,
"repo_name": "msebire/intellij-community",
"id": "f7f61404413cd408c502661fdc527f9777c465de",
"size": "21093",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "platform/util/src/com/intellij/openapi/application/PathManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.wso2.carbon.integration.test.processflow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.carbon.automation.test.utils.common.FileManager;
import org.wso2.carbon.integration.common.utils.LoginLogoutClient;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;
import org.wso2.carbon.integration.test.CEPIntegrationTest;
import org.wso2.carbon.integration.test.client.PizzaOrderClient;
import org.xml.sax.SAXException;
import javax.xml.stream.XMLStreamException;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.rmi.RemoteException;
public class HTTPXMLMessageTestCase extends CEPIntegrationTest {
private static final Log log = LogFactory.getLog(HTTPXMLMessageTestCase.class);
private ServerConfigurationManager serverManager = null;
protected final String webAppFileName = "GenericLogService.war";
@BeforeClass(alwaysRun = true)
public void init()
throws Exception, IOException, XMLStreamException,
SAXException, XPathExpressionException, URISyntaxException {
super.init(TestUserMode.SUPER_TENANT_ADMIN);
serverManager = new ServerConfigurationManager(cepServer);
try {
String warFilePath = FrameworkPathUtil.getSystemResourceLocation() +
"artifacts" + File.separator + "CEP" + File.separator + "war"
+ File.separator;
String webAppDirectoryPath = FrameworkPathUtil.getCarbonHome() + File.separator + "repository" + File.separator + "deployment" + File.separator + "server" + File.separator + "webapps" + File.separator;
FileManager.copyResourceToFileSystem(warFilePath+webAppFileName, webAppDirectoryPath, webAppFileName);
Thread.sleep(5000);
} catch (IOException e) {
throw new RemoteException("IOException when initializing JMS broker", e);
} catch (Exception e) {
throw new RemoteException("Exception caught when restarting server", e);
}
String loggedInSessionCookie = new LoginLogoutClient(cepServer).login();
eventBuilderAdminServiceClient = configurationUtil.getEventBuilderAdminServiceClient(backendURL, loggedInSessionCookie);
eventFormatterAdminServiceClient = configurationUtil.getEventFormatterAdminServiceClient(backendURL, loggedInSessionCookie);
eventProcessorAdminServiceClient = configurationUtil.getEventProcessorAdminServiceClient(backendURL, loggedInSessionCookie);
inputEventAdaptorManagerAdminServiceClient = configurationUtil.getInputEventAdaptorManagerAdminServiceClient(backendURL, loggedInSessionCookie);
outputEventAdaptorManagerAdminServiceClient = configurationUtil.getOutputEventAdaptorManagerAdminServiceClient(backendURL, loggedInSessionCookie);
eventStreamManagerAdminServiceClient = configurationUtil.getEventStreamManagerAdminServiceClient(backendURL, loggedInSessionCookie);
}
@Test(groups = {"wso2.cep"}, description = "Test xml message with http transport")
public void testHTTPXMLMessage() throws Exception {
int startEbCount = eventBuilderAdminServiceClient.getActiveEventBuilderCount();
configurationUtil.addHTTPInputEventAdaptor("httpInputEventAdaptor");
configurationUtil.addHTTPOutputEventAdaptor("HttpOutputEventAdaptor");
String eventBuilderConfigPath = getTestArtifactLocation() + "/artifacts/CEP/ebconfigs/PizzaOrder.xml";
String eventBuilderConfig = getArtifactConfigurationFromClasspath(eventBuilderConfigPath);
configurationUtil.addStream("org.wso2.sample.pizza.order", "1.0.0", "HTTP_XML");
eventBuilderAdminServiceClient.addEventBuilderConfiguration(eventBuilderConfig);
addEventFormatterForHTTPXML();
Assert.assertEquals(eventBuilderAdminServiceClient.getActiveEventBuilderCount(), startEbCount + 1);
Thread.sleep(2000);
try {
PizzaOrderClient.sendPizzaOrder("http://localhost:9763/endpoints/httpInputEventAdaptor/PizzaOrder");
Thread.sleep(2000);
} catch (Throwable e) {
log.error("Exception thrown: " + e.getMessage(), e);
Assert.fail("Exception: " + e.getMessage());
}
}
private void addEventFormatterForHTTPXML() throws Exception {
int initialEventFormatterCount = eventFormatterAdminServiceClient.getActiveEventFormatterCount();
String eventFormatterConfigPath = getTestArtifactLocation() + "/artifacts/CEP/efconfigs/PizzaDeliveryNofication.xml";
String eventFormatterConfig = getArtifactConfigurationFromClasspath(eventFormatterConfigPath);
configurationUtil.addStream("org.wso2.sample.pizza.order", "1.0.0", "HTTP_XML");
eventFormatterAdminServiceClient.addEventFormatterConfiguration(eventFormatterConfig);
Thread.sleep(5000);
Assert.assertEquals(eventFormatterAdminServiceClient.getActiveEventFormatterCount(), initialEventFormatterCount + 1);
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
try {
} finally {
//reverting the changes done to cep sever
if (serverManager != null) {
serverManager.restoreToLastConfiguration();
}
}
super.cleanup();
}
}
| {
"content_hash": "5a8d5e0d4b1ae42eda5851f681ea92ad",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 213,
"avg_line_length": 52.345454545454544,
"alnum_prop": 0.7485237929836749,
"repo_name": "jsdjayanga/product-cep",
"id": "c1ffd6ca5cb8c92af6b3b2649a1662146422dc7c",
"size": "6405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/integration/tests-integration/tests/src/test/java/org/wso2/carbon/integration/test/processflow/HTTPXMLMessageTestCase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
CVE-2022-35959
### Impact
The implementation of `AvgPool3DGradOp` does not fully validate the input `orig_input_shape`. This results in an overflow that results in a `CHECK` failure which can be used to trigger a denial of service attack:
```python
import tensorflow as tf
ksize = [1, 2, 2, 1]
strides = [1, 2, 2, 1]
padding = "VALID"
data_format = "NHWC"
orig_input_shape = tf.constant(-536870912, shape=[4], dtype=tf.int32)
grad = tf.constant(.0890338004362538, shape=[1,5,7,1], dtype=tf.float64)
tf.raw_ops.AvgPoolGrad(orig_input_shape=orig_input_shape, grad=grad, ksize=ksize, strides=strides, padding=padding, data_format=data_format)
```
### Patches
We have patched the issue in GitHub commit [9178ac9d6389bdc54638ab913ea0e419234d14eb](https://github.com/tensorflow/tensorflow/commit/9178ac9d6389bdc54638ab913ea0e419234d14eb).
The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range.
### For more information
Please consult [our security guide](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for more information regarding the security model and how to contact us with issues and questions.
### Attribution
This vulnerability has been reported by Neophytos Christou, Secure Systems Labs, Brown University.
| {
"content_hash": "2d373d9634d7de511aecec7c8f7e47c6",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 213,
"avg_line_length": 49.42857142857143,
"alnum_prop": 0.7745664739884393,
"repo_name": "karllessard/tensorflow",
"id": "7c6b8073e7c4fb14dfa14bcba40c132cc7b1279e",
"size": "1454",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "tensorflow/security/advisory/tfsa-2022-094.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "36962"
},
{
"name": "C",
"bytes": "1366182"
},
{
"name": "C#",
"bytes": "13584"
},
{
"name": "C++",
"bytes": "124800442"
},
{
"name": "CMake",
"bytes": "183072"
},
{
"name": "Cython",
"bytes": "5003"
},
{
"name": "Dockerfile",
"bytes": "416070"
},
{
"name": "Go",
"bytes": "2104698"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "1074438"
},
{
"name": "Jupyter Notebook",
"bytes": "792868"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "11176792"
},
{
"name": "Makefile",
"bytes": "2760"
},
{
"name": "Objective-C",
"bytes": "169288"
},
{
"name": "Objective-C++",
"bytes": "294187"
},
{
"name": "Pawn",
"bytes": "5552"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "42620525"
},
{
"name": "Roff",
"bytes": "5034"
},
{
"name": "Ruby",
"bytes": "9199"
},
{
"name": "Shell",
"bytes": "620121"
},
{
"name": "Smarty",
"bytes": "89545"
},
{
"name": "SourcePawn",
"bytes": "14607"
},
{
"name": "Starlark",
"bytes": "7545879"
},
{
"name": "Swift",
"bytes": "78435"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
Dobbscoin Core version 0.9.1 is now available from:
https://dobbscoin.org/bin/0.9.1/
This is a security update. It is recommended to upgrade to this release
as soon as possible.
It is especially important to upgrade if you currently have version
0.9.0 installed and are using the graphical interface OR you are using
dobbscoind from any pre-0.9.1 version, and have enabled SSL for RPC and
have configured allowip to allow rpc connections from potentially
hostile hosts.
Please report bugs using the issue tracker at github:
https://github.com/dobbscoin/dobbscoin-source/issues
How to Upgrade
--------------
If you are running an older version, shut it down. Wait until it has completely
shut down (which might take a few minutes for older versions), then run the
installer (on Windows) or just copy over /Applications/Dobbscoin-Qt (on Mac) or
dobbscoind/dobbscoin-qt (on Linux).
If you are upgrading from version 0.7.2 or earlier, the first time you run
0.9.1 your blockchain files will be re-indexed, which will take anywhere from
30 minutes to several hours, depending on the speed of your machine.
0.9.1 Release notes
=======================
No code changes were made between 0.9.0 and 0.9.1. Only the dependencies were changed.
- Upgrade OpenSSL to 1.0.1g. This release fixes the following vulnerabilities which can
affect the Dobbscoin Core software:
- CVE-2014-0160 ("heartbleed")
A missing bounds check in the handling of the TLS heartbeat extension can
be used to reveal up to 64k of memory to a connected client or server.
- CVE-2014-0076
The Montgomery ladder implementation in OpenSSL does not ensure that
certain swap operations have a constant-time behavior, which makes it
easier for local users to obtain ECDSA nonces via a FLUSH+RELOAD cache
side-channel attack.
- Add statically built executables to Linux build
Credits
--------
Credits go to the OpenSSL team for fixing the vulnerabilities quickly.
| {
"content_hash": "fb1c463a07a262f99468d5a543510225",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 87,
"avg_line_length": 37.132075471698116,
"alnum_prop": 0.7591463414634146,
"repo_name": "dobbscoin/dobbscoin-source",
"id": "0ef9c64edbbf121d53569eb9ff3ca2bc076a2baa",
"size": "1968",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/release-notes/release-notes-0.9.1.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "7639"
},
{
"name": "C",
"bytes": "325852"
},
{
"name": "C++",
"bytes": "3549593"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "2102"
},
{
"name": "M4",
"bytes": "141760"
},
{
"name": "Makefile",
"bytes": "86430"
},
{
"name": "Objective-C",
"bytes": "54023"
},
{
"name": "Objective-C++",
"bytes": "7254"
},
{
"name": "Python",
"bytes": "212285"
},
{
"name": "QMake",
"bytes": "2021"
},
{
"name": "Roff",
"bytes": "18168"
},
{
"name": "Shell",
"bytes": "45189"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for lib/components/texteditor</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="../../../prettify.css" />
<link rel="stylesheet" href="../../../base.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(../../../sort-arrow-sprite.png);
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='pad1'>
<h1>
<a href="../../../index.html">All files</a> lib/components/texteditor
</h1>
<div class='clearfix'>
<div class='fl pad1y space-right2'>
<span class="strong">45.16% </span>
<span class="quiet">Statements</span>
<span class='fraction'>56/124</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">71.26% </span>
<span class="quiet">Branches</span>
<span class='fraction'>124/174</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">38.71% </span>
<span class="quiet">Functions</span>
<span class='fraction'>12/31</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">42.48% </span>
<span class="quiet">Lines</span>
<span class='fraction'>48/113</span>
</div>
</div>
<p class="quiet">
Press <em>n</em> or <em>j</em> to go to the next uncovered block, <em>b</em>, <em>p</em> or <em>k</em> for the previous block.
</p>
</div>
<div class='status-line low'></div>
<div class="pad1">
<table class="coverage-summary">
<thead>
<tr>
<th data-col="file" data-fmt="html" data-html="true" class="file">File</th>
<th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th>
<th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th>
<th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th>
<th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th>
<th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th>
<th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th>
<th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th>
<th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th>
<th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th>
</tr>
</thead>
<tbody><tr>
<td class="file low" data-value="index.vue"><a href="index.vue.html">index.vue</a></td>
<td data-value="45.16" class="pic low"><div class="chart"><div class="cover-fill" style="width: 45%;"></div><div class="cover-empty" style="width:55%;"></div></div></td>
<td data-value="45.16" class="pct low">45.16%</td>
<td data-value="124" class="abs low">56/124</td>
<td data-value="71.26" class="pct medium">71.26%</td>
<td data-value="174" class="abs medium">124/174</td>
<td data-value="38.71" class="pct low">38.71%</td>
<td data-value="31" class="abs low">12/31</td>
<td data-value="42.48" class="pct low">42.48%</td>
<td data-value="113" class="abs low">48/113</td>
</tr>
</tbody>
</table>
</div><div class='push'></div><!-- for sticky footer -->
</div><!-- /wrapper -->
<div class='footer quiet pad2 space-top1 center small'>
Code coverage
generated by <a href="https://istanbul.js.org/" target="_blank">istanbul</a> at Sun Mar 17 2019 12:45:45 GMT+0800 (CST)
</div>
</div>
<script src="../../../prettify.js"></script>
<script>
window.onload = function () {
if (typeof prettyPrint === 'function') {
prettyPrint();
}
};
</script>
<script src="../../../sorter.js"></script>
<script src="../../../block-navigation.js"></script>
</body>
</html>
| {
"content_hash": "5ad5afa4fca2d9303c8b5499be815084",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 170,
"avg_line_length": 39.83505154639175,
"alnum_prop": 0.6040372670807453,
"repo_name": "Morning-UI/morning-ui",
"id": "a3c576a47c4b14ea54b6969b143ed2f6e0632bd8",
"size": "3864",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "report/coverage/lib/components/texteditor/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "685478"
},
{
"name": "HTML",
"bytes": "118711"
},
{
"name": "JavaScript",
"bytes": "780509"
},
{
"name": "Vue",
"bytes": "2763341"
}
],
"symlink_target": ""
} |
<?php
/**
* jParser example
*
*/
require '../jparser-libs/jparser.php';
/**
* Get some example source code from a *.js file
*/
$source = file_get_contents('complex.js');
/**
* Get the full parse tree
*/
$Prog = JParser::parse_string( $source );
if( ! $Prog instanceof JProgramNode ){
die('Root of parse tree is not a JProgramNode');
}
// Collapsing back to a string minifies by default, because whitespace and comments are not in the tree
$min = $Prog->__toString();
// Obfuascate tree
$protect = array();
$Prog->obfuscate( $protect );
$obf = $Prog->__toString();
echo '<?xml version="1.0" encoding="UTF-8" ?>'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jParser example :: j_obfuscate</title>
</head>
<body>
<h2>Minified code</h2>
<div style="font: 10pt monospace">
<?php
echo preg_replace('/(\r\n|\n|\r)/','<br />',htmlentities( $min, ENT_COMPAT, 'UTF-8') );
?>
</div>
<h2>Obfuscated code</h2>
<div style="font: 10pt monospace">
<?php
echo preg_replace('/(\r\n|\n|\r)/','<br />',htmlentities( $obf, ENT_COMPAT, 'UTF-8') );
?>
</div>
</body>
</html> | {
"content_hash": "1f4538dc0692aa68b05d93d5d098fe9f",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 121,
"avg_line_length": 24.236363636363638,
"alnum_prop": 0.6181545386346586,
"repo_name": "S3RK/jParser",
"id": "ab7733ea8f1a101f164da182acdf8182c41b8368",
"size": "1333",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "httpdocs/jparser-examples/j_obfuscate.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "914"
},
{
"name": "PHP",
"bytes": "2012077"
},
{
"name": "Perl",
"bytes": "10331"
},
{
"name": "Shell",
"bytes": "1794"
}
],
"symlink_target": ""
} |
import { Component, OnInit, Input, Output, EventEmitter, AfterViewInit } from '@angular/core';
import { DynamicPopup } from 'app/shared/services';
@Component({
selector: 'pp-message-popup-container',
templateUrl: './message-popup-container.component.html',
styleUrls: ['./message-popup-container.component.css'],
})
export class MessagePopupContainerComponent implements OnInit, AfterViewInit, DynamicPopup {
@Input() data: ITransactionMessage;
@Output() outClose = new EventEmitter<void>();
@Output() outCreated = new EventEmitter<ICoordinate>();
constructor() {}
ngOnInit() {}
ngAfterViewInit() {
this.outCreated.emit({ coordX: 0, coordY: 0 });
}
onClosePopup() {
this.outClose.emit();
}
}
| {
"content_hash": "b3862036ab286e07b5235d119ce135bd",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 94,
"avg_line_length": 31.666666666666668,
"alnum_prop": 0.6802631578947368,
"repo_name": "denzelsN/pinpoint",
"id": "cf294dd730c31f16aac3fc820ba8bb94fff8b5e3",
"size": "760",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "web/src/main/webapp/v2/src/app/core/components/message-popup/message-popup-container.component.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22887"
},
{
"name": "CSS",
"bytes": "614658"
},
{
"name": "CoffeeScript",
"bytes": "10124"
},
{
"name": "Groovy",
"bytes": "1423"
},
{
"name": "HTML",
"bytes": "775712"
},
{
"name": "Java",
"bytes": "13863723"
},
{
"name": "JavaScript",
"bytes": "4817037"
},
{
"name": "Makefile",
"bytes": "5246"
},
{
"name": "PLSQL",
"bytes": "4156"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "Ruby",
"bytes": "943"
},
{
"name": "Shell",
"bytes": "31667"
},
{
"name": "Thrift",
"bytes": "14916"
},
{
"name": "TypeScript",
"bytes": "1449771"
}
],
"symlink_target": ""
} |
package purecollections;
interface Computation<T> {
T compute();
}
| {
"content_hash": "073f845a83c43c020c01ec873305d698",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 26,
"avg_line_length": 11.285714285714286,
"alnum_prop": 0.6455696202531646,
"repo_name": "btj/purecollections",
"id": "60ac79e85ae17b1d258f73265a129ba83049e51b",
"size": "79",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/purecollections/Computation.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "50890"
}
],
"symlink_target": ""
} |
<?php
// comainBundle:Default:index.html.twig
return array (
);
| {
"content_hash": "df9dedf30cadeee8cdcdb3dac63c3cff",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 39,
"avg_line_length": 13,
"alnum_prop": 0.7076923076923077,
"repo_name": "djepo/Site-Perso",
"id": "fc2c345df4ff4ac66d2f62b73072ce12a3d0f874",
"size": "65",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/cache/dev/assetic/config/2/21de9f67252fe88a8a4433f8348b088f.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "104191"
},
{
"name": "PHP",
"bytes": "74657"
},
{
"name": "Shell",
"bytes": "186"
}
],
"symlink_target": ""
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ScriptLinkStandard.Helpers;
using ScriptLinkStandard.Objects;
namespace ScriptLinkStandard.Tests.HelpersTests
{
[TestClass]
public class GetParentRowIdTests
{
[TestMethod]
public void GetParentRowIdOptionObjectReturnsString()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject optionObject = new OptionObject()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected.GetType(), optionObject.GetParentRowId("1").GetType());
}
[TestMethod]
public void GetParentRowIdHelperOptionObjectReturnsString()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject optionObject = new OptionObject()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected.GetType(), ScriptLinkHelpers.GetParentRowId(optionObject, "1").GetType());
}
[TestMethod]
public void GetParentRowIdOptionObjectReturnsExpected()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject optionObject = new OptionObject()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected, optionObject.GetParentRowId("1"));
}
[TestMethod]
public void GetParentRowIdHelperOptionObjectReturnsExpected()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject optionObject = new OptionObject()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void GetParentRowIdHelperOptionObjectReturnsNotFound()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject optionObject = new OptionObject()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "2||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "2"));
}
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public void GetParentRowIdHelperOptionObjectNoCurrentRowReturnsError()
{
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true
};
OptionObject optionObject = new OptionObject()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void GetParentRowIdHelperOptionObjectNoFormsReturnsError()
{
OptionObject optionObject = new OptionObject()
{
EntityID = "1",
SystemCode = "UAT"
};
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
public void GetParentRowIdOptionObject2ReturnsString()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2 optionObject = new OptionObject2()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected.GetType(), optionObject.GetParentRowId("1").GetType());
}
[TestMethod]
public void GetParentRowIdHelperOptionObject2ReturnsString()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2 optionObject = new OptionObject2()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected.GetType(), ScriptLinkHelpers.GetParentRowId(optionObject, "1").GetType());
}
[TestMethod]
public void GetParentRowIdOptionObject2ReturnsExpected()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2 optionObject = new OptionObject2()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected, optionObject.GetParentRowId("1"));
}
[TestMethod]
public void GetParentRowIdHelperOptionObject2ReturnsExpected()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2 optionObject = new OptionObject2()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void GetParentRowIdHelperOptionObject2ReturnsNotFound()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2 optionObject = new OptionObject2()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "2||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "2"));
}
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public void GetParentRowIdHelperOptionObject2NoCurrentRowReturnsError()
{
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true
};
OptionObject2 optionObject = new OptionObject2()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void GetParentRowIdHelperOptionObject2NoFormsReturnsError()
{
OptionObject2 optionObject = new OptionObject2()
{
EntityID = "1",
SystemCode = "UAT"
};
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
public void GetParentRowIdOptionObject2015ReturnsString()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2015 optionObject = new OptionObject2015()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected.GetType(), optionObject.GetParentRowId("1").GetType());
}
[TestMethod]
public void GetParentRowIdHelperOptionObject2015ReturnsString()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2015 optionObject = new OptionObject2015()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected.GetType(), ScriptLinkHelpers.GetParentRowId(optionObject, "1").GetType());
}
[TestMethod]
public void GetParentRowIdOptionObject2015ReturnsExpected()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2015 optionObject = new OptionObject2015()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected, optionObject.GetParentRowId("1"));
}
[TestMethod]
public void GetParentRowIdHelperOptionObject2015ReturnsExpected()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2015 optionObject = new OptionObject2015()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void GetParentRowIdHelperOptionObject2015ReturnsNotFound()
{
RowObject rowObject1 = new RowObject()
{
RowId = "1||1",
ParentRowId = "1||1"
};
RowObject rowObject2 = new RowObject()
{
RowId = "1||2",
ParentRowId = "1||1"
};
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true,
CurrentRow = rowObject1
};
formObject.OtherRows.Add(rowObject2);
OptionObject2015 optionObject = new OptionObject2015()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "2||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "2"));
}
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public void GetParentRowIdHelperOptionObject2015NoCurrentRowReturnsError()
{
FormObject formObject = new FormObject()
{
FormId = "1",
MultipleIteration = true
};
OptionObject2015 optionObject = new OptionObject2015()
{
EntityID = "1",
SystemCode = "UAT"
};
optionObject.Forms.Add(formObject);
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void GetParentRowIdHelperOptionObject2015NoFormsReturnsError()
{
OptionObject2015 optionObject = new OptionObject2015()
{
EntityID = "1",
SystemCode = "UAT"
};
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void GetParentRowIdHelperNullReturnsExpected()
{
OptionObject optionObject = null;
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void GetParentRowIdHelperNull2ReturnsExpected()
{
OptionObject2 optionObject = null;
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void GetParentRowIdHelperNull2015ReturnsExpected()
{
OptionObject2015 optionObject = null;
string expected = "1||1";
Assert.AreEqual(expected, ScriptLinkHelpers.GetParentRowId(optionObject, "1"));
}
}
}
| {
"content_hash": "68b0b496012662facb808813e1228429",
"timestamp": "",
"source": "github",
"line_count": 595,
"max_line_length": 111,
"avg_line_length": 33.09075630252101,
"alnum_prop": 0.49062928538778,
"repo_name": "rcskids/ScriptLinkStandard",
"id": "7da949e96e2afe9077deafad22acb837fa36a95b",
"size": "19691",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ScriptLinkStandard.Tests/HelpersTests/GetParentRowIdTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1242503"
}
],
"symlink_target": ""
} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.04.20 at 03:09:04 PM EDT
//
package org.slc.sli.sample.entities;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* This entity represents the academic weeks for a school year, optionally captured to support analyses.
*
* <p>Java class for AcademicWeek complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="AcademicWeek">
* <complexContent>
* <extension base="{http://ed-fi.org/0100}ComplexObjectType">
* <sequence>
* <element name="WeekIdentifier" type="{http://ed-fi.org/0100}WeekIdentifier"/>
* <element name="BeginDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
* <element name="EndDate" type="{http://www.w3.org/2001/XMLSchema}date"/>
* <element name="TotalInstructionalDays" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="CalendarDateReference" type="{http://ed-fi.org/0100}ReferenceType" maxOccurs="unbounded"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AcademicWeek", propOrder = {
"weekIdentifier",
"beginDate",
"endDate",
"totalInstructionalDays",
"calendarDateReference"
})
public class AcademicWeek
extends ComplexObjectType
{
@XmlElement(name = "WeekIdentifier", required = true)
protected String weekIdentifier;
@XmlElement(name = "BeginDate", required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "date")
protected Calendar beginDate;
@XmlElement(name = "EndDate", required = true, type = String.class)
@XmlJavaTypeAdapter(Adapter2 .class)
@XmlSchemaType(name = "date")
protected Calendar endDate;
@XmlElement(name = "TotalInstructionalDays")
protected int totalInstructionalDays;
@XmlElement(name = "CalendarDateReference", required = true)
protected List<ReferenceType> calendarDateReference;
/**
* Gets the value of the weekIdentifier property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getWeekIdentifier() {
return weekIdentifier;
}
/**
* Sets the value of the weekIdentifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setWeekIdentifier(String value) {
this.weekIdentifier = value;
}
/**
* Gets the value of the beginDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public Calendar getBeginDate() {
return beginDate;
}
/**
* Sets the value of the beginDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBeginDate(Calendar value) {
this.beginDate = value;
}
/**
* Gets the value of the endDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public Calendar getEndDate() {
return endDate;
}
/**
* Sets the value of the endDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEndDate(Calendar value) {
this.endDate = value;
}
/**
* Gets the value of the totalInstructionalDays property.
*
*/
public int getTotalInstructionalDays() {
return totalInstructionalDays;
}
/**
* Sets the value of the totalInstructionalDays property.
*
*/
public void setTotalInstructionalDays(int value) {
this.totalInstructionalDays = value;
}
/**
* Gets the value of the calendarDateReference property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the calendarDateReference property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCalendarDateReference().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ReferenceType }
*
*
*/
public List<ReferenceType> getCalendarDateReference() {
if (calendarDateReference == null) {
calendarDateReference = new ArrayList<ReferenceType>();
}
return this.calendarDateReference;
}
}
| {
"content_hash": "b2a8c364a455051198ffded86d43ae1d",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 124,
"avg_line_length": 28.067010309278352,
"alnum_prop": 0.6282828282828283,
"repo_name": "inbloom/secure-data-service",
"id": "68d5202a43d86ccb3b91019b522c2851e16cc88b",
"size": "6062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/csv2xml/src/org/slc/sli/sample/entities/AcademicWeek.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "9748"
},
{
"name": "CSS",
"bytes": "112888"
},
{
"name": "Clojure",
"bytes": "37861"
},
{
"name": "CoffeeScript",
"bytes": "18305"
},
{
"name": "Groovy",
"bytes": "26568"
},
{
"name": "Java",
"bytes": "12115410"
},
{
"name": "JavaScript",
"bytes": "390822"
},
{
"name": "Objective-C",
"bytes": "490386"
},
{
"name": "Python",
"bytes": "34255"
},
{
"name": "Ruby",
"bytes": "2543748"
},
{
"name": "Shell",
"bytes": "111267"
},
{
"name": "XSLT",
"bytes": "144746"
}
],
"symlink_target": ""
} |
import Base.sign, Base.size, Base.length, Base.endof, Base.ndims, Base.convert
export AbstractExpr, Constraint
export vexity, sign, size, evaluate, monotonicity, curvature, length, convert
export conic_form!
export endof, ndims
export Value, ValueOrNothing
export get_vectorized_size
### Abstract types
abstract AbstractExpr
abstract Constraint
# Override hash function because of
# https://github.com/JuliaLang/julia/issues/10267
import Base.hash
export hash
const hashaa_seed = Uint === Uint64 ? 0x7f53e68ceb575e76 : 0xeb575e7
function hash(a::Array{AbstractExpr}, h::Uint)
h += hashaa_seed
h += hash(size(a))
for x in a
h = hash(x, h)
end
return h
end
# If h(x)=f∘g(x), then (for single variable calculus)
# h''(x) = g'(x)^T f''(g(x)) g'(x) + f'(g(x))g''(x)
# We calculate the vexity according to this
function vexity(x::AbstractExpr)
monotonicities = monotonicity(x)
vex = curvature(x)
for i = 1:length(x.children)
vex += monotonicities[i] * vexity(x.children[i])
end
return vex
end
# This function should never be reached
function monotonicity(x::AbstractExpr)
error("monotonicity not implemented for $(x.head).")
end
# This function should never be reached
function curvature(x::AbstractExpr)
error("curvature not implemented for $(x.head).")
end
# This function should never be reached
function evaluate(x::AbstractExpr)
error("evaluate not implemented for $(x.head).")
end
# This function should never be reached
function sign(x::AbstractExpr)
error("sign not implemented for $(x.head).")
end
function size(x::AbstractExpr)
return x.size
end
function length(x::AbstractExpr)
return prod(x.size)
end
### User-defined Unions
Value = Union(Number, AbstractArray)
ValueOrNothing = Union(Value, Nothing)
AbstractExprOrValue = Union(AbstractExpr, Value)
convert(::Type{AbstractExpr}, x::Value) = Constant(x)
convert(::Type{AbstractExpr}, x::AbstractExpr) = x
function size(x::AbstractExpr, dim::Integer)
if dim < 1
error("dimension out of range")
elseif dim > 2
return 1
else
return size(x)[dim]
end
end
ndims(x::AbstractExpr) = 2
get_vectorized_size(x::AbstractExpr) = reduce(*, size(x))
endof(x::AbstractExpr) = get_vectorized_size(x)
| {
"content_hash": "ab73ec16e3512b50a582c6105bc80d57",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 78,
"avg_line_length": 24.876404494382022,
"alnum_prop": 0.7258355916892503,
"repo_name": "Vgrunert/Convex.jl",
"id": "0c576faf8528976855ebcf754c6581f57034714c",
"size": "3811",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/expressions.jl",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Julia",
"bytes": "179086"
}
],
"symlink_target": ""
} |
module Merb::Test::Fixtures
module Abstract
class Testing < Merb::AbstractController
self._template_root = File.dirname(__FILE__) / "views"
end
class RenderTwoAppendContents < Testing
def index
render
end
end
class RenderString < Testing
def index
render "the index"
end
end
class RenderStringCustomLayout < RenderString
layout :custom
end
class RenderStringAppLayout < RenderString
self._template_root = File.dirname(__FILE__) / "alt_views"
end
class RenderStringControllerLayout < RenderString
self._template_root = File.dirname(__FILE__) / "alt_views"
end
class RenderStringDynamicLayout < RenderString
layout :determine_layout
def alt_index
render "the alt index"
end
def determine_layout
action_name.index('alt') == 0 ? 'alt' : 'custom'
end
end
class RenderTemplate < Testing
def index
render
end
end
class RenderTemplateCustomLayout < RenderString
layout :custom
end
class RenderTemplateAppLayout < RenderString
self._template_root = File.dirname(__FILE__) / "alt_views"
end
class RenderTemplateControllerLayout < RenderString
self._template_root = File.dirname(__FILE__) / "alt_views"
end
class RenderNoDefaultAppLayout < RenderString
self._template_root = File.dirname(__FILE__) / "alt_views"
self.layout false
end
class RenderNoDefaultAppLayoutInherited < RenderNoDefaultAppLayout
end
class RenderDefaultAppLayoutInheritedOverride < RenderNoDefaultAppLayout
self.default_layout
end
class RenderTemplateCustomLocation < RenderTemplate
def _template_location(context, type = nil, controller = controller_name)
"wonderful/#{context}"
end
end
class RenderTemplateAbsolutePath < RenderTemplate
def index
render :template => File.expand_path(self._template_root) / 'wonderful' / 'index'
end
end
class RenderTemplateMultipleRoots < RenderTemplate
self._template_roots << [File.dirname(__FILE__) / "alt_views", :_template_location]
def show
render :layout => false
end
end
class RenderTemplateMultipleRootsAndCustomLocation < RenderTemplate
self._template_roots = [[File.dirname(__FILE__) / "alt_views", :_custom_template_location]]
def _custom_template_location(context, type = nil, controller = controller_name)
"#{self.class.name.split('::')[-1].to_const_path}/#{context}"
end
end
class RenderTemplateMultipleRootsInherited < RenderTemplateMultipleRootsAndCustomLocation
end
end
end
| {
"content_hash": "df01755d8d14c0a5e90376f5ca265186",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 97,
"avg_line_length": 25.55855855855856,
"alnum_prop": 0.6383503701092703,
"repo_name": "wycats/merb",
"id": "834231174dc4e79ab58a1b9e902a89b9bae88cf1",
"size": "2839",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "merb-core/spec/public/abstract_controller/controllers/render.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "213128"
},
{
"name": "Java",
"bytes": "34151"
},
{
"name": "JavaScript",
"bytes": "58209"
},
{
"name": "PHP",
"bytes": "857"
},
{
"name": "Ruby",
"bytes": "5110991"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "7c884be1da212b6de021f083a35b6efc",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "854252880224106ba225e33ad3186a8e749423bb",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Chromolaena leivensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.joisanegamgo.hospital.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author josiane
* @version 1.0.0
* This should validate user entries in the forms.
* A Roomnumber has A letter followed by maximum 4 digits
* Supplies,Services,DailyRate are all canadian currency
*
*/
public class DataValidator {
//private members
Matcher priceMatcher,roomNumberMatcher,numberMatcher;
String doubleRegex = "^\\d{1,4}.\\d{1,5}";
String roomNumberRegex = "^[\\p{Lower}\\p{Upper}][0-9]{1,4}"; // A roomnumber is a Letter with 4 digits
public String numberRegEx = "\\b((-1)|([1-9][0-9]{0,2}))\\b"; // regex to determin if some string is a number
// constructor
public DataValidator(){
super();
}
public boolean isADouble(double value){
boolean isadouble ;
Pattern p = Pattern.compile(doubleRegex);
priceMatcher = p.matcher(Double.toString(value));
isadouble = priceMatcher.matches();
return isadouble;
}
public boolean isARoomNumber(String value){
boolean isaroom ;
Pattern p = Pattern.compile(roomNumberRegex);
roomNumberMatcher = p.matcher(value);
isaroom = roomNumberMatcher.matches();
return isaroom;
}
/**
*
* @param text
* @return
*/
public boolean isANumber(String text) {
return (text.matches(numberRegEx));
}
}
| {
"content_hash": "e6f7fe07244b0cde2404a26fc3781b0a",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 115,
"avg_line_length": 24.53968253968254,
"alnum_prop": 0.684993531694696,
"repo_name": "josigam15/hospital",
"id": "f200bbf3f4c9eecec1df4d10daaf17c00415988a",
"size": "1546",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "1.0/src/main/java/com/joisanegamgo/hospital/util/DataValidator.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39"
},
{
"name": "Java",
"bytes": "165008"
},
{
"name": "JavaScript",
"bytes": "49"
}
],
"symlink_target": ""
} |
class game {
public:
game(void);
player* getPlayer(uint32_t ID);
galaxy* getGalaxy(void);
private:
galaxy the_galaxy;
player player1;
player player2;
};
#endif
| {
"content_hash": "3504256949295c6c0cb0f5ad6091dbc2",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 35,
"avg_line_length": 12.0625,
"alnum_prop": 0.616580310880829,
"repo_name": "markfogleman/LightQuest",
"id": "31bba537aba288a98fd6f120afb4e9fe29b32d43",
"size": "466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/game.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "12391"
}
],
"symlink_target": ""
} |
<?xml version='1.0' encoding='utf-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>net.ontopia</groupId>
<artifactId>ontopia-parent</artifactId>
<version>5.4.1-SNAPSHOT</version>
</parent>
<artifactId>webapp-root</artifactId>
<packaging>war</packaging>
<name>Ontopia ROOT webapplication</name>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-reload4j</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<finalName>ROOT</finalName>
</build>
</project>
| {
"content_hash": "4e26fb97ba9cdc0875bd16ef4e29fb03",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 201,
"avg_line_length": 27.703703703703702,
"alnum_prop": 0.7112299465240641,
"repo_name": "ontopia/ontopia",
"id": "0853ce082af55def5e0a9264f8a21a5df1d402e0",
"size": "748",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webapp-root/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "229"
},
{
"name": "CSS",
"bytes": "102701"
},
{
"name": "GAP",
"bytes": "55644"
},
{
"name": "HTML",
"bytes": "56107"
},
{
"name": "Java",
"bytes": "11884136"
},
{
"name": "JavaScript",
"bytes": "365763"
},
{
"name": "Lex",
"bytes": "19344"
},
{
"name": "Python",
"bytes": "27528"
},
{
"name": "SCSS",
"bytes": "6338"
},
{
"name": "Shell",
"bytes": "202"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>avro-parent</artifactId>
<groupId>org.apache.avro</groupId>
<version>1.9.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<artifactId>trevni-java</artifactId>
<name>Trevni Java</name>
<groupId>org.apache.avro</groupId>
<description>Trevni Java</description>
<url>http://avro.apache.org/</url>
<packaging>pom</packaging>
<modules>
<module>core</module>
<module>avro</module>
<module>doc</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<failIfNoTests>false</failIfNoTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle-plugin.version}</version>
<configuration>
<consoleOutput>true</consoleOutput>
<configLocation>checkstyle.xml</configLocation>
</configuration>
<executions>
<execution>
<id>checkstyle-check</id>
<phase>test</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${jar-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
</profiles>
</project>
| {
"content_hash": "9296236b93ad82043549db2c534652da",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 100,
"avg_line_length": 33.00990099009901,
"alnum_prop": 0.617876424715057,
"repo_name": "massie/avro",
"id": "13e64989971094b2d9ec43d28e4ef5593e709a18",
"size": "3334",
"binary": false,
"copies": "13",
"ref": "refs/heads/trunk",
"path": "lang/java/trevni/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1557"
},
{
"name": "C",
"bytes": "1188825"
},
{
"name": "C#",
"bytes": "811965"
},
{
"name": "C++",
"bytes": "642621"
},
{
"name": "CMake",
"bytes": "23592"
},
{
"name": "CSS",
"bytes": "3562"
},
{
"name": "HTML",
"bytes": "77556"
},
{
"name": "Java",
"bytes": "2970052"
},
{
"name": "JavaScript",
"bytes": "64598"
},
{
"name": "LLVM",
"bytes": "7858"
},
{
"name": "PHP",
"bytes": "205889"
},
{
"name": "Perl",
"bytes": "102415"
},
{
"name": "Perl6",
"bytes": "2316"
},
{
"name": "Protocol Buffer",
"bytes": "1756"
},
{
"name": "Python",
"bytes": "539555"
},
{
"name": "Ruby",
"bytes": "129012"
},
{
"name": "Shell",
"bytes": "325038"
},
{
"name": "Thrift",
"bytes": "1558"
},
{
"name": "VimL",
"bytes": "2764"
},
{
"name": "Yacc",
"bytes": "5228"
}
],
"symlink_target": ""
} |
export * from './create-job.component';
| {
"content_hash": "14f1addc8cccc619235e5fb128d96a44",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 39,
"avg_line_length": 40,
"alnum_prop": 0.7,
"repo_name": "khemon/talented_front_angular",
"id": "8d26e5d660c728ed5056a9ea6403f907fa00f55f",
"size": "40",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/create-job/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "942902"
},
{
"name": "HTML",
"bytes": "107911"
},
{
"name": "JavaScript",
"bytes": "1734096"
},
{
"name": "PHP",
"bytes": "12172"
},
{
"name": "TypeScript",
"bytes": "57699"
}
],
"symlink_target": ""
} |
"""
Python API for B2FIND.
Retrieve dataset info by given search criteria using CKAN portal
"""
__author__ = 'Roberto Mucci (r.mucci@cineca.it)'
import json
import requests
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(NullHandler())
def get_dataset_source(ckan_url='eudat-b1.dkrz.de', community='', pattern=[],
ckan_limit=1000):
"""
Retrieve datasets source by given search criteria using CKAN portal.
:param ckan_url: CKAN portal address, to which search requests are submitted
(default is eudat-b1.dkrz.de).
:param community: Community where you want to search in.
:param pattern: CKAN search pattern, i.e. (a list of) field:value terms.
:param ckan_limit: Limit of listed datasets (default is 1000).
:return: list of datasets source (each source should be physical URL to the
data object).
"""
if (not pattern) and (not community):
print "[ERROR] Need at least a community or a search pattern as " \
"argument!"
return
ckan_pattern = ''
sand = ''
pattern = ' AND '.join(pattern)
if community:
ckan_pattern += "groups:%s" % community
sand = " AND "
if pattern:
ckan_pattern += sand + pattern
LOGGER.debug("Search in %s for pattern %s\n....." % (ckan_url, ckan_pattern))
answer = _action(ckan_url, {"q": ckan_pattern, "rows": ckan_limit,
"start": 0})
if answer is None:
return answer
countURL = 0
results = []
for ds in answer['result']['results']:
results.append(ds['url'])
countURL += 1
LOGGER.info("Found %d Sources\n" % (countURL))
return results
def get_dataset_info(ckan_url='eudat-b1.dkrz.de', community='', pattern=[],
ckan_limit=1000):
"""
Retrieve datasets info by given search criteria using CKAN portal.
:param ckan_url: CKAN portal address, to which search requests are submitted
(default is eudat-b1.dkrz.de).
:param community: Community where you want to search in.
:param pattern: CKAN search pattern, i.e. (a list of) field:value terms.
:param ckan_limit: Limit of listed datasets (default is 1000).
:return: list of datasets (each dataset is a list of dictionary
composed by key and value) considering only the datasets containing a pid
value.
"""
if (not pattern) and (not community):
print "[ERROR] Need at least a community or a search pattern as " \
"argument!"
return
ckan_pattern = ''
sand = ''
pattern = ' AND '.join(pattern)
if community:
ckan_pattern += "groups:%s" % community
sand = " AND "
if pattern:
ckan_pattern += sand + pattern
LOGGER.debug("Search in %s for pattern %s\n....." % (ckan_url, ckan_pattern))
answer = _action(ckan_url, {"q": ckan_pattern, "rows": ckan_limit,
"start": 0})
if answer is None:
return answer
countPID = 0
results = []
for ds in answer['result']['results']:
for extra in ds['extras']:
if extra['key'] == 'PID':
# add dataset to list
results.append(ds['extras'])
countPID += 1
break
LOGGER.info("Found %d PIDs\n" % (countPID))
return results
def _action(host, data, action='package_search'):
# Make the HTTP request for data set generation.
action_url = "http://{host}/api/3/action/{action}".format(host=host,
action=action)
try:
response = requests.get(action_url, params=data)
except requests.exceptions.RequestException as e:
print e.message
return
except requests.exceptions.HTTPError as e:
print e
return
if response.status_code != 200:
print "Error code {0}. The server {1} couldn't fulfill the action {2}.\n"\
.format(response.status_code, host, action)
return
out = json.loads(response.text)
return out
def main():
""" Main function to test the script """
#get_dataset_info(pattern=['tags:MPIOM'])
get_dataset_info(community='aleph')
get_dataset_source(community='aleph')
get_dataset_source(pattern=['tags:climate'])
if __name__ == '__main__':
main() | {
"content_hash": "dbe94ebc9bb71c5acae5e024dc4f08d7",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 82,
"avg_line_length": 31.20408163265306,
"alnum_prop": 0.5955962502725093,
"repo_name": "EUDAT-B2STAGE/EUDAT-Library",
"id": "af4ae2fd101204399a7ce238f06e7861b451b281",
"size": "4610",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "eudat/b2find.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "28800"
}
],
"symlink_target": ""
} |
// `assert` initialized at top of scope
// Assert helpers
// All of these must either call QUnit.push() or manually do:
// - runLoggingCallbacks( "log", .. );
// - config.current.assertions.push({ .. });
assert = QUnit.assert = {
/**
* Asserts rough true-ish result.
* @name ok
* @function
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function( result, msg ) {
if ( !config.current ) {
throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) );
}
result = !!result;
msg = msg || ( result ? "okay" : "failed" );
var source,
details = {
module: config.current.module,
name: config.current.testName,
result: result,
message: msg
};
msg = "<span class='test-message'>" + escapeText( msg ) + "</span>";
if ( !result ) {
source = sourceFromStacktrace( 2 );
if ( source ) {
details.source = source;
msg += "<table><tr class='test-source'><th>Source: </th><td><pre>" +
escapeText( source ) +
"</pre></td></tr></table>";
}
}
runLoggingCallbacks( "log", QUnit, details );
config.current.assertions.push({
result: result,
message: msg
});
},
/**
* Assert that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
* @name equal
* @function
* @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" );
*/
equal: function( actual, expected, message ) {
/*jshint eqeqeq:false */
QUnit.push( expected == actual, actual, expected, message );
},
/**
* @name notEqual
* @function
*/
notEqual: function( actual, expected, message ) {
/*jshint eqeqeq:false */
QUnit.push( expected != actual, actual, expected, message );
},
/**
* @name propEqual
* @function
*/
propEqual: function( actual, expected, message ) {
actual = objectValues(actual);
expected = objectValues(expected);
QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
},
/**
* @name notPropEqual
* @function
*/
notPropEqual: function( actual, expected, message ) {
actual = objectValues(actual);
expected = objectValues(expected);
QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
},
/**
* @name deepEqual
* @function
*/
deepEqual: function( actual, expected, message ) {
QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
},
/**
* @name notDeepEqual
* @function
*/
notDeepEqual: function( actual, expected, message ) {
QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
},
/**
* @name strictEqual
* @function
*/
strictEqual: function( actual, expected, message ) {
QUnit.push( expected === actual, actual, expected, message );
},
/**
* @name notStrictEqual
* @function
*/
notStrictEqual: function( actual, expected, message ) {
QUnit.push( expected !== actual, actual, expected, message );
},
"throws": function( block, expected, message ) {
var actual,
expectedOutput = expected,
ok = false;
// 'expected' is optional
if ( typeof expected === "string" ) {
message = expected;
expected = null;
}
config.current.ignoreGlobalErrors = true;
try {
block.call( config.current.testEnvironment );
} catch (e) {
actual = e;
}
config.current.ignoreGlobalErrors = false;
if ( actual ) {
// we don't want to validate thrown error
if ( !expected ) {
ok = true;
expectedOutput = null;
// expected is a regexp
} else if ( QUnit.objectType( expected ) === "regexp" ) {
ok = expected.test( errorString( actual ) );
// expected is a constructor
} else if ( actual instanceof expected ) {
ok = true;
// expected is a validation function which returns true is validation passed
} else if ( expected.call( {}, actual ) === true ) {
expectedOutput = null;
ok = true;
}
QUnit.push( ok, actual, expectedOutput, message );
} else {
QUnit.pushFailure( message, null, "No exception was thrown." );
}
}
};
/**
* @deprecated since 1.8.0
* Kept assertion helpers in root for backwards compatibility.
*/
extend( QUnit.constructor.prototype, assert );
/**
* @deprecated since 1.9.0
* Kept to avoid TypeErrors for undefined methods.
*/
QUnit.constructor.prototype.raises = function() {
QUnit.push( false, false, false, "QUnit.raises has been deprecated since 2012 (fad3c1ea), use QUnit.throws instead" );
};
/**
* @deprecated since 1.0.0, replaced with error pushes since 1.3.0
* Kept to avoid TypeErrors for undefined methods.
*/
QUnit.constructor.prototype.equals = function() {
QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" );
};
QUnit.constructor.prototype.same = function() {
QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" );
};
| {
"content_hash": "0fedd445f40232262abda29a1c593d62",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 121,
"avg_line_length": 26.91891891891892,
"alnum_prop": 0.6475903614457831,
"repo_name": "bulgr0z/clevershoot",
"id": "ba8083b23f8c1049bc2dcfd2d87f8309ec2a00f7",
"size": "4980",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "assets/js/bower_components/qunit/src/assert.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "188139"
},
{
"name": "JavaScript",
"bytes": "172587"
},
{
"name": "PHP",
"bytes": "707"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "Scala",
"bytes": "456"
},
{
"name": "Shell",
"bytes": "128"
}
],
"symlink_target": ""
} |
package at.forsyte.apalache.tla.bmcmt.rules.aux
import at.forsyte.apalache.tla.bmcmt._
import at.forsyte.apalache.tla.bmcmt.implicitConversions._
import at.forsyte.apalache.tla.bmcmt.types._
import at.forsyte.apalache.tla.lir.convenience.tla
import at.forsyte.apalache.tla.lir.values.{TlaIntSet, TlaNatSet}
import at.forsyte.apalache.tla.lir.{NameEx, NullEx, TlaEx, ValEx}
/**
* An element picket that allows us:
*
* <ul>
* <li>to pick from a list of cells instead of a set, and</li>
* <li>directly uses a choice oracle to avoid multiple comparisons.</li>
* </ul>
*
* @param rewriter a state rewriter
* @author Igor Konnov
*/
class CherryPick(rewriter: SymbStateRewriter) {
private val defaultValueFactory = new DefaultValueFactory(rewriter)
val oracleFactory = new OracleFactory(rewriter)
/**
* Determine the type of the set elements an element of this type by introducing an oracle
*
* @param set a set
* @param state a symbolic state
* @param elseAssert an assertion that is used when the set is empty
* @return a new symbolic state whose expression stores a fresh cell that corresponds to the picked element.
*/
def pick(set: ArenaCell, state: SymbState, elseAssert: TlaEx): SymbState = {
set.cellType match {
// all kinds of sets that should be kept unexpanded
case PowSetT(t@FinSetT(_)) =>
// a powerset is never empty, pick an element
pickFromPowset(t, set, state)
case FinFunSetT(domt@FinSetT(_), cdm@FinSetT(rest)) =>
// No emptiness check, since we are dealing with a function set [S -> T].
// If S is empty, we get a function of the empty set.
pickFunFromFunSet(FunT(domt, rest), set, state)
case FinFunSetT(domt@FinSetT(_), cdm@InfSetT(rest)) =>
// No emptiness check, since we are dealing with a function set [S -> T].
// If S is empty, we get a function of the empty set.
pickFunFromFunSet(FunT(domt, rest), set, state)
case FinFunSetT(domt@FinSetT(_), cdm@PowSetT(resultT @ FinSetT(_))) =>
// No emptiness check, since we are dealing with a function set [S -> T].
// If S is empty, we get a function of the empty set.
pickFunFromFunSet(FunT(domt, resultT), set, state)
case FinFunSetT(dom1T@FinSetT(_), FinFunSetT(dom2T @ FinSetT(_), FinSetT(result2T))) =>
pickFunFromFunSet(FunT(dom1T, FunT(dom2T, result2T)), set, state)
case FinFunSetT(dom1T@FinSetT(_), cdm @ FinFunSetT(dom2T @ FinSetT(_), PowSetT(result2T @ FinSetT(_)))) =>
pickFunFromFunSet(FunT(dom1T, FunT(dom2T, result2T)), set, state)
case FinFunSetT(FinSetT(_), PowSetT(_)) | FinFunSetT(FinSetT(_), FinFunSetT(_, _)) =>
throw new RewriterException(s"Rewriting for the type ${set.cellType} is not implemented. Raise an issue.", state.ex)
case InfSetT(IntT()) if set == state.arena.cellIntSet() || set == state.arena.cellNatSet() =>
// pick an integer or natural
pickFromIntOrNatSet(set, state)
case _ =>
val elems = state.arena.getHas(set)
if (elems.isEmpty) {
throw new RuntimeException(s"The set $set is statically empty. Pick should not be called on that.")
}
var (nextState, oracle) = oracleFactory.newDefaultOracle(state, elems.size + 1)
// pick only the elements that belong to the set
val elemsIn = elems map { tla.in(_, set) }
rewriter.solverContext.assertGroundExpr(oracle.caseAssertions(nextState, elemsIn :+ elseAssert))
pickByOracle(nextState, oracle, elems, elseAssert)
}
}
/**
* Determine the type of the set elements and pick an element of this type.
*
* Warning: this method does not check, whether the picked element actually belongs to the set.
* You have to do it yourself.
*
* @param state a symbolic state
* @param oracle a variable that stores which element (by index) should be picked, can be unrestricted
* @param elems a non-empty set of cells
* @return a new symbolic state whose expression stores a fresh cell that corresponds to the picked element.
*/
def pickByOracle(state: SymbState, oracle: Oracle, elems: Seq[ArenaCell], elseAssert: TlaEx): SymbState = {
assert(elems.nonEmpty) // this is an advanced operator -- you should know what you are doing
val targetType = elems.head.cellType
// An optimization: if the (multi-) set consists of identical cells, return the cell
// (e.g., this happens when all enabled transitions do not change a variable.)
if (elems.distinct.size == 1) {
return state.setRex(elems.head)
}
// the general case
targetType match {
case ConstT() =>
pickBasic(ConstT(), state, oracle, elems, elseAssert)
case IntT() =>
pickBasic(IntT(), state, oracle, elems, elseAssert)
case BoolT() =>
pickBasic(BoolT(), state, oracle, elems, elseAssert)
case t@TupleT(_) =>
pickTuple(t, state, oracle, elems, elseAssert)
case t@RecordT(_) =>
pickRecord(t, state, oracle, elems, elseAssert)
case t@FinSetT(_) =>
pickSet(t, state, oracle, elems, elseAssert)
case t@SeqT(_) =>
pickSequence(t, state, oracle, elems, elseAssert)
case t@FunT(FinSetT(_), _) =>
pickFun(t, state, oracle, elems, elseAssert)
case _ =>
throw new RewriterException("Do not know how pick an element from a set of type: " + targetType, state.ex)
}
}
/**
* Pick a basic value, that is, an integer, Boolean, or constant.
*
* @param cellType a cell type to assign to the picked cell.
* @param state a symbolic state
* @param oracle a variable that stores which element (by index) should be picked, can be unrestricted
* @param elems a sequence of elements of cellType
* @return a new symbolic state with the expression holding a fresh cell that stores the picked element.
*/
def pickBasic(cellType: CellT, state: SymbState, oracle: Oracle,
elems: Seq[ArenaCell], elseAssert: TlaEx): SymbState = {
rewriter.solverContext.log("; CHERRY-PICK %s FROM [%s] {".format(cellType, elems.map(_.toString).mkString(", ")))
var arena = state.arena.appendCell(cellType)
val resultCell = arena.topCell
// compare the set contents with the result
val eqState = rewriter.lazyEq.cacheEqConstraints(state, elems.map(e => (e, resultCell)))
// the new element equals to an existing element in the set
val asserts = elems map { el => rewriter.lazyEq.safeEq(resultCell, el) }
rewriter.solverContext.assertGroundExpr(oracle.caseAssertions(eqState, asserts :+ elseAssert))
rewriter.solverContext.log(s"; } CHERRY-PICK $resultCell:$cellType")
eqState.setArena(arena).setRex(resultCell)
}
/**
* Implements SE-PICK-TUPLE.
*
* @param cellType a cell type to assign to the picked cell.
* @param state a symbolic state
* @param oracle a variable that stores which element (by index) should be picked, can be unrestricted
* @param tuples a sequence of records of cellType
* @return a new symbolic state with the expression holding a fresh cell that stores the picked element.
*/
def pickTuple(cellType: CellT, state: SymbState, oracle: Oracle,
tuples: Seq[ArenaCell], elseAssert: TlaEx): SymbState = {
rewriter.solverContext.log("; CHERRY-PICK %s FROM [%s] {".format(cellType, tuples.map(_.toString).mkString(", ")))
val tupleType = cellType.asInstanceOf[TupleT]
var newState = state
def pickAtPos(i: Int): ArenaCell = {
// as we know the field index, we just directly project tuples on this index
val slice = tuples.map(c => newState.arena.getHas(c)(i))
newState = pickByOracle(newState, oracle, slice, elseAssert)
newState.asCell
}
// introduce a new tuple
newState = newState.setArena(newState.arena.appendCell(cellType))
val newTuple = newState.arena.topCell
// for each index i, pick a value from the projection { t[i] : t \in tuples }
val newFields = tupleType.args.indices map pickAtPos
// The awesome property: we do not have to enforce equality of the field values, as this will be enforced by
// the rule for the respective element t[i], as it will use the same oracle!
// add the new fields to arena
val newArena = newState.arena.appendHasNoSmt(newTuple, newFields: _*)
rewriter.solverContext.log(s"; } CHERRY-PICK $newTuple:$cellType")
newState
.setArena(newArena)
.setRex(newTuple.toNameEx)
}
/**
* Implements SE-PICK-RECORD.
*
* Note that some record fields may have bogus values, since not all the records in the set
* are required to have all the keys assigned. That is an unavoidable loophole in the record types.
*
* @param cellType a cell type to assign to the picked cell.
* @param state a symbolic state
* @param oracle a variable that stores which element (by index) should be picked, can be unrestricted
* @param records a sequence of records of cellType
* @return a new symbolic state with the expression holding a fresh cell that stores the picked element.
*/
def pickRecord(cellType: CellT, state: SymbState, oracle: Oracle,
records: Seq[ArenaCell], elseAssert: TlaEx): SymbState = {
// since we require all records to have exactly the same type, the code became much simpler
rewriter.solverContext.log("; CHERRY-PICK %s FROM [%s] {".format(cellType, records.map(_.toString).mkString(", ")))
val recordType = cellType.asInstanceOf[RecordT]
def findKeyIndex(key: String): Int =
recordType.fields.keySet.toList.indexOf(key)
var newState = state
def pickAtPos(key: String): ArenaCell = {
val keyIndex = findKeyIndex(key)
val slice = records.map(c => newState.arena.getHas(c)(keyIndex))
newState = pickByOracle(newState, oracle, slice, elseAssert)
newState.asCell
}
// introduce a new record
newState = newState.setArena(newState.arena.appendCell(cellType))
val newRecord = newState.arena.topCell
// pick the domain using the oracle.
// newState = pickSet(FinSetT(ConstT()), newState, oracle, records map (r => newState.arena.getDom(r)))
newState = pickRecordDomain(FinSetT(ConstT()), newState, oracle, records map (r => newState.arena.getDom(r)))
val newDom = newState.asCell
// pick the fields using the oracle
val fieldCells = recordType.fields.keySet.toSeq map pickAtPos
// and connect them to the record
var newArena = newState.arena.setDom(newRecord, newDom)
newArena = newArena.appendHasNoSmt(newRecord, fieldCells: _*)
// The awesome property: we do not have to enforce equality of the field values, as this will be enforced by
// the rule for the respective element r.key, as it will use the same oracle!
rewriter.solverContext.log(s"; } CHERRY-PICK $newRecord:$cellType")
newState.setArena(newArena)
.setRex(newRecord.toNameEx)
}
/**
* Pick a set among a sequence of record domains. We know that the types of all the domains are compatible.
* Moreover, from the record constructor, we know that the record domains have exactly the same sequence
* of keys in the arena. Hence, we only have to define the SMT constraints that regulate which keys belong to the new set.
* This optimization prevents the model checker from blowing up in the number of record domains, e.g., in Raft.
*
* @param domType the goal type
* @param state a symbolic state
* @param oracle the oracle to use
* @param domains the domains to pick from
* @return a new cell that encodes a picked domain
*/
private def pickRecordDomain(domType: CellT, state: SymbState, oracle: Oracle, domains: Seq[ArenaCell]): SymbState = {
// TODO: use elseAssert and Oracle.caseAssertions?
// It often happens that all the domains are actually the same cell. Return this cell.
val distinct = domains.distinct
if (distinct.size == 1) {
state.setRex(distinct.head)
} else {
// consistency check: make sure that all the domains consist of exactly the same sets of keys
val keyCells = state.arena.getHas(domains.head)
for (dom <- domains.tail) {
val otherKeyCells = state.arena.getHas(dom)
assert(otherKeyCells.size == keyCells.size,
"inconsistent record domains of size %d and %d".format(keyCells.size, otherKeyCells.size))
for ((k, o) <- keyCells.zip(otherKeyCells)) {
assert(k == o, s"inconsistent record domains: $k != $o")
}
}
// introduce a new cell for the picked domain
var nextState = state.updateArena(_.appendCell(domType))
val newDom = nextState.arena.topCell
nextState = nextState.updateArena(_.appendHas(newDom, keyCells: _*))
// once we know that all the keys coincide, constrain membership with SMT
for ((dom, no) <- domains.zipWithIndex) {
def iffKey(keyCell: ArenaCell) = tla.equiv(tla.in(keyCell, newDom), tla.in(keyCell, dom))
val keysMatch = tla.and(keyCells map iffKey: _*)
rewriter.solverContext.assertGroundExpr(tla.impl(oracle.whenEqualTo(nextState, no), keysMatch))
}
nextState.setRex(newDom)
}
}
/**
* Implements SE-PICK-SET.
*
* Note that some record fields may have bogus values, since not all the records in the set
* are required to have all the keys assigned. That is an unavoidable loophole in the record types.
*
* @param cellType a cell type to assign to the picked cell.
* @param state a symbolic state
* @param oracle a variable that stores which element (by index) should be picked, can be unrestricted
* @param memberSets a sequence of sets of cellType
* @return a new symbolic state with the expression holding a fresh cell that stores the picked element.
*/
def pickSet(cellType: CellT, state: SymbState, oracle: Oracle,
memberSets: Seq[ArenaCell], elseAssert: TlaEx): SymbState = {
if (memberSets.isEmpty) {
throw new RuntimeException("Picking from a statically empty set")
} else if (memberSets.length == 1) {
// one set, either empty, or not
state.setRex(memberSets.head)
} else if (memberSets.distinct.length == 1) {
// all sets are actually the same, this is quite common for function domains
state.setRex(memberSets.head)
} else if (memberSets.forall(ms => state.arena.getHas(ms).isEmpty)) {
// multiple sets that are statically empty, just pick the first one
state.setRex(memberSets.head)
} else {
pickSetNonEmpty(cellType, state, oracle, memberSets, elseAssert)
}
}
private def pickSetNonEmpty(cellType: CellT,
state: SymbState,
oracle: Oracle,
memberSets: Seq[ArenaCell],
elseAssert: TlaEx): SymbState = {
def solverAssert(e: TlaEx): Unit = rewriter.solverContext.assertGroundExpr(e)
rewriter.solverContext.log("; CHERRY-PICK %s FROM [%s] {".format(cellType, memberSets.map(_.toString).mkString(", ")))
var nextState = state
// introduce a fresh cell for the set
nextState = nextState.setArena(state.arena.appendCell(cellType))
val resultCell = nextState.arena.topCell
// get all the cells pointed by the elements of every member set
val elemsOfMemberSets: Seq[Seq[ArenaCell]] = memberSets map (s => Set(nextState.arena.getHas(s): _*).toSeq)
// Here we are using the awesome linear encoding that uses interleaving.
// We give an explanation for two statically non-empty sets, statically empty sets should be treated differently.
// Assume S_1 = { c_1, ..., c_n } and S_2 = { d_1, ..., d_n } (pad if they have different lengths)
//
// We construct a new set R = { z_1, ..., z_n } where z_i = FROM { c_i, d_i }
//
// The principal constraint: chosen = 1 => in(S_1, S) /\ chosen = 2 => in(S_2, S)
//
// Here are the additional constraints for i \in 1..n:
//
// ChooseProper: chosen = 1 => z_i = c_i /\ chosen = 2 => z_i = d_i
// ChooseIn: in(z_i, R) <=> (chosen = 1 /\ in(c_i, S_1) \/ (chosen = 2 /\ in(d_i, S_2)
val maxLen = elemsOfMemberSets map (_.size) reduce ((i, j) => if (i > j) i else j)
assert(maxLen != 0)
val maxPadded = elemsOfMemberSets.find(_.size == maxLen).get // existence is guaranteed by maxLen
// pad a non-empty sequence to the given length, keep the empty sequence intact
def padNonEmptySeq(s: Seq[ArenaCell], len: Int): Seq[ArenaCell] = s match {
// copy last as many times as needed
case allButLast :+ last => allButLast ++ Seq.fill(len - allButLast.length)(last)
// the empty sequence is a special case
case Nil => maxPadded
}
val paddedOfMemberSets = elemsOfMemberSets.map(padNonEmptySeq(_, maxLen))
// for each index i, pick from {c_i, ..., d_i}.
def pickOneElement(i: Int): Unit = {
val toPickFrom = paddedOfMemberSets map { _(i) }
nextState = pickByOracle(nextState, oracle, toPickFrom, elseAssert)
val picked = nextState.asCell
// this property is enforced by the oracle magic: chosen = 1 => z_i = c_i /\ chosen = 2 => z_i = d_i
// The awesome property of the oracle is that we do not have to compare the sets directly!
// Instead, we compare the oracle values.
// (chosen = 1 /\ in(z_i, R) <=> in(c_i, S_1)) \/ (chosen = 2 /\ in(z_i, R) <=> in(d_i, S_2)) \/ (chosen = N <=> elseAssert)
def nthIn(elemAndSet: (ArenaCell, ArenaCell), no: Int): TlaEx = {
if (elemsOfMemberSets(no).nonEmpty) {
tla.equiv(tla.in(picked.toNameEx, resultCell.toNameEx), tla.in(elemAndSet._1, elemAndSet._2))
} else {
tla.not(tla.in(picked.toNameEx, resultCell.toNameEx)) // nothing belongs to the set
}
}
val assertions = toPickFrom.zip(memberSets).zipWithIndex map (nthIn _).tupled
// add the cell to the arena
nextState = nextState.updateArena(_.appendHas(resultCell, picked))
// (chosen = 1 /\ in(z_i, R) = in(c_i, S_1)) \/ (chosen = 2 /\ in(z_i, R) = in(d_i, S_2))
solverAssert(oracle.caseAssertions(nextState, assertions :+ elseAssert))
}
0.until(maxLen) foreach pickOneElement
rewriter.solverContext.log(s"; } CHERRY-PICK $resultCell:$cellType")
nextState.setRex(resultCell)
}
/**
* Picks a sequence from a list of sequences
*
* @param cellType a cell type to assign to the picked cell.
* @param state a symbolic state
* @param oracle a variable that stores which element (by index) should be picked, can be unrestricted
* @param memberSeqs a sequence of sequences of cellType
* @return a new symbolic state with the expression holding a fresh cell that stores the picked element.
*/
def pickSequence(cellType: CellT, state: SymbState, oracle: Oracle,
memberSeqs: Seq[ArenaCell], elseAssert: TlaEx): SymbState = {
if (memberSeqs.isEmpty) {
throw new RuntimeException("Picking a sequence from a statically empty set")
} else if (memberSeqs.length == 1) {
// one sequence, either empty, or not
state.setRex(memberSeqs.head)
} else if (memberSeqs.distinct.length == 1) {
// all sequences are actually the same cell
state.setRex(memberSeqs.head)
} else if (memberSeqs.forall(ms => state.arena.getHas(ms).size == 2)) {
// multiple sequences that are statically empty (note that the first two elements are start and end)
state.setRex(memberSeqs.head)
} else if (memberSeqs.forall(ms => state.arena.getHas(ms).isEmpty)) {
throw new IllegalStateException(s"Corrupted sequences, no start and end: $memberSeqs")
} else {
pickSequenceNonEmpty(cellType, state, oracle, memberSeqs, elseAssert)
}
}
// Pick from a set of sequence. There is a large overlap with pickSetNonEmpty
private def pickSequenceNonEmpty(seqType: CellT,
state: SymbState,
oracle: Oracle,
memberSeqs: Seq[ArenaCell],
elseAssert: TlaEx): SymbState = {
def solverAssert(e: TlaEx): Unit = rewriter.solverContext.assertGroundExpr(e)
rewriter.solverContext.log("; CHERRY-PICK %s FROM [%s] {".format(seqType, memberSeqs.map(_.toString).mkString(", ")))
var nextState = state
// introduce a fresh cell for the set
nextState = nextState.setArena(state.arena.appendCell(seqType))
val resultCell = nextState.arena.topCell
// get all the cells pointed by the elements of every member set, without changing their order!
val elemsOfMemberSeqs: Seq[Seq[ArenaCell]] = memberSeqs map (s => nextState.arena.getHas(s).toSeq)
// Here we are using the awesome linear encoding that uses interleaving.
// We give an explanation for two statically non-empty sequences, the static case should be handled differently.
// Assume S_1 = << c_1, ..., c_n >> and S_2 = << d_1, ..., d_n >> (pad if they have different lengths)
//
// We construct a new sequence R = << z_1, ..., z_n >> where z_i = FROM { c_i, d_i }
//
// As we are not tracking membership for sequences, no additional SMT constraints are needed
val maxLen = elemsOfMemberSeqs map (_.size) reduce ((i, j) => if (i > j) i else j)
assert(maxLen != 0)
val maxPadded = elemsOfMemberSeqs.find(_.size == maxLen).get // there must be one like this
def padNonEmptySeq(s: Seq[ArenaCell], len: Int): Seq[ArenaCell] = s match {
// copy the last element as many times as needed
case allButLast :+ last if allButLast.size >= 2 => // the first two elements are start and end
allButLast ++ Seq.fill(len - allButLast.length)(last)
// the empty sequence is a special case
case start :: end :: Nil => start +: end +: maxPadded.tail.tail // keep the start and end (should be 0 anyhow)
case _ => throw new IllegalStateException("A corrupted encoding of a sequence")
}
val paddedSeqElems = elemsOfMemberSeqs.map(padNonEmptySeq(_, maxLen))
// no empty sequences beyond this point
// for each index i, pick from {c_i, ..., d_i}.
def pickOneElement(i: Int): Unit = {
val toPickFrom = paddedSeqElems map { _(i) }
nextState = pickByOracle(nextState, oracle, toPickFrom, elseAssert)
val picked = nextState.asCell
// this property is enforced by the oracle magic: chosen = 1 => z_i = c_i /\ chosen = 2 => z_i = d_i
// add the cell to the arena
nextState = nextState.updateArena(_.appendHasNoSmt(resultCell, picked))
}
0.until(maxLen) foreach pickOneElement
rewriter.solverContext.log(s"; } CHERRY-PICK $resultCell:$seqType")
nextState.setRex(resultCell)
}
/**
* This is a new implementation of picking a function from a set. Since we started to encode functions
* as relations, the implementation became trivial
*
* @param funType a cell type to assign to the picked cell.
* @param oracle a variable that stores which element (by index) should be picked, can be unrestricted
* @param funs a sequence of cells that store functions
* @param state a symbolic state
* @return a new symbolic state with the expression holding a fresh cell that stores the picked element.
*/
def pickFun(funType: FunT, state: SymbState, oracle: Oracle, funs: Seq[ArenaCell], elseAssert: TlaEx): SymbState = {
rewriter.solverContext.log("; CHERRY-PICK %s FROM [%s] {".format(funType, funs.map(_.toString).mkString(", ")))
var nextState = state
// pick the relation
val relationT = FinSetT(TupleT(Seq(funType.argType, funType.resultType)))
nextState = pickSet(relationT, nextState, oracle, funs map state.arena.getCdm, elseAssert)
val pickedRelation = nextState.asCell
// create a fresh cell to hold the function
nextState = nextState.setArena(nextState.arena.appendCell(funType))
val funCell = nextState.arena.topCell
val newArena = nextState.arena.setCdm(funCell, pickedRelation)
rewriter.solverContext.log(s"; } CHERRY-PICK $funCell:$funType")
// That's it! Compare to pickFunPreWarp.
nextState.setArena(newArena).setRex(funCell)
}
/**
* Implements SE-PICK-SET, that is, assume that the picked element is a set itself.
*
* @param resultType a cell type to assign to the picked cell.
* @param set a powerset
* @param state a symbolic state
* @return a new symbolic state with the expression holding a fresh cell that stores the picked element.
*/
def pickFromPowset(resultType: CellT, set: ArenaCell, state: SymbState): SymbState = {
rewriter.solverContext.log("; PICK %s FROM %s {".format(resultType, set))
var arena = state.arena.appendCell(resultType)
val resultSet = arena.topCell
val baseSet = arena.getDom(set)
val elems = arena.getHas(baseSet)
// resultSet may contain all the elements from the baseSet of the powerset SUBSET(S)
arena = arena.appendHas(resultSet, elems: _*)
// if resultSet has an element, then it must be also in baseSet
def inResultIfInBase(elem: ArenaCell): Unit = {
val inResult = tla.in(elem, resultSet)
val inBase = tla.in(elem, baseSet)
rewriter.solverContext.assertGroundExpr(tla.impl(inResult, inBase))
}
elems foreach inResultIfInBase
rewriter.solverContext.log("; } PICK %s FROM %s".format(resultType, set))
state.setArena(arena).setRex(resultSet)
}
/**
* Picks a function from a set [S -> T].
* Since [S -> T] is in its unexpanded form, it is easy to pick a function by imposing the constraints
* from S and T, so we are not using an oracle here. However, we have to take care of T, as it can be
* an unexpanded set itself, e.g., SUBSET X, or [X -> Y].
*
* @param funT a cell type to assign to the picked cell.
* @param funSet a function set [S -> T]
* @param state a symbolic state
* @return a new symbolic state with the expression holding a fresh cell that stores the picked element.
*/
def pickFunFromFunSet(funT: CellT, funSet: ArenaCell, state: SymbState): SymbState = {
rewriter.solverContext.log("; PICK %s FROM %s {".format(funT, funSet))
var arena = state.arena
val dom = arena.getDom(funSet) // this is a set of potential arguments, always expanded!
val cdm = arena.getCdm(funSet) // this is a set of potential results, may be expanded, may be not.
// TODO: take care of [S -> {}], what is the semantics of it?
val funType = funT.asInstanceOf[FunT] // for now, only FunT is supported
// create the function cell
arena = arena.appendCell(funT)
val funCell = arena.topCell
// create the relation cell
arena = arena.appendCell(FinSetT(TupleT(Seq(funType.argType, funType.resultType))))
val relationCell = arena.topCell
// not keeping the domain explicitly
// TODO: why don't we keep the domain? It is always expanded and thus already pre-computed!
// arena = arena.setDom(funCell, dom)
arena = arena.setCdm(funCell, relationCell)
var nextState = state.setArena(arena)
// For every domain cell, pick a result from the co-domain.
// The beauty of CherryPick: When the co-domain is not expanded, CherryPick will pick one value out of the co-domain,
// instead of constructing the co-domain first.
for (arg <- arena.getHas(dom)) {
nextState = pick(cdm, nextState, nextState.arena.cellFalse()) // the co-domain should be non-empty
val pickedResult = nextState.asCell
arena = nextState.arena.appendCell(TupleT(Seq(funType.argType, funType.resultType)))
val pair = arena.topCell
arena = arena.appendHasNoSmt(pair, arg, pickedResult)
arena = arena.appendHas(relationCell, pair)
nextState = nextState.setArena(arena)
val iff = tla.equiv(tla.in(arg, dom), tla.in(pair, relationCell))
rewriter.solverContext.assertGroundExpr(iff)
}
// If S is empty, the relation is empty too.
rewriter.solverContext.log("; } PICK %s FROM %s".format(funT, funSet))
nextState.setRex(funCell)
}
// just declare an integer, and in case of Nat make it non-negative
def pickFromIntOrNatSet(set: ArenaCell, state: SymbState): SymbState = {
assert(set == state.arena.cellNatSet() || set == state.arena.cellIntSet())
var nextState = state.updateArena(_.appendCell(IntT()))
val intCell = nextState.arena.topCell
if (set == state.arena.cellNatSet()) {
rewriter.solverContext.assertGroundExpr(tla.ge(intCell.toNameEx, tla.int(0)))
}
nextState.setRex(intCell)
}
}
| {
"content_hash": "66ad279fbd954808228d8d3be0797c48",
"timestamp": "",
"source": "github",
"line_count": 604,
"max_line_length": 131,
"avg_line_length": 47.700331125827816,
"alnum_prop": 0.6698830307868523,
"repo_name": "konnov/apalache",
"id": "9361e0bc9f9d32578266a7045682b403c0c7a596",
"size": "28811",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tla-bmcmt/src/main/scala/at/forsyte/apalache/tla/bmcmt/rules/aux/CherryPick.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1032"
},
{
"name": "Makefile",
"bytes": "707"
},
{
"name": "Python",
"bytes": "3420"
},
{
"name": "SMT",
"bytes": "2002"
},
{
"name": "Scala",
"bytes": "1531342"
},
{
"name": "Shell",
"bytes": "9964"
},
{
"name": "TLA",
"bytes": "469747"
}
],
"symlink_target": ""
} |
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="EmployeeService">
<jta-data-source>jdbc/removingWithRelationships</jta-data-source>
<validation-mode>NONE</validation-mode>
<properties>
<property name="eclipselink.target-server" value="SunAS9"/>
<property name="eclipselink.target-database"
value="org.eclipse.persistence.platform.database.DerbyPlatform"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence> | {
"content_hash": "4371b8b557ab44e863c73f53dfde9794",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 87,
"avg_line_length": 51,
"alnum_prop": 0.6601307189542484,
"repo_name": "velmuruganvelayutham/jpa",
"id": "e65ddd3415b32f4883010f612aa7d39645ff2b2a",
"size": "612",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/Chapter6/17-removingWithRelationships/etc/persistence/META-INF/persistence.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "831359"
},
{
"name": "Shell",
"bytes": "8424"
}
],
"symlink_target": ""
} |
package ru.aserdyuchenko.servlet;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import ru.aserdyuchenko.storage.DataSource;
import ru.aserdyuchenko.storage.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
/**
* @author Anton Serdyuchenko. anton415@gmail.com
* @since 05.11.2017 18:30
*/
public class ServletEditUser extends HttpServlet {
Logger logger = Logger.getLogger(ServletEditUser.class);
public void init() {
org.apache.log4j.BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.INFO);
}
/**
* Get role by login.
* @param login
* @return role
*/
private String getRoleByLogin(String login) throws SQLException {
String userRole = "";
DataSource storage = DataSource.getInstance();
List<User> allUsers = storage.getList();
System.out.println("allUsers: " + allUsers.toString());
for(User user : allUsers) {
if (user.getLogin().equals(login))
userRole = user.getRole();
}
System.out.println("userRole: " + userRole);
return userRole;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
logger.info("Hello this is an info message, from doGet method in ServletEditUser.java");
HttpSession session = request.getSession();
synchronized (session) {
//TODO Rewrite this code!!!
String login = session.getAttribute("login").toString(); // this work!
System.out.println("login: "+login);
System.out.println("role: "+getRoleByLogin(login));
request.setAttribute("role", getRoleByLogin(login));
request.setAttribute("login", session.getAttribute("login"));
request.setAttribute("users", DataSource.getInstance().getList());
//TODO Add another attributes.
}
request.getRequestDispatcher("/edit.html").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html");
try {
HttpSession session = request.getSession();
synchronized (session) {
Class.forName("org.postgresql.Driver");
DataSource storage = DataSource.getInstance();
// if (session.getAttribute("role").toString().equals("admin")) {
// storage.update(request.getParameter("name"), request.getParameter("email"), request.getParameter("createDate"), request.getParameter("login"), request.getParameter("password"), request.getParameter("role"));
// } else if(session.getAttribute("role").toString().equals("user")) {
// storage.update(request.getParameter("name"), request.getParameter("email"), request.getParameter("createDate"), session.getAttribute("login").toString(), request.getParameter("password"), request.getParameter("role"));
// }
if (request.getParameter("role").toString().equals("admin")) {
storage.update(request.getParameter("name"), request.getParameter("email"), request.getParameter("createDate"), request.getParameter("login"), request.getParameter("password"), request.getParameter("role"));
} else if(request.getParameter("role").toString().equals("user")) {
storage.updateByUser(request.getParameter("name"),
request.getParameter("email"),
request.getParameter("createDate"),
request.getParameter("login")
);
}
response.sendRedirect(String.format("%s/editUser", request.getContextPath()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| {
"content_hash": "02fd5a65b6730972e718693ea297c58c",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 240,
"avg_line_length": 43.48,
"alnum_prop": 0.6235050597976081,
"repo_name": "anton415/Job4j",
"id": "68061c6ef15d060aa9207bdecabcf195ad48a965",
"size": "4348",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Junior/Part_3_Servlet/src/main/java/ru.aserdyuchenko/servlet/ServletEditUser.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "21252"
},
{
"name": "Java",
"bytes": "393706"
}
],
"symlink_target": ""
} |
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using log4net;
using SmallSharpTools;
using SmallSharpTools.Logging;
/// <summary>
/// Summary description for Utility
/// </summary>
public class Utility
{
public static string GetSiteUrl(string url)
{
if (String.IsNullOrEmpty(url))
{
return GetSiteRoot() + "/";
}
if (url.StartsWith("~/"))
{
url = url.Substring(1, url.Length - 1);
}
return GetSiteRoot() + url;
}
public static string GetUrlPath(string url)
{
return HttpContext.Current.Request.MapPath(url);
}
public static string GetRelativeSiteUrl(string url)
{
if (!String.IsNullOrEmpty(url))
{
if (url.StartsWith("~/"))
{
url = url.Substring(1, url.Length - 1);
}
return GetRelativeSiteRoot() + url;
}
return GetRelativeSiteRoot() + "/";
}
public static string GetSiteRoot()
{
string Port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
if (Port == null || Port == "80" || Port == "443")
Port = "";
else
Port = ":" + Port;
string Protocol = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
if (Protocol == null || Protocol == "0")
Protocol = "http://";
else
Protocol = "https://";
string sOut = Protocol + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + Port + HttpContext.Current.Request.ApplicationPath;
return sOut;
}
public static string GetRelativeSiteRoot()
{
return HttpContext.Current.Request.ApplicationPath;
}
public static ILogger GetLogger(Type type)
{
return LoggingProvider.Instance.GetLogger(type);
}
}
| {
"content_hash": "69bfc56222ba41f8c216fc4718653f3f",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 145,
"avg_line_length": 27,
"alnum_prop": 0.5738396624472574,
"repo_name": "smallsharptools/SmallSharpToolsDotNet",
"id": "5aa43cc92f0b49d07f54fa03fc95d59276f059b6",
"size": "2133",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "UrlMapper/Website/App_Code/Utility.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "33761"
},
{
"name": "C",
"bytes": "2067"
},
{
"name": "C#",
"bytes": "1230811"
},
{
"name": "C++",
"bytes": "1582"
},
{
"name": "CSS",
"bytes": "671146"
},
{
"name": "JavaScript",
"bytes": "768547"
},
{
"name": "Shell",
"bytes": "11363"
},
{
"name": "Visual Basic",
"bytes": "60689"
},
{
"name": "XSLT",
"bytes": "3054"
}
],
"symlink_target": ""
} |
int Types::AttributedSum(int A, int B)
{
return A + B;
}
std::string Date::testStdString(std::string s)
{
return s + "_test";
}
void testFreeFunction()
{
} | {
"content_hash": "cca80e59df8bc7f7a2634af1f926162c",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 46,
"avg_line_length": 11.857142857142858,
"alnum_prop": 0.6265060240963856,
"repo_name": "genuinelucifer/CppSharp",
"id": "448d3de8934816a897789c981791466096390a6d",
"size": "184",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tests/CLI/CLI.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "803"
},
{
"name": "C",
"bytes": "608"
},
{
"name": "C#",
"bytes": "6743965"
},
{
"name": "C++",
"bytes": "803224"
},
{
"name": "Lua",
"bytes": "39398"
},
{
"name": "Ruby",
"bytes": "1193"
},
{
"name": "Shell",
"bytes": "1240"
}
],
"symlink_target": ""
} |
package org.semispace.notification;
import java.util.concurrent.atomic.AtomicInteger;
import org.semispace.SemiEventListener;
import org.semispace.SemiEventRegistration;
import org.semispace.event.SemiAvailabilityEvent;
public class ToBeNotified implements SemiEventListener<SemiAvailabilityEvent> {
private AtomicInteger notified = new AtomicInteger();
private boolean toCancelLease;
private SemiEventRegistration lease;
public ToBeNotified(boolean toCancelLease) {
this.toCancelLease = toCancelLease;
}
public int getNotified() {
return this.notified.intValue();
}
/**
* synchronized in order to avoid it being called twice (as it may be removed)
*/
@Override
public void notify(SemiAvailabilityEvent theEvent) {
notified.incrementAndGet();
if (toCancelLease) {
lease.getLease().cancel();
}
}
public void setNotify(SemiEventRegistration lease) {
this.lease = lease;
}
}
| {
"content_hash": "a86ff19a4cf91cd17f6a14a4cf8498aa",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 82,
"avg_line_length": 25.94871794871795,
"alnum_prop": 0.7015810276679841,
"repo_name": "nostra/semispace",
"id": "d045ad8ee4e19eeda6e5bff25833e415ecdcdb7e",
"size": "1960",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "semispace-main/src/test/java/org/semispace/notification/ToBeNotified.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "41625"
},
{
"name": "HTML",
"bytes": "31142"
},
{
"name": "Java",
"bytes": "509785"
},
{
"name": "JavaScript",
"bytes": "527518"
},
{
"name": "Shell",
"bytes": "41916"
}
],
"symlink_target": ""
} |
/* dom/dom.css */
/*
-webkit-user-select: none can cause a major
performance problem in webkit unless mousedown
is prevented.
*/
body {
-webkit-user-select: none;
overflow: hidden;
}
/*
div, object, img, textarea, iframe {
position: relative;
}
.enyo-bbox {
box-sizing: border-box;
-webkit-box-sizing: border-box;
}
*/
.enyo-fit {
position: absolute !important;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
}
/* base/themes/default-theme/css/base-layout.css */
/**/
.enyo-inline {
display: inline-block;
}
/**/
.enyo-grid {
/*overflow: auto;*/
padding: 8px;
}
.enyo-grid-div {
float: left;
width: 64px;
height: 48px;
margin: 4px;
border: 1px solid gray;
box-shadow: 4px 4px 9px #888;
-moz-box-shadow: 4px 4px 9px #888;
-webkit-box-shadow: 4px 4px 9px #888;
}
/* base/themes/default-theme/css/FlexLayout.css */
.enyo-hflexbox, .enyo-vflexbox {
display: -webkit-box;
-webkit-box-sizing: border-box;
}
.enyo-hflexbox {
-webkit-box-orient: horizontal;
}
.enyo-vflexbox {
-webkit-box-orient: vertical;
}
/* base/themes/default-theme/css/HLayout.css */
.enyo-hlayout {
white-space: nowrap;
}
.enyo-hlayout > * {
display: inline-block;
}
/* base/themes/default-theme/css/Box.css */
.enyo-hbox-div, .enyo-vbox-div{
position: absolute !important;
}
/* base/themes/default-theme/css/Drawer.css */
.enyo-drawer {
overflow: hidden;
}
/* base/themes/default-theme/css/FloatingHeader.css */
.enyo-floating-header {
position: absolute;
left: 0;
top: 0;
right: 0;
z-index: 2;
}
/* base/themes/default-theme/css/Iframe.css */
.enyo-iframe {
/*
position: relative;
*/
background-color: white;
width: 100%;
height: 100%;
overflow: auto;
}
/* base/themes/default-theme/css/RichText.css */
.enyo-richtext {
word-wrap: break-word;
cursor: text;
border: none;
outline: none;
overflow: hidden;
}
.enyo-richtext-hint {
color: #A9A9A9;
}
.enyo-richtext {
-webkit-user-select: text;
-webkit-user-modify: read-write;
-webkit-line-break: after-white-space;
}
.enyo-richtext.enyo-richtext-plaintext {
-webkit-user-modify: read-write-plaintext-only;
}
.enyo-richtext.enyo-richtext-disabled, .enyo-richtext.enyo-richtext-plaintext.enyo-richtext-disabled {
-webkit-user-modify: read-only;
color: darkGray;
}
/* base/themes/default-theme/css/Scroller.css */
.enyo-scroller {
overflow: hidden;
position: relative;
}
.enyo-scroller-client {
}
.enyo-scroller-scrollee {
-webkit-box-sizing: border-box;
min-height: 100%;
position: relative;
}
.enyo-scroller-fps {
z-index: 2;
font-size: 9px;
position: absolute;
top: 8px;
right: 8px;
pointer-events: none;
}
/* base/themes/default-theme/css/ScrollFades.css */
.enyo-scrollfades-top,
.enyo-scrollfades-bottom,
.enyo-scrollfades-left,
.enyo-scrollfades-right {
position: absolute;
z-index: 100;
pointer-events: none;
}
.enyo-scrollfades-top {
top: 0;
height: 54px;
width: 100%;
background: url(base/themes/default-theme/images/fade-top.png) top center repeat-x;
}
.enyo-scrollfades-bottom {
bottom: 0;
height: 54px;
width: 100%;
background: url(base/themes/default-theme/images/fade-bottom.png) bottom center repeat-x;
}
.enyo-scrollfades-left {
top: 0;
left: 0;
height: 100%;
width: 54px;
background: url(base/themes/default-theme/images/fade-left.png) left center repeat-y;
}
.enyo-scrollfades-right {
top: 0;
right: 0;
height: 100%;
width: 54px;
background: url(base/themes/default-theme/images/fade-right.png) right center repeat-y;
}
/* base/themes/default-theme/css/VirtualRepeater.css */
.enyo-virtual-repeater-strip {
-webkit-transform-style: preserve-3d;
}
/* base/themes/default-theme/css/PopupLayer.css */
/*
.enyo-popup-layer {
z-index: 1;
pointer-events: none;
}
.enyo-popup-layer > .enyo-popup-float, .enyo-popup-layer > .enyo-popup {
pointer-events: auto;
}
*/
/* base/themes/default-theme/css/Pane.css */
.enyo-pane {
-webkit-box-sizing: border-box;
position: relative;
}
.enyo-view {
position: absolute !important;
left: 0;
top: 0;
right: 0;
height: 100%;
-webkit-box-sizing: border-box;
}
/* palm/controls/image/RotatingImage.css */
@-webkit-keyframes enyo-rotating-image-rotate {
0% { -webkit-transform: rotateZ(0deg);}
100% { -webkit-transform: rotateZ(359deg);}
}
.enyo-rotating-image {
-webkit-animation-name: enyo-rotating-image-rotate;
-webkit-animation-iteration-count: infinite;
-webkit-animation-duration: 1s;
-webkit-animation-timing-function: linear;
overflow: hidden;
/*background: -webkit-gradient(linear, left top, left bottom, from(#00ABEB), to(white), color-stop(0.5, white), color-stop(0.5, #6C0));*/
-webkit-background-origin: padding-box;
-webkit-background-clip: content-box;
}
/* palm/themes/Onyx/css/theme.css */
html {
width: 100%;
position: relative;
}
body {
position: relative;
/* make this color transparent; note only transparent actually removes this color */
-webkit-tap-highlight-color: transparent;
background-color: #d8d8d8;
color: #333;
}
body, html {
margin: 0;
padding: 0;
height: 100%;
}
html, body, input, button {
font-family: Prelude, Prelude Medium, Segoe UI, Arial, Helvetica, Sans-Serif;
font-size: 20px;
cursor: default;
}
.enyo-bg {
background-color: #d8d8d8;
}
.enyo-text-filter-highlight {
background: url(palm/themes/Onyx/images/filter-highlight.png) bottom left repeat-x;
background-size: 1px 4px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-text-filter-highlight {
background-image: url(palm/themes/Onyx/images-1.5/filter-highlight.png);
}
}
.enyo-text-ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.enyo-label {
color: #1879cd;
font-size: .7rem;
text-transform: uppercase;
}
.enyo-text-header {
font-size: 1rem;
}
.enyo-text-subheader {
font-size: .9rem;
}
.enyo-text-body,
.enyo-paragraph,
.enyo-item-secondary {
font-size: .8rem;
}
.enyo-paragraph {
margin: .5em 0;
}
.enyo-item-ternary,
.enyo-subtext {
font-size: .7rem;
color: #828282;
}
.enyo-footnote {
font-size: .8rem;
color: #666;
}
.enyo-text-error {
font-size: .7rem;
color: #d70000;
}
/* Preferences Styles */
.enyo-preferences-box {
width: 500px;
margin: 23px auto 0;
}
.enyo-preference-button {
width: 290px;
}
/* palm/themes/Onyx/css/CheckBox.css */
.enyo-checkbox {
cursor: pointer;
display: inline-block;
vertical-align: middle;
height: 31px;
width: 30px;
margin: 0px;
background: url(palm/themes/Onyx/images/checkbox.png) -1px -1px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-checkbox {
background-image: url(palm/themes/Onyx/images-1.5/checkbox.png);
background-size: 32px 128px;
}
}
.enyo-checkbox-checked {
background-position: -1px -33px;
}
.enyo-checkbox-disabled {
opacity: 0.4;
}
/* palm/themes/Onyx/css/Button.css */
.enyo-button {
/* defeats flex; flex layout could set children to display block */
/*display: inline-block;*/
/*-webkit-box-sizing: border-box;*/
font-size: 16px;
line-height: 20px;
text-align: center;
padding: 4px 8px;
min-width: 14px;
min-height: 20px;
-webkit-border-image: url(palm/themes/Onyx/images/button-up.png) 4 4 4 4 stretch stretch;
border-width: 4px;
border-radius: 5px;
margin: 3px;
color: #292929;
background-color: rgba(255,255,255,0.8);
}
.enyo-button.enyo-button-down, .enyo-button.enyo-button-depressed {
-webkit-border-image: url(palm/themes/Onyx/images/button-down.png) 4 4 4 4 stretch stretch;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-button {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/button-up.png) 6 6 6 6 stretch stretch;
}
.enyo-button.enyo-button-down, .enyo-button.enyo-button-depressed {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/button-down.png) 6 6 6 6 stretch stretch;
}
}
.enyo-button.enyo-button-disabled {
opacity: 0.4;
/*color: rgba(255,254,255,0.4);*/
}
.enyo-button-natural-width {
}
.enyo-button-standard-width {
min-width: 120px;
}
.enyo-button img {
padding: 0px 3px;
}
/* light button (often cancel) */
.enyo-button-light {
background-color: rgba(255,255,255,0.8);
color: #292929;
}
/* dark button */
.enyo-button-dark {
color: white;
background-color: rgba(23,23,23,0.5);
}
/* affirmative (green) */
.enyo-button-affirmative {
color: white;
background-color: #2aa100;
}
/* negative (red) */
.enyo-button-negative {
color: white;
background-color: #be0003;
}
/* blue */
.enyo-button-blue {
color: white;
background-color: #2071bb;
}
/* gray */
.enyo-button-gray {
color: white;
background-color: #4b4b4b;
}
/* notification button */
.enyo-notification-button {
color: white;
background-color: #000;
padding: 6px 10px;
font-weight: bold;
}
/* notification button (affirmative) */
.enyo-notification-button-affirmative {
background-color: #43a200;
}
/* notification button (negative) */
.enyo-notification-button-negative {
background-color: #c01b1e;
}
/* notification button (alternate) */
.enyo-notification-button-alternate {
background-color: #e5b900;
}
/* palm/themes/Onyx/css/ActivityButton.css */
.enyo-activitybutton-spinner {
margin: -6px 0;
}
/* palm/themes/Onyx/css/RadioButton.css */
.enyo-radiogroup {
white-space: nowrap;
cursor: pointer;
margin: 3px 0;
}
.enyo-radiobutton, .enyo-tabbutton {
text-align: center;
-webkit-box-sizing: border-box;
font-size: 16px;
border-width: 0px 16px;
padding: 7px 0 8px 0;
}
.enyo-tabbutton {
font-size: 18px;
padding: 8px 0 9px 0;
margin: -3px 0;
}
.enyo-radiobutton-dark {
color: white;
}
.enyo-radiobutton.enyo-button-disabled {
color: #7f7f7f;
opacity: 0.4;
}
.enyo-radiobutton-dark.enyo-button-disabled,
.enyo-tabbutton.enyo-button-disabled {
color: #666;
opacity: 0.4;
}
.enyo-radiobutton.enyo-button-depressed,
.enyo-radiobutton.enyo-button-down,
.enyo-tabbutton.enyo-button-depressed,
.enyo-tabbutton.enyo-button-down
{
color: white;
}
@media (-webkit-max-device-pixel-ratio:1.49) { /* 1x */
.enyo-radiobutton.enyo-first {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 0 16 556 16;
}
.enyo-radiobutton.enyo-first.enyo-button-depressed,
.enyo-radiobutton.enyo-first.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 37 16 519 16;
}
.enyo-radiobutton.enyo-middle {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 74 16 482 16;
}
.enyo-radiobutton.enyo-middle.enyo-button-depressed,
.enyo-radiobutton.enyo-middle.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 111 16 445 16;
}
.enyo-radiobutton.enyo-last {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 148 16 408 16;
}
.enyo-radiobutton.enyo-last.enyo-button-depressed,
.enyo-radiobutton.enyo-last.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 185 16 371 16;
}
.enyo-radiobutton.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 222 16 334 16;
}
.enyo-radiobutton.enyo-single.enyo-button-depressed,
.enyo-radiobutton.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 259 16 297 16;
}
/* dark */
.enyo-radiobutton-dark.enyo-first {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 296 16 260 16;
}
.enyo-radiobutton-dark.enyo-first.enyo-button-depressed,
.enyo-radiobutton-dark.enyo-first.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 333 16 223 16;
}
.enyo-radiobutton-dark.enyo-middle {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 370 16 186 16;
}
.enyo-radiobutton-dark.enyo-middle.enyo-button-depressed,
.enyo-radiobutton-dark.enyo-middle.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 407 16 149 16;
}
.enyo-radiobutton-dark.enyo-last {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 444 16 112 16;
}
.enyo-radiobutton-dark.enyo-last.enyo-button-depressed,
.enyo-radiobutton-dark.enyo-last.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 481 16 75 16;
}
.enyo-radiobutton-dark.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 518 16 38 16;
}
.enyo-radiobutton-dark.enyo-single.enyo-button-depressed,
.enyo-radiobutton-dark.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 555 16 1 16;
}
/* tabs */
.enyo-tabbutton.enyo-first, .enyo-tabbutton.enyo-middle, .enyo-tabbutton.enyo-last, .enyo-tabbutton.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 74 16 482 16;
}
.enyo-tabbutton.enyo-first.enyo-button-depressed,
.enyo-tabbutton.enyo-first.enyo-button-down,
.enyo-tabbutton.enyo-middle.enyo-button-depressed,
.enyo-tabbutton.enyo-middle.enyo-button-down,
.enyo-tabbutton.enyo-last.enyo-button-depressed,
.enyo-tabbutton.enyo-last.enyo-button-down,
.enyo-tabbutton.enyo-single.enyo-button-depressed,
.enyo-tabbutton.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 111 16 445 16;
}
}
.enyo-tabbutton.enyo-first.enyo-button-disabled,
.enyo-tabbutton.enyo-middle.enyo-button-disabled,
.enyo-tabbutton.enyo-last.enyo-button-disabled,
.enyo-tabbutton.enyo-single.enyo-button-disabled {
opacity: 0.4;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-radiobutton.enyo-first {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 0 16 834 16;
}
.enyo-radiobutton.enyo-first.enyo-button-depressed,
.enyo-radiobutton.enyo-first.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 55 16 779 16;
}
.enyo-radiobutton.enyo-middle {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 110 16 724 16;
}
.enyo-radiobutton.enyo-middle.enyo-button-depressed,
.enyo-radiobutton.enyo-middle.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 165 16 669 16;
}
.enyo-radiobutton.enyo-last {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 220 16 614 16;
}
.enyo-radiobutton.enyo-last.enyo-button-depressed,
.enyo-radiobutton.enyo-last.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 275 16 559 16;
}
.enyo-radiobutton.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 330 16 504 16;
}
.enyo-radiobutton.enyo-single.enyo-button-depressed,
.enyo-radiobutton.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 385 16 449 16;
}
/* dark */
.enyo-radiobutton-dark.enyo-first {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 440 16 394 16;
}
.enyo-radiobutton-dark.enyo-first.enyo-button-depressed,
.enyo-radiobutton-dark.enyo-first.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 495 16 339 16;
}
.enyo-radiobutton-dark.enyo-middle {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 550 16 284 16;
}
.enyo-radiobutton-dark.enyo-middle.enyo-button-depressed,
.enyo-radiobutton-dark.enyo-middle.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 605 16 229 16;
}
.enyo-radiobutton-dark.enyo-last {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 660 16 174 16;
}
.enyo-radiobutton-dark.enyo-last.enyo-button-depressed,
.enyo-radiobutton-dark.enyo-last.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 715 16 119 16;
}
.enyo-radiobutton-dark.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 770 16 64 16;
}
.enyo-radiobutton-dark.enyo-single.enyo-button-depressed,
.enyo-radiobutton-dark.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 825 16 9 16;
}
/* tabs */
.enyo-tabbutton.enyo-first, .enyo-tabbutton.enyo-middle, .enyo-tabbutton.enyo-last, .enyo-tabbutton.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 110 16 724 16;
}
.enyo-tabbutton.enyo-first.enyo-button-depressed,
.enyo-tabbutton.enyo-first.enyo-button-down,
.enyo-tabbutton.enyo-middle.enyo-button-depressed,
.enyo-tabbutton.enyo-middle.enyo-button-down,
.enyo-tabbutton.enyo-last.enyo-button-depressed,
.enyo-tabbutton.enyo-last.enyo-button-down,
.enyo-tabbutton.enyo-single.enyo-button-depressed,
.enyo-tabbutton.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 165 16 669 16;
}
}
/* palm/themes/Onyx/css/GroupedToolButton.css */
.enyo-grouped-toolbutton {
text-align: center;
-webkit-box-sizing: border-box;
font-size: 16px;
border-width: 0px 16px;
padding: 7px 0 8px 0;
color: #332;
}
.enyo-grouped-toolbutton-dark {
color: white;
}
.enyo-grouped-toolbutton.enyo-button-disabled {
color: white;
opacity: 0.4;
}
.enyo-grouped-toolbutton-dark.enyo-button-disabled {
color: #666;
opacity: 0.4;
}
.enyo-grouped-toolbutton.enyo-button-depressed, .enyo-grouped-toolbutton.enyo-button-down {
color: white;
}
@media (-webkit-max-device-pixel-ratio:1.49) { /* 1x */
.enyo-grouped-toolbutton.enyo-first {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 0 16 556 16;
}
.enyo-grouped-toolbutton.enyo-first.enyo-button-depressed,
.enyo-grouped-toolbutton.enyo-first.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 37 16 519 16;
}
.enyo-grouped-toolbutton.enyo-middle {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 74 16 482 16;
}
.enyo-grouped-toolbutton.enyo-middle.enyo-button-depressed,
.enyo-grouped-toolbutton.enyo-middle.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 111 16 445 16;
}
.enyo-grouped-toolbutton.enyo-last {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 148 16 408 16;
}
.enyo-grouped-toolbutton.enyo-last.enyo-button-depressed,
.enyo-grouped-toolbutton.enyo-last.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 185 16 371 16;
}
.enyo-grouped-toolbutton.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 222 16 334 16;
}
.enyo-grouped-toolbutton.enyo-single.enyo-button-depressed,
.enyo-grouped-toolbutton.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 259 16 297 16;
}
/* dark */
.enyo-grouped-toolbutton-dark.enyo-first {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 296 16 260 16;
}
.enyo-grouped-toolbutton-dark.enyo-first.enyo-button-depressed,
.enyo-grouped-toolbutton-dark.enyo-first.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 333 16 223 16;
}
.enyo-grouped-toolbutton-dark.enyo-middle {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 370 16 186 16;
}
.enyo-grouped-toolbutton-dark.enyo-middle.enyo-button-depressed,
.enyo-grouped-toolbutton-dark.enyo-middle.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 407 16 149 16;
}
.enyo-grouped-toolbutton-dark.enyo-last {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 444 16 112 16;
}
.enyo-grouped-toolbutton-dark.enyo-last.enyo-button-depressed,
.enyo-grouped-toolbutton-dark.enyo-last.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 481 16 75 16;
}
.enyo-grouped-toolbutton-dark.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 518 16 38 16;
}
.enyo-grouped-toolbutton-dark.enyo-single.enyo-button-depressed,
.enyo-grouped-toolbutton-dark.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/radiobutton.png) 555 16 1 16;
}
}
@media (-webkit-min-device-pixel-ratio:1.5) { /* 1.5x */
.enyo-grouped-toolbutton.enyo-first {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 0 16 834 16;
}
.enyo-grouped-toolbutton.enyo-first.enyo-button-depressed,
.enyo-grouped-toolbutton.enyo-first.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 55 16 779 16;
}
.enyo-grouped-toolbutton.enyo-middle {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 110 16 724 16;
}
.enyo-grouped-toolbutton.enyo-middle.enyo-button-depressed,
.enyo-grouped-toolbutton.enyo-middle.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 165 16 669 16;
}
.enyo-grouped-toolbutton.enyo-last {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 220 16 614 16;
}
.enyo-grouped-toolbutton.enyo-last.enyo-button-depressed,
.enyo-grouped-toolbutton.enyo-last.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 275 16 559 16;
}
.enyo-grouped-toolbutton.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 330 16 504 16;
}
.enyo-grouped-toolbutton.enyo-single.enyo-button-depressed,
.enyo-grouped-toolbutton.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 385 16 449 16;
}
/* dark */
.enyo-grouped-toolbutton-dark.enyo-first {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 440 16 394 16;
}
.enyo-grouped-toolbutton-dark.enyo-first.enyo-button-depressed,
.enyo-grouped-toolbutton-dark.enyo-first.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 495 16 339 16;
}
.enyo-grouped-toolbutton-dark.enyo-middle {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 550 16 284 16;
}
.enyo-grouped-toolbutton-dark.enyo-middle.enyo-button-depressed,
.enyo-grouped-toolbutton-dark.enyo-middle.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 605 16 229 16;
}
.enyo-grouped-toolbutton-dark.enyo-last {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 660 16 174 16;
}
.enyo-grouped-toolbutton-dark.enyo-last.enyo-button-depressed,
.enyo-grouped-toolbutton-dark.enyo-last.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 715 16 119 16;
}
.enyo-grouped-toolbutton-dark.enyo-single {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 770 16 64 16;
}
.enyo-grouped-toolbutton-dark.enyo-single.enyo-button-depressed,
.enyo-grouped-toolbutton-dark.enyo-single.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/radiobutton.png) 825 16 9 16;
}
}
/* palm/themes/Onyx/css/GrabButton.css */
.enyo-grabbutton {
background-image: url(palm/themes/Onyx/images/grabbutton.png);
background-size: 46px 54px;
width: 46px;
height: 54px;
position: absolute;
left: 0;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-grabbutton {
background-image: url(palm/themes/Onyx/images-1.5/grabbutton.png);
}
}
/* palm/themes/Onyx/css/IconButton.css */
.enyo-button-icon {
display: inline-block;
vertical-align: baseline;
width: 32px;
height: 32px;
/* background-size: 32px 64px;*/
margin: -6px -6px -10px -6px;
}
.enyo-button-down .enyo-button-icon {
background-position: 0 -32px;
}
/* palm/themes/Onyx/css/ToolButton.css */
.enyo-tool-button {
cursor: pointer;
padding: 5px;
}
.enyo-tool-button-client {
font-size: 16px;
line-height: 20px;
text-align: center;
cursor: pointer;
border-width: 4px;
border-radius: 5px;
border-style: solid;
border-color: transparent;
min-width: 14px;
min-height: 20px;
margin: 3px;
color: #f2f2f2;
}
.enyo-tool-button-client > .enyo-button-icon {
margin: -2px -2px -6px;
}
.enyo-tool-button-client.enyo-tool-button-captioned {
padding: 4px 8px;
border-style: none;
-webkit-border-image: url(palm/themes/Onyx/images/button-toolbar.png) 4 4 4 4 stretch stretch;
}
.enyo-tool-button-client.enyo-tool-button-captioned.enyo-button-down, .enyo-tool-button-client.enyo-button-depressed {
-webkit-border-image: url(palm/themes/Onyx/images/button-down.png) 4 4 4 4 stretch stretch;
}
.enyo-tool-button-client.enyo-button-depressed {
/*background-color: #2071bb;*/
}
.enyo-tool-button-client.enyo-button-disabled {
opacity: 0.4;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-tool-button-client.enyo-tool-button-captioned.enyo-button-down, .enyo-tool-button-client.enyo-button-depressed {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/button-down.png) 6 6 6 6 stretch stretch;
}
.enyo-tool-button-client.enyo-tool-button-captioned {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/button-toolbar.png) 6 6 6 6 stretch stretch;
}
}
/* palm/themes/Onyx/css/Scrim.css */
.enyo-scrim {
position: fixed;
top: 0px;
right: 0px;
left: 0px;
bottom: 0px;
opacity: 0;
z-index: 100;
background: black;
-webkit-transition-property: opacity;
-webkit-transition-duration: 0.5s;
}
.enyo-scrim.enyo-scrim-dim {
opacity: 0.65;
}
.enyo-scrim.enyo-scrim-transparent {
background: transparent;
opacity: 1;
}
/* palm/themes/Onyx/css/Popup.css */
.enyo-popup {
min-width: 300px;
z-index: 120;
/* Causes rendering artifacts */
/*position: fixed;*/
position: absolute;
left: 0px;
top: 0px;
-webkit-box-sizing: border-box;
border-width: 24px;
-webkit-border-image: url(palm/themes/Onyx/images/popup.png) 24 24 24 24 stretch stretch;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-popup {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/popup.png) 36 36 36 36 stretch stretch;
}
}
.enyo-popup-inner {
margin: -7px -14px;
/* NOTE: experimental use of css clipping to solve highlights not overflowing curved corners */
/* does not work on pre/emulator as of build 3455. */
/*-webkit-mask-box-image: url(palm/themes/Onyx/images/popup-mask.png) 10 10 10 10 stretch stretch;*/
}
/* palm/themes/Onyx/css/Menu.css */
.enyo-popup.enyo-popup-menu {
min-width: inherit;
border-width: 20px;
-webkit-border-image: url(palm/themes/Onyx/images/menu-background.png) 20 20 20 20 stretch stretch;
/* FIXME: consider when works more reliably */
/*
-webkit-transition-property: opacity, -webkit-tranform;
-webkit-transition-duration: 0.25s, 0.25s;
-webkit-transform: scale(0);
-webkit-transform-origin: 50% 0;
opacity: 0;
*/
}
/*
.enyo-popup.enyo-menu-open {
-webkit-transform: scale(1);
opacity: 1;
}
*/
.enyo-menu-inner {
margin: -3px -14px;
}
.enyo-menu-scroll-fades {
pointer-events: none;
}
.enyo-menu-top-fade,
.enyo-menu-bottom-fade {
position: absolute;
pointer-events: none;
}
.enyo-menu-top-fade {
top: -10px;
height: 10px;
width: 100%;
background: url(palm/themes/Onyx/images/menu-fade-arrow-up.png) top center no-repeat no-repeat;
}
.enyo-menu-bottom-fade {
bottom: -11px;
height: 10px;
width: 100%;
background: url(palm/themes/Onyx/images/menu-fade-arrow-down.png) bottom center no-repeat no-repeat;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-menu-top-fade {
background-image: url(palm/themes/Onyx/images-1.5/menu-fade-arrow-up.png);
background-size: 8px 8px;
}
.enyo-menu-bottom-fade {
background-image: url(palm/themes/Onyx/images-1.5/menu-fade-arrow-down.png);
background-size: 8px 8px;
}
.enyo-popup.enyo-popup-menu {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/menu-background.png) 30 30 30 30 stretch stretch;
}
}
/* palm/themes/Onyx/css/Item.css */
.enyo-item {
border-top: 1px solid rgba(255,255,255,0.5);
border-bottom: 1px solid rgba(0,0,0,0.2);
padding: 10px;
font-size: .9rem;
}
.enyo-held {
/*background-color: gray;*/
/* fancy... can we get away with this or do we need to use images? */
background: -webkit-gradient(linear, left top, left bottom, from(rgba(218,235,251,0.4)), to(rgba(197,224,249,0.4)));
}
.enyo-item-selected {
background: -webkit-gradient(linear, left top, left bottom, from(rgba(218,235,251,0.4)), to(rgba(197,224,249,0.4)));
}
.enyo-disabled {
opacity: 0.5;
}
.enyo-item.enyo-first {
border-top: 0;
}
.enyo-item.enyo-last {
border-bottom: 0;
}
.enyo-item.enyo-single {
/*
due to webos webkit bug, must have a non-zero border when -webkit-gradient
and border-radius are used together or else the border radius will be ignored.
*/
/* border: 0;*/
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
}
.enyo-group-inner > .enyo-item, .enyo-item.rounded {
-webkit-border-radius: 8px;
}
.enyo-group-inner > .enyo-item.enyo-first, .enyo-item.rounded.enyo-first {
-webkit-border-bottom-right-radius: 0;
-webkit-border-bottom-left-radius: 0;
}
.enyo-group-inner > .enyo-item.enyo-middle, .enyo-item.rounded.enyo-middle {
-webkit-border-radius: 0;
}
.enyo-group-inner > .enyo-item.enyo-last, .enyo-item.rounded.enyo-last {
-webkit-border-top-right-radius: 0;
-webkit-border-top-left-radius: 0;
}
/* palm/themes/Onyx/css/MenuItem.css */
.enyo-menuitem {
}
.enyo-menuitem-caption {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
font-size: 16px;
line-height: 22px;
}
.enyo-menuitem-icon {
padding: 2px 8px;
}
.enyo-menuitem-arrow.enyo-button-depressed,
.enyo-menuitem-arrow.enyo-button-down {
background-position: 0px -24px;
}
.enyo-menuitem-arrow {
height: 24px;
width: 30px;
background: url(palm/themes/Onyx/images/menuitem-arrow.png) center 0px;
margin-right: -5px;
}
.enyo-menuitem.enyo-checked.enyo-menucheckitem-caption, .enyo-menuitem.enyo-checked .enyo-menucheckitem-caption {
background: url(palm/themes/Onyx/images/checkmark.png) center right no-repeat;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-menuitem-arrow {
background-image: url(palm/themes/Onyx/images-1.5/menuitem-arrow.png);
background-size: 24px 48px;
}
.enyo-menuitem.enyo-checked.enyo-menucheckitem-caption, .enyo-menuitem.enyo-checked .enyo-menucheckitem-caption {
background-image: url(palm/themes/Onyx/images-1.5/checkmark.png);
background-size: 32px;
}
}
.enyo-menucheckitem-caption {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
font-size: 16px;
line-height: 22px;
padding-right: 34px;
}
/* palm/themes/Onyx/css/EditMenuItem.css */
/* palm/themes/Onyx/css/AppMenu.css */
.enyo-popup.enyo-appmenu {
z-index: 120;
position: fixed;
font-size: 18px;
border-width: 12px 24px 20px 24px;
-webkit-border-image: url(palm/themes/Onyx/images/appmenu.png) 12 24 20 24 stretch stretch;
color: white;
top: 0px;
left: -10px;
min-width: 210px;
/* FIXME: consider when works more reliably */
/*
-webkit-transition-property: opacity, -webkit-tranform;
-webkit-transition-duration: 0.5s, 0.5s;
-webkit-transform: translateY(-100%);
*/
}
/*
.enyo-appmenu.enyo-menu-open {
-webkit-transform: translateY(0%);
opacity: 1;
}
*/
.enyo-appmenu-inner {
margin: -12px -14px 0 -13px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-popup.enyo-appmenu {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/appmenu.png) 18 36 30 36 stretch stretch;
}
}
/* palm/themes/Onyx/css/AppMenuItem.css */
.enyo-appmenu-item.enyo-item {
-webkit-border-image: url(palm/themes/Onyx/images/appmenu-divider.png) 0 0 2 0 stretch;
color: white;
border-bottom: 2px;
padding: 10px 7px 10px 5px;
font-size: 18px;
}
.enyo-appmenu-item.enyo-held {
background-image: url(palm/themes/Onyx/images/appmenu-highlight.png);
background-size: 40px 56px;
}
.enyo-appmenu-item.enyo-item.enyo-menu-last {
border-bottom: 0;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-appmenu-item.enyo-item {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/appmenu-divider.png) 0 0 3 0 stretch;
}
.enyo-appmenu-item.enyo-held {
background-image: url(palm/themes/Onyx/images-1.5/appmenu-highlight.png);
}
}
/* palm/themes/Onyx/css/Divider.css */
.enyo-divider,
.enyo-divider-right-cap,
.enyo-divider-left-cap {
height: 4px;
margin: 13px 0px;
}
.enyo-divider {
background: url(palm/themes/Onyx/images/divider.png) left top repeat-x;
background-size: 6px 4px;
}
.enyo-divider-right-cap {
border-right-width: 0px;
margin-right: 7px;
}
.enyo-divider-left-cap {
min-width: 3px;
border-width: 0px;
background: url(palm/themes/Onyx/images/divider.png) left top repeat-x;
background-size: 6px 4px;
margin-left: 6px;
/* Needs to be effectively infinity compared to .enyo-divider-caption's
flex so the left cap will take as much space as possible */
-webkit-box-flex: 1000;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-divider,
.enyo-divider-left-cap {
background-image: url(palm/themes/Onyx/images-1.5/divider.png);
}
}
.enyo-divider-icon {
margin: 0 6px;
}
.enyo-divider-icon-collapse {
margin: 0 6px 0 0;
}
.enyo-divider-caption {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: bold;
font-size: 12pt;
color: #3a8bcb;
/* Needs to be effectively zero compared to .enyo-divider-left-cap's
flex so the caption will flex but take as little space as possible
and still truncate properly */
-webkit-box-flex: .1;
}
.enyo-divider-alpha {
background: url(palm/themes/Onyx/images/divider.png) left center repeat-x;
background-size: 6px 4px;
height: 30px;
line-height: 30px;
margin: 0 0 0 30px;
}
.enyo-divider-alpha-caption {
margin-left: -23px;
font-size: 12pt;
font-weight: bold;
color: #4299ea;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-divider-alpha {
background-image: url(palm/themes/Onyx/images-1.5/divider.png);
}
}
/* palm/themes/Onyx/css/DividerDrawer.css */
.enyo-collapsible-arrow {
height: 40px;
width: 50px;
background: url(palm/themes/Onyx/images/divider-arrow.png) center -80px;
background-size: 50px 160px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-collapsible-arrow {
background-image: url(palm/themes/Onyx/images-1.5/divider-arrow.png);
}
}
.enyo-button-switched.enyo-collapsible-arrow {
background-position: center 0px;
}
.enyo-button-down.enyo-button-switched.enyo-collapsible-arrow {
background-position: center -40px;
}
.enyo-button-down.enyo-collapsible-arrow {
background-position: center -120px;
}
/* palm/themes/Onyx/css/ProgressBar.css */
.enyo-progress-bar {
height: 12px;
border-width: 0 4px;
-webkit-border-image: url(palm/themes/Onyx/images/progress-bar.png) 0 4 0 4 repeat repeat;
-webkit-box-sizing: border-box;
position:relative;
}
.enyo-progress-bar-inner {
margin: 0 -5px;
height: 12px;
border-width: 0 4px;
position: absolute;
z-index:10; /* for progressSlider altBarPosition */
-webkit-border-image: url(palm/themes/Onyx/images/progress-bar-inner.png) 0 4 0 4 repeat repeat;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-progress-bar {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/progress-bar.png) 0 6 0 6 stretch stretch;
}
.enyo-progress-bar-inner {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/progress-bar-inner.png) 0 6 0 6 stretch stretch;
}
}
/* palm/themes/Onyx/css/ProgressBarItem.css */
.enyo-progress-bar-item {
min-height: 24px;
border-width: 12px 0px;
-webkit-border-image: url(palm/themes/Onyx/images/progress-item.png) 12 0 12 0 repeat repeat;
-webkit-box-sizing: border-box;
position:relative;
}
.enyo-progress-bar-item-inner {
margin: -12px 0px;
padding: 12px 0px;
height:100%;
border-width: 0 8px 0 0;
position:absolute;
-webkit-border-image: url(palm/themes/Onyx/images/progress-item-inner.png) 0 8 0 0 repeat stretch;
}
.enyo-progress-bar-item-client {
margin: -12px 0px;
position:relative;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-progress-bar-item {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/progress-item.png) 18 0 18 0 stretch repeat;
}
.enyo-progress-bar-item-inner {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/progress-item-inner.png) 0 12 0 0 repeat stretch;
}
}
/* palm/themes/Onyx/css/ProgressButton.css */
.enyo-progress-button {
min-height: 34px;
border-width: 4px;
border-radius: 5px;
-webkit-border-image: url(palm/themes/Onyx/images/button-down.png) 4 4 4 4 stretch stretch;
color: white;
background-color: rgba(23,23,23,0.5);
margin: 3px;
position:relative;
font-size: 18px;
line-height: 34px;
}
.enyo-progress-button-inner {
margin: -4px;
top: 0;
bottom: 0;
border-width: 4px;
border-radius: 5px;
position: absolute;
-webkit-border-image: url(palm/themes/Onyx/images/button.png) 4 4 4 4 stretch stretch;
}
.enyo-progress-button-client {
margin: 0 5px;
position:relative;
}
.enyo-progress-button-cancel {
position:relative;
width:32px;
height:32px;
margin-right:2px;
margin-top:2px;
background-image: url(palm/themes/Onyx/images/progress-button-cancel.png);
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-progress-button {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/button-down.png) 6 6 6 6 stretch stretch;
}
.enyo-progress-button-inner {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/button.png) 6 6 6 6 stretch stretch;
}
.enyo-progress-button-cancel {
background-image: url(palm/themes/Onyx/images-1.5/progress-button-cancel.png);
background-size: 32px 64px;
}
}
.enyo-progress-button-cancel:active {
background-position: 0 -32px;
}
.enyo-progress-button.affirmative > .enyo-progress-button-inner {
color: white;
background-color: #2aa100;
}
.enyo-progress-button.negative > .enyo-progress-button-inner {
color: white;
background-color: #be0003;
}
.enyo-progress-button.light > .enyo-progress-button-inner {
background-color: rgba(255,255,255,0.8);
color: #292929;
}
.enyo-progress-button.dark > .enyo-progress-button-inner {
color: white;
background-color: rgba(23,23,23,0.5);
}
.enyo-progress-button.blue > .enyo-progress-button-inner {
color: white;
background-color: #2071bb;
}
/* palm/themes/Onyx/css/ProgressSlider.css */
.enyo-progress-slider {
height: 10px;
border-width: 0 4px;
-webkit-border-image: url(palm/themes/Onyx/images/slider-track.png) 0 4 0 4 repeat repeat;
-webkit-box-sizing: border-box;
position:relative;
}
.enyo-progress-slider-alt-bar, .enyo-progress-slider > .enyo-progress-bar-inner {
height: 10px;
border-width: 0 4px;
margin: 0 -4px;
position: absolute;
-webkit-border-image: url(palm/themes/Onyx/images/slider-progress.png) 0 4 0 4 repeat repeat;
}
.enyo-progress-slider-alt-bar {
z-index:5; /* under primary progress */
-webkit-border-image: url(palm/themes/Onyx/images/slider-progress-secondary.png) 0 4 0 4 repeat repeat;
-webkit-transition: width 0.3s ease;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-progress-slider {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/slider-track.png) 0 6 0 6 repeat stretch;
}
.enyo-progress-slider > .enyo-progress-bar-inner {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/slider-progress.png) 0 6 0 6 repeat stretch;
}
.enyo-progress-slider-alt-bar {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/slider-progress-secondary.png) 0 6 0 6 repeat stretch;
}
}
/* palm/themes/Onyx/css/Slider.css */
.enyo-slider-button {
height: 40px;
width: 40px;
z-index: 50;
background: url(palm/themes/Onyx/images/slider-handle.png) left top no-repeat;
position: absolute;
margin: -14px -20px;
}
.enyo-slider-button.enyo-button-down {
background-position-y: -40px;
}
.enyo-slider {
/*
FIXME: why in the heck does this work to properly position the progress
div inside this one?
*/
padding: 1px 0;
position:relative;
}
.enyo-slider-progress {
height: 10px;
border-width: 0px 4px;
-webkit-border-image: url(palm/themes/Onyx/images/slider-track.png) 0 4 0 4 repeat repeat;
margin: 20px 0px;
position:relative;
}
.enyo-slider-inner {
margin: 0 -4px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-slider-button {
background-image: url(palm/themes/Onyx/images-1.5/slider-handle.png);
background-size: 40px 80px;
}
.enyo-slider-progress {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/slider-track.png) 0 6 0 6 repeat stretch;
}
}
/* palm/themes/Onyx/css/Header.css */
.enyo-header {
-webkit-border-image: url(palm/themes/Onyx/images/header.png) 2 0;
-webkit-box-sizing: border-box;
min-height: 50px;
border-width: 2px 0;
background-color: #ccc;
color: #444;
/*
Note: shadow is problematic if we support background colors.
Afaict, has to be done with a separate div or webkit-box-shadow; (unsupported on device)
*/
/*
-webkit-box-shadow: 0 0 4px #888;
*/
}
.enyo-header.enyo-header-dark {
-webkit-border-image: url(palm/themes/Onyx/images/toolbar.png) 2 4 repeat stretch;
border-width: 2px 0;
background-color: #343434;
color: #fff;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-header {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/header.png) 3 0;
}
.enyo-header.enyo-header-dark {
-webkit-border-image: url(palm/themes/Onyx/images/toolbar.png) 3 6 repeat stretch;
}
}
.enyo-header-inner {
padding: 13px 12px;
min-height: 52px;
}
.enyo-header-icon {
padding-right: 10px;
}
/* palm/themes/Onyx/css/Toolbar.css */
.enyo-toolbar {
/* needed to host a GrabButton, which is position: absolute */
position: relative;
min-height: 54px;
-webkit-box-sizing: border-box;
-webkit-border-image: url(palm/themes/Onyx/images/toolbar.png) 2 4 repeat stretch;
border-width: 2px 4px;
background-color: #343434;
}
.enyo-toolbar-light {
-webkit-border-image: url(palm/themes/Onyx/images/toolbar-light.png) 2 4 repeat stretch;
background-color: #a9a9a9;
}
.enyo-toolbar-snap-out {
opacity: 0;
}
.enyo-toolbar-fade-in {
-webkit-transition: opacity 0.15s linear;
opacity: 1;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-toolbar {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/toolbar.png) 3 6 repeat stretch;
}
.enyo-toolbar-light {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/toolbar-light.png) 3 6 repeat stretch;
}
}
/* palm/themes/Onyx/css/ConfirmPrompt.css */
.enyo-confirmprompt {
position: relative;
}
.enyo-confirmprompt-scrim {
-webkit-border-image: url(palm/themes/Onyx/images/confirmprompt-background.png) 20 0 repeat;
-webkit-box-sizing: border-box;
border-width: 20px 0px;
background-color: #fff;
}
.enyo-confirmprompt-button {
margin: 0 10px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-confirmprompt-scrim {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/confirmprompt-background.png) 30 0 stretch;
}
}
/* palm/themes/Onyx/css/SwipeableItem.css */
.enyo-swipeableitem {
/*position: relative;*/
min-height: 44px;
padding: 8px 14px;
}
/* palm/themes/Onyx/css/ToggleButton.css */
.enyo-item > .enyo-toggle-button {
margin: -10px;
}
.enyo-toggle-button {
padding: 10px;
}
.enyo-toggle-button-bar {
min-width: 36px;
height: 30px;
line-height: 26px;
display: inline-block;
vertical-align: middle;
text-align: center;
}
.enyo-toggle-button-bar.on {
border-width: 0px 30px 0px 8px;
-webkit-border-image: url(palm/themes/Onyx/images/toggle-button.png) 1 30 97 8 repeat repeat;
}
.enyo-toggle-button-bar.off {
border-width: 0px 8px 0px 30px;
-webkit-border-image: url(palm/themes/Onyx/images/toggle-button.png) 33 8 65 30 repeat repeat;
}
.enyo-toggle-button-bar.disabled.on {
border-width: 0px 30px 0px 8px;
-webkit-border-image: url(palm/themes/Onyx/images/toggle-button.png) 65 30 33 8 repeat repeat;
}
.enyo-toggle-button-bar.disabled.off {
border-width: 0px 8px 0px 30px;
-webkit-border-image: url(palm/themes/Onyx/images/toggle-button.png) 97 8 1 30 repeat repeat;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-toggle-button-bar.on {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/toggle-button.png) 2 45 145 12 stretch stretch;
}
.enyo-toggle-button-bar.off {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/toggle-button.png) 50 12 97 45 stretch stretch;
}
.enyo-toggle-button-bar.disabled.on {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/toggle-button.png) 98 45 49 12 stretch stretch;
}
.enyo-toggle-button-bar.disabled.off {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/toggle-button.png) 146 12 1 45 stretch stretch;
}
}
.enyo-toggle-label-off, .enyo-toggle-label-on {
color: white;
font-size: 14px;
font-weight: bold;
}
.enyo-toggle-label-off {
padding-left: 4px;
padding-right: 2px;
text-transform: uppercase;
}
.enyo-toggle-label-on {
padding-right: 4px;
padding-left: 2px;
text-transform: uppercase;
}
.enyo-tool-button.enyo-button-disabled {
opacity: 0.4;
/*color: rgba(255,254,255,0.4);*/
}
/* palm/themes/Onyx/css/PopupSelect.css */
.enyo-popupselect {
/*border-width: 19px;
-webkit-border-image: url(palm/themes/Onyx/images/popupselect-background.png) 23 23 23 23 stretch stretch;*/
}
/* palm/themes/Onyx/css/ListSelector.css */
.enyo-listselector-arrow {
min-height: 34px;
width: 14px;
background: url(palm/themes/Onyx/images/menu-arrow.png) center right no-repeat;
background-size: 14px 10px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-listselector-arrow {
background-image: url(palm/themes/Onyx/images-1.5/menu-arrow.png);
}
}
.enyo-listselector-label {
margin: 1px 6px 0px 6px;
line-height: 34px;
font-size: 14px;
white-space: nowrap;
}
.enyo-listselector-item {
border: 0;
padding: 0;
}
.enyo-listselector-item > .enyo-menucheckitem-caption {
padding-right: 2px;
}
.enyo-item > .enyo-listselector {
margin: -10px 0;
padding: 10px 0;
}
/* palm/themes/Onyx/css/PickerButton.css */
.enyo-picker-button {
-webkit-border-image: url(palm/themes/Onyx/images/picker-pill.png) 10;
border-width: 10px;
font-size: 16px;
line-height: 32px;
}
.enyo-picker-button-caption {
padding: 0 6px;
min-width: 24px;
text-align: center;
}
.enyo-picker-button.enyo-button {
-webkit-border-image: url(palm/themes/Onyx/images/picker-pill.png) 10;
}
.enyo-picker-button.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images/picker-pill-downstate.png) 10;
}
.enyo-picker-button.enyo-button-focus {
-webkit-border-image: url(palm/themes/Onyx/images/picker-pill-focus.png) 10;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-picker-button {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/picker-pill.png) 15;
}
.enyo-picker-button.enyo-button-down {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/picker-pill-downstate.png) 15;
}
.enyo-picker-button.enyo-button-focus {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/picker-pill-focus.png) 15;
}
}
/* palm/themes/Onyx/css/Picker.css */
.enyo-picker-label {
line-height: 52px;
padding-right: 5px;
font-size: 18px;
}
.enyo-picker-popup {
}
.enyo-picker-item-selected {
font-weight: bold;
background: #fff;
}
/* palm/themes/Onyx/css/PickerGroup.css */
.enyo-pickergroup-above-scrim {
z-index: 110;
}
.enyo-pickergroup-pickerpopup {
border-width: 0;
-webkit-border-image: none;
min-width: 0px;
}
/* palm/themes/Onyx/css/Group.css */
.enyo-group {
border-width: 14px 14px 14px 14px;
-webkit-border-image: url(palm/themes/Onyx/images/group-unlabeled.png) 14 14 repeat repeat;
margin: 8px 3px;
}
.enyo-group-inner {
margin: -12px;
}
.enyo-row {
border-bottom: 1px solid gray;
}
.enyo-group.labeled {
border-width: 36px 14px 14px 14px;
-webkit-border-image: url(palm/themes/Onyx/images/group-labeled.png) 36 14 14 14 repeat repeat;
margin: 8px 3px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-group {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/group-unlabeled.png) 21 21 stretch stretch;
}
.enyo-group.labeled {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/group-labeled.png) 54 21 21 21 stretch stretch;
}
}
.enyo-group-label {
margin: -34px -12px;
padding: 4px 0 12px 10px;
font-size: .7rem;
color: #fff;
text-shadow: #646454 0 1px 0;
font-weight: bold;
height: 44px;
text-transform: uppercase;
}
.enyo-group-label.enyo-group-fit {
margin-bottom: -21px;
}
/* palm/themes/Onyx/css/RoundedInput.css */
.enyo-input.enyo-rounded-input, .enyo-input.enyo-rounded-input.enyo-input-focus {
border-width: 6px 20px;
-webkit-box-sizing: border-box;
-webkit-border-image: url(palm/themes/Onyx/images/roundedbox.png) 6 20;
margin: 2px 0;
font-size: .8rem;
}
.enyo-input.enyo-rounded-input > .enyo-input-spacing {
margin: -1px -10px 0 -10px;
min-height: 26px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-input.enyo-rounded-input, .enyo-input.enyo-rounded-input.enyo-input-focus {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/roundedbox.png) 9 30;
}
}
/* palm/themes/Onyx/css/Input.css */
.enyo-input {
border-width: 14px;
border-style: solid;
border-color: transparent;
-webkit-box-sizing: border-box;
font-size: .9rem;
}
.enyo-input.enyo-input-focus {
-webkit-border-image: url(palm/themes/Onyx/images/input-focus.png) 14 14;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-input.enyo-input-focus {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/input-focus.png) 21 21;
}
}
.enyo-input > .enyo-input-spacing {
margin: -2px -4px;
}
.enyo-input-input {
display: block;
border: none;
margin: 0;
outline: none;
background-color: transparent;
padding: 0;
width: 100%;
-webkit-appearance: caret;
-webkit-box-sizing: border-box;
cursor: pointer;
font-size: .9rem;
}
input::-webkit-input-placeholder, isindex::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
color: #888;
}
.enyo-input-disabled {
/*color: darkGray;*/
/* HACK: this is needed to color a disabled input placeholder.
* Also works for filled inputs as well thankfully */
-webkit-text-fill-color: #888;
opacity: 0.625;
}
.enyo-input-input:focus {
cursor: text;
}
/*
FIXME: we almost always want some padding on a enyo-item, except when it's surrounding
a fancy-input.... so we special case that here, non-ideal
*/
.enyo-item > .enyo-input {
margin: -11px -10px;
}
/* Row styling for inputs */
.enyo-first.enyo-input.enyo-input-focus, .enyo-first > .enyo-input.enyo-input-focus {
padding-bottom: 12px;
border-width: 14px 14px 2px 14px;
-webkit-border-image: url(palm/themes/Onyx/images/input-first-focus.png) 14 14 2 14;
}
.enyo-last.enyo-input.enyo-input-focus, .enyo-last > .enyo-input.enyo-input-focus {
padding-top: 12px;
border-width: 2px 14px 14px 14px;
-webkit-border-image: url(palm/themes/Onyx/images/input-last-focus.png) 2 14 14 14;
}
/* NOTE: .enyo-middle is a boxy input type automatically applied when the input is the middle item in a group
.enyo-box-input an alias which users can use to create a rectangular input.
*/
.enyo-box-input.enyo-input.enyo-input-focus, .enyo-middle.enyo-input.enyo-input-focus, .enyo-middle > .enyo-input.enyo-input-focus {
background-color: transparent;
border-width: 14px;
-webkit-border-image: url(palm/themes/Onyx/images/input-middle-focus.png) 14 14;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-first.enyo-input.enyo-input-focus, .enyo-first > .enyo-input.enyo-input-focus {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/input-first-focus.png) 21 21 3 21;
}
.enyo-last.enyo-input.enyo-input-focus, .enyo-last > .enyo-input.enyo-input-focus {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/input-last-focus.png) 3 21 21 21;
}
.enyo-box-input.enyo-input.enyo-input-focus, .enyo-middle.enyo-input.enyo-input-focus, .enyo-middle > .enyo-input.enyo-input-focus {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/input-middle-focus.png) 21 21;
}
}
/* palm/themes/Onyx/css/SearchInput.css */
.enyo-search-input-search {
height: 20px;
width: 20px;
margin: 2px;
background-image: url(palm/themes/Onyx/images/search-input-search.png);
}
.enyo-search-input-cancel {
background-image: url(palm/themes/Onyx/images/search-input-cancel.png);
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-search-input-search {
background-image: url(palm/themes/Onyx/images-1.5/search-input-search.png);
background-size: 20px 20px;
}
.enyo-search-input-cancel {
background-image: url(palm/themes/Onyx/images-1.5/search-input-cancel.png);
background-size: 20px 20px;
}
}
/* palm/themes/Onyx/css/ToolInput.css */
.enyo-input.enyo-tool-input {
font-size: .8rem;
border-width: 6px 6px 6px 6px;
border-style: solid;
border-color: transparent;
-webkit-box-sizing: border-box;
-webkit-border-image: url(palm/themes/Onyx/images/input-tool.png) 6 6 6 6;
margin: 0 3px;
}
.enyo-input.enyo-tool-input.enyo-input-focus {
-webkit-border-image: url(palm/themes/Onyx/images/input-tool-focus.png) 6 6 6 6;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-input.enyo-tool-input {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/input-tool.png) 9 9 9 9;
}
.enyo-input.enyo-tool-input.enyo-input-focus {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/input-tool-focus.png) 9 9 9 9;
}
}
.enyo-input.enyo-tool-input > .enyo-input-spacing {
margin: -1px;
}
.enyo-input.enyo-tool-input .enyo-input-input {
color: #e5e5e5;
font-size: 16px;
padding: 2px 0 1px 0;
}
.enyo-input.enyo-tool-input .enyo-input-input:focus, .enyo-input.enyo-tool-input.enyo-input-focus .enyo-input-input {
color: #000;
}
.enyo-input.enyo-tool-input .enyo-input-input::-webkit-input-placeholder {
color: #ddd;
}
.enyo-input.enyo-tool-input.enyo-input-focus .enyo-input-input::-webkit-input-placeholder {
color: DarkGray;
}
/* palm/themes/Onyx/css/RichText.css */
.enyo-richtext-hint {
color: #888;
}
/* palm/themes/Onyx/css/Spinner.css */
.enyo-spinner {
width: 32px;
height: 32px;
-webkit-box-sizing: border-box;
background-image: url(palm/themes/Onyx/images/spinner.png);
}
.enyo-spinner-large {
width: 128px;
height: 128px;
-webkit-box-sizing: border-box;
background-image: url(palm/themes/Onyx/images/spinner-large.png);
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-spinner {
background-image: url(palm/themes/Onyx/images-1.5/spinner.png);
background-size: 32px 384px;
}
.enyo-spinner-large {
background-image: url(palm/themes/Onyx/images-1.5/spinner-large.png);
background-size: 128px 1536px;
}
}
/* palm/themes/Onyx/css/Dialog.css */
.enyo-dialog {
left: 0px;
right: 0px;
bottom: 0;
border-width: 32px 24px 32px 24px;
-webkit-border-image: url(palm/themes/Onyx/images/toaster-dialog.png) 32 24 32 24 stretch stretch;
}
.enyo-dialog-inner {
margin: -32px -24px -32px -24px;
padding-top: 23px;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-toaster-dialog {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/toaster-dialog.png) 48 36 48 36 stretch stretch;
}
}
/* palm/themes/Onyx/css/DialogPrompt.css */
.enyo-dialog-prompt-title {
color: #4c4c4c;
text-shadow: #f2f2f2 0px 0px 1px;
font-size: 21px;
padding: 0 0 10px 10px;
word-wrap: break-word;
border-bottom: 1px solid gray;
}
.enyo-dialog-prompt-message {
color: #222;
font-size: 16px;
padding: 10px;
}
.enyo-dialog-prompt-content {
padding: 10px;
}
/* palm/themes/Onyx/css/Toaster.css */
.enyo-toaster {
position: absolute;
-webkit-box-sizing: border-box;
-webkit-transform-style: preserve-3d;
}
/* palm/themes/Onyx/css/SlidingPane.css */
.enyo-sliding-pane {
overflow: hidden;
}
/* palm/themes/Onyx/css/SlidingView.css */
.enyo-sliding-view-shadow {
position: absolute;
z-index: 2;
height: 100%;
width: 20px;
left: -20px;
background: url(palm/themes/Onyx/images/sliding-shadow.png) repeat-y;
background-size: 20px 2px;
pointer-events: none;
}
.enyo-sliding-view-nub {
position: absolute;
-webkit-box-sizing: border-box;
cursor: pointer;
z-index: 2;
left: -20px;
width: 40px;
top: 0;
bottom: 0;
}
.enyo-sliding-view {
position: relative;
/* make sure the layer exist from the beginning so behavior doesn't change
the first time it's dragged. This makes debugging and performance
erratic */
-webkit-transform: translate3d(0,0,0);
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-sliding-view-shadow {
background-image: url(palm/themes/Onyx/images-1.5/sliding-shadow.png);
}
}
/* palm/themes/Onyx/css/ImageView.css */
.enyo-viewimage {
position: relative;
}
.enyo-viewimage-image {
display: block;
margin: auto;
}
/* palm/themes/Onyx/css/CroppableImage.css */
.enyo-croppable-image {
position: relative;
}
/* palm/themes/Onyx/css/WebView.css */
.enyo-webview-animate {
-webkit-transition: -webkit-transform 0.5s ease-in;
}
.enyo-webview-flashpopup-animate {
-webkit-transition: opacity 1s linear;
}
.enyo-webview-popup-spinner {
min-width: 0px;
-webkit-border-image: none;
}
/* palm/themes/Onyx/css/ModalDialog.css */
.enyo-modaldialog {
width: 320px;
border-width: 42px 24px 24px;
-webkit-border-image: url(palm/themes/Onyx/images/dialog.png) 42 24 24 24 stretch stretch;
-webkit-transition-property: opacity;
-webkit-transition-duration: 0.5s;
opacity: 0;
}
.enyo-modaldialog.enyo-modaldialog-open {
opacity: 1;
}
.enyo-modaldialog-container {
margin: -22px -4px -4px;
}
.enyo-modaldialog-title {
font-size: 1rem;
margin: 0 0 10px;
text-align: center;
}
.enyo-modaldialog-container .enyo-group,
.enyo-modaldialog-container .group {
border-width: 14px;
-webkit-border-image: url(palm/themes/Onyx/images/dialog-group-unlabeled.png) 14 14 repeat repeat;
margin: 8px 0;
}
.enyo-modaldialog-container .enyo-group.labeled {
border-width: 36px 14px 14px 14px;
-webkit-border-image: url(palm/themes/Onyx/images/dialog-group-labeled.png) 36 14 14 14 repeat repeat;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-modaldialog {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/dialog.png) 63 36 36 36 stretch stretch;
}
.enyo-modaldialog-container .enyo-group,
.enyo-modaldialog-container .group {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/dialog-group-unlabeled.png) 21 21 stretch stretch;
}
.enyo-modaldialog-container .enyo-group.labeled {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/dialog-group-labeled.png) 54 21 21 21 stretch stretch;
}
}
/* palm/themes/Onyx/css/FilePicker.css */
.enyo-filepicker {
width: 450px;
border-width: 24px;
-webkit-border-image: url(palm/themes/Onyx/images/filepicker.png) 25 stretch stretch;
}
.enyo-filepicker-container {
margin: -4px;
height: 600px;
}
.enyo-filepicker .enyo-iframe {
background-color: #ccc;
}
.enyo-filepicker-mainview .enyo-group,
.enyo-filepicker-mainview .group {
border-width: 14px;
-webkit-border-image: url(palm/themes/Onyx/images/dialog-group-unlabeled.png) 14 14 repeat repeat;
margin: 8px 0;
}
.enyo-filepicker-mainview .enyo-group.labeled {
border-width: 36px 14px 14px 14px;
-webkit-border-image: url(palm/themes/Onyx/images/dialog-group-labeled.png) 36 14 14 14 repeat repeat;
}
@media (-webkit-min-device-pixel-ratio:1.5) {
.enyo-filepicker {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/filepicker.png) 36 stretch stretch;
}
.enyo-filepicker-mainview .enyo-group,
.enyo-filepicker-mainview .group {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/modaldialog-group-unlabeled.png) 21 21 stretch stretch;
}
.enyo-filepicker-mainview .enyo-group.labeled {
-webkit-border-image: url(palm/themes/Onyx/images-1.5/modaldialog-group-labeled.png) 54 21 21 21 stretch stretch;
}
}
/* palm/themes/Onyx/css/VirtualScroller.css */
.enyo-virtual-scroller {
overflow: hidden;
position: relative;
}
.enyo-accel-children > * {
-webkit-transform-style: preserve-3d;
}
| {
"content_hash": "1ab1527e777d470996bd01742db4046b",
"timestamp": "",
"source": "github",
"line_count": 2524,
"max_line_length": 138,
"avg_line_length": 23.605388272583202,
"alnum_prop": 0.7187143336690165,
"repo_name": "blackberry/WebWorks-Community-Samples",
"id": "725cdbd5fbef49cbaa4658599fcc8069ee7f0ac6",
"size": "59693",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Enyo-1.0-StyleMatters/framework/build/enyo-build.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "3467000"
},
{
"name": "PHP",
"bytes": "2791"
},
{
"name": "Shell",
"bytes": "813"
}
],
"symlink_target": ""
} |
/*************************************************************
*
* MathJax/localization/pt/pt.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("pt", null, {
menuTitle: "portugu\u00EAs",
version: "2.7.5",
isLoaded: true,
domains: {
_: {
version: "2.7.5",
isLoaded: true,
strings: {
MathProcessingError: "Erro no processamento das f\u00F3rmulas",
MathError: "Erro de matem\u00E1tica",
LoadFile: "A carregar %1",
Loading: "A carregar",
LoadFailed: "O ficheiro n\u00E3o pode ser carregado: %1",
ProcessMath: "A processar f\u00F3rmula: %1%%",
Processing: "A processar",
TypesetMath: "A formatar f\u00F3rmulas: %1%%",
Typesetting: "A formatar",
MathJaxNotSupported: "O seu navegador n\u00E3o suporta MathJax",
ErrorTips: "Dicas de depura\u00E7\u00E3o: use %%1, para inspecionar %%2 no console do navegador"
}
},
FontWarnings: {},
"HTML-CSS": {},
HelpDialog: {},
MathML: {},
MathMenu: {},
TeX: {}
},
plural: function(n) {
if (n === 1) {
return 1;
} // one
return 2; // other
},
number: function(n) {
return String(n).replace(".", ","); // replace dot by comma
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/pt/pt.js");
| {
"content_hash": "60bd7b6da45d9b3d2e6747e9d80663ad",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 104,
"avg_line_length": 31.096774193548388,
"alnum_prop": 0.6099585062240664,
"repo_name": "GerHobbelt/MathJax",
"id": "5f7771406697a7737ee32811a2cea85ce0423437",
"size": "2594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "localization/pt/pt.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "12610385"
},
{
"name": "JavaScript",
"bytes": "50653811"
}
],
"symlink_target": ""
} |
"""
Known Issues:
-------------
- GlyphLineView does not properly handle fonts that are not saved to a file.
this is because there is not good way to find the font index for a given font
and the preview control requires a font index. so, the best thing i can
do at this point is get the font index by comparing file paths.
- GlyphView only works with the first master in a multiple master font.
Dealing with multiple masters is a pain, so I have no plans for fixing this.
"""
import os
import weakref
from FL import *
__all__ = ['ModalDialog', 'Button', 'TextBox', 'EditText', 'PopUpButton', 'List', 'CheckBox', 'GlyphLineView', 'GlyphView', 'HorizontalLine', 'VerticalLine']
osName = os.name
if osName == 'possix':
osName = 'mac'
class ModalDialog(object):
def __init__(self, posSize, title=None, okText="OK", cancelText="Cancel", okCallback=None, cancelCallback=None):
self._dialog = Dialog(self)
if len(posSize) == 2:
x, y = posSize
self._dialog.size = Point(x, y)
self._dialog.Center()
self._size = (x, y)
else:
x, y, w, h = posSize
self._dialog.rectangle = Rect(x, y, x+w, y+h)
self._size = (w, h)
if title is None:
title = ''
self._dialog.title = title
self._dialog.ok = okText
self._dialog.cancel = cancelText
#
self._okCallback=okCallback
self._cancelCallback=cancelCallback
def __setattr__(self, attr, value):
if isinstance(value, UIBaseObject):
assert not hasattr(self, attr), "attribute '%s' can not be replaced" % attr
#
value._contentID = 'contentID_for_' + attr
# hack for canvas controls:
# FL requires that custom controls begin with '_'
if isinstance(value, _CanvasWrapper):
value._contentID = '_' + value._contentID
#
value._setDialog(self)
value._setupContent()
#
x, y, w, h = value._posSize
# convert posSize to Dialog coordinates
winW, winH = self._size
if x < 0:
l = winW + x
else:
l = x
#
if w <= 0:
r = winW + w
else:
r = l + w
#
if y < 0:
t = winH + y
else:
t = y
#
if h <= 0:
b = winH + h
else:
b = t + h
#
# _CanvasWrapper needs to know the rect size
# when it is painting, so store it.
value._rectSize = (r-l, b-t)
#
pos = Rect(l, t, r, b)
self._dialog.AddControl(value._type, pos, value._contentID, value._style, value._title)
#
# it doesn't matter if the value does not have a callback
# assigned. the _callbackWrapper method safely handles
# those cases. the reason it is not handled here is that
# custom controls (used by _CanvasWrapper) use the method
# normally reserved for control hits to paint the control.
setattr(self, 'on_%s' % value._contentID, value._callbackWrapper)
super(ModalDialog, self).__setattr__(attr, value)
def open(self):
"""open the dialog"""
self._dialog.Run()
def close(self):
"""close the dialog"""
self._dialog.End()
def on_cancel(self, code):
if self._cancelCallback is not None:
self._cancelCallback(self)
def on_ok(self, code):
if self._okCallback is not None:
self._okCallback(self)
class UIBaseObject(object):
def __init__(self, posSize, title, callback=None, content=None):
self._posSize = posSize
self._title = title
self._callback = callback
self._content = content
def _setDialog(self, dialog):
self._dialog = weakref.ref(dialog)
def _callbackWrapper(self, code):
if self._callback is not None:
self._callback(self)
def _setupContent(self):
# set the attribute data in the parent class.
# this will be used for GetValue and PutValue operations.
setattr(self._dialog(), self._contentID, self._content)
def enable(self, value):
"""
enable the object by passing True
disable the object by passing False
"""
value = int(value)
dialog = self._dialog()
dialog._dialog.Enable(self._contentID, value)
def show(self, value):
"""
show the object by passing True
hide the object by passing False
"""
dialog = self._dialog()
dialog._dialog.Show(self._contentID, value)
def set(self, value):
"""
set the content of the object
"""
# temporarily suspend the callback
# bacause FontLab 5 calls the method
# assigned to a control when the
# control value is set programatically
callback = self._callback
self._callback = None
# set the ccontent
self._content = value
dialog = self._dialog()
setattr(dialog, self._contentID, value)
dialog._dialog.PutValue(self._contentID)
# reset the callback
self._callback = callback
def get(self):
"""
return the contents of the object
"""
dialog = self._dialog()
dialog._dialog.GetValue(self._contentID)
self._content = getattr(dialog, self._contentID)
return self._content
class Button(UIBaseObject):
_type = BUTTONCONTROL
_style = STYLE_BUTTON
def __init__(self, posSize, title, callback=None):
super(Button, self).__init__(posSize=posSize, title=title, callback=callback, content=title)
def set(self, value):
"""
Not implemented for Button
"""
raise NotImplementedError, "It is not possible to set the text in a button"
class PopUpButton(UIBaseObject):
_type = CHOICECONTROL
_style = STYLE_CHOICE
def __init__(self, posSize, items, callback=None):
super(PopUpButton, self).__init__(posSize=posSize, title='', callback=callback, content=items)
def _setupContent(self):
super(PopUpButton, self)._setupContent()
self._contentIndexID = self._contentID + '_index'
self.setSelection(0)
def setSelection(self, value):
"""
set the selected item
value should be an index
"""
# temporarily suspend the callback
callback = self._callback
self._callback = None
# set the value
if value is None:
value = -1
dialog = self._dialog()
setattr(dialog, self._contentIndexID, value)
dialog._dialog.PutValue(self._contentID)
# reset the callback
self._callback = callback
def getSelection(self):
"""
return the index of the selected item
"""
dialog = self._dialog()
dialog._dialog.GetValue(self._contentID)
getattr(dialog, self._contentID)
index = getattr(dialog, self._contentIndexID)
if index == -1:
index = None
return index
class List(UIBaseObject):
_type = LISTCONTROL
_style = STYLE_LIST
def __init__(self, posSize, items, callback=None):
super(List, self).__init__(posSize=posSize, title='', callback=callback, content=items)
def _setupContent(self):
super(List, self)._setupContent()
self._contentIndexID = self._contentID + '_index'
self.setSelection([0])
def __len__(self):
return len(self._content)
def __getitem__(self, index):
return self._content[index]
def __setitem__(self, index, value):
self._content[index] = value
self.set(self._content)
def __delitem__(self, index):
del self._content[index]
self.set(self._content)
def __getslice__(self, a, b):
return self._content[a:b]
def __delslice__(self, a, b):
del self._content[a:b]
self.set(self._content)
def __setslice__(self, a, b, items):
self._content[a:b] = items
self.set(self._content)
def append(self, item):
self._content.append(item)
self.set(self._content)
def remove(self, item):
index = self._content.index(item)
del self._content[index]
self.set(self._content)
def index(self, item):
return self._content.index(item)
def insert(self, index, item):
self._content.insert(index, item)
self.set(self._content)
def extend(self, items):
self._content.extend(items)
self.set(self._content)
def replace(self, index, item):
del self._content[index]
self._content.insert(index, item)
self.set(self._content)
#
def setSelection(self, value):
"""
set the selected item index(es)
value should be a list of indexes
in FontLab, it setting multiple
selection indexes is not possible.
"""
dialog = self._dialog()
if len(value) < 1:
value = -1
else:
value = value[0]
setattr(dialog, self._contentIndexID, value)
dialog._dialog.PutValue(self._contentID)
def getSelection(self):
"""
return a list of selected item indexes
"""
import sys
dialog = self._dialog()
dialog._dialog.GetValue(self._contentID)
getattr(dialog, self._contentID)
index = getattr(dialog, self._contentIndexID)
# Since FLS v5.2, the GetValue() method of the Dialog() class returns
# a 'wrong' index value from the specified LISTCONTROL.
# If the selected index is n, it will return n-1. For example, when
# the index is 1, it returns 0; when it's 2, it returns 1, and so on.
# If the selection is empty, FLS v5.2 returns -2, while the old v5.0
# returned None.
# See also:
# - https://github.com/robofab-developers/robofab/pull/14
# - http://forum.fontlab.com/index.php?topic=8807.0
# - http://forum.fontlab.com/index.php?topic=9003.0
if fl.buildnumber > 4600 and sys.platform == 'win32':
if index == -2:
index == -1
else:
index += 1
if index == -1:
return []
return [index]
def set(self, value):
"""
set the contents of the list
"""
self._content = value
dialog = self._dialog()
setattr(dialog, self._contentID, value)
dialog._dialog.PutValue(self._contentID)
def get(self):
"""
return the contents of the list
"""
return self._content
class EditText(UIBaseObject):
_type = EDITCONTROL
_style = STYLE_EDIT
def __init__(self, posSize, text="", callback=None):
super(EditText, self).__init__(posSize=posSize, title='', callback=callback, content=text)
def set(self, value):
if osName == 'mac':
value = '\r'.join(value.splitlines())
super(EditText, self).set(value)
class TextBox(UIBaseObject):
_type = STATICCONTROL
_style = STYLE_LABEL
def __init__(self, posSize, text):
super(TextBox, self).__init__(posSize=posSize, title=text, callback=None, content=text)
def set(self, value):
if osName == 'mac':
value = '\r'.join(value.splitlines())
super(TextBox, self).set(value)
class CheckBox(UIBaseObject):
_type = CHECKBOXCONTROL
_style = STYLE_CHECKBOX
def __init__(self, posSize, title, callback=None, value=False):
value = int(value)
super(CheckBox, self).__init__(posSize=posSize, title=title, callback=callback, content=value)
def set(self, value):
"""
set the state of the object
value should be a boolean
"""
value = int(value)
super(CheckBox, self).set(value)
def get(self):
"""
returns a boolean representing the state of the object
"""
value = super(CheckBox, self).get()
return bool(value)
class _CanvasWrapper(UIBaseObject):
_type = STATICCONTROL
_style = STYLE_CUSTOM
def __init__(self, posSize):
super(_CanvasWrapper, self).__init__(posSize=posSize, title='', callback=None, content=None)
def _callbackWrapper(self, canvas):
# oddly, the custom control is painted
# by the method that would normally be
# called when the control is hit.
self._paint(canvas)
class _Line(_CanvasWrapper):
def __init__(self, posSize):
super(_Line, self).__init__(posSize=posSize)
def _paint(self, canvas):
canvas.brush_color = cRGB_GRAY
canvas.brush_style = cBRUSH_SOLID
canvas.draw_style = 1
#
w, h = self._rectSize
r = Rect(0, 0, w, h)
canvas.Rectangle(0, r)
class HorizontalLine(_Line):
def __init__(self, posSize):
x, y, w, h = posSize
super(HorizontalLine, self).__init__(posSize=(x, y, w, 1))
class VerticalLine(_Line):
def __init__(self, posSize):
x, y, w, h = posSize
super(VerticalLine, self).__init__(posSize=(x, y, 1, h))
def _unwrapRobofab(obj):
# this could be a raw FontLab object or a robofab object.
# the preference is for raw FontLab objects. this
# function safely unwraps robofab objects.
try:
from robofab.world import RFont, RGlyph
haveRobofab = True
except ImportError:
haveRobofab = False
if haveRobofab:
if isinstance(obj, RFont) or isinstance(obj, RGlyph):
return obj.naked()
return obj
def _fontIndex(font):
font = _unwrapRobofab(font)
#
fonts = [(fl[i], i) for i in xrange(len(fl))]
#
for otherFont, index in fonts:
if otherFont.file_name == font.file_name: # grrr.
return index
return -1
class GlyphLineView(UIBaseObject):
_type = PREVIEWCONTROL
_style = STYLE_LABEL
def __init__(self, posSize, text="", font=None, rightToLeft=False):
if font is None:
self._fontIndex = fl.ifont
else:
self._fontIndex = _fontIndex(font)
self._rightToLeft = False
text = self._makeText(text)
super(GlyphLineView, self).__init__(posSize=posSize, title="", callback=None, content=text)
def _makeText(self, text):
text = "f:%d|d:%s|r:%d" % (self._fontIndex, text, self._rightToLeft)
return text
def set(self, text):
"""
set the text displayed text string
"""
text = self._makeText(text)
super(GlyphLineView, self).set(text)
def get(self):
"""
return the displayed text string
"""
return self._content[6:-4]
def setFont(self, font):
"""
set the index for the font that should be displayed
"""
if font is None:
self._fontIndex = -1
else:
self._fontIndex = _fontIndex(font)
self.set(self.get())
def setRightToLeft(self, value):
"""
set the setting directon of the display
"""
self._rightToLeft = value
self.set(self.get())
class GlyphView(_CanvasWrapper):
def __init__(self, posSize, font, glyph, margin=30,
showFill=True, showOutline=False,
showDescender=True, showBaseline=True, showXHeight=True,
showAscender=True, showCapHeight=True, showUPMTop=False,
showLeftSidebearing=True, showRightSidebearing=True,
showOnCurvePoints=True):
#
super(GlyphView, self).__init__(posSize=posSize)
#
self._showFill = showFill
self._showOutline = showOutline
self._margin = margin
self._showDescender = showDescender
self._showBaseline = showBaseline
self._showXHeight = showXHeight
self._showAscender = showAscender
self._showCapHeight = showCapHeight
self._showUPMTop = showUPMTop
self._showLeftSidebearing = showLeftSidebearing
self._showRightSidebearing = showRightSidebearing
#
self._showOnCurvePoints = showOnCurvePoints
#
self.set(font, glyph)
def set(self, font, glyph):
"""
change the glyph displayed in the view
"""
if font is None or glyph is None:
self._font = None
self._glyph = None
else:
self._font = _unwrapRobofab(font)
self._glyph = _unwrapRobofab(glyph)
###
def getShowFill(self):
return self._showFill
def setShowFill(self, value):
self._showFill = value
def getShowOutline(self):
return self._showOutline
def setShowOutline(self, value):
self._showOutline = value
def getMargin(self):
return self._margin
def setMargin(self, value):
self._margin = value
def getShowDescender(self):
return self._showDescender
def setShowDescender(self, value):
self._showDescender = value
def getShowBaseline(self):
return self._showBaseline
def setShowBaseline(self, value):
self._showBaseline = value
def getShowXHeight(self):
return self._showXHeight
def setShowXHeight(self, value):
self._showXHeight = value
def getShowAscender(self):
return self._showAscender
def setShowAscender(self, value):
self._showAscender = value
def getShowCapHeight(self):
return self._showCapHeight
def setShowCapHeight(self, value):
self._showCapHeight = value
def getShowUPMTop(self):
return self._showUPMTop
def setShowUPMTop(self, value):
self._showUPMTop = value
def getShowLeftSidebearing(self):
return self._showLeftSidebearing
def setShowLeftSidebearing(self, value):
self._showLeftSidebearing = value
def getShowRightSidebearing(self):
return self._showRightSidebearing
def setShowRightSidebearing(self, value):
self._showRightSidebearing = value
def getShowOnCurvePoints(self):
return self._showOnCurvePoints
def setShowOnCurvePoints(self, value):
self._showOnCurvePoints = value
###
def update(self):
if hasattr(self, '_dialog'):
dialog = self._dialog()
dialog._dialog.Repaint(self._contentID)
def _paint(self, canvas):
if self._font is None or self._glyph is None:
return
font = self._font
glyph = self._glyph
#
upm = font.upm
descender = font.descender[0]
baseline = 0
xHeight = font.x_height[0]
ascender = font.ascender[0]
capHeight = font.cap_height[0]
#
glyphWidth = glyph.width
#
viewWidth, viewHeight = self._rectSize
liveWidth = viewWidth - (self._margin * 2)
liveHeight = viewHeight - (self._margin * 2)
#
scale = liveHeight / float(upm)
#
xOffset = (viewWidth - (glyphWidth * scale)) / 2
yOffset = ((upm + descender) * scale) + self._margin
#
left = -xOffset * (1.0 / scale)
right = glyphWidth + abs(left)
top = upm + descender + (self._margin * (1.0 / scale))
bottom = descender - (self._margin * (1.0 / scale))
#
canvas.delta = Point(xOffset, yOffset)
canvas.scale = Point(scale, -scale)
#
canvas.pen_color = cRGB_LTGRAY
#
if self._showDescender:
canvas.MoveTo(Point(left, descender))
canvas.LineTo(Point(right, descender))
if self._showBaseline:
canvas.MoveTo(Point(left, baseline))
canvas.LineTo(Point(right, baseline))
if self._showXHeight:
canvas.MoveTo(Point(left, xHeight))
canvas.LineTo(Point(right, xHeight))
if self._showAscender:
canvas.MoveTo(Point(left, ascender))
canvas.LineTo(Point(right, ascender))
if self._showCapHeight:
canvas.MoveTo(Point(left, capHeight))
canvas.LineTo(Point(right, capHeight))
if self._showUPMTop:
canvas.MoveTo(Point(left, upm+descender))
canvas.LineTo(Point(right, upm+descender))
#
if self._showLeftSidebearing:
canvas.MoveTo(Point(0, bottom))
canvas.LineTo(Point(0, top))
if self._showRightSidebearing:
canvas.MoveTo(Point(glyphWidth, bottom))
canvas.LineTo(Point(glyphWidth, top))
#
if self._showFill:
canvas.FillGlyph(glyph)
canvas.OutlineGlyph(glyph) # XXX hack to hide gray outline
if self._showOutline:
canvas.OutlineGlyph(glyph)
#
if self._showOnCurvePoints:
canvas.pen_color = cRGB_RED
canvas.brush_color = cRGB_RED
markerSize = 5 * (1.0 / scale)
halfMarkerSize = markerSize / 2
for node in glyph.nodes:
x, y = node.x, node.y
x -= halfMarkerSize
y -= halfMarkerSize
if node.alignment == nSMOOTH:
mode = 1
else:
mode = 0
canvas.Rectangle(mode, Rect(x, y, x+markerSize, y+markerSize))
| {
"content_hash": "27fd2205c60f849f137efe6328d8406d",
"timestamp": "",
"source": "github",
"line_count": 730,
"max_line_length": 157,
"avg_line_length": 29.980821917808218,
"alnum_prop": 0.5673032989125468,
"repo_name": "anthrotype/dialogKit",
"id": "69210672d792ef78e059e29a69ed1cfacb9829c8",
"size": "21886",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Lib/dialogKit/_dkFL.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4320"
},
{
"name": "Python",
"bytes": "63091"
}
],
"symlink_target": ""
} |
var _ = require('underscore');
var util = require('util');
var CommandParser = require('./parser');
/**
* Get the arguments to send to an autocomplete handler implemented by a readcommand consumer. This
* function will also determine if auto-complete should be handled at all.
*
* @param {String} currentCommand The current command string, not including what is in the
* current line buffer
* @param {String} currentLine The contents of the current line buffer
* @param {Function} callback Invoked when complete
* @param {Boolean} callback.abort Whether or not auto-complete should be passed to the
* caller. `true`thy indicates it should not, `false`y
* indicates it should not
* @param {String[]} callback.args The arguments array to send to the caller. This will not
* be specified if `callback.abort` is `true`thy
*/
module.exports.getAutocompleteArguments = function(currentCommand, currentLine, callback) {
currentCommand = currentCommand || '';
currentLine = currentLine || '';
/*!
* Parse the full command to see if we are in a state where we can reasonably do an auto-
* complete
*/
var fullCommandStr = currentCommand + currentLine;
var fullCommandParsed = _parseForAutocomplete(fullCommandStr);
// The last argument of the current command string is the only thing that can be auto-completed
var lastArg = _.last(fullCommandParsed.args);
if (fullCommandParsed.open === CommandParser.OPEN_ESCAPE) {
// We can't complete on an escape sequence, it doesn't really make sense I don't think
return callback(true);
} else if (fullCommandStr.slice(lastArg.i).indexOf('\n') !== -1) {
// We can't complete if the last argument spans a new line. This would imply we need to do a
// replacement on data that has already been accepted which is not possible
return callback(true);
}
// Hand just the string arguments (not parsed metadata) to the autocomplete caller
return callback(false, _.pluck(_filterAutocompleteArguments(fullCommandParsed.args), 'str'));
};
/**
* Get the replacement values and replacement substring given the array of potential replacements
* provided by the autocomplete implementation.
*
* @param {String} currentCommand The current command string, not including what is in
* the current line buffer
* @param {String} currentLine The contents of the current line buffer
* @param {Function} callback Invoked when complete
* @param {String[]} callback.replacements The potential replacements
* @param {String} callback.toReplace The replacement substring of the `currentLine` of
* user input
*/
module.exports.getAutocompleteReplacements = function(currentCommand, currentLine, replacementsArray, callback) {
if (_.isEmpty(replacementsArray)) {
return callback([], currentLine);
}
currentCommand = currentCommand || '';
currentLine = currentLine || '';
var fullCommandStr = currentCommand + currentLine;
var fullCommandParsed = _parseForAutocomplete(fullCommandStr);
// The last argument of the current command string is the only thing that can be auto-completed
var lastArg = _.last(fullCommandParsed.args);
// The replacement string is always from where the last argument began on the current line until
// the end
var distanceIndex = _getDistanceFromLastNewline(fullCommandStr, lastArg.i);
var toReplaceStr = currentLine.slice(distanceIndex);
replacementsArray = _.map(replacementsArray, function(replacement) {
if (lastArg.quoted || replacement.indexOf(' ') !== -1 || replacement.indexOf('\n') !== -1) {
var quote = lastArg.quoted || '"';
// If the last argument was quoted, reconstruct the quotes around the potential
// replacements
replacement = util.format('%s%s%s', quote, replacement, quote);
}
// Add a space to the end of all replacements
return util.format('%s ', replacement);
});
return callback(replacementsArray, toReplaceStr);
};
/*!
* Parse the given command string, handling the scenario where there is an unstarted command at the
* end and assigning it an index. This is a requirement specific for auto-complete, so it is not
* done by the parser itself.
*/
function _parseForAutocomplete(fullCommandStr) {
var fullCommandParsed = CommandParser.parse(fullCommandStr);
var lastArg = _.last(fullCommandParsed.args);
// If the last argument does not have an index, it means it's a cliff hanger (e.g., a space at
// the end of the command string). Therefore, we'll assign it an index at the end of the input
// string
if (!_.isNumber(lastArg.i)) {
lastArg.i = fullCommandStr.length;
}
return fullCommandParsed;
}
/*!
* Clear empty arguments out of the arguments array except for the last one.
*
* When giving the args array to the caller, we need to indicate if the cursor position is beginning
* a new argument, or if it is in progress on a current argument. The parser will strip that
* information in its sanitized `str` representation of the arguments. For example:
*
* `"--log-level"` will look example the same as `"--log-level "` (trailing space)
*
* ... but for doing auto-complete on either argument keys or argument values, it is an important
* distinction to make. So if the state is the latter, we maintain the empty string at the end of
* the args array.
*/
function _filterAutocompleteArguments(args) {
args = _.filter(args, function(arg, i) {
return (i === (args.length - 1) || arg.quote || arg.str !== '');
});
// If there is only one argument and its unintentially empty, don't bother including it
if (args.length === 1 && !args[0].quote && args[0].str === '') {
return [];
} else {
return args;
}
}
/*!
* Given a string that might contain new-lines, the number of characters `i` is away from the last
* new-line in the string. If the string does not contain a new-line, the result is just `i`
*/
function _getDistanceFromLastNewline(str, i) {
var distance = i;
var lastNewlineIndex = str.lastIndexOf('\n');
if (lastNewlineIndex !== -1) {
distance = (i - lastNewlineIndex - 1);
}
return distance;
}
| {
"content_hash": "a4067edffae55897934320a6304332ba",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 113,
"avg_line_length": 43.80921052631579,
"alnum_prop": 0.6589578014716925,
"repo_name": "mrvisser/node-readcommand",
"id": "e7b70e7dd9649d3c4b1992940be99dd63a37e8b0",
"size": "6659",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/autocomplete.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "52086"
}
],
"symlink_target": ""
} |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// Main decoding functions for WebP images.
//
// Author: Skal (pascal.massimino@gmail.com)
#ifndef WEBP_WEBP_DECODE_H_
#define WEBP_WEBP_DECODE_H_
#include "./types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define WEBP_DECODER_ABI_VERSION 0x0206 // MAJOR(8b) + MINOR(8b)
// Note: forward declaring enumerations is not allowed in (strict) C and C++,
// the types are left here for reference.
// typedef enum VP8StatusCode VP8StatusCode;
// typedef enum WEBP_CSP_MODE WEBP_CSP_MODE;
typedef struct WebPRGBABuffer WebPRGBABuffer;
typedef struct WebPYUVABuffer WebPYUVABuffer;
typedef struct WebPDecBuffer WebPDecBuffer;
typedef struct WebPIDecoder WebPIDecoder;
typedef struct WebPBitstreamFeatures WebPBitstreamFeatures;
typedef struct WebPDecoderOptions WebPDecoderOptions;
typedef struct WebPDecoderConfig WebPDecoderConfig;
// Return the decoder's version number, packed in hexadecimal using 8bits for
// each of major/minor/revision. E.g: v2.5.7 is 0x020507.
WEBP_EXTERN(int) WebPGetDecoderVersion(void);
// Retrieve basic header information: width, height.
// This function will also validate the header and return 0 in
// case of formatting error.
// Pointers 'width' and 'height' can be passed NULL if deemed irrelevant.
WEBP_EXTERN(int) WebPGetInfo(const uint8_t* data, size_t data_size,
int* width, int* height);
// Decodes WebP images pointed to by 'data' and returns RGBA samples, along
// with the dimensions in *width and *height. The ordering of samples in
// memory is R, G, B, A, R, G, B, A... in scan order (endian-independent).
// The returned pointer should be deleted calling WebPFree().
// Returns NULL in case of error.
WEBP_EXTERN(uint8_t*) WebPDecodeRGBA(const uint8_t* data, size_t data_size,
int* width, int* height);
// Same as WebPDecodeRGBA, but returning A, R, G, B, A, R, G, B... ordered data.
WEBP_EXTERN(uint8_t*) WebPDecodeARGB(const uint8_t* data, size_t data_size,
int* width, int* height);
// Same as WebPDecodeRGBA, but returning B, G, R, A, B, G, R, A... ordered data.
WEBP_EXTERN(uint8_t*) WebPDecodeBGRA(const uint8_t* data, size_t data_size,
int* width, int* height);
// Same as WebPDecodeRGBA, but returning R, G, B, R, G, B... ordered data.
// If the bitstream contains transparency, it is ignored.
WEBP_EXTERN(uint8_t*) WebPDecodeRGB(const uint8_t* data, size_t data_size,
int* width, int* height);
// Same as WebPDecodeRGB, but returning B, G, R, B, G, R... ordered data.
WEBP_EXTERN(uint8_t*) WebPDecodeBGR(const uint8_t* data, size_t data_size,
int* width, int* height);
// Decode WebP images pointed to by 'data' to Y'UV format(*). The pointer
// returned is the Y samples buffer. Upon return, *u and *v will point to
// the U and V chroma data. These U and V buffers need NOT be passed to
// WebPFree(), unlike the returned Y luma one. The dimension of the U and V
// planes are both (*width + 1) / 2 and (*height + 1)/ 2.
// Upon return, the Y buffer has a stride returned as '*stride', while U and V
// have a common stride returned as '*uv_stride'.
// Return NULL in case of error.
// (*) Also named Y'CbCr. See: http://en.wikipedia.org/wiki/YCbCr
WEBP_EXTERN(uint8_t*) WebPDecodeYUV(const uint8_t* data, size_t data_size,
int* width, int* height,
uint8_t** u, uint8_t** v,
int* stride, int* uv_stride);
// Releases memory returned by the WebPDecode*() functions above.
WEBP_EXTERN(void) WebPFree(void* ptr);
// These five functions are variants of the above ones, that decode the image
// directly into a pre-allocated buffer 'output_buffer'. The maximum storage
// available in this buffer is indicated by 'output_buffer_size'. If this
// storage is not sufficient (or an error occurred), NULL is returned.
// Otherwise, output_buffer is returned, for convenience.
// The parameter 'output_stride' specifies the distance (in bytes)
// between scanlines. Hence, output_buffer_size is expected to be at least
// output_stride x picture-height.
WEBP_EXTERN(uint8_t*) WebPDecodeRGBAInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
WEBP_EXTERN(uint8_t*) WebPDecodeARGBInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
WEBP_EXTERN(uint8_t*) WebPDecodeBGRAInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
// RGB and BGR variants. Here too the transparency information, if present,
// will be dropped and ignored.
WEBP_EXTERN(uint8_t*) WebPDecodeRGBInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
WEBP_EXTERN(uint8_t*) WebPDecodeBGRInto(
const uint8_t* data, size_t data_size,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
// WebPDecodeYUVInto() is a variant of WebPDecodeYUV() that operates directly
// into pre-allocated luma/chroma plane buffers. This function requires the
// strides to be passed: one for the luma plane and one for each of the
// chroma ones. The size of each plane buffer is passed as 'luma_size',
// 'u_size' and 'v_size' respectively.
// Pointer to the luma plane ('*luma') is returned or NULL if an error occurred
// during decoding (or because some buffers were found to be too small).
WEBP_EXTERN(uint8_t*) WebPDecodeYUVInto(
const uint8_t* data, size_t data_size,
uint8_t* luma, size_t luma_size, int luma_stride,
uint8_t* u, size_t u_size, int u_stride,
uint8_t* v, size_t v_size, int v_stride);
//------------------------------------------------------------------------------
// Output colorspaces and buffer
// Colorspaces
// Note: the naming describes the byte-ordering of packed samples in memory.
// For instance, MODE_BGRA relates to samples ordered as B,G,R,A,B,G,R,A,...
// Non-capital names (e.g.:MODE_Argb) relates to pre-multiplied RGB channels.
// RGBA-4444 and RGB-565 colorspaces are represented by following byte-order:
// RGBA-4444: [r3 r2 r1 r0 g3 g2 g1 g0], [b3 b2 b1 b0 a3 a2 a1 a0], ...
// RGB-565: [r4 r3 r2 r1 r0 g5 g4 g3], [g2 g1 g0 b4 b3 b2 b1 b0], ...
// In the case WEBP_SWAP_16BITS_CSP is defined, the bytes are swapped for
// these two modes:
// RGBA-4444: [b3 b2 b1 b0 a3 a2 a1 a0], [r3 r2 r1 r0 g3 g2 g1 g0], ...
// RGB-565: [g2 g1 g0 b4 b3 b2 b1 b0], [r4 r3 r2 r1 r0 g5 g4 g3], ...
typedef enum WEBP_CSP_MODE {
MODE_RGB = 0, MODE_RGBA = 1,
MODE_BGR = 2, MODE_BGRA = 3,
MODE_ARGB = 4, MODE_RGBA_4444 = 5,
MODE_RGB_565 = 6,
// RGB-premultiplied transparent modes (alpha value is preserved)
MODE_rgbA = 7,
MODE_bgrA = 8,
MODE_Argb = 9,
MODE_rgbA_4444 = 10,
// YUV modes must come after RGB ones.
MODE_YUV = 11, MODE_YUVA = 12, // yuv 4:2:0
MODE_LAST = 13
} WEBP_CSP_MODE;
// Some useful macros:
static WEBP_INLINE int WebPIsPremultipliedMode(WEBP_CSP_MODE mode) {
return (mode == MODE_rgbA || mode == MODE_bgrA || mode == MODE_Argb ||
mode == MODE_rgbA_4444);
}
static WEBP_INLINE int WebPIsAlphaMode(WEBP_CSP_MODE mode) {
return (mode == MODE_RGBA || mode == MODE_BGRA || mode == MODE_ARGB ||
mode == MODE_RGBA_4444 || mode == MODE_YUVA ||
WebPIsPremultipliedMode(mode));
}
static WEBP_INLINE int WebPIsRGBMode(WEBP_CSP_MODE mode) {
return (mode < MODE_YUV);
}
//------------------------------------------------------------------------------
// WebPDecBuffer: Generic structure for describing the output sample buffer.
struct WebPRGBABuffer { // view as RGBA
uint8_t* rgba; // pointer to RGBA samples
int stride; // stride in bytes from one scanline to the next.
size_t size; // total size of the *rgba buffer.
};
struct WebPYUVABuffer { // view as YUVA
uint8_t* y, *u, *v, *a; // pointer to luma, chroma U/V, alpha samples
int y_stride; // luma stride
int u_stride, v_stride; // chroma strides
int a_stride; // alpha stride
size_t y_size; // luma plane size
size_t u_size, v_size; // chroma planes size
size_t a_size; // alpha-plane size
};
// Output buffer
struct WebPDecBuffer {
WEBP_CSP_MODE colorspace; // Colorspace.
int width, height; // Dimensions.
int is_external_memory; // If true, 'internal_memory' pointer is not used.
union {
WebPRGBABuffer RGBA;
WebPYUVABuffer YUVA;
} u; // Nameless union of buffer parameters.
uint32_t pad[4]; // padding for later use
uint8_t* private_memory; // Internally allocated memory (only when
// is_external_memory is false). Should not be used
// externally, but accessed via the buffer union.
};
// Internal, version-checked, entry point
WEBP_EXTERN(int) WebPInitDecBufferInternal(WebPDecBuffer*, int);
// Initialize the structure as empty. Must be called before any other use.
// Returns false in case of version mismatch
static WEBP_INLINE int WebPInitDecBuffer(WebPDecBuffer* buffer) {
return WebPInitDecBufferInternal(buffer, WEBP_DECODER_ABI_VERSION);
}
// Free any memory associated with the buffer. Must always be called last.
// Note: doesn't free the 'buffer' structure itself.
WEBP_EXTERN(void) WebPFreeDecBuffer(WebPDecBuffer* buffer);
//------------------------------------------------------------------------------
// Enumeration of the status codes
typedef enum VP8StatusCode {
VP8_STATUS_OK = 0,
VP8_STATUS_OUT_OF_MEMORY,
VP8_STATUS_INVALID_PARAM,
VP8_STATUS_BITSTREAM_ERROR,
VP8_STATUS_UNSUPPORTED_FEATURE,
VP8_STATUS_SUSPENDED,
VP8_STATUS_USER_ABORT,
VP8_STATUS_NOT_ENOUGH_DATA
} VP8StatusCode;
//------------------------------------------------------------------------------
// Incremental decoding
//
// This API allows streamlined decoding of partial data.
// Picture can be incrementally decoded as data become available thanks to the
// WebPIDecoder object. This object can be left in a SUSPENDED state if the
// picture is only partially decoded, pending additional input.
// Code example:
//
// WebPInitDecBuffer(&buffer);
// buffer.colorspace = mode;
// ...
// WebPIDecoder* idec = WebPINewDecoder(&buffer);
// while (has_more_data) {
// // ... (get additional data)
// status = WebPIAppend(idec, new_data, new_data_size);
// if (status != VP8_STATUS_SUSPENDED ||
// break;
// }
//
// // The above call decodes the current available buffer.
// // Part of the image can now be refreshed by calling to
// // WebPIDecGetRGB()/WebPIDecGetYUVA() etc.
// }
// WebPIDelete(idec);
// Creates a new incremental decoder with the supplied buffer parameter.
// This output_buffer can be passed NULL, in which case a default output buffer
// is used (with MODE_RGB). Otherwise, an internal reference to 'output_buffer'
// is kept, which means that the lifespan of 'output_buffer' must be larger than
// that of the returned WebPIDecoder object.
// The supplied 'output_buffer' content MUST NOT be changed between calls to
// WebPIAppend() or WebPIUpdate() unless 'output_buffer.is_external_memory' is
// set to 1. In such a case, it is allowed to modify the pointers, size and
// stride of output_buffer.u.RGBA or output_buffer.u.YUVA, provided they remain
// within valid bounds.
// All other fields of WebPDecBuffer MUST remain constant between calls.
// Returns NULL if the allocation failed.
WEBP_EXTERN(WebPIDecoder*) WebPINewDecoder(WebPDecBuffer* output_buffer);
// This function allocates and initializes an incremental-decoder object, which
// will output the RGB/A samples specified by 'csp' into a preallocated
// buffer 'output_buffer'. The size of this buffer is at least
// 'output_buffer_size' and the stride (distance in bytes between two scanlines)
// is specified by 'output_stride'.
// Additionally, output_buffer can be passed NULL in which case the output
// buffer will be allocated automatically when the decoding starts. The
// colorspace 'csp' is taken into account for allocating this buffer. All other
// parameters are ignored.
// Returns NULL if the allocation failed, or if some parameters are invalid.
WEBP_EXTERN(WebPIDecoder*) WebPINewRGB(
WEBP_CSP_MODE csp,
uint8_t* output_buffer, size_t output_buffer_size, int output_stride);
// This function allocates and initializes an incremental-decoder object, which
// will output the raw luma/chroma samples into a preallocated planes if
// supplied. The luma plane is specified by its pointer 'luma', its size
// 'luma_size' and its stride 'luma_stride'. Similarly, the chroma-u plane
// is specified by the 'u', 'u_size' and 'u_stride' parameters, and the chroma-v
// plane by 'v' and 'v_size'. And same for the alpha-plane. The 'a' pointer
// can be pass NULL in case one is not interested in the transparency plane.
// Conversely, 'luma' can be passed NULL if no preallocated planes are supplied.
// In this case, the output buffer will be automatically allocated (using
// MODE_YUVA) when decoding starts. All parameters are then ignored.
// Returns NULL if the allocation failed or if a parameter is invalid.
WEBP_EXTERN(WebPIDecoder*) WebPINewYUVA(
uint8_t* luma, size_t luma_size, int luma_stride,
uint8_t* u, size_t u_size, int u_stride,
uint8_t* v, size_t v_size, int v_stride,
uint8_t* a, size_t a_size, int a_stride);
// Deprecated version of the above, without the alpha plane.
// Kept for backward compatibility.
WEBP_EXTERN(WebPIDecoder*) WebPINewYUV(
uint8_t* luma, size_t luma_size, int luma_stride,
uint8_t* u, size_t u_size, int u_stride,
uint8_t* v, size_t v_size, int v_stride);
// Deletes the WebPIDecoder object and associated memory. Must always be called
// if WebPINewDecoder, WebPINewRGB or WebPINewYUV succeeded.
WEBP_EXTERN(void) WebPIDelete(WebPIDecoder* idec);
// Copies and decodes the next available data. Returns VP8_STATUS_OK when
// the image is successfully decoded. Returns VP8_STATUS_SUSPENDED when more
// data is expected. Returns error in other cases.
WEBP_EXTERN(VP8StatusCode) WebPIAppend(
WebPIDecoder* idec, const uint8_t* data, size_t data_size);
// A variant of the above function to be used when data buffer contains
// partial data from the beginning. In this case data buffer is not copied
// to the internal memory.
// Note that the value of the 'data' pointer can change between calls to
// WebPIUpdate, for instance when the data buffer is resized to fit larger data.
WEBP_EXTERN(VP8StatusCode) WebPIUpdate(
WebPIDecoder* idec, const uint8_t* data, size_t data_size);
// Returns the RGB/A image decoded so far. Returns NULL if output params
// are not initialized yet. The RGB/A output type corresponds to the colorspace
// specified during call to WebPINewDecoder() or WebPINewRGB().
// *last_y is the index of last decoded row in raster scan order. Some pointers
// (*last_y, *width etc.) can be NULL if corresponding information is not
// needed.
WEBP_EXTERN(uint8_t*) WebPIDecGetRGB(
const WebPIDecoder* idec, int* last_y,
int* width, int* height, int* stride);
// Same as above function to get a YUVA image. Returns pointer to the luma
// plane or NULL in case of error. If there is no alpha information
// the alpha pointer '*a' will be returned NULL.
WEBP_EXTERN(uint8_t*) WebPIDecGetYUVA(
const WebPIDecoder* idec, int* last_y,
uint8_t** u, uint8_t** v, uint8_t** a,
int* width, int* height, int* stride, int* uv_stride, int* a_stride);
// Deprecated alpha-less version of WebPIDecGetYUVA(): it will ignore the
// alpha information (if present). Kept for backward compatibility.
static WEBP_INLINE uint8_t* WebPIDecGetYUV(
const WebPIDecoder* idec, int* last_y, uint8_t** u, uint8_t** v,
int* width, int* height, int* stride, int* uv_stride) {
return WebPIDecGetYUVA(idec, last_y, u, v, NULL, width, height,
stride, uv_stride, NULL);
}
// Generic call to retrieve information about the displayable area.
// If non NULL, the left/right/width/height pointers are filled with the visible
// rectangular area so far.
// Returns NULL in case the incremental decoder object is in an invalid state.
// Otherwise returns the pointer to the internal representation. This structure
// is read-only, tied to WebPIDecoder's lifespan and should not be modified.
WEBP_EXTERN(const WebPDecBuffer*) WebPIDecodedArea(
const WebPIDecoder* idec, int* left, int* top, int* width, int* height);
//------------------------------------------------------------------------------
// Advanced decoding parametrization
//
// Code sample for using the advanced decoding API
/*
// A) Init a configuration object
WebPDecoderConfig config;
CHECK(WebPInitDecoderConfig(&config));
// B) optional: retrieve the bitstream's features.
CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK);
// C) Adjust 'config', if needed
config.no_fancy_upsampling = 1;
config.output.colorspace = MODE_BGRA;
// etc.
// Note that you can also make config.output point to an externally
// supplied memory buffer, provided it's big enough to store the decoded
// picture. Otherwise, config.output will just be used to allocate memory
// and store the decoded picture.
// D) Decode!
CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK);
// E) Decoded image is now in config.output (and config.output.u.RGBA)
// F) Reclaim memory allocated in config's object. It's safe to call
// this function even if the memory is external and wasn't allocated
// by WebPDecode().
WebPFreeDecBuffer(&config.output);
*/
// Features gathered from the bitstream
struct WebPBitstreamFeatures {
int width; // Width in pixels, as read from the bitstream.
int height; // Height in pixels, as read from the bitstream.
int has_alpha; // True if the bitstream contains an alpha channel.
int has_animation; // True if the bitstream is an animation.
int format; // 0 = undefined (/mixed), 1 = lossy, 2 = lossless
// Unused for now:
int no_incremental_decoding; // if true, using incremental decoding is not
// recommended.
int rotate; // TODO(later)
int uv_sampling; // should be 0 for now. TODO(later)
uint32_t pad[2]; // padding for later use
};
// Internal, version-checked, entry point
WEBP_EXTERN(VP8StatusCode) WebPGetFeaturesInternal(
const uint8_t*, size_t, WebPBitstreamFeatures*, int);
// Retrieve features from the bitstream. The *features structure is filled
// with information gathered from the bitstream.
// Returns VP8_STATUS_OK when the features are successfully retrieved. Returns
// VP8_STATUS_NOT_ENOUGH_DATA when more data is needed to retrieve the
// features from headers. Returns error in other cases.
static WEBP_INLINE VP8StatusCode WebPGetFeatures(
const uint8_t* data, size_t data_size,
WebPBitstreamFeatures* features) {
return WebPGetFeaturesInternal(data, data_size, features,
WEBP_DECODER_ABI_VERSION);
}
// Decoding options
struct WebPDecoderOptions {
int bypass_filtering; // if true, skip the in-loop filtering
int no_fancy_upsampling; // if true, use faster pointwise upsampler
int use_cropping; // if true, cropping is applied _first_
int crop_left, crop_top; // top-left position for cropping.
// Will be snapped to even values.
int crop_width, crop_height; // dimension of the cropping area
int use_scaling; // if true, scaling is applied _afterward_
int scaled_width, scaled_height; // final resolution
int use_threads; // if true, use multi-threaded decoding
int dithering_strength; // dithering strength (0=Off, 100=full)
int flip; // flip output vertically
int alpha_dithering_strength; // alpha dithering strength in [0..100]
// Unused for now:
int force_rotation; // forced rotation (to be applied _last_)
int no_enhancement; // if true, discard enhancement layer
uint32_t pad[3]; // padding for later use
};
// Main object storing the configuration for advanced decoding.
struct WebPDecoderConfig {
WebPBitstreamFeatures input; // Immutable bitstream features (optional)
WebPDecBuffer output; // Output buffer (can point to external mem)
WebPDecoderOptions options; // Decoding options
};
// Internal, version-checked, entry point
WEBP_EXTERN(int) WebPInitDecoderConfigInternal(WebPDecoderConfig*, int);
// Initialize the configuration as empty. This function must always be
// called first, unless WebPGetFeatures() is to be called.
// Returns false in case of mismatched version.
static WEBP_INLINE int WebPInitDecoderConfig(WebPDecoderConfig* config) {
return WebPInitDecoderConfigInternal(config, WEBP_DECODER_ABI_VERSION);
}
// Instantiate a new incremental decoder object with the requested
// configuration. The bitstream can be passed using 'data' and 'data_size'
// parameter, in which case the features will be parsed and stored into
// config->input. Otherwise, 'data' can be NULL and no parsing will occur.
// Note that 'config' can be NULL too, in which case a default configuration
// is used.
// The return WebPIDecoder object must always be deleted calling WebPIDelete().
// Returns NULL in case of error (and config->status will then reflect
// the error condition).
WEBP_EXTERN(WebPIDecoder*) WebPIDecode(const uint8_t* data, size_t data_size,
WebPDecoderConfig* config);
// Non-incremental version. This version decodes the full data at once, taking
// 'config' into account. Returns decoding status (which should be VP8_STATUS_OK
// if the decoding was successful).
WEBP_EXTERN(VP8StatusCode) WebPDecode(const uint8_t* data, size_t data_size,
WebPDecoderConfig* config);
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* WEBP_WEBP_DECODE_H_ */
| {
"content_hash": "67e1d066da7b68fb808f3e8308b19bf4",
"timestamp": "",
"source": "github",
"line_count": 496,
"max_line_length": 80,
"avg_line_length": 46.32056451612903,
"alnum_prop": 0.6798694232861806,
"repo_name": "zofuthan/libwebp",
"id": "d819f4484c4612966fe436d18ef8f528e8102e2d",
"size": "22975",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/webp/decode.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2288636"
},
{
"name": "C++",
"bytes": "6054"
},
{
"name": "Go",
"bytes": "1235"
},
{
"name": "Makefile",
"bytes": "5908"
},
{
"name": "Objective-C",
"bytes": "3052"
},
{
"name": "Python",
"bytes": "7805"
},
{
"name": "Shell",
"bytes": "3506"
}
],
"symlink_target": ""
} |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package XrefParser::OTTTParser;
use strict;
use warnings;
use Carp;
use File::Basename;
use XrefParser::Database;
use base qw( XrefParser::BaseParser );
sub run_script {
my ($self, $ref_arg) = @_;
my $source_id = $ref_arg->{source_id};
my $species_id = $ref_arg->{species_id};
my $file = $ref_arg->{file};
my $verbose = $ref_arg->{verbose};
if((!defined $source_id) or (!defined $species_id) or (!defined $file) ){
croak "Need to pass source_id, species_id and file as pairs";
}
$verbose |=0;
my ($type, $my_args) = split(/:/,$file);
my $user = "ensro";
my $host ="ens-staging";
my $port = "3306";
my $dbname = "homo_sapiens_vega_51_36m";
my $pass;
if($my_args =~ /host[=][>](\S+?)[,]/){
$host = $1;
}
if($my_args =~ /port[=][>](\S+?)[,]/){
$port = $1;
}
if($my_args =~ /dbname[=][>](\S+?)[,]/){
$dbname = $1;
}
if($my_args =~ /pass[=][>](\S+?)[,]/){
$pass = $1;
}
my $sql =(<<'SQL');
SELECT t.stable_id, x.display_label
FROM xref x, object_xref ox , transcript t, external_db e
WHERE e.external_db_id = x.external_db_id AND
x.xref_id = ox.xref_id AND
t.transcript_id = ox.ensembl_id AND
e.db_name like ?
SQL
my %ott_to_enst;
my $db = XrefParser::Database->new({ host => $host,
port => $port,
user => $user,
dbname => $dbname,
pass => $pass});
my $dbi2 = $db->dbi();
if(!defined($dbi2)){
return 1;
}
my $sth = $dbi2->prepare($sql); # funny number instead of stable id ?????
$sth->execute("ENST_CDS") or croak( $dbi2->errstr() );
while ( my @row = $sth->fetchrow_array() ) {
$ott_to_enst{$row[0]} = $row[1];
}
$sth->finish;
$sth = $dbi2->prepare($sql);
$sth->execute("ENST_ident") or croak( $dbi2->errstr() );
while ( my @row = $sth->fetchrow_array() ) {
$ott_to_enst{$row[0]} = $row[1];
}
$sth->finish;
my $xref_count = 0;
foreach my $ott (keys %ott_to_enst){
my $xref_id = $self->add_xref({ acc => $ott,
label => $ott,
source_id => $source_id,
species_id => $species_id,
info_type => "DIRECT"} );
$xref_count++;
$self->add_direct_xref($xref_id, $ott_to_enst{$ott}, "transcript", "");
}
return 0;
}
1;
| {
"content_hash": "797ab772cfb77a347c585144c5bb55be",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 100,
"avg_line_length": 25.504347826086956,
"alnum_prop": 0.5860893283327651,
"repo_name": "mjg17/ensembl",
"id": "c2bf3bd639bef207a3fbcaba74cdfd84dc9ed6e1",
"size": "2933",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "misc-scripts/xref_mapping/XrefParser/OTTTParser.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7944"
},
{
"name": "HTML",
"bytes": "1434"
},
{
"name": "PLpgSQL",
"bytes": "261360"
},
{
"name": "Perl",
"bytes": "6328332"
},
{
"name": "Perl6",
"bytes": "13360"
},
{
"name": "Shell",
"bytes": "8738"
}
],
"symlink_target": ""
} |
<!doctype html>
<!--
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<html>
<head>
<title>iron-component-page</title>
<script src="../../../bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<script src="../../../bower_components/web-component-tester/browser.js"></script>
<script src="../../../bower_components/test-fixture/test-fixture-mocha.js"></script>
<link rel="import" href="../../../bower_components/polymer/polymer.html">
<link rel="import" href="../../../bower_components/test-fixture/test-fixture.html">
<link rel="import" href="../x-factory.html">
</head>
<body>
<test-fixture id="basic">
<template>
<x-factory></x-factory>
</template>
</test-fixture>
<script>
suite('active-state', function() {
var testElement;
setup(function() {
testElement = fixture('basic');
});
test('Name of element should be x-factory', function() {
assert.equal(testElement.localName, 'x-factory');
});
test('Should have shadyRoot', function() {
expect(testElement.shadyRoot).to.be.an('object');
});
});
</script>
</body>
</html>
| {
"content_hash": "e43b699505236f94ad17bc0dba080d7d",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 100,
"avg_line_length": 31.470588235294116,
"alnum_prop": 0.6679127725856698,
"repo_name": "denineguy/polymer-workshop",
"id": "8f5cf022a21fa14d82d4172bdc38b557e469103e",
"size": "1605",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/elements/x-factory/test/tests.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "622"
},
{
"name": "HTML",
"bytes": "146651"
},
{
"name": "JavaScript",
"bytes": "10412"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.